entities
listlengths 1
9.05k
| max_stars_repo_path
stringlengths 5
154
| max_stars_repo_name
stringlengths 6
76
| max_stars_count
int64 0
38.8k
| content
stringlengths 24
1.03M
| id
stringlengths 1
5
| new_content
stringlengths 17
1.03M
| modified
bool 1
class | references
stringlengths 31
1.03M
|
---|---|---|---|---|---|---|---|---|
[
{
"context": ";;;;; Copyright (c) 2009-2012, Martin Loetzsch\n;;;;; All rights reserved.\n\n;;;;; Redistribution ",
"end": 46,
"score": 0.9998005032539368,
"start": 31,
"tag": "NAME",
"value": "Martin Loetzsch"
}
] |
libraries/gtfl_0.1.3/examples/basic-usage.lisp
|
lucas8/Babel2
| 3 |
;;;;; Copyright (c) 2009-2012, Martin Loetzsch
;;;;; All rights reserved.
;;;;; Redistribution and use in source and binary forms, with or
;;;;; without modification, are permitted provided that the following
;;;;; conditions are met:
;;;;; Redistributions of source code must retain the above copyright
;;;;; notice, this list of conditions and the following disclaimer.
;;;;; Redistributions in binary form must reproduce the above
;;;;; copyright notice, this list of conditions and the following
;;;;; disclaimer in the documentation and/or other materials provided
;;;;; with the distribution.
;;;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
;;;;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
;;;;; INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
;;;;; MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;;;;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
;;;;; CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
;;;;; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
;;;;; USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
;;;;; AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
;;;;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
;;;;; IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
;;;;; THE POSSIBILITY OF SUCH DAMAGE.
(asdf:operate 'asdf:load-op 'gtfl)
(in-package :gtfl)
;; starting gtfl. When you want to use another address or port
;; than localhost:8000 then please set the *gtfl-address* and
;; *gtfl-port* variables
(start-gtfl)
;; reset the page (the same as clicking on the 'reset' in the browser)
;; this deletes all content on the client page and resets things on
;; the lisp side
(reset-gtfl)
;; displaying stuff
;; any expressions that are ok in cl-who's with-html-output macro can go here
(gtfl-out (:h1 "hello world"))
(gtfl-out (:p "some text, "
(:span :style "color:red;" "and some in red."))
(:p "and a second paragraph"))
;; replacing content of existing elements
(defparameter *element-id* nil)
(gtfl-out (:p "a paragraph, "
(:span :id (setf *element-id* (make-id-string))
:style "border:1px solid red"
"and a span as child element")))
(replace-element-content *element-id* "and " (:b "new") " span content")
;; appending content to existing elements
(gtfl-out (:p "a paragraph, "
(:span :id (setf *element-id* (make-id-string))
:style "border:1px solid red"
"and a span as child element")))
(append-to-element *element-id* ", and " (:b "more") " content")
;; expandable elements (see expandable-elements.lisp)
(expandable-elements-example)
;; drawing trees (see tree-drawing.lisp)
(tree-drawing-example)
;; pprinting s-expressions (see html-pprint.lisp)
(html-pprint-example)
|
63026
|
;;;;; Copyright (c) 2009-2012, <NAME>
;;;;; All rights reserved.
;;;;; Redistribution and use in source and binary forms, with or
;;;;; without modification, are permitted provided that the following
;;;;; conditions are met:
;;;;; Redistributions of source code must retain the above copyright
;;;;; notice, this list of conditions and the following disclaimer.
;;;;; Redistributions in binary form must reproduce the above
;;;;; copyright notice, this list of conditions and the following
;;;;; disclaimer in the documentation and/or other materials provided
;;;;; with the distribution.
;;;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
;;;;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
;;;;; INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
;;;;; MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;;;;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
;;;;; CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
;;;;; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
;;;;; USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
;;;;; AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
;;;;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
;;;;; IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
;;;;; THE POSSIBILITY OF SUCH DAMAGE.
(asdf:operate 'asdf:load-op 'gtfl)
(in-package :gtfl)
;; starting gtfl. When you want to use another address or port
;; than localhost:8000 then please set the *gtfl-address* and
;; *gtfl-port* variables
(start-gtfl)
;; reset the page (the same as clicking on the 'reset' in the browser)
;; this deletes all content on the client page and resets things on
;; the lisp side
(reset-gtfl)
;; displaying stuff
;; any expressions that are ok in cl-who's with-html-output macro can go here
(gtfl-out (:h1 "hello world"))
(gtfl-out (:p "some text, "
(:span :style "color:red;" "and some in red."))
(:p "and a second paragraph"))
;; replacing content of existing elements
(defparameter *element-id* nil)
(gtfl-out (:p "a paragraph, "
(:span :id (setf *element-id* (make-id-string))
:style "border:1px solid red"
"and a span as child element")))
(replace-element-content *element-id* "and " (:b "new") " span content")
;; appending content to existing elements
(gtfl-out (:p "a paragraph, "
(:span :id (setf *element-id* (make-id-string))
:style "border:1px solid red"
"and a span as child element")))
(append-to-element *element-id* ", and " (:b "more") " content")
;; expandable elements (see expandable-elements.lisp)
(expandable-elements-example)
;; drawing trees (see tree-drawing.lisp)
(tree-drawing-example)
;; pprinting s-expressions (see html-pprint.lisp)
(html-pprint-example)
| true |
;;;;; Copyright (c) 2009-2012, PI:NAME:<NAME>END_PI
;;;;; All rights reserved.
;;;;; Redistribution and use in source and binary forms, with or
;;;;; without modification, are permitted provided that the following
;;;;; conditions are met:
;;;;; Redistributions of source code must retain the above copyright
;;;;; notice, this list of conditions and the following disclaimer.
;;;;; Redistributions in binary form must reproduce the above
;;;;; copyright notice, this list of conditions and the following
;;;;; disclaimer in the documentation and/or other materials provided
;;;;; with the distribution.
;;;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
;;;;; CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
;;;;; INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
;;;;; MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;;;;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
;;;;; CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
;;;;; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
;;;;; USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
;;;;; AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
;;;;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
;;;;; IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
;;;;; THE POSSIBILITY OF SUCH DAMAGE.
(asdf:operate 'asdf:load-op 'gtfl)
(in-package :gtfl)
;; starting gtfl. When you want to use another address or port
;; than localhost:8000 then please set the *gtfl-address* and
;; *gtfl-port* variables
(start-gtfl)
;; reset the page (the same as clicking on the 'reset' in the browser)
;; this deletes all content on the client page and resets things on
;; the lisp side
(reset-gtfl)
;; displaying stuff
;; any expressions that are ok in cl-who's with-html-output macro can go here
(gtfl-out (:h1 "hello world"))
(gtfl-out (:p "some text, "
(:span :style "color:red;" "and some in red."))
(:p "and a second paragraph"))
;; replacing content of existing elements
(defparameter *element-id* nil)
(gtfl-out (:p "a paragraph, "
(:span :id (setf *element-id* (make-id-string))
:style "border:1px solid red"
"and a span as child element")))
(replace-element-content *element-id* "and " (:b "new") " span content")
;; appending content to existing elements
(gtfl-out (:p "a paragraph, "
(:span :id (setf *element-id* (make-id-string))
:style "border:1px solid red"
"and a span as child element")))
(append-to-element *element-id* ", and " (:b "more") " content")
;; expandable elements (see expandable-elements.lisp)
(expandable-elements-example)
;; drawing trees (see tree-drawing.lisp)
(tree-drawing-example)
;; pprinting s-expressions (see html-pprint.lisp)
(html-pprint-example)
|
[
{
"context": "(in-package :lispmake)\n\n;; lispmake, written by Matthew Veety, et al.\n;; (c) Matthew Veety 2012-2021. Under BSD",
"end": 61,
"score": 0.9998824596405029,
"start": 48,
"tag": "NAME",
"value": "Matthew Veety"
},
{
"context": " lispmake, written by Matthew Veety, et al.\n;; (c) Matthew Veety 2012-2021. Under BSD License.\n\n(defun loadfile (o",
"end": 90,
"score": 0.9998721480369568,
"start": 77,
"tag": "NAME",
"value": "Matthew Veety"
}
] |
core.lisp
|
mveety/lispmake
| 0 |
(in-package :lispmake)
;; lispmake, written by Matthew Veety, et al.
;; (c) Matthew Veety 2012-2021. Under BSD License.
(defun loadfile (outstream fname)
(format outstream "(load #P\"~A\")~%" fname))
(defun quickloads (outstream library)
(format outstream "(ql:quickload '~A)~%" library))
(defun pl-package (args)
(setf *lm-package* args)
(set-var 'package (car args)))
(defun pl-toplevel (args)
(setf *toplevel* args)
(set-var 'toplevel (car args)))
(defun pl-file (args)
(if (listp args)
(dolist (x args)
(let ((var (varhdl x)))
(if (not (nilp var))
(setf *sources* (append *sources* (list var))))))
(lm-error "file" "invalid arguments")))
(defun pl-output (args)
(setf *outfile* args)
(set-var 'outfile (car args)))
(defun pl-quicklisp (args)
(if (listp args)
(dolist (x args)
(setf *quickloads* (append *quickloads* (list x))))
(lm-error "quicklisp" "invalid arguments")))
|
87718
|
(in-package :lispmake)
;; lispmake, written by <NAME>, et al.
;; (c) <NAME> 2012-2021. Under BSD License.
(defun loadfile (outstream fname)
(format outstream "(load #P\"~A\")~%" fname))
(defun quickloads (outstream library)
(format outstream "(ql:quickload '~A)~%" library))
(defun pl-package (args)
(setf *lm-package* args)
(set-var 'package (car args)))
(defun pl-toplevel (args)
(setf *toplevel* args)
(set-var 'toplevel (car args)))
(defun pl-file (args)
(if (listp args)
(dolist (x args)
(let ((var (varhdl x)))
(if (not (nilp var))
(setf *sources* (append *sources* (list var))))))
(lm-error "file" "invalid arguments")))
(defun pl-output (args)
(setf *outfile* args)
(set-var 'outfile (car args)))
(defun pl-quicklisp (args)
(if (listp args)
(dolist (x args)
(setf *quickloads* (append *quickloads* (list x))))
(lm-error "quicklisp" "invalid arguments")))
| true |
(in-package :lispmake)
;; lispmake, written by PI:NAME:<NAME>END_PI, et al.
;; (c) PI:NAME:<NAME>END_PI 2012-2021. Under BSD License.
(defun loadfile (outstream fname)
(format outstream "(load #P\"~A\")~%" fname))
(defun quickloads (outstream library)
(format outstream "(ql:quickload '~A)~%" library))
(defun pl-package (args)
(setf *lm-package* args)
(set-var 'package (car args)))
(defun pl-toplevel (args)
(setf *toplevel* args)
(set-var 'toplevel (car args)))
(defun pl-file (args)
(if (listp args)
(dolist (x args)
(let ((var (varhdl x)))
(if (not (nilp var))
(setf *sources* (append *sources* (list var))))))
(lm-error "file" "invalid arguments")))
(defun pl-output (args)
(setf *outfile* args)
(set-var 'outfile (car args)))
(defun pl-quicklisp (args)
(if (listp args)
(dolist (x args)
(setf *quickloads* (append *quickloads* (list x))))
(lm-error "quicklisp" "invalid arguments")))
|
[
{
"context": "(in-package :polisher)\n\n\n;;; From Paul Graham's \"On Lisp\"\n(defmacro acond (&rest clauses)\n (if",
"end": 45,
"score": 0.9998403191566467,
"start": 34,
"tag": "NAME",
"value": "Paul Graham"
}
] |
src/tokenizer.lisp
|
mrcdr/polisher
| 3 |
(in-package :polisher)
;;; From Paul Graham's "On Lisp"
(defmacro acond (&rest clauses)
(if (null clauses)
nil
(let ((cl1 (car clauses))
(sym (gensym)))
`(let ((,sym ,(car cl1)))
(if ,sym
(let ((it ,sym)) ,@(cdr cl1))
(acond ,@(cdr clauses)))))))
(defun match-length (regex target-string &optional group-index)
(let ((scanner (cl-ppcre:create-scanner regex :case-insensitive-mode t)))
(multiple-value-bind (start end s-group e-group)
(cl-ppcre:scan scanner target-string)
(when start
(if group-index
(- (aref e-group group-index) (aref s-group group-index))
(- end start))))))
(defun create-operator-regex ()
(format nil "~{~a~^|~}" (mapcar
#'(lambda (x)
(cl-ppcre:quote-meta-chars
(symbol-name (slot-value x 'symbol))))
*operator-list*)))
(defun read-safely (str)
(multiple-value-bind (read position) (read-from-string str)
(when (/= (length str) position)
(error (format nil "Illegal read: trying to read \"~a\", got ~a" str (string read))))
read))
(defun tokenize (formula-str)
(let* ((unsigned-value-regex "^[0-9]+(?:\\.[0-9]*)?(?:[dDeEfFlLsS][+-]?[0-9]+)?")
(unsigned-double-quote-regex "^\".*?\"")
(operator-regex-tmp (create-operator-regex))
(operator-regex (format nil "^(~a)" operator-regex-tmp))
(separator-regex (format nil "~a|\\(|\\)|," operator-regex-tmp))
(unsigned-symbol-regex (format nil "^(.+?)(?:~a|\\s|\\z)" separator-regex))) ; \z is required to terminate non-greedy match
(let ((tokenized nil))
(loop with rest-str = formula-str
with sign-allowed = t
if (zerop (length rest-str)) do (loop-finish)
do (acond
((match-length "^\\s+" rest-str)
(setf rest-str (subseq rest-str it))) ; remove spaces
((match-length "^#" rest-str) ;; parse reader macro
(declare (ignore it))
(multiple-value-bind (read-form position)
(read-from-string rest-str)
(push read-form tokenized)
(setf rest-str (subseq rest-str position))
(setf sign-allowed nil)))
((and sign-allowed (match-length "^[+-]" rest-str))
(declare (ignore it))
(progn
(when (char= (char rest-str 0) #\-)
(push *left-paren* tokenized)
(push -1 tokenized)
(push *right-paren* tokenized)
(push (symbol-to-operator '*) tokenized))
(setf rest-str (subseq rest-str 1))
(setf sign-allowed nil)))
((match-length unsigned-value-regex rest-str)
(progn
(push (read-safely (subseq rest-str 0 it)) tokenized)
(setf rest-str (subseq rest-str it))
(setf sign-allowed nil)))
((match-length unsigned-double-quote-regex rest-str)
(progn
(push (read-safely (subseq rest-str 1 (- it 1))) tokenized) ; remove double quotes
(setf rest-str (subseq rest-str it))
(setf sign-allowed nil)))
((cl-ppcre:scan "^\"" rest-str)
;; Reaching here through the above conditions means unmatched double quote existing
(declare (ignore it))
(error "Unmatched double quote"))
((match-length operator-regex rest-str 0)
(progn
(push (symbol-to-operator (read-from-string (subseq rest-str 0 it))) tokenized)
(setf rest-str (subseq rest-str it))
(setf sign-allowed nil)))
((match-length "^\\(" rest-str)
(progn
(push *left-paren* tokenized)
(setf rest-str (subseq rest-str it))
(setf sign-allowed t)))
((match-length "^\\)" rest-str)
(progn
(push *right-paren* tokenized)
(setf rest-str (subseq rest-str it))
(setf sign-allowed nil)))
((match-length "^," rest-str)
(progn
(push *separator* tokenized)
(setf rest-str (subseq rest-str it))
(setf sign-allowed t)))
((match-length unsigned-symbol-regex rest-str 0)
(progn
(push (read-safely (subseq rest-str 0 it)) tokenized)
(setf rest-str (subseq rest-str it))
(setf sign-allowed nil)))
(t
(declare (ignore it))
(error "Invalid sytax"))))
(nreverse tokenized))))
|
94261
|
(in-package :polisher)
;;; From <NAME>'s "On Lisp"
(defmacro acond (&rest clauses)
(if (null clauses)
nil
(let ((cl1 (car clauses))
(sym (gensym)))
`(let ((,sym ,(car cl1)))
(if ,sym
(let ((it ,sym)) ,@(cdr cl1))
(acond ,@(cdr clauses)))))))
(defun match-length (regex target-string &optional group-index)
(let ((scanner (cl-ppcre:create-scanner regex :case-insensitive-mode t)))
(multiple-value-bind (start end s-group e-group)
(cl-ppcre:scan scanner target-string)
(when start
(if group-index
(- (aref e-group group-index) (aref s-group group-index))
(- end start))))))
(defun create-operator-regex ()
(format nil "~{~a~^|~}" (mapcar
#'(lambda (x)
(cl-ppcre:quote-meta-chars
(symbol-name (slot-value x 'symbol))))
*operator-list*)))
(defun read-safely (str)
(multiple-value-bind (read position) (read-from-string str)
(when (/= (length str) position)
(error (format nil "Illegal read: trying to read \"~a\", got ~a" str (string read))))
read))
(defun tokenize (formula-str)
(let* ((unsigned-value-regex "^[0-9]+(?:\\.[0-9]*)?(?:[dDeEfFlLsS][+-]?[0-9]+)?")
(unsigned-double-quote-regex "^\".*?\"")
(operator-regex-tmp (create-operator-regex))
(operator-regex (format nil "^(~a)" operator-regex-tmp))
(separator-regex (format nil "~a|\\(|\\)|," operator-regex-tmp))
(unsigned-symbol-regex (format nil "^(.+?)(?:~a|\\s|\\z)" separator-regex))) ; \z is required to terminate non-greedy match
(let ((tokenized nil))
(loop with rest-str = formula-str
with sign-allowed = t
if (zerop (length rest-str)) do (loop-finish)
do (acond
((match-length "^\\s+" rest-str)
(setf rest-str (subseq rest-str it))) ; remove spaces
((match-length "^#" rest-str) ;; parse reader macro
(declare (ignore it))
(multiple-value-bind (read-form position)
(read-from-string rest-str)
(push read-form tokenized)
(setf rest-str (subseq rest-str position))
(setf sign-allowed nil)))
((and sign-allowed (match-length "^[+-]" rest-str))
(declare (ignore it))
(progn
(when (char= (char rest-str 0) #\-)
(push *left-paren* tokenized)
(push -1 tokenized)
(push *right-paren* tokenized)
(push (symbol-to-operator '*) tokenized))
(setf rest-str (subseq rest-str 1))
(setf sign-allowed nil)))
((match-length unsigned-value-regex rest-str)
(progn
(push (read-safely (subseq rest-str 0 it)) tokenized)
(setf rest-str (subseq rest-str it))
(setf sign-allowed nil)))
((match-length unsigned-double-quote-regex rest-str)
(progn
(push (read-safely (subseq rest-str 1 (- it 1))) tokenized) ; remove double quotes
(setf rest-str (subseq rest-str it))
(setf sign-allowed nil)))
((cl-ppcre:scan "^\"" rest-str)
;; Reaching here through the above conditions means unmatched double quote existing
(declare (ignore it))
(error "Unmatched double quote"))
((match-length operator-regex rest-str 0)
(progn
(push (symbol-to-operator (read-from-string (subseq rest-str 0 it))) tokenized)
(setf rest-str (subseq rest-str it))
(setf sign-allowed nil)))
((match-length "^\\(" rest-str)
(progn
(push *left-paren* tokenized)
(setf rest-str (subseq rest-str it))
(setf sign-allowed t)))
((match-length "^\\)" rest-str)
(progn
(push *right-paren* tokenized)
(setf rest-str (subseq rest-str it))
(setf sign-allowed nil)))
((match-length "^," rest-str)
(progn
(push *separator* tokenized)
(setf rest-str (subseq rest-str it))
(setf sign-allowed t)))
((match-length unsigned-symbol-regex rest-str 0)
(progn
(push (read-safely (subseq rest-str 0 it)) tokenized)
(setf rest-str (subseq rest-str it))
(setf sign-allowed nil)))
(t
(declare (ignore it))
(error "Invalid sytax"))))
(nreverse tokenized))))
| true |
(in-package :polisher)
;;; From PI:NAME:<NAME>END_PI's "On Lisp"
(defmacro acond (&rest clauses)
(if (null clauses)
nil
(let ((cl1 (car clauses))
(sym (gensym)))
`(let ((,sym ,(car cl1)))
(if ,sym
(let ((it ,sym)) ,@(cdr cl1))
(acond ,@(cdr clauses)))))))
(defun match-length (regex target-string &optional group-index)
(let ((scanner (cl-ppcre:create-scanner regex :case-insensitive-mode t)))
(multiple-value-bind (start end s-group e-group)
(cl-ppcre:scan scanner target-string)
(when start
(if group-index
(- (aref e-group group-index) (aref s-group group-index))
(- end start))))))
(defun create-operator-regex ()
(format nil "~{~a~^|~}" (mapcar
#'(lambda (x)
(cl-ppcre:quote-meta-chars
(symbol-name (slot-value x 'symbol))))
*operator-list*)))
(defun read-safely (str)
(multiple-value-bind (read position) (read-from-string str)
(when (/= (length str) position)
(error (format nil "Illegal read: trying to read \"~a\", got ~a" str (string read))))
read))
(defun tokenize (formula-str)
(let* ((unsigned-value-regex "^[0-9]+(?:\\.[0-9]*)?(?:[dDeEfFlLsS][+-]?[0-9]+)?")
(unsigned-double-quote-regex "^\".*?\"")
(operator-regex-tmp (create-operator-regex))
(operator-regex (format nil "^(~a)" operator-regex-tmp))
(separator-regex (format nil "~a|\\(|\\)|," operator-regex-tmp))
(unsigned-symbol-regex (format nil "^(.+?)(?:~a|\\s|\\z)" separator-regex))) ; \z is required to terminate non-greedy match
(let ((tokenized nil))
(loop with rest-str = formula-str
with sign-allowed = t
if (zerop (length rest-str)) do (loop-finish)
do (acond
((match-length "^\\s+" rest-str)
(setf rest-str (subseq rest-str it))) ; remove spaces
((match-length "^#" rest-str) ;; parse reader macro
(declare (ignore it))
(multiple-value-bind (read-form position)
(read-from-string rest-str)
(push read-form tokenized)
(setf rest-str (subseq rest-str position))
(setf sign-allowed nil)))
((and sign-allowed (match-length "^[+-]" rest-str))
(declare (ignore it))
(progn
(when (char= (char rest-str 0) #\-)
(push *left-paren* tokenized)
(push -1 tokenized)
(push *right-paren* tokenized)
(push (symbol-to-operator '*) tokenized))
(setf rest-str (subseq rest-str 1))
(setf sign-allowed nil)))
((match-length unsigned-value-regex rest-str)
(progn
(push (read-safely (subseq rest-str 0 it)) tokenized)
(setf rest-str (subseq rest-str it))
(setf sign-allowed nil)))
((match-length unsigned-double-quote-regex rest-str)
(progn
(push (read-safely (subseq rest-str 1 (- it 1))) tokenized) ; remove double quotes
(setf rest-str (subseq rest-str it))
(setf sign-allowed nil)))
((cl-ppcre:scan "^\"" rest-str)
;; Reaching here through the above conditions means unmatched double quote existing
(declare (ignore it))
(error "Unmatched double quote"))
((match-length operator-regex rest-str 0)
(progn
(push (symbol-to-operator (read-from-string (subseq rest-str 0 it))) tokenized)
(setf rest-str (subseq rest-str it))
(setf sign-allowed nil)))
((match-length "^\\(" rest-str)
(progn
(push *left-paren* tokenized)
(setf rest-str (subseq rest-str it))
(setf sign-allowed t)))
((match-length "^\\)" rest-str)
(progn
(push *right-paren* tokenized)
(setf rest-str (subseq rest-str it))
(setf sign-allowed nil)))
((match-length "^," rest-str)
(progn
(push *separator* tokenized)
(setf rest-str (subseq rest-str it))
(setf sign-allowed t)))
((match-length unsigned-symbol-regex rest-str 0)
(progn
(push (read-safely (subseq rest-str 0 it)) tokenized)
(setf rest-str (subseq rest-str it))
(setf sign-allowed nil)))
(t
(declare (ignore it))
(error "Invalid sytax"))))
(nreverse tokenized))))
|
[
{
"context": "he LICENSE file distributed with ACL2.\n;\n; Author: Alessandro Coglio ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 208,
"score": 0.9998798370361328,
"start": 191,
"tag": "NAME",
"value": "Alessandro Coglio"
},
{
"context": "ributed with ACL2.\n;\n; Author: Alessandro Coglio ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 228,
"score": 0.9999280571937561,
"start": 210,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/std/typed-alists/string-symbollist-alistp.lisp
|
nzt/acl2
| 0 |
; Standard Typed Alists Library
;
; Copyright (C) 2019 Kestrel Institute (http://www.kestrel.edu)
;
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;
; Author: Alessandro Coglio ([email protected])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(include-book "std/util/defalist" :dir :system)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(std::defalist string-symbollist-alistp (x)
:parents (std/typed-alists)
:short "Recognize alists from strings to true lists of symbols."
:key (stringp x)
:val (symbol-listp x)
:true-listp t
:keyp-of-nil nil
:valp-of-nil t
///
(defthm symbol-listp-of-cdr-of-assoc-equal-when-string-symbollist-alistp
(implies (string-symbollist-alistp alist)
(symbol-listp (cdr (assoc-equal key alist)))))
(defthm string-symbollist-alistp-of-put-assoc-equal
(implies (string-symbollist-alistp alist)
(equal (string-symbollist-alistp (put-assoc-equal key val alist))
(and (stringp key)
(symbol-listp val))))))
|
25190
|
; Standard Typed Alists Library
;
; Copyright (C) 2019 Kestrel Institute (http://www.kestrel.edu)
;
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;
; Author: <NAME> (<EMAIL>)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(include-book "std/util/defalist" :dir :system)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(std::defalist string-symbollist-alistp (x)
:parents (std/typed-alists)
:short "Recognize alists from strings to true lists of symbols."
:key (stringp x)
:val (symbol-listp x)
:true-listp t
:keyp-of-nil nil
:valp-of-nil t
///
(defthm symbol-listp-of-cdr-of-assoc-equal-when-string-symbollist-alistp
(implies (string-symbollist-alistp alist)
(symbol-listp (cdr (assoc-equal key alist)))))
(defthm string-symbollist-alistp-of-put-assoc-equal
(implies (string-symbollist-alistp alist)
(equal (string-symbollist-alistp (put-assoc-equal key val alist))
(and (stringp key)
(symbol-listp val))))))
| true |
; Standard Typed Alists Library
;
; Copyright (C) 2019 Kestrel Institute (http://www.kestrel.edu)
;
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;
; Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(include-book "std/util/defalist" :dir :system)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(std::defalist string-symbollist-alistp (x)
:parents (std/typed-alists)
:short "Recognize alists from strings to true lists of symbols."
:key (stringp x)
:val (symbol-listp x)
:true-listp t
:keyp-of-nil nil
:valp-of-nil t
///
(defthm symbol-listp-of-cdr-of-assoc-equal-when-string-symbollist-alistp
(implies (string-symbollist-alistp alist)
(symbol-listp (cdr (assoc-equal key alist)))))
(defthm string-symbollist-alistp-of-put-assoc-equal
(implies (string-symbollist-alistp alist)
(equal (string-symbollist-alistp (put-assoc-equal key val alist))
(and (stringp key)
(symbol-listp val))))))
|
[
{
"context": ";; Copyright (c) 2015 YOKOTA Yuki <[email protected]>\n;;\n;; This software is ",
"end": 33,
"score": 0.9998440742492676,
"start": 22,
"tag": "NAME",
"value": "YOKOTA Yuki"
},
{
"context": ";; Copyright (c) 2015 YOKOTA Yuki <[email protected]>\n;;\n;; This software is released under the MIT Li",
"end": 58,
"score": 0.9999299049377441,
"start": 35,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "ings. (experimental)\"\n :license \"MIT\"\n :author \"YOKOTA Yuki <[email protected]>\"\n :components\n ((:mod",
"end": 444,
"score": 0.9998455047607422,
"start": 433,
"tag": "NAME",
"value": "YOKOTA Yuki"
},
{
"context": "mental)\"\n :license \"MIT\"\n :author \"YOKOTA Yuki <[email protected]>\"\n :components\n ((:module \"error_handler\"\n :",
"end": 469,
"score": 0.9999282956123352,
"start": 446,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "bnuma.error-handler.\"\n :license \"MIT\"\n :author \"YOKOTA Yuki <[email protected]>\"\n :pathname \"error_han",
"end": 1098,
"score": 0.9998115301132202,
"start": 1087,
"tag": "NAME",
"value": "YOKOTA Yuki"
},
{
"context": "andler.\"\n :license \"MIT\"\n :author \"YOKOTA Yuki <[email protected]>\"\n :pathname \"error_handler/avail_check\"\n :comp",
"end": 1123,
"score": 0.999930202960968,
"start": 1100,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
cl-libnuma-error-handler.asd
|
y2q-actionman/cl-libnuma
| 0 |
;; Copyright (c) 2015 YOKOTA Yuki <[email protected]>
;;
;; This software is released under the MIT License.
;; See the LICENSE file.
(in-package :cl-user)
(eval-when (:compile-toplevel :load-toplevel :execute)
(asdf:load-system :cffi-grovel))
(asdf:defsystem :cl-libnuma.error-handler
:description "cl-libnuma, a set of CFFI bindings for numa(3), with lispy error handlings. (experimental)"
:license "MIT"
:author "YOKOTA Yuki <[email protected]>"
:components
((:module "error_handler"
:serial t
:components
((:file "package")
(:file "wrapper-syntax")
(cffi-grovel:wrapper-file "wrapping" :soname "cl-libnuma-error-handler-wrapping")
(:file "condition")
)))
:in-order-to ((asdf:load-op (asdf:load-op #:cl-libnuma) ; This must be loaded after!
(asdf:load-op #:cl-libnuma.error-handler.avail-check))
(asdf:test-op (asdf:test-op #:cl-libnuma.error-handler.test))))
(asdf:defsystem :cl-libnuma.error-handler.avail-check
:description "An availability check for cl-libnuma.error-handler."
:license "MIT"
:author "YOKOTA Yuki <[email protected]>"
:pathname "error_handler/avail_check"
:components
((:file "avail-check")))
(defmethod asdf:operate :after ((operate (eql 'asdf:load-op))
(component (eql :cl-libnuma.error-handler))
&rest args &key &allow-other-keys)
(declare (ignore args))
(unless (uiop:symbol-call :cl-libnuma.error-handler.avail-check '#:error-handler-available?)
(warn "cl-libnuma-error-handler is unavailable. Please load cl-libnuma.error-handler before cl-libnuma.")))
|
65266
|
;; Copyright (c) 2015 <NAME> <<EMAIL>>
;;
;; This software is released under the MIT License.
;; See the LICENSE file.
(in-package :cl-user)
(eval-when (:compile-toplevel :load-toplevel :execute)
(asdf:load-system :cffi-grovel))
(asdf:defsystem :cl-libnuma.error-handler
:description "cl-libnuma, a set of CFFI bindings for numa(3), with lispy error handlings. (experimental)"
:license "MIT"
:author "<NAME> <<EMAIL>>"
:components
((:module "error_handler"
:serial t
:components
((:file "package")
(:file "wrapper-syntax")
(cffi-grovel:wrapper-file "wrapping" :soname "cl-libnuma-error-handler-wrapping")
(:file "condition")
)))
:in-order-to ((asdf:load-op (asdf:load-op #:cl-libnuma) ; This must be loaded after!
(asdf:load-op #:cl-libnuma.error-handler.avail-check))
(asdf:test-op (asdf:test-op #:cl-libnuma.error-handler.test))))
(asdf:defsystem :cl-libnuma.error-handler.avail-check
:description "An availability check for cl-libnuma.error-handler."
:license "MIT"
:author "<NAME> <<EMAIL>>"
:pathname "error_handler/avail_check"
:components
((:file "avail-check")))
(defmethod asdf:operate :after ((operate (eql 'asdf:load-op))
(component (eql :cl-libnuma.error-handler))
&rest args &key &allow-other-keys)
(declare (ignore args))
(unless (uiop:symbol-call :cl-libnuma.error-handler.avail-check '#:error-handler-available?)
(warn "cl-libnuma-error-handler is unavailable. Please load cl-libnuma.error-handler before cl-libnuma.")))
| true |
;; Copyright (c) 2015 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;
;; This software is released under the MIT License.
;; See the LICENSE file.
(in-package :cl-user)
(eval-when (:compile-toplevel :load-toplevel :execute)
(asdf:load-system :cffi-grovel))
(asdf:defsystem :cl-libnuma.error-handler
:description "cl-libnuma, a set of CFFI bindings for numa(3), with lispy error handlings. (experimental)"
:license "MIT"
:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:components
((:module "error_handler"
:serial t
:components
((:file "package")
(:file "wrapper-syntax")
(cffi-grovel:wrapper-file "wrapping" :soname "cl-libnuma-error-handler-wrapping")
(:file "condition")
)))
:in-order-to ((asdf:load-op (asdf:load-op #:cl-libnuma) ; This must be loaded after!
(asdf:load-op #:cl-libnuma.error-handler.avail-check))
(asdf:test-op (asdf:test-op #:cl-libnuma.error-handler.test))))
(asdf:defsystem :cl-libnuma.error-handler.avail-check
:description "An availability check for cl-libnuma.error-handler."
:license "MIT"
:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:pathname "error_handler/avail_check"
:components
((:file "avail-check")))
(defmethod asdf:operate :after ((operate (eql 'asdf:load-op))
(component (eql :cl-libnuma.error-handler))
&rest args &key &allow-other-keys)
(declare (ignore args))
(unless (uiop:symbol-call :cl-libnuma.error-handler.avail-check '#:error-handler-available?)
(warn "cl-libnuma-error-handler is unavailable. Please load cl-libnuma.error-handler before cl-libnuma.")))
|
[
{
"context": "p - Parsnip library test suite\n\n;;; Copyright 2021 Samuel Hunter <samuel (at) shunter (dot) xyz>\n;;; BSD-3-Clause\n",
"end": 76,
"score": 0.9998739957809448,
"start": 63,
"tag": "NAME",
"value": "Samuel Hunter"
},
{
"context": " typep to\n ;; parser-error: https://github.com/armedbear/abcl/issues/388\n #-ABCL\n (of-type stream (s",
"end": 3932,
"score": 0.9993899464607239,
"start": 3923,
"tag": "USERNAME",
"value": "armedbear"
}
] |
test.lisp
|
samuel-hunter/parsnip
| 0 |
;;; test.lisp - Parsnip library test suite
;;; Copyright 2021 Samuel Hunter <samuel (at) shunter (dot) xyz>
;;; BSD-3-Clause
(defpackage #:xyz.shunter.parsnip.test
(:use #:cl #:parachute
#:xyz.shunter.parsnip
#:xyz.shunter.parsnip.examples.json))
(in-package #:xyz.shunter.parsnip.test)
(defun parse-string (parser string)
(with-input-from-string (stream string)
(parse parser stream)))
(defun capture-parse-error (parser string)
(multiple-value-bind (always-nil err) (ignore-errors (parse-string parser string))
(declare (ignore always-nil))
err))
(defun close-enough (float-1 float-2)
"Return whether two decimal numbers are within tolerance (0.05%)"
(when (zerop (+ float-1 float-2))
(return-from close-enough nil))
(let ((difference (abs (/ (- float-1 float-2) (abs (+ float-1 float-2)) 2)))
(tolerance 0.0005))
(< difference tolerance)))
;; Unit Tests
(define-test char-parser
(let ((parser (char-parser #\a)))
(is char= #\a
(parse-string parser "abc"))
(is char= #\a
(parse-string parser "a"))
(fail (parse-string parser "z")
'parser-error)
(fail (parse-string parser "")
'parser-error)
(is char= #\a
(parser-error-expected
(capture-parse-error parser "z")))))
(define-test predicate-parser
(let ((parser (predicate-parser #'digit-char-p)))
(is char= #\0
(parse-string parser "0"))
(is char= #\0
(parse-string parser "012"))
(is char= #\9
(parse-string parser "9"))
(fail (parse-string parser "z")
'parser-error)
(fail (parse-string parser "")
'parser-error)
(is eq #'digit-char-p
(parser-error-expected
(capture-parse-error parser "z")))))
(define-test string-parser
(let ((parser (string-parser "foo")))
(is string= "foo"
(parse-string parser "foo"))
(is string= "foo"
(parse-string parser "foobar"))
(fail (parse-string parser "bar")
'parser-error)
(fail (parse-string parser "fo")
'parser-error)
(fail (parse-string parser "")
'parser-error)
(is string= "foo"
(parser-error-expected
(capture-parse-error parser "bar")))))
(define-test eof-parser
(let ((parser (eof-parser)))
(is eq nil
(parse-string parser ""))
(fail (parse-string parser "foo")
'parser-error)
(is eq :eof
(parser-error-expected
(capture-parse-error parser "foo"))))
(is eq :eof
(parse-string (eof-parser :eof) "")))
(define-test parse-map
:depends-on (char-parser)
(let ((parser (parse-map #'char-code
(char-parser #\a))))
(is = #.(char-code #\a)
(parse-string parser "a"))
(fail (parse-string parser "z")
'parser-error)
(is char= #\a
(parser-error-expected
(capture-parse-error parser "z"))))
(let ((parser (parse-map #'list
(char-parser #\a)
(char-parser #\b))))
(is equal '(#\a #\b)
(parse-string parser "ab"))
(fail (parse-string parser "a")
'parser-error)))
(define-test parser-error
:depends-on (char-parser parse-map)
(let* ((parser (parse-map #'list
(predicate-parser (constantly t))
(char-parser #\Newline)
(char-parser #\c)))
(err1 (capture-parse-error parser "abc"))
(err2 (capture-parse-error parser (format nil "a~%z")))
(err3 (capture-parse-error parser (format nil "~Cbc" #\Tab))))
;; stream-error-stream on ABCL fails on subconditions to stream-error,
;; because ABCL's code checks if the condition is directly instanceof
;; ParserError (the Java class), instead of checking if it's typep to
;; parser-error: https://github.com/armedbear/abcl/issues/388
#-ABCL
(of-type stream (stream-error-stream err1))
(is = 1 (parser-error-line err1))
(is = 1 (parser-error-column err1))
(is equal #\Newline (parser-error-expected err1))
(is = 2 (parser-error-line err2))
(is = 0 (parser-error-column err2))
(is = 1 (parser-error-line err3))
(is = 8 (parser-error-column err3))))
(define-test parse-progn
:depends-on (char-parser)
(let ((a (parse-progn (char-parser #\a))))
;; parse-progn with a single element should act like its child parser
(is char= #\a
(parse-string a "a"))
(fail (parse-string a "z")
'parser-error))
(let ((ab (parse-progn (char-parser #\a)
(char-parser #\b))))
(is char= #\b
(parse-string ab "ab"))
(fail (parse-string ab "az")
'parser-error)
(fail (parse-string ab "b")
'parser-error))
(let ((abc (parse-progn (char-parser #\a)
(char-parser #\b)
(char-parser #\c))))
(is char= #\c
(parse-string abc "abc"))
(fail (parse-string abc "abz")
'parser-error)
(fail (parse-string abc "az")
'parser-error)
(fail (parse-string abc "bc")
'parser-error)
(fail (parse-string abc "c")
'parser-error)))
(define-test parse-prog1
:depends-on (char-parser)
(let ((a (parse-prog1 (char-parser #\a))))
;; parse-prog1 with a single element should act like its child parser
(is char= #\a
(parse-string a "a"))
(fail (parse-string a "z")
'parser-error))
(let ((ab (parse-prog1 (char-parser #\a)
(char-parser #\b))))
(is char= #\a
(parse-string ab "ab"))
(fail (parse-string ab "az")
'parser-error)
(fail (parse-string ab "b")
'parser-error))
(let ((abc (parse-prog1 (char-parser #\a)
(char-parser #\b)
(char-parser #\c))))
(is char= #\a
(parse-string abc "abc"))
(fail (parse-string abc "abz")
'parser-error)
(is char= #\c
(parser-error-expected
(capture-parse-error abc "abz")))
(fail (parse-string abc "az")
'parser-error)
(fail (parse-string abc "z")
'parser-error)
(is char= #\a
(parser-error-expected
(capture-parse-error abc "z")))
(fail (parse-string abc "bc")
'parser-error)
(fail (parse-string abc "c")
'parser-error)))
(define-test parse-prog2
:depends-on (char-parser)
(let ((ab (parse-prog2 (char-parser #\a)
(char-parser #\b))))
(is char= #\b
(parse-string ab "ab"))
(fail (parse-string ab "az")
'parser-error)
(fail (parse-string ab "z")
'parser-error))
(let ((abc (parse-prog2 (char-parser #\a)
(char-parser #\b)
(char-parser #\c))))
(is char= #\b
(parse-string abc "abc"))
(fail (parse-string abc "abz")
'parser-error)
(fail (parse-string abc "az")
'parser-error)
(fail (parse-string abc "bc")
'parser-error)
(fail (parse-string abc "c")
'parser-error)))
(define-test parse-or
:depends-on (char-parser string-parser)
(let ((a (parse-or (char-parser #\a))))
(is char= #\a
(parse-string a "a"))
(fail (parse-string a "z")
'parser-error))
(let ((abc (parse-or (char-parser #\a)
(char-parser #\b)
(char-parser #\c))))
(is char= #\a
(parse-string abc "a"))
(is char= #\b
(parse-string abc "b"))
(is char= #\c
(parse-string abc "c"))
(fail (parse-string abc "z")
'parser-error)
(is equal '(#\a #\b #\c)
(parser-error-expected
(capture-parse-error abc "z"))))
(let ((foobar (parse-or (string-parser "foo")
(string-parser "bar"))))
(is string= "foo"
(parse-string foobar "foo"))
(fail (parse-string foobar "bar")
'parser-error
"parse-or fails early on a partial parse.")))
(define-test parse-optional
:depends-on (char-parser string-parser)
(let ((a (parse-optional (char-parser #\a))))
(is char= #\a
(parse-string a "a"))
(is eq nil
(parse-string a "z"))
(is eq nil
(parse-string a "")))
(let ((a-or-b (parse-optional (char-parser #\a)
#\b)))
(is char= #\b
(parse-string a-or-b "z"))
(is char= #\b
(parse-string a-or-b "")))
(let ((foo (parse-optional (string-parser "foo"))))
(is string= "foo"
(parse-string foo "foo"))
(fail (parse-string foo "bar")
'parser-error
"parse-optional fails when any input is consumed.")))
(define-test parse-collect
:depends-on (predicate-parser string-parser)
(let ((parser (parse-collect (predicate-parser #'alpha-char-p))))
(is equal '(#\a)
(parse-string parser "a"))
(is equal '(#\a #\b #\c)
(parse-string parser "abc"))
(is equal ()
(parse-string parser "")))
(let ((foos (parse-collect (string-parser "foo"))))
(is equal '("foo" "foo" "foo")
(parse-string foos "foofoofoo"))
(fail (parse-string foos "foofoobar")
'parser-error
"parse-collect fails when the last (errorful) parse consumes input.")))
(define-test parse-collect1
:depends-on (predicate-parser string-parser)
(let ((parser (parse-collect1 (predicate-parser #'alpha-char-p))))
(is equal '(#\a)
(parse-string parser "a"))
(is equal '(#\a #\b #\c)
(parse-string parser "abc"))
(fail (parse-string parser "")
'parser-error))
(let ((foos (parse-collect (string-parser "foo"))))
(is equal '("foo" "foo" "foo")
(parse-string foos "foofoofoo"))
(fail (parse-string foos "foofoobar")
'parser-error
"parse-collect1 fails when the last (errorful) parse consumes input.")))
(define-test parse-reduce
:depends-on (predicate-parser)
(let ((number-parser (parse-reduce
(lambda (num digit)
(+ (* 10 num)
(- (char-code digit) #.(char-code #\0))))
(predicate-parser #'digit-char-p) 0)))
(is = 123
(parse-string number-parser "123"))
(is = 0
(parse-string number-parser ""))))
(define-test parse-take
:depends-on (predicate-parser)
(let ((letters (parse-take 3 (predicate-parser #'alpha-char-p))))
(is equal '(#\a #\a #\a)
(parse-string letters "aaa"))
(is equal '(#\a #\b #\c)
(parse-string letters "abc123"))
(fail (parse-string letters "ab!")
'parser-error)
(fail (parse-string letters "ab")
'parser-error)))
(define-test parse-try
:depends-on (string-parser parse-or)
(let* ((try-foo (parse-try (string-parser "foo")))
(foo-or-bar (parse-or try-foo
(string-parser "bar"))))
(is string= "foo"
(parse-string try-foo "foo"))
(is string= "foo"
(parse-string foo-or-bar "foo"))
(is string= "bar"
(parse-string foo-or-bar "bar"))))
(define-test parse-tag
:depends-on (parser-error char-parser)
(let ((parser (parse-tag :the-letter-a (char-parser #\a))))
(is char= #\a
(parse-string parser "a"))
(is eq :the-letter-a
(parser-error-expected
(capture-parse-error parser "z")))))
(define-test parse-let
:depends-on (predicate-parser)
(let ((parser (parse-let ((digit (predicate-parser #'digit-char-p))
(alpha (predicate-parser #'alpha-char-p)))
(cons digit alpha))))
(is equal (cons #\1 #\a)
(parse-string parser "1a"))
(is equal (cons #\2 #\b)
(parse-string parser "2b"))
(fail (parse-string parser "3!")
'parser-error)
(fail (parse-string parser "!")
'parser-error))
(fail (eval '(parse-let (invalid-binding)
:whatever)))
(fail (eval '(parse-let ((10 20 030 05 i5025 9258))
whatever))))
(define-test digit-parser
(let ((decimalparser (digit-parser))
(hexparser (digit-parser 16)))
(is = 0
(parse-string decimalparser "0"))
(is = 9
(parse-string decimalparser "9"))
(fail (parse-string decimalparser "A")
'parser-error)
(is = 0
(parse-string hexparser "0"))
(is = 15
(parse-string hexparser "F"))
(is = 15
(parse-string hexparser "f"))
(fail (parse-string hexparser "G")
'parser-error)))
(define-test integer-parser
(let ((decimalparser (integer-parser))
(hexparser (integer-parser 16)))
(is = 0
(parse-string decimalparser "0"))
(is = 10
(parse-string decimalparser "10"))
(is = 5
(parse-string decimalparser "00005"))
(is = 123
(parse-string decimalparser "123A"))
(fail (parse-string decimalparser "A")
'parser-error)
(is = 255
(parse-string hexparser "FF"))
(is = 255
(parse-string hexparser "ff"))
(fail (parse-string hexparser "G")
'parser-error)))
;; JSON Tests
(define-test json-numbers
(is = 123
(decode-json-from-string "123"))
(is = 50
(decode-json-from-string "000050"))
(is = -123
(decode-json-from-string "-123"))
(is close-enough 1.5
(decode-json-from-string "1.5"))
(is close-enough 1.05
(decode-json-from-string "1.05"))
(is close-enough 1e5
(decode-json-from-string "1e5"))
(is close-enough 1e5
(decode-json-from-string "1e+5"))
(is close-enough 1e-5
(decode-json-from-string "1e-5"))
(is close-enough 15.0
(decode-json-from-string "1.5e1")))
(define-test json-strings
(is string= "hello, world"
(decode-json-from-string "\"hello, world\""))
(is string= (coerce #(#\" #\\ #\/ #\Backspace #\Page #\Newline #\Return #\Tab) 'string)
(decode-json-from-string "\"\\\"\\\\\\/\\b\\f\\n\\r\\t\""))
(is string= "(λ (n) (* n n))"
(decode-json-from-string "\"(\\u03BB (n) (* n n))\"")))
(define-test json-arrays
:depends-on (json-numbers json-strings)
(is equal '(10 20 30)
(decode-json-from-string "[10,20,30]"))
(is equal '(10)
(decode-json-from-string "[10]"))
(is equal ()
(decode-json-from-string "[]"))
(is equal '(10 "string" (20 30 40))
(decode-json-from-string "[10, \"string\", [20, 30, 40]]"))
(is equal '(10 20 30)
(decode-json-from-string " [ 10 , 20 , 30 ] ")))
(define-test json-objects
:depends-on (json-numbers json-strings)
(is equal '(("key" . "value"))
(decode-json-from-string "{\"key\":\"value\"}"))
(is equal '(("one" . 1) ("two" . 2) ("three" . 3))
(decode-json-from-string "{\"one\":1,\"two\":2,\"three\":3}"))
(is equal '(("object" . (("key" . "value"))))
(decode-json-from-string "{\"object\":{\"key\":\"value\"}}"))
(is equal '(("key" . "value") ("foo" . "bar"))
(decode-json-from-string " { \"key\" : \"value\" , \"foo\" : \"bar\" }")))
|
6580
|
;;; test.lisp - Parsnip library test suite
;;; Copyright 2021 <NAME> <samuel (at) shunter (dot) xyz>
;;; BSD-3-Clause
(defpackage #:xyz.shunter.parsnip.test
(:use #:cl #:parachute
#:xyz.shunter.parsnip
#:xyz.shunter.parsnip.examples.json))
(in-package #:xyz.shunter.parsnip.test)
(defun parse-string (parser string)
(with-input-from-string (stream string)
(parse parser stream)))
(defun capture-parse-error (parser string)
(multiple-value-bind (always-nil err) (ignore-errors (parse-string parser string))
(declare (ignore always-nil))
err))
(defun close-enough (float-1 float-2)
"Return whether two decimal numbers are within tolerance (0.05%)"
(when (zerop (+ float-1 float-2))
(return-from close-enough nil))
(let ((difference (abs (/ (- float-1 float-2) (abs (+ float-1 float-2)) 2)))
(tolerance 0.0005))
(< difference tolerance)))
;; Unit Tests
(define-test char-parser
(let ((parser (char-parser #\a)))
(is char= #\a
(parse-string parser "abc"))
(is char= #\a
(parse-string parser "a"))
(fail (parse-string parser "z")
'parser-error)
(fail (parse-string parser "")
'parser-error)
(is char= #\a
(parser-error-expected
(capture-parse-error parser "z")))))
(define-test predicate-parser
(let ((parser (predicate-parser #'digit-char-p)))
(is char= #\0
(parse-string parser "0"))
(is char= #\0
(parse-string parser "012"))
(is char= #\9
(parse-string parser "9"))
(fail (parse-string parser "z")
'parser-error)
(fail (parse-string parser "")
'parser-error)
(is eq #'digit-char-p
(parser-error-expected
(capture-parse-error parser "z")))))
(define-test string-parser
(let ((parser (string-parser "foo")))
(is string= "foo"
(parse-string parser "foo"))
(is string= "foo"
(parse-string parser "foobar"))
(fail (parse-string parser "bar")
'parser-error)
(fail (parse-string parser "fo")
'parser-error)
(fail (parse-string parser "")
'parser-error)
(is string= "foo"
(parser-error-expected
(capture-parse-error parser "bar")))))
(define-test eof-parser
(let ((parser (eof-parser)))
(is eq nil
(parse-string parser ""))
(fail (parse-string parser "foo")
'parser-error)
(is eq :eof
(parser-error-expected
(capture-parse-error parser "foo"))))
(is eq :eof
(parse-string (eof-parser :eof) "")))
(define-test parse-map
:depends-on (char-parser)
(let ((parser (parse-map #'char-code
(char-parser #\a))))
(is = #.(char-code #\a)
(parse-string parser "a"))
(fail (parse-string parser "z")
'parser-error)
(is char= #\a
(parser-error-expected
(capture-parse-error parser "z"))))
(let ((parser (parse-map #'list
(char-parser #\a)
(char-parser #\b))))
(is equal '(#\a #\b)
(parse-string parser "ab"))
(fail (parse-string parser "a")
'parser-error)))
(define-test parser-error
:depends-on (char-parser parse-map)
(let* ((parser (parse-map #'list
(predicate-parser (constantly t))
(char-parser #\Newline)
(char-parser #\c)))
(err1 (capture-parse-error parser "abc"))
(err2 (capture-parse-error parser (format nil "a~%z")))
(err3 (capture-parse-error parser (format nil "~Cbc" #\Tab))))
;; stream-error-stream on ABCL fails on subconditions to stream-error,
;; because ABCL's code checks if the condition is directly instanceof
;; ParserError (the Java class), instead of checking if it's typep to
;; parser-error: https://github.com/armedbear/abcl/issues/388
#-ABCL
(of-type stream (stream-error-stream err1))
(is = 1 (parser-error-line err1))
(is = 1 (parser-error-column err1))
(is equal #\Newline (parser-error-expected err1))
(is = 2 (parser-error-line err2))
(is = 0 (parser-error-column err2))
(is = 1 (parser-error-line err3))
(is = 8 (parser-error-column err3))))
(define-test parse-progn
:depends-on (char-parser)
(let ((a (parse-progn (char-parser #\a))))
;; parse-progn with a single element should act like its child parser
(is char= #\a
(parse-string a "a"))
(fail (parse-string a "z")
'parser-error))
(let ((ab (parse-progn (char-parser #\a)
(char-parser #\b))))
(is char= #\b
(parse-string ab "ab"))
(fail (parse-string ab "az")
'parser-error)
(fail (parse-string ab "b")
'parser-error))
(let ((abc (parse-progn (char-parser #\a)
(char-parser #\b)
(char-parser #\c))))
(is char= #\c
(parse-string abc "abc"))
(fail (parse-string abc "abz")
'parser-error)
(fail (parse-string abc "az")
'parser-error)
(fail (parse-string abc "bc")
'parser-error)
(fail (parse-string abc "c")
'parser-error)))
(define-test parse-prog1
:depends-on (char-parser)
(let ((a (parse-prog1 (char-parser #\a))))
;; parse-prog1 with a single element should act like its child parser
(is char= #\a
(parse-string a "a"))
(fail (parse-string a "z")
'parser-error))
(let ((ab (parse-prog1 (char-parser #\a)
(char-parser #\b))))
(is char= #\a
(parse-string ab "ab"))
(fail (parse-string ab "az")
'parser-error)
(fail (parse-string ab "b")
'parser-error))
(let ((abc (parse-prog1 (char-parser #\a)
(char-parser #\b)
(char-parser #\c))))
(is char= #\a
(parse-string abc "abc"))
(fail (parse-string abc "abz")
'parser-error)
(is char= #\c
(parser-error-expected
(capture-parse-error abc "abz")))
(fail (parse-string abc "az")
'parser-error)
(fail (parse-string abc "z")
'parser-error)
(is char= #\a
(parser-error-expected
(capture-parse-error abc "z")))
(fail (parse-string abc "bc")
'parser-error)
(fail (parse-string abc "c")
'parser-error)))
(define-test parse-prog2
:depends-on (char-parser)
(let ((ab (parse-prog2 (char-parser #\a)
(char-parser #\b))))
(is char= #\b
(parse-string ab "ab"))
(fail (parse-string ab "az")
'parser-error)
(fail (parse-string ab "z")
'parser-error))
(let ((abc (parse-prog2 (char-parser #\a)
(char-parser #\b)
(char-parser #\c))))
(is char= #\b
(parse-string abc "abc"))
(fail (parse-string abc "abz")
'parser-error)
(fail (parse-string abc "az")
'parser-error)
(fail (parse-string abc "bc")
'parser-error)
(fail (parse-string abc "c")
'parser-error)))
(define-test parse-or
:depends-on (char-parser string-parser)
(let ((a (parse-or (char-parser #\a))))
(is char= #\a
(parse-string a "a"))
(fail (parse-string a "z")
'parser-error))
(let ((abc (parse-or (char-parser #\a)
(char-parser #\b)
(char-parser #\c))))
(is char= #\a
(parse-string abc "a"))
(is char= #\b
(parse-string abc "b"))
(is char= #\c
(parse-string abc "c"))
(fail (parse-string abc "z")
'parser-error)
(is equal '(#\a #\b #\c)
(parser-error-expected
(capture-parse-error abc "z"))))
(let ((foobar (parse-or (string-parser "foo")
(string-parser "bar"))))
(is string= "foo"
(parse-string foobar "foo"))
(fail (parse-string foobar "bar")
'parser-error
"parse-or fails early on a partial parse.")))
(define-test parse-optional
:depends-on (char-parser string-parser)
(let ((a (parse-optional (char-parser #\a))))
(is char= #\a
(parse-string a "a"))
(is eq nil
(parse-string a "z"))
(is eq nil
(parse-string a "")))
(let ((a-or-b (parse-optional (char-parser #\a)
#\b)))
(is char= #\b
(parse-string a-or-b "z"))
(is char= #\b
(parse-string a-or-b "")))
(let ((foo (parse-optional (string-parser "foo"))))
(is string= "foo"
(parse-string foo "foo"))
(fail (parse-string foo "bar")
'parser-error
"parse-optional fails when any input is consumed.")))
(define-test parse-collect
:depends-on (predicate-parser string-parser)
(let ((parser (parse-collect (predicate-parser #'alpha-char-p))))
(is equal '(#\a)
(parse-string parser "a"))
(is equal '(#\a #\b #\c)
(parse-string parser "abc"))
(is equal ()
(parse-string parser "")))
(let ((foos (parse-collect (string-parser "foo"))))
(is equal '("foo" "foo" "foo")
(parse-string foos "foofoofoo"))
(fail (parse-string foos "foofoobar")
'parser-error
"parse-collect fails when the last (errorful) parse consumes input.")))
(define-test parse-collect1
:depends-on (predicate-parser string-parser)
(let ((parser (parse-collect1 (predicate-parser #'alpha-char-p))))
(is equal '(#\a)
(parse-string parser "a"))
(is equal '(#\a #\b #\c)
(parse-string parser "abc"))
(fail (parse-string parser "")
'parser-error))
(let ((foos (parse-collect (string-parser "foo"))))
(is equal '("foo" "foo" "foo")
(parse-string foos "foofoofoo"))
(fail (parse-string foos "foofoobar")
'parser-error
"parse-collect1 fails when the last (errorful) parse consumes input.")))
(define-test parse-reduce
:depends-on (predicate-parser)
(let ((number-parser (parse-reduce
(lambda (num digit)
(+ (* 10 num)
(- (char-code digit) #.(char-code #\0))))
(predicate-parser #'digit-char-p) 0)))
(is = 123
(parse-string number-parser "123"))
(is = 0
(parse-string number-parser ""))))
(define-test parse-take
:depends-on (predicate-parser)
(let ((letters (parse-take 3 (predicate-parser #'alpha-char-p))))
(is equal '(#\a #\a #\a)
(parse-string letters "aaa"))
(is equal '(#\a #\b #\c)
(parse-string letters "abc123"))
(fail (parse-string letters "ab!")
'parser-error)
(fail (parse-string letters "ab")
'parser-error)))
(define-test parse-try
:depends-on (string-parser parse-or)
(let* ((try-foo (parse-try (string-parser "foo")))
(foo-or-bar (parse-or try-foo
(string-parser "bar"))))
(is string= "foo"
(parse-string try-foo "foo"))
(is string= "foo"
(parse-string foo-or-bar "foo"))
(is string= "bar"
(parse-string foo-or-bar "bar"))))
(define-test parse-tag
:depends-on (parser-error char-parser)
(let ((parser (parse-tag :the-letter-a (char-parser #\a))))
(is char= #\a
(parse-string parser "a"))
(is eq :the-letter-a
(parser-error-expected
(capture-parse-error parser "z")))))
(define-test parse-let
:depends-on (predicate-parser)
(let ((parser (parse-let ((digit (predicate-parser #'digit-char-p))
(alpha (predicate-parser #'alpha-char-p)))
(cons digit alpha))))
(is equal (cons #\1 #\a)
(parse-string parser "1a"))
(is equal (cons #\2 #\b)
(parse-string parser "2b"))
(fail (parse-string parser "3!")
'parser-error)
(fail (parse-string parser "!")
'parser-error))
(fail (eval '(parse-let (invalid-binding)
:whatever)))
(fail (eval '(parse-let ((10 20 030 05 i5025 9258))
whatever))))
(define-test digit-parser
(let ((decimalparser (digit-parser))
(hexparser (digit-parser 16)))
(is = 0
(parse-string decimalparser "0"))
(is = 9
(parse-string decimalparser "9"))
(fail (parse-string decimalparser "A")
'parser-error)
(is = 0
(parse-string hexparser "0"))
(is = 15
(parse-string hexparser "F"))
(is = 15
(parse-string hexparser "f"))
(fail (parse-string hexparser "G")
'parser-error)))
(define-test integer-parser
(let ((decimalparser (integer-parser))
(hexparser (integer-parser 16)))
(is = 0
(parse-string decimalparser "0"))
(is = 10
(parse-string decimalparser "10"))
(is = 5
(parse-string decimalparser "00005"))
(is = 123
(parse-string decimalparser "123A"))
(fail (parse-string decimalparser "A")
'parser-error)
(is = 255
(parse-string hexparser "FF"))
(is = 255
(parse-string hexparser "ff"))
(fail (parse-string hexparser "G")
'parser-error)))
;; JSON Tests
(define-test json-numbers
(is = 123
(decode-json-from-string "123"))
(is = 50
(decode-json-from-string "000050"))
(is = -123
(decode-json-from-string "-123"))
(is close-enough 1.5
(decode-json-from-string "1.5"))
(is close-enough 1.05
(decode-json-from-string "1.05"))
(is close-enough 1e5
(decode-json-from-string "1e5"))
(is close-enough 1e5
(decode-json-from-string "1e+5"))
(is close-enough 1e-5
(decode-json-from-string "1e-5"))
(is close-enough 15.0
(decode-json-from-string "1.5e1")))
(define-test json-strings
(is string= "hello, world"
(decode-json-from-string "\"hello, world\""))
(is string= (coerce #(#\" #\\ #\/ #\Backspace #\Page #\Newline #\Return #\Tab) 'string)
(decode-json-from-string "\"\\\"\\\\\\/\\b\\f\\n\\r\\t\""))
(is string= "(λ (n) (* n n))"
(decode-json-from-string "\"(\\u03BB (n) (* n n))\"")))
(define-test json-arrays
:depends-on (json-numbers json-strings)
(is equal '(10 20 30)
(decode-json-from-string "[10,20,30]"))
(is equal '(10)
(decode-json-from-string "[10]"))
(is equal ()
(decode-json-from-string "[]"))
(is equal '(10 "string" (20 30 40))
(decode-json-from-string "[10, \"string\", [20, 30, 40]]"))
(is equal '(10 20 30)
(decode-json-from-string " [ 10 , 20 , 30 ] ")))
(define-test json-objects
:depends-on (json-numbers json-strings)
(is equal '(("key" . "value"))
(decode-json-from-string "{\"key\":\"value\"}"))
(is equal '(("one" . 1) ("two" . 2) ("three" . 3))
(decode-json-from-string "{\"one\":1,\"two\":2,\"three\":3}"))
(is equal '(("object" . (("key" . "value"))))
(decode-json-from-string "{\"object\":{\"key\":\"value\"}}"))
(is equal '(("key" . "value") ("foo" . "bar"))
(decode-json-from-string " { \"key\" : \"value\" , \"foo\" : \"bar\" }")))
| true |
;;; test.lisp - Parsnip library test suite
;;; Copyright 2021 PI:NAME:<NAME>END_PI <samuel (at) shunter (dot) xyz>
;;; BSD-3-Clause
(defpackage #:xyz.shunter.parsnip.test
(:use #:cl #:parachute
#:xyz.shunter.parsnip
#:xyz.shunter.parsnip.examples.json))
(in-package #:xyz.shunter.parsnip.test)
(defun parse-string (parser string)
(with-input-from-string (stream string)
(parse parser stream)))
(defun capture-parse-error (parser string)
(multiple-value-bind (always-nil err) (ignore-errors (parse-string parser string))
(declare (ignore always-nil))
err))
(defun close-enough (float-1 float-2)
"Return whether two decimal numbers are within tolerance (0.05%)"
(when (zerop (+ float-1 float-2))
(return-from close-enough nil))
(let ((difference (abs (/ (- float-1 float-2) (abs (+ float-1 float-2)) 2)))
(tolerance 0.0005))
(< difference tolerance)))
;; Unit Tests
(define-test char-parser
(let ((parser (char-parser #\a)))
(is char= #\a
(parse-string parser "abc"))
(is char= #\a
(parse-string parser "a"))
(fail (parse-string parser "z")
'parser-error)
(fail (parse-string parser "")
'parser-error)
(is char= #\a
(parser-error-expected
(capture-parse-error parser "z")))))
(define-test predicate-parser
(let ((parser (predicate-parser #'digit-char-p)))
(is char= #\0
(parse-string parser "0"))
(is char= #\0
(parse-string parser "012"))
(is char= #\9
(parse-string parser "9"))
(fail (parse-string parser "z")
'parser-error)
(fail (parse-string parser "")
'parser-error)
(is eq #'digit-char-p
(parser-error-expected
(capture-parse-error parser "z")))))
(define-test string-parser
(let ((parser (string-parser "foo")))
(is string= "foo"
(parse-string parser "foo"))
(is string= "foo"
(parse-string parser "foobar"))
(fail (parse-string parser "bar")
'parser-error)
(fail (parse-string parser "fo")
'parser-error)
(fail (parse-string parser "")
'parser-error)
(is string= "foo"
(parser-error-expected
(capture-parse-error parser "bar")))))
(define-test eof-parser
(let ((parser (eof-parser)))
(is eq nil
(parse-string parser ""))
(fail (parse-string parser "foo")
'parser-error)
(is eq :eof
(parser-error-expected
(capture-parse-error parser "foo"))))
(is eq :eof
(parse-string (eof-parser :eof) "")))
(define-test parse-map
:depends-on (char-parser)
(let ((parser (parse-map #'char-code
(char-parser #\a))))
(is = #.(char-code #\a)
(parse-string parser "a"))
(fail (parse-string parser "z")
'parser-error)
(is char= #\a
(parser-error-expected
(capture-parse-error parser "z"))))
(let ((parser (parse-map #'list
(char-parser #\a)
(char-parser #\b))))
(is equal '(#\a #\b)
(parse-string parser "ab"))
(fail (parse-string parser "a")
'parser-error)))
(define-test parser-error
:depends-on (char-parser parse-map)
(let* ((parser (parse-map #'list
(predicate-parser (constantly t))
(char-parser #\Newline)
(char-parser #\c)))
(err1 (capture-parse-error parser "abc"))
(err2 (capture-parse-error parser (format nil "a~%z")))
(err3 (capture-parse-error parser (format nil "~Cbc" #\Tab))))
;; stream-error-stream on ABCL fails on subconditions to stream-error,
;; because ABCL's code checks if the condition is directly instanceof
;; ParserError (the Java class), instead of checking if it's typep to
;; parser-error: https://github.com/armedbear/abcl/issues/388
#-ABCL
(of-type stream (stream-error-stream err1))
(is = 1 (parser-error-line err1))
(is = 1 (parser-error-column err1))
(is equal #\Newline (parser-error-expected err1))
(is = 2 (parser-error-line err2))
(is = 0 (parser-error-column err2))
(is = 1 (parser-error-line err3))
(is = 8 (parser-error-column err3))))
(define-test parse-progn
:depends-on (char-parser)
(let ((a (parse-progn (char-parser #\a))))
;; parse-progn with a single element should act like its child parser
(is char= #\a
(parse-string a "a"))
(fail (parse-string a "z")
'parser-error))
(let ((ab (parse-progn (char-parser #\a)
(char-parser #\b))))
(is char= #\b
(parse-string ab "ab"))
(fail (parse-string ab "az")
'parser-error)
(fail (parse-string ab "b")
'parser-error))
(let ((abc (parse-progn (char-parser #\a)
(char-parser #\b)
(char-parser #\c))))
(is char= #\c
(parse-string abc "abc"))
(fail (parse-string abc "abz")
'parser-error)
(fail (parse-string abc "az")
'parser-error)
(fail (parse-string abc "bc")
'parser-error)
(fail (parse-string abc "c")
'parser-error)))
(define-test parse-prog1
:depends-on (char-parser)
(let ((a (parse-prog1 (char-parser #\a))))
;; parse-prog1 with a single element should act like its child parser
(is char= #\a
(parse-string a "a"))
(fail (parse-string a "z")
'parser-error))
(let ((ab (parse-prog1 (char-parser #\a)
(char-parser #\b))))
(is char= #\a
(parse-string ab "ab"))
(fail (parse-string ab "az")
'parser-error)
(fail (parse-string ab "b")
'parser-error))
(let ((abc (parse-prog1 (char-parser #\a)
(char-parser #\b)
(char-parser #\c))))
(is char= #\a
(parse-string abc "abc"))
(fail (parse-string abc "abz")
'parser-error)
(is char= #\c
(parser-error-expected
(capture-parse-error abc "abz")))
(fail (parse-string abc "az")
'parser-error)
(fail (parse-string abc "z")
'parser-error)
(is char= #\a
(parser-error-expected
(capture-parse-error abc "z")))
(fail (parse-string abc "bc")
'parser-error)
(fail (parse-string abc "c")
'parser-error)))
(define-test parse-prog2
:depends-on (char-parser)
(let ((ab (parse-prog2 (char-parser #\a)
(char-parser #\b))))
(is char= #\b
(parse-string ab "ab"))
(fail (parse-string ab "az")
'parser-error)
(fail (parse-string ab "z")
'parser-error))
(let ((abc (parse-prog2 (char-parser #\a)
(char-parser #\b)
(char-parser #\c))))
(is char= #\b
(parse-string abc "abc"))
(fail (parse-string abc "abz")
'parser-error)
(fail (parse-string abc "az")
'parser-error)
(fail (parse-string abc "bc")
'parser-error)
(fail (parse-string abc "c")
'parser-error)))
(define-test parse-or
:depends-on (char-parser string-parser)
(let ((a (parse-or (char-parser #\a))))
(is char= #\a
(parse-string a "a"))
(fail (parse-string a "z")
'parser-error))
(let ((abc (parse-or (char-parser #\a)
(char-parser #\b)
(char-parser #\c))))
(is char= #\a
(parse-string abc "a"))
(is char= #\b
(parse-string abc "b"))
(is char= #\c
(parse-string abc "c"))
(fail (parse-string abc "z")
'parser-error)
(is equal '(#\a #\b #\c)
(parser-error-expected
(capture-parse-error abc "z"))))
(let ((foobar (parse-or (string-parser "foo")
(string-parser "bar"))))
(is string= "foo"
(parse-string foobar "foo"))
(fail (parse-string foobar "bar")
'parser-error
"parse-or fails early on a partial parse.")))
(define-test parse-optional
:depends-on (char-parser string-parser)
(let ((a (parse-optional (char-parser #\a))))
(is char= #\a
(parse-string a "a"))
(is eq nil
(parse-string a "z"))
(is eq nil
(parse-string a "")))
(let ((a-or-b (parse-optional (char-parser #\a)
#\b)))
(is char= #\b
(parse-string a-or-b "z"))
(is char= #\b
(parse-string a-or-b "")))
(let ((foo (parse-optional (string-parser "foo"))))
(is string= "foo"
(parse-string foo "foo"))
(fail (parse-string foo "bar")
'parser-error
"parse-optional fails when any input is consumed.")))
(define-test parse-collect
:depends-on (predicate-parser string-parser)
(let ((parser (parse-collect (predicate-parser #'alpha-char-p))))
(is equal '(#\a)
(parse-string parser "a"))
(is equal '(#\a #\b #\c)
(parse-string parser "abc"))
(is equal ()
(parse-string parser "")))
(let ((foos (parse-collect (string-parser "foo"))))
(is equal '("foo" "foo" "foo")
(parse-string foos "foofoofoo"))
(fail (parse-string foos "foofoobar")
'parser-error
"parse-collect fails when the last (errorful) parse consumes input.")))
(define-test parse-collect1
:depends-on (predicate-parser string-parser)
(let ((parser (parse-collect1 (predicate-parser #'alpha-char-p))))
(is equal '(#\a)
(parse-string parser "a"))
(is equal '(#\a #\b #\c)
(parse-string parser "abc"))
(fail (parse-string parser "")
'parser-error))
(let ((foos (parse-collect (string-parser "foo"))))
(is equal '("foo" "foo" "foo")
(parse-string foos "foofoofoo"))
(fail (parse-string foos "foofoobar")
'parser-error
"parse-collect1 fails when the last (errorful) parse consumes input.")))
(define-test parse-reduce
:depends-on (predicate-parser)
(let ((number-parser (parse-reduce
(lambda (num digit)
(+ (* 10 num)
(- (char-code digit) #.(char-code #\0))))
(predicate-parser #'digit-char-p) 0)))
(is = 123
(parse-string number-parser "123"))
(is = 0
(parse-string number-parser ""))))
(define-test parse-take
:depends-on (predicate-parser)
(let ((letters (parse-take 3 (predicate-parser #'alpha-char-p))))
(is equal '(#\a #\a #\a)
(parse-string letters "aaa"))
(is equal '(#\a #\b #\c)
(parse-string letters "abc123"))
(fail (parse-string letters "ab!")
'parser-error)
(fail (parse-string letters "ab")
'parser-error)))
(define-test parse-try
:depends-on (string-parser parse-or)
(let* ((try-foo (parse-try (string-parser "foo")))
(foo-or-bar (parse-or try-foo
(string-parser "bar"))))
(is string= "foo"
(parse-string try-foo "foo"))
(is string= "foo"
(parse-string foo-or-bar "foo"))
(is string= "bar"
(parse-string foo-or-bar "bar"))))
(define-test parse-tag
:depends-on (parser-error char-parser)
(let ((parser (parse-tag :the-letter-a (char-parser #\a))))
(is char= #\a
(parse-string parser "a"))
(is eq :the-letter-a
(parser-error-expected
(capture-parse-error parser "z")))))
(define-test parse-let
:depends-on (predicate-parser)
(let ((parser (parse-let ((digit (predicate-parser #'digit-char-p))
(alpha (predicate-parser #'alpha-char-p)))
(cons digit alpha))))
(is equal (cons #\1 #\a)
(parse-string parser "1a"))
(is equal (cons #\2 #\b)
(parse-string parser "2b"))
(fail (parse-string parser "3!")
'parser-error)
(fail (parse-string parser "!")
'parser-error))
(fail (eval '(parse-let (invalid-binding)
:whatever)))
(fail (eval '(parse-let ((10 20 030 05 i5025 9258))
whatever))))
(define-test digit-parser
(let ((decimalparser (digit-parser))
(hexparser (digit-parser 16)))
(is = 0
(parse-string decimalparser "0"))
(is = 9
(parse-string decimalparser "9"))
(fail (parse-string decimalparser "A")
'parser-error)
(is = 0
(parse-string hexparser "0"))
(is = 15
(parse-string hexparser "F"))
(is = 15
(parse-string hexparser "f"))
(fail (parse-string hexparser "G")
'parser-error)))
(define-test integer-parser
(let ((decimalparser (integer-parser))
(hexparser (integer-parser 16)))
(is = 0
(parse-string decimalparser "0"))
(is = 10
(parse-string decimalparser "10"))
(is = 5
(parse-string decimalparser "00005"))
(is = 123
(parse-string decimalparser "123A"))
(fail (parse-string decimalparser "A")
'parser-error)
(is = 255
(parse-string hexparser "FF"))
(is = 255
(parse-string hexparser "ff"))
(fail (parse-string hexparser "G")
'parser-error)))
;; JSON Tests
(define-test json-numbers
(is = 123
(decode-json-from-string "123"))
(is = 50
(decode-json-from-string "000050"))
(is = -123
(decode-json-from-string "-123"))
(is close-enough 1.5
(decode-json-from-string "1.5"))
(is close-enough 1.05
(decode-json-from-string "1.05"))
(is close-enough 1e5
(decode-json-from-string "1e5"))
(is close-enough 1e5
(decode-json-from-string "1e+5"))
(is close-enough 1e-5
(decode-json-from-string "1e-5"))
(is close-enough 15.0
(decode-json-from-string "1.5e1")))
(define-test json-strings
(is string= "hello, world"
(decode-json-from-string "\"hello, world\""))
(is string= (coerce #(#\" #\\ #\/ #\Backspace #\Page #\Newline #\Return #\Tab) 'string)
(decode-json-from-string "\"\\\"\\\\\\/\\b\\f\\n\\r\\t\""))
(is string= "(λ (n) (* n n))"
(decode-json-from-string "\"(\\u03BB (n) (* n n))\"")))
(define-test json-arrays
:depends-on (json-numbers json-strings)
(is equal '(10 20 30)
(decode-json-from-string "[10,20,30]"))
(is equal '(10)
(decode-json-from-string "[10]"))
(is equal ()
(decode-json-from-string "[]"))
(is equal '(10 "string" (20 30 40))
(decode-json-from-string "[10, \"string\", [20, 30, 40]]"))
(is equal '(10 20 30)
(decode-json-from-string " [ 10 , 20 , 30 ] ")))
(define-test json-objects
:depends-on (json-numbers json-strings)
(is equal '(("key" . "value"))
(decode-json-from-string "{\"key\":\"value\"}"))
(is equal '(("one" . 1) ("two" . 2) ("three" . 3))
(decode-json-from-string "{\"one\":1,\"two\":2,\"three\":3}"))
(is equal '(("object" . (("key" . "value"))))
(decode-json-from-string "{\"object\":{\"key\":\"value\"}}"))
(is equal '(("key" . "value") ("foo" . "bar"))
(decode-json-from-string " { \"key\" : \"value\" , \"foo\" : \"bar\" }")))
|
[
{
"context": " 3d-vectors\n (c) 2015 Shirakumo http://tymoon.eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n",
"end": 94,
"score": 0.9999049305915833,
"start": 76,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "umo http://tymoon.eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(in-package #:org.shirak",
"end": 119,
"score": 0.9998841881752014,
"start": 105,
"tag": "NAME",
"value": "Nicolas Hafner"
},
{
"context": ".eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(in-package #:org.shirakumo.flare.vector)\n\n(",
"end": 139,
"score": 0.9999170303344727,
"start": 121,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
struct.lisp
|
kpoeck/3d-vectors
| 1 |
#|
This file is a part of 3d-vectors
(c) 2015 Shirakumo http://tymoon.eu ([email protected])
Author: Nicolas Hafner <[email protected]>
|#
(in-package #:org.shirakumo.flare.vector)
(defmacro define-vecx-accessor (name rel)
`(progn
(declaim (inline ,name))
(declaim (ftype (function (vec) ,*float-type*) ,name))
(defun ,name (vec) (,rel vec))
(defsetf* ,name (vec &environment env) (value)
`(setf (,',rel ,vec) ,(ensure-float-param value env)))))
(defstruct (vec2 (:conc-name NIL)
(:constructor %vec2 (%vx2 %vy2))
(:copier vcopy2)
(:predicate vec2-p))
(%vx2 (ensure-float 0) :type #.*float-type*)
(%vy2 (ensure-float 0) :type #.*float-type*))
(define-vecx-accessor vx2 %vx2)
(define-vecx-accessor vy2 %vy2)
(declaim (inline vec2))
(declaim (ftype (function (real real) vec2) vec2))
(define-ofun vec2 (x y)
(%vec2 (ensure-float x) (ensure-float y)))
(define-compiler-macro vec2 (&whole whole &environment env x y)
`(%vec2 ,(ensure-float-param x env)
,(ensure-float-param y env)))
(define-ofun vec2-random (lower upper)
(let ((range (- upper lower)))
(vec2 (+ (random range) lower)
(+ (random range) lower))))
(defmethod print-object ((v vec2) stream)
(write (make-load-form v) :stream stream))
(defmethod make-load-form ((v vec2) &optional env)
(declare (ignore env))
`(vec2 ,(vx2 v) ,(vy2 v)))
(defstruct (vec3 (:conc-name NIL)
(:constructor %vec3 (%vx3 %vy3 %vz3))
(:copier vcopy3)
(:predicate vec3-p))
(%vx3 (ensure-float 0) :type #.*float-type*)
(%vy3 (ensure-float 0) :type #.*float-type*)
(%vz3 (ensure-float 0) :type #.*float-type*))
(define-vecx-accessor vx3 %vx3)
(define-vecx-accessor vy3 %vy3)
(define-vecx-accessor vz3 %vz3)
(declaim (inline vec3))
(declaim (ftype (function (real real real) vec3) vec3))
(define-ofun vec3 (x y z)
(%vec3 (ensure-float x) (ensure-float y) (ensure-float z)))
(define-compiler-macro vec3 (&whole whole &environment env x y z)
`(%vec3 ,(ensure-float-param x env)
,(ensure-float-param y env)
,(ensure-float-param z env)))
(define-ofun vec3-random (lower upper)
(let ((range (- upper lower)))
(vec3 (+ (random range) lower)
(+ (random range) lower)
(+ (random range) lower))))
(defmethod print-object ((v vec3) stream)
(write (make-load-form v) :stream stream))
(defmethod make-load-form ((v vec3) &optional env)
(declare (ignore env))
`(vec3 ,(vx3 v) ,(vy3 v) ,(vz3 v)))
(defstruct (vec4 (:conc-name NIL)
(:constructor %vec4 (%vx4 %vy4 %vz4 %vw4))
(:copier vcopy4)
(:predicate vec4-p))
(%vx4 (ensure-float 0) :type #.*float-type*)
(%vy4 (ensure-float 0) :type #.*float-type*)
(%vz4 (ensure-float 0) :type #.*float-type*)
(%vw4 (ensure-float 0) :type #.*float-type*))
(define-vecx-accessor vx4 %vx4)
(define-vecx-accessor vy4 %vy4)
(define-vecx-accessor vz4 %vz4)
(define-vecx-accessor vw4 %vw4)
(declaim (inline vec4))
(declaim (ftype (function (real real real real) vec4) vec4))
(define-ofun vec4 (x y z w)
(%vec4 (ensure-float x) (ensure-float y) (ensure-float z) (ensure-float w)))
(define-compiler-macro vec4 (&whole whole &environment env x y z w)
`(%vec4 ,(ensure-float-param x env)
,(ensure-float-param y env)
,(ensure-float-param z env)
,(ensure-float-param w env)))
(define-ofun vec4-random (lower upper)
(let ((range (- upper lower)))
(vec4 (+ (random range) lower)
(+ (random range) lower)
(+ (random range) lower)
(+ (random range) lower))))
(defmethod print-object ((v vec4) stream)
(write (make-load-form v) :stream stream))
(defmethod make-load-form ((v vec4) &optional env)
(declare (ignore env))
`(vec4 ,(vx4 v) ,(vy4 v) ,(vz4 v) ,(vw4 v)))
;; Backwards-compat
(deftype vec () '(or vec2 vec3 vec4))
(defmacro define-vec-accessor (name a2 a3 a4)
`(progn
(declaim (inline ,name))
(declaim (ftype (function (vec) ,*float-type*)))
(define-ofun ,name (vec)
(etypecase vec
,@(when a3 `((vec3 (,a3 vec))))
,@(when a4 `((vec4 (,a4 vec))))
,@(when a2 `((vec2 (,a2 vec))))))
(defsetf* ,name (vec &environment env) (value)
`(etypecase ,vec
,@(when ',a3 `((vec3 (setf (,',a3 ,vec) ,(ensure-float-param value env)))))
,@(when ',a4 `((vec4 (setf (,',a4 ,vec) ,(ensure-float-param value env)))))
,@(when ',a2 `((vec2 (setf (,',a2 ,vec) ,(ensure-float-param value env)))))))))
(define-vec-accessor vx %vx2 %vx3 %vx4)
(define-vec-accessor vy %vy2 %vy3 %vy4)
(define-vec-accessor vz NIL %vz3 %vz4)
(define-vec-accessor vw NIL NIL %vw4)
(declaim (inline vec))
(define-ofun vec-p (vec)
(typecase vec (vec2 T) (vec3 T) (vec4 T)))
(declaim (inline vcopy))
(define-ofun vcopy (vec)
(etypecase vec
(vec2 (vec2 (vx2 vec) (vy2 vec)))
(vec3 (vec3 (vx3 vec) (vy3 vec) (vz3 vec)))
(vec4 (vec4 (vx4 vec) (vy4 vec) (vz4 vec) (vw4 vec)))))
(declaim (inline vec))
#+ecl (declaim (ftype (function (real real &optional (or null real) (or null real)) vec) vec))
#-ecl (declaim (ftype (function (real real &optional real real) vec) vec))
(define-ofun vec (x y &optional z w)
(cond (w (%vec4 (ensure-float x) (ensure-float y) (ensure-float z) (ensure-float w)))
(z (%vec3 (ensure-float x) (ensure-float y) (ensure-float z)))
(T (%vec2 (ensure-float x) (ensure-float y)))))
(define-compiler-macro vec (&environment env x y &optional z w)
(cond (w `(%vec4 ,(ensure-float-param x env) ,(ensure-float-param y env) ,(ensure-float-param z env) ,(ensure-float-param w env)))
(z `(%vec3 ,(ensure-float-param x env) ,(ensure-float-param y env) ,(ensure-float-param z env)))
(T `(%vec2 ,(ensure-float-param x env) ,(ensure-float-param y env)))))
(defun vec-from-vector (vector)
(ecase (length vector)
(2 (vec2 (aref vector 0) (aref vector 1)))
(3 (vec3 (aref vector 0) (aref vector 1) (aref vector 2)))
(4 (vec4 (aref vector 0) (aref vector 1) (aref vector 2) (aref vector 3)))))
|
80523
|
#|
This file is a part of 3d-vectors
(c) 2015 Shirakumo http://tymoon.eu (<EMAIL>)
Author: <NAME> <<EMAIL>>
|#
(in-package #:org.shirakumo.flare.vector)
(defmacro define-vecx-accessor (name rel)
`(progn
(declaim (inline ,name))
(declaim (ftype (function (vec) ,*float-type*) ,name))
(defun ,name (vec) (,rel vec))
(defsetf* ,name (vec &environment env) (value)
`(setf (,',rel ,vec) ,(ensure-float-param value env)))))
(defstruct (vec2 (:conc-name NIL)
(:constructor %vec2 (%vx2 %vy2))
(:copier vcopy2)
(:predicate vec2-p))
(%vx2 (ensure-float 0) :type #.*float-type*)
(%vy2 (ensure-float 0) :type #.*float-type*))
(define-vecx-accessor vx2 %vx2)
(define-vecx-accessor vy2 %vy2)
(declaim (inline vec2))
(declaim (ftype (function (real real) vec2) vec2))
(define-ofun vec2 (x y)
(%vec2 (ensure-float x) (ensure-float y)))
(define-compiler-macro vec2 (&whole whole &environment env x y)
`(%vec2 ,(ensure-float-param x env)
,(ensure-float-param y env)))
(define-ofun vec2-random (lower upper)
(let ((range (- upper lower)))
(vec2 (+ (random range) lower)
(+ (random range) lower))))
(defmethod print-object ((v vec2) stream)
(write (make-load-form v) :stream stream))
(defmethod make-load-form ((v vec2) &optional env)
(declare (ignore env))
`(vec2 ,(vx2 v) ,(vy2 v)))
(defstruct (vec3 (:conc-name NIL)
(:constructor %vec3 (%vx3 %vy3 %vz3))
(:copier vcopy3)
(:predicate vec3-p))
(%vx3 (ensure-float 0) :type #.*float-type*)
(%vy3 (ensure-float 0) :type #.*float-type*)
(%vz3 (ensure-float 0) :type #.*float-type*))
(define-vecx-accessor vx3 %vx3)
(define-vecx-accessor vy3 %vy3)
(define-vecx-accessor vz3 %vz3)
(declaim (inline vec3))
(declaim (ftype (function (real real real) vec3) vec3))
(define-ofun vec3 (x y z)
(%vec3 (ensure-float x) (ensure-float y) (ensure-float z)))
(define-compiler-macro vec3 (&whole whole &environment env x y z)
`(%vec3 ,(ensure-float-param x env)
,(ensure-float-param y env)
,(ensure-float-param z env)))
(define-ofun vec3-random (lower upper)
(let ((range (- upper lower)))
(vec3 (+ (random range) lower)
(+ (random range) lower)
(+ (random range) lower))))
(defmethod print-object ((v vec3) stream)
(write (make-load-form v) :stream stream))
(defmethod make-load-form ((v vec3) &optional env)
(declare (ignore env))
`(vec3 ,(vx3 v) ,(vy3 v) ,(vz3 v)))
(defstruct (vec4 (:conc-name NIL)
(:constructor %vec4 (%vx4 %vy4 %vz4 %vw4))
(:copier vcopy4)
(:predicate vec4-p))
(%vx4 (ensure-float 0) :type #.*float-type*)
(%vy4 (ensure-float 0) :type #.*float-type*)
(%vz4 (ensure-float 0) :type #.*float-type*)
(%vw4 (ensure-float 0) :type #.*float-type*))
(define-vecx-accessor vx4 %vx4)
(define-vecx-accessor vy4 %vy4)
(define-vecx-accessor vz4 %vz4)
(define-vecx-accessor vw4 %vw4)
(declaim (inline vec4))
(declaim (ftype (function (real real real real) vec4) vec4))
(define-ofun vec4 (x y z w)
(%vec4 (ensure-float x) (ensure-float y) (ensure-float z) (ensure-float w)))
(define-compiler-macro vec4 (&whole whole &environment env x y z w)
`(%vec4 ,(ensure-float-param x env)
,(ensure-float-param y env)
,(ensure-float-param z env)
,(ensure-float-param w env)))
(define-ofun vec4-random (lower upper)
(let ((range (- upper lower)))
(vec4 (+ (random range) lower)
(+ (random range) lower)
(+ (random range) lower)
(+ (random range) lower))))
(defmethod print-object ((v vec4) stream)
(write (make-load-form v) :stream stream))
(defmethod make-load-form ((v vec4) &optional env)
(declare (ignore env))
`(vec4 ,(vx4 v) ,(vy4 v) ,(vz4 v) ,(vw4 v)))
;; Backwards-compat
(deftype vec () '(or vec2 vec3 vec4))
(defmacro define-vec-accessor (name a2 a3 a4)
`(progn
(declaim (inline ,name))
(declaim (ftype (function (vec) ,*float-type*)))
(define-ofun ,name (vec)
(etypecase vec
,@(when a3 `((vec3 (,a3 vec))))
,@(when a4 `((vec4 (,a4 vec))))
,@(when a2 `((vec2 (,a2 vec))))))
(defsetf* ,name (vec &environment env) (value)
`(etypecase ,vec
,@(when ',a3 `((vec3 (setf (,',a3 ,vec) ,(ensure-float-param value env)))))
,@(when ',a4 `((vec4 (setf (,',a4 ,vec) ,(ensure-float-param value env)))))
,@(when ',a2 `((vec2 (setf (,',a2 ,vec) ,(ensure-float-param value env)))))))))
(define-vec-accessor vx %vx2 %vx3 %vx4)
(define-vec-accessor vy %vy2 %vy3 %vy4)
(define-vec-accessor vz NIL %vz3 %vz4)
(define-vec-accessor vw NIL NIL %vw4)
(declaim (inline vec))
(define-ofun vec-p (vec)
(typecase vec (vec2 T) (vec3 T) (vec4 T)))
(declaim (inline vcopy))
(define-ofun vcopy (vec)
(etypecase vec
(vec2 (vec2 (vx2 vec) (vy2 vec)))
(vec3 (vec3 (vx3 vec) (vy3 vec) (vz3 vec)))
(vec4 (vec4 (vx4 vec) (vy4 vec) (vz4 vec) (vw4 vec)))))
(declaim (inline vec))
#+ecl (declaim (ftype (function (real real &optional (or null real) (or null real)) vec) vec))
#-ecl (declaim (ftype (function (real real &optional real real) vec) vec))
(define-ofun vec (x y &optional z w)
(cond (w (%vec4 (ensure-float x) (ensure-float y) (ensure-float z) (ensure-float w)))
(z (%vec3 (ensure-float x) (ensure-float y) (ensure-float z)))
(T (%vec2 (ensure-float x) (ensure-float y)))))
(define-compiler-macro vec (&environment env x y &optional z w)
(cond (w `(%vec4 ,(ensure-float-param x env) ,(ensure-float-param y env) ,(ensure-float-param z env) ,(ensure-float-param w env)))
(z `(%vec3 ,(ensure-float-param x env) ,(ensure-float-param y env) ,(ensure-float-param z env)))
(T `(%vec2 ,(ensure-float-param x env) ,(ensure-float-param y env)))))
(defun vec-from-vector (vector)
(ecase (length vector)
(2 (vec2 (aref vector 0) (aref vector 1)))
(3 (vec3 (aref vector 0) (aref vector 1) (aref vector 2)))
(4 (vec4 (aref vector 0) (aref vector 1) (aref vector 2) (aref vector 3)))))
| true |
#|
This file is a part of 3d-vectors
(c) 2015 Shirakumo http://tymoon.eu (PI:EMAIL:<EMAIL>END_PI)
Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
|#
(in-package #:org.shirakumo.flare.vector)
(defmacro define-vecx-accessor (name rel)
`(progn
(declaim (inline ,name))
(declaim (ftype (function (vec) ,*float-type*) ,name))
(defun ,name (vec) (,rel vec))
(defsetf* ,name (vec &environment env) (value)
`(setf (,',rel ,vec) ,(ensure-float-param value env)))))
(defstruct (vec2 (:conc-name NIL)
(:constructor %vec2 (%vx2 %vy2))
(:copier vcopy2)
(:predicate vec2-p))
(%vx2 (ensure-float 0) :type #.*float-type*)
(%vy2 (ensure-float 0) :type #.*float-type*))
(define-vecx-accessor vx2 %vx2)
(define-vecx-accessor vy2 %vy2)
(declaim (inline vec2))
(declaim (ftype (function (real real) vec2) vec2))
(define-ofun vec2 (x y)
(%vec2 (ensure-float x) (ensure-float y)))
(define-compiler-macro vec2 (&whole whole &environment env x y)
`(%vec2 ,(ensure-float-param x env)
,(ensure-float-param y env)))
(define-ofun vec2-random (lower upper)
(let ((range (- upper lower)))
(vec2 (+ (random range) lower)
(+ (random range) lower))))
(defmethod print-object ((v vec2) stream)
(write (make-load-form v) :stream stream))
(defmethod make-load-form ((v vec2) &optional env)
(declare (ignore env))
`(vec2 ,(vx2 v) ,(vy2 v)))
(defstruct (vec3 (:conc-name NIL)
(:constructor %vec3 (%vx3 %vy3 %vz3))
(:copier vcopy3)
(:predicate vec3-p))
(%vx3 (ensure-float 0) :type #.*float-type*)
(%vy3 (ensure-float 0) :type #.*float-type*)
(%vz3 (ensure-float 0) :type #.*float-type*))
(define-vecx-accessor vx3 %vx3)
(define-vecx-accessor vy3 %vy3)
(define-vecx-accessor vz3 %vz3)
(declaim (inline vec3))
(declaim (ftype (function (real real real) vec3) vec3))
(define-ofun vec3 (x y z)
(%vec3 (ensure-float x) (ensure-float y) (ensure-float z)))
(define-compiler-macro vec3 (&whole whole &environment env x y z)
`(%vec3 ,(ensure-float-param x env)
,(ensure-float-param y env)
,(ensure-float-param z env)))
(define-ofun vec3-random (lower upper)
(let ((range (- upper lower)))
(vec3 (+ (random range) lower)
(+ (random range) lower)
(+ (random range) lower))))
(defmethod print-object ((v vec3) stream)
(write (make-load-form v) :stream stream))
(defmethod make-load-form ((v vec3) &optional env)
(declare (ignore env))
`(vec3 ,(vx3 v) ,(vy3 v) ,(vz3 v)))
(defstruct (vec4 (:conc-name NIL)
(:constructor %vec4 (%vx4 %vy4 %vz4 %vw4))
(:copier vcopy4)
(:predicate vec4-p))
(%vx4 (ensure-float 0) :type #.*float-type*)
(%vy4 (ensure-float 0) :type #.*float-type*)
(%vz4 (ensure-float 0) :type #.*float-type*)
(%vw4 (ensure-float 0) :type #.*float-type*))
(define-vecx-accessor vx4 %vx4)
(define-vecx-accessor vy4 %vy4)
(define-vecx-accessor vz4 %vz4)
(define-vecx-accessor vw4 %vw4)
(declaim (inline vec4))
(declaim (ftype (function (real real real real) vec4) vec4))
(define-ofun vec4 (x y z w)
(%vec4 (ensure-float x) (ensure-float y) (ensure-float z) (ensure-float w)))
(define-compiler-macro vec4 (&whole whole &environment env x y z w)
`(%vec4 ,(ensure-float-param x env)
,(ensure-float-param y env)
,(ensure-float-param z env)
,(ensure-float-param w env)))
(define-ofun vec4-random (lower upper)
(let ((range (- upper lower)))
(vec4 (+ (random range) lower)
(+ (random range) lower)
(+ (random range) lower)
(+ (random range) lower))))
(defmethod print-object ((v vec4) stream)
(write (make-load-form v) :stream stream))
(defmethod make-load-form ((v vec4) &optional env)
(declare (ignore env))
`(vec4 ,(vx4 v) ,(vy4 v) ,(vz4 v) ,(vw4 v)))
;; Backwards-compat
(deftype vec () '(or vec2 vec3 vec4))
(defmacro define-vec-accessor (name a2 a3 a4)
`(progn
(declaim (inline ,name))
(declaim (ftype (function (vec) ,*float-type*)))
(define-ofun ,name (vec)
(etypecase vec
,@(when a3 `((vec3 (,a3 vec))))
,@(when a4 `((vec4 (,a4 vec))))
,@(when a2 `((vec2 (,a2 vec))))))
(defsetf* ,name (vec &environment env) (value)
`(etypecase ,vec
,@(when ',a3 `((vec3 (setf (,',a3 ,vec) ,(ensure-float-param value env)))))
,@(when ',a4 `((vec4 (setf (,',a4 ,vec) ,(ensure-float-param value env)))))
,@(when ',a2 `((vec2 (setf (,',a2 ,vec) ,(ensure-float-param value env)))))))))
(define-vec-accessor vx %vx2 %vx3 %vx4)
(define-vec-accessor vy %vy2 %vy3 %vy4)
(define-vec-accessor vz NIL %vz3 %vz4)
(define-vec-accessor vw NIL NIL %vw4)
(declaim (inline vec))
(define-ofun vec-p (vec)
(typecase vec (vec2 T) (vec3 T) (vec4 T)))
(declaim (inline vcopy))
(define-ofun vcopy (vec)
(etypecase vec
(vec2 (vec2 (vx2 vec) (vy2 vec)))
(vec3 (vec3 (vx3 vec) (vy3 vec) (vz3 vec)))
(vec4 (vec4 (vx4 vec) (vy4 vec) (vz4 vec) (vw4 vec)))))
(declaim (inline vec))
#+ecl (declaim (ftype (function (real real &optional (or null real) (or null real)) vec) vec))
#-ecl (declaim (ftype (function (real real &optional real real) vec) vec))
(define-ofun vec (x y &optional z w)
(cond (w (%vec4 (ensure-float x) (ensure-float y) (ensure-float z) (ensure-float w)))
(z (%vec3 (ensure-float x) (ensure-float y) (ensure-float z)))
(T (%vec2 (ensure-float x) (ensure-float y)))))
(define-compiler-macro vec (&environment env x y &optional z w)
(cond (w `(%vec4 ,(ensure-float-param x env) ,(ensure-float-param y env) ,(ensure-float-param z env) ,(ensure-float-param w env)))
(z `(%vec3 ,(ensure-float-param x env) ,(ensure-float-param y env) ,(ensure-float-param z env)))
(T `(%vec2 ,(ensure-float-param x env) ,(ensure-float-param y env)))))
(defun vec-from-vector (vector)
(ecase (length vector)
(2 (vec2 (aref vector 0) (aref vector 1)))
(3 (vec3 (aref vector 0) (aref vector 1) (aref vector 2)))
(4 (vec4 (aref vector 0) (aref vector 1) (aref vector 2) (aref vector 3)))))
|
[
{
"context": " distriubtions.\"\n :version \"1549598006\"\n :author \"Mitch Richling <https://www.mitchr.me/>\"\n :licence \"See the BSD-",
"end": 124,
"score": 0.9998828172683716,
"start": 110,
"tag": "NAME",
"value": "Mitch Richling"
}
] |
mjr_probe.asd
|
richmit/mjrcalc
| 17 |
(defsystem
"mjr_probe"
:description "Empirical probability distriubtions."
:version "1549598006"
:author "Mitch Richling <https://www.mitchr.me/>"
:licence "See the BSD-style license in LICENSE.TXT"
:defsystem-depends-on (:MJR_PRNG :MJR_PWF)
:components ((:file "use-probe"))
)
|
61890
|
(defsystem
"mjr_probe"
:description "Empirical probability distriubtions."
:version "1549598006"
:author "<NAME> <https://www.mitchr.me/>"
:licence "See the BSD-style license in LICENSE.TXT"
:defsystem-depends-on (:MJR_PRNG :MJR_PWF)
:components ((:file "use-probe"))
)
| true |
(defsystem
"mjr_probe"
:description "Empirical probability distriubtions."
:version "1549598006"
:author "PI:NAME:<NAME>END_PI <https://www.mitchr.me/>"
:licence "See the BSD-style license in LICENSE.TXT"
:defsystem-depends-on (:MJR_PRNG :MJR_PWF)
:components ((:file "use-probe"))
)
|
[
{
"context": "sdl2 - FFI bindings to SDL2\r\n;;;Written in 2017 by Wilfredo Velázquez-Rodríguez <[email protected]>\r\n;;;\r\n;;;To the extent pos",
"end": 95,
"score": 0.9998749494552612,
"start": 67,
"tag": "NAME",
"value": "Wilfredo Velázquez-Rodríguez"
},
{
"context": ";Written in 2017 by Wilfredo Velázquez-Rodríguez <[email protected]>\r\n;;;\r\n;;;To the extent possible under law, the a",
"end": 117,
"score": 0.9999343156814575,
"start": 97,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
src/ffi/mouse.lisp
|
Zulu-Inuoe/raw-bindings-sdl2
| 6 |
;;;raw-bindings-sdl2 - FFI bindings to SDL2
;;;Written in 2017 by Wilfredo Velázquez-Rodríguez <[email protected]>
;;;
;;;To the extent possible under law, the author(s) have dedicated all copyright
;;;and related and neighboring rights to this software to the public domain
;;;worldwide. This software is distributed without any warranty.
;;;You should have received a copy of the CC0 Public Domain Dedication along
;;;with this software. If not, see
;;;<http://creativecommons.org/publicdomain/zero/1.0/>.
(in-package #:raw-bindings-sdl2)
(defsdl2enum sdl-system-cursor
+sdl-system-cursor-arrow+
+sdl-system-cursor-ibeam+
+sdl-system-cursor-wait+
+sdl-system-cursor-crosshair+
+sdl-system-cursor-waitarrow+
+sdl-system-cursor-sizenwse+
+sdl-system-cursor-sizenesw+
+sdl-system-cursor-sizewe+
+sdl-system-cursor-sizens+
+sdl-system-cursor-sizeall+
+sdl-system-cursor-no+
+sdl-system-cursor-hand+)
(defsdl2enum sdl-mouse-wheel-direction
+sdl-mousewheel-normal+
+sdl-mousewheel-flipped+)
(defsdl2-lispfun sdl-button (x)
(ash 1 (1- x)))
(defsdl2constant +sdl-button-left+ 1)
(defsdl2constant +sdl-button-middle+ 2)
(defsdl2constant +sdl-button-right+ 3)
(defsdl2constant +sdl-button-x1+ 4)
(defsdl2constant +sdl-button-x2+ 5)
(defsdl2constant +sdl-button-lmask+ (sdl-button +sdl-button-left+))
(defsdl2constant +sdl-button-mmask+ (sdl-button +sdl-button-middle+))
(defsdl2constant +sdl-button-rmask+ (sdl-button +sdl-button-right+))
(defsdl2constant +sdl-button-x1mask+ (sdl-button +sdl-button-x1+))
(defsdl2constant +sdl-button-x2mask+ (sdl-button +sdl-button-x2+))
(defsdl2struct sdl-cursor)
(defsdl2fun ("SDL_CaptureMouse" sdl-capture-mouse) :int
(enabled sdl-bool))
(defsdl2fun ("SDL_CreateColorCursor" sdl-create-color-cursor) (:pointer sdl-cursor)
(surface (:pointer sdl-surface))
(hot-x :int)
(hot-y :int))
(defsdl2fun ("SDL_CreateCursor" sdl-create-cursor) (:pointer sdl-cursor)
(data (:pointer :uint8))
(mask (:pointer :uint8))
(w :int)
(h :int)
(hot-x :int)
(hot-y :int))
(defsdl2fun ("SDL_CreateSystemCursor" sdl-create-system-cursor) (:pointer sdl-cursor)
(id sdl-system-cursor))
(defsdl2fun ("SDL_FreeCursor" sdl-free-cursor) :void
(cursor (:pointer sdl-cursor)))
(defsdl2fun ("SDL_GetCursor" sdl-get-cursor) (:pointer sdl-cursor))
(defsdl2fun ("SDL_GetDefaultCursor" sdl-get-default-cursor) (:pointer sdl-cursor))
(defsdl2fun ("SDL_GetGlobalMouseState" sdl-get-global-mouse-state) :uint32
(x (:pointer :int))
(y (:pointer :int)))
(defsdl2fun ("SDL_GetMouseFocus" sdl-get-mouse-focus) (:pointer sdl-window))
(defsdl2fun ("SDL_GetMouseState" sdl-get-mouse-state) :uint32
(x (:pointer :int))
(y (:pointer :int)))
(defsdl2fun ("SDL_GetRelativeMouseMode" sdl-get-relative-mouse-mode) sdl-bool)
(defsdl2fun ("SDL_GetRelativeMouseState" sdl-get-relative-mouse-state) :uint32
(x (:pointer :int))
(y (:pointer :int)))
(defsdl2fun ("SDL_SetCursor" sdl-set-cursor) :void
(cursor (:pointer sdl-cursor)))
(defsdl2fun ("SDL_SetRelativeMouseMode" sdl-set-relative-mouse-mode) :int
(enabled sdl-bool))
(defsdl2fun ("SDL_ShowCursor" sdl-show-cursor) :int
(toggle :int))
(defsdl2fun ("SDL_WarpMouseGlobal" sdl-warp-mouse-global) :int
(x :int)
(y :int))
(defsdl2fun ("SDL_WarpMouseInWindow" sdl-warp-mouse-in-window) :int
(window (:pointer sdl-window))
(x :int)
(y :int))
|
85183
|
;;;raw-bindings-sdl2 - FFI bindings to SDL2
;;;Written in 2017 by <NAME> <<EMAIL>>
;;;
;;;To the extent possible under law, the author(s) have dedicated all copyright
;;;and related and neighboring rights to this software to the public domain
;;;worldwide. This software is distributed without any warranty.
;;;You should have received a copy of the CC0 Public Domain Dedication along
;;;with this software. If not, see
;;;<http://creativecommons.org/publicdomain/zero/1.0/>.
(in-package #:raw-bindings-sdl2)
(defsdl2enum sdl-system-cursor
+sdl-system-cursor-arrow+
+sdl-system-cursor-ibeam+
+sdl-system-cursor-wait+
+sdl-system-cursor-crosshair+
+sdl-system-cursor-waitarrow+
+sdl-system-cursor-sizenwse+
+sdl-system-cursor-sizenesw+
+sdl-system-cursor-sizewe+
+sdl-system-cursor-sizens+
+sdl-system-cursor-sizeall+
+sdl-system-cursor-no+
+sdl-system-cursor-hand+)
(defsdl2enum sdl-mouse-wheel-direction
+sdl-mousewheel-normal+
+sdl-mousewheel-flipped+)
(defsdl2-lispfun sdl-button (x)
(ash 1 (1- x)))
(defsdl2constant +sdl-button-left+ 1)
(defsdl2constant +sdl-button-middle+ 2)
(defsdl2constant +sdl-button-right+ 3)
(defsdl2constant +sdl-button-x1+ 4)
(defsdl2constant +sdl-button-x2+ 5)
(defsdl2constant +sdl-button-lmask+ (sdl-button +sdl-button-left+))
(defsdl2constant +sdl-button-mmask+ (sdl-button +sdl-button-middle+))
(defsdl2constant +sdl-button-rmask+ (sdl-button +sdl-button-right+))
(defsdl2constant +sdl-button-x1mask+ (sdl-button +sdl-button-x1+))
(defsdl2constant +sdl-button-x2mask+ (sdl-button +sdl-button-x2+))
(defsdl2struct sdl-cursor)
(defsdl2fun ("SDL_CaptureMouse" sdl-capture-mouse) :int
(enabled sdl-bool))
(defsdl2fun ("SDL_CreateColorCursor" sdl-create-color-cursor) (:pointer sdl-cursor)
(surface (:pointer sdl-surface))
(hot-x :int)
(hot-y :int))
(defsdl2fun ("SDL_CreateCursor" sdl-create-cursor) (:pointer sdl-cursor)
(data (:pointer :uint8))
(mask (:pointer :uint8))
(w :int)
(h :int)
(hot-x :int)
(hot-y :int))
(defsdl2fun ("SDL_CreateSystemCursor" sdl-create-system-cursor) (:pointer sdl-cursor)
(id sdl-system-cursor))
(defsdl2fun ("SDL_FreeCursor" sdl-free-cursor) :void
(cursor (:pointer sdl-cursor)))
(defsdl2fun ("SDL_GetCursor" sdl-get-cursor) (:pointer sdl-cursor))
(defsdl2fun ("SDL_GetDefaultCursor" sdl-get-default-cursor) (:pointer sdl-cursor))
(defsdl2fun ("SDL_GetGlobalMouseState" sdl-get-global-mouse-state) :uint32
(x (:pointer :int))
(y (:pointer :int)))
(defsdl2fun ("SDL_GetMouseFocus" sdl-get-mouse-focus) (:pointer sdl-window))
(defsdl2fun ("SDL_GetMouseState" sdl-get-mouse-state) :uint32
(x (:pointer :int))
(y (:pointer :int)))
(defsdl2fun ("SDL_GetRelativeMouseMode" sdl-get-relative-mouse-mode) sdl-bool)
(defsdl2fun ("SDL_GetRelativeMouseState" sdl-get-relative-mouse-state) :uint32
(x (:pointer :int))
(y (:pointer :int)))
(defsdl2fun ("SDL_SetCursor" sdl-set-cursor) :void
(cursor (:pointer sdl-cursor)))
(defsdl2fun ("SDL_SetRelativeMouseMode" sdl-set-relative-mouse-mode) :int
(enabled sdl-bool))
(defsdl2fun ("SDL_ShowCursor" sdl-show-cursor) :int
(toggle :int))
(defsdl2fun ("SDL_WarpMouseGlobal" sdl-warp-mouse-global) :int
(x :int)
(y :int))
(defsdl2fun ("SDL_WarpMouseInWindow" sdl-warp-mouse-in-window) :int
(window (:pointer sdl-window))
(x :int)
(y :int))
| true |
;;;raw-bindings-sdl2 - FFI bindings to SDL2
;;;Written in 2017 by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;;
;;;To the extent possible under law, the author(s) have dedicated all copyright
;;;and related and neighboring rights to this software to the public domain
;;;worldwide. This software is distributed without any warranty.
;;;You should have received a copy of the CC0 Public Domain Dedication along
;;;with this software. If not, see
;;;<http://creativecommons.org/publicdomain/zero/1.0/>.
(in-package #:raw-bindings-sdl2)
(defsdl2enum sdl-system-cursor
+sdl-system-cursor-arrow+
+sdl-system-cursor-ibeam+
+sdl-system-cursor-wait+
+sdl-system-cursor-crosshair+
+sdl-system-cursor-waitarrow+
+sdl-system-cursor-sizenwse+
+sdl-system-cursor-sizenesw+
+sdl-system-cursor-sizewe+
+sdl-system-cursor-sizens+
+sdl-system-cursor-sizeall+
+sdl-system-cursor-no+
+sdl-system-cursor-hand+)
(defsdl2enum sdl-mouse-wheel-direction
+sdl-mousewheel-normal+
+sdl-mousewheel-flipped+)
(defsdl2-lispfun sdl-button (x)
(ash 1 (1- x)))
(defsdl2constant +sdl-button-left+ 1)
(defsdl2constant +sdl-button-middle+ 2)
(defsdl2constant +sdl-button-right+ 3)
(defsdl2constant +sdl-button-x1+ 4)
(defsdl2constant +sdl-button-x2+ 5)
(defsdl2constant +sdl-button-lmask+ (sdl-button +sdl-button-left+))
(defsdl2constant +sdl-button-mmask+ (sdl-button +sdl-button-middle+))
(defsdl2constant +sdl-button-rmask+ (sdl-button +sdl-button-right+))
(defsdl2constant +sdl-button-x1mask+ (sdl-button +sdl-button-x1+))
(defsdl2constant +sdl-button-x2mask+ (sdl-button +sdl-button-x2+))
(defsdl2struct sdl-cursor)
(defsdl2fun ("SDL_CaptureMouse" sdl-capture-mouse) :int
(enabled sdl-bool))
(defsdl2fun ("SDL_CreateColorCursor" sdl-create-color-cursor) (:pointer sdl-cursor)
(surface (:pointer sdl-surface))
(hot-x :int)
(hot-y :int))
(defsdl2fun ("SDL_CreateCursor" sdl-create-cursor) (:pointer sdl-cursor)
(data (:pointer :uint8))
(mask (:pointer :uint8))
(w :int)
(h :int)
(hot-x :int)
(hot-y :int))
(defsdl2fun ("SDL_CreateSystemCursor" sdl-create-system-cursor) (:pointer sdl-cursor)
(id sdl-system-cursor))
(defsdl2fun ("SDL_FreeCursor" sdl-free-cursor) :void
(cursor (:pointer sdl-cursor)))
(defsdl2fun ("SDL_GetCursor" sdl-get-cursor) (:pointer sdl-cursor))
(defsdl2fun ("SDL_GetDefaultCursor" sdl-get-default-cursor) (:pointer sdl-cursor))
(defsdl2fun ("SDL_GetGlobalMouseState" sdl-get-global-mouse-state) :uint32
(x (:pointer :int))
(y (:pointer :int)))
(defsdl2fun ("SDL_GetMouseFocus" sdl-get-mouse-focus) (:pointer sdl-window))
(defsdl2fun ("SDL_GetMouseState" sdl-get-mouse-state) :uint32
(x (:pointer :int))
(y (:pointer :int)))
(defsdl2fun ("SDL_GetRelativeMouseMode" sdl-get-relative-mouse-mode) sdl-bool)
(defsdl2fun ("SDL_GetRelativeMouseState" sdl-get-relative-mouse-state) :uint32
(x (:pointer :int))
(y (:pointer :int)))
(defsdl2fun ("SDL_SetCursor" sdl-set-cursor) :void
(cursor (:pointer sdl-cursor)))
(defsdl2fun ("SDL_SetRelativeMouseMode" sdl-set-relative-mouse-mode) :int
(enabled sdl-bool))
(defsdl2fun ("SDL_ShowCursor" sdl-show-cursor) :int
(toggle :int))
(defsdl2fun ("SDL_WarpMouseGlobal" sdl-warp-mouse-global) :int
(x :int)
(y :int))
(defsdl2fun ("SDL_WarpMouseInWindow" sdl-warp-mouse-in-window) :int
(window (:pointer sdl-window))
(x :int)
(y :int))
|
[
{
"context": " ;;;;;\n;;; Copyright (c) 1984,1987 by William Schelter,University of Texas ;;;;;\n;;; All rights re",
"end": 356,
"score": 0.9998825192451477,
"start": 340,
"tag": "NAME",
"value": "William Schelter"
}
] |
maxima/src/maxima/src/trigo.lisp
|
nilqed/spadlib
| 1 |
;;; -*- Mode: Lisp; Package: Maxima; Syntax: Common-Lisp; Base: 10 -*- ;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The data in this file contains enhancments. ;;;;;
;;; ;;;;;
;;; Copyright (c) 1984,1987 by William Schelter,University of Texas ;;;;;
;;; All rights reserved ;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; (c) Copyright 1982 Massachusetts Institute of Technology ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :maxima)
(macsyma-module trigo)
(load-macsyma-macros mrgmac)
(defun simp-%sinh (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((big-float-eval (mop form) y))
((taylorize (mop form) (second form)))
((and $%piargs (if (zerop1 y) 0)))
((and $%iargs (multiplep y '$%i)) (mul '$%i (cons-exp '%sin (coeff y '$%i 1))))
((and $triginverses (not (atom y))
(let ((fcn (caar y))
(arg (cadr y)))
(cond ((eq '%asinh fcn)
arg)
((eq '%acosh fcn)
;; ratsimp(logarc(exponentialize(sinh(acosh(x))))),algebraic;
;; -> sqrt(x-1)*sqrt(x+1)
(mul (power (sub arg 1) 1//2)
(power (add arg 1) 1//2)))
((eq '%atanh fcn)
;; radcan(logarc(exponentialize(sinh(atanh(x)))));
;; -> x/(sqrt(1-x)*sqrt(1+x))
(div arg
(mul (power (sub 1 arg) 1//2)
(power (add 1 arg) 1//2))))))))
((and $trigexpand (trigexpand '%sinh y)))
($exponentialize (exponentialize '%sinh y))
((and $halfangles (halfangle '%sinh y)))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%sinh (neg y))))
(t (eqtest (list '(%sinh) y) form))))
(defun simp-%cosh (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (zerop1 y) 1)))
((and $%iargs (multiplep y '$%i)) (cons-exp '%cos (coeff y '$%i 1)))
((and $triginverses (not (atom y))
(let ((fcn (caar y))
(arg (cadr y)))
(cond ((eq '%acosh fcn)
arg)
((eq '%asinh fcn)
;; ex: cosh(asinh(x));
;; ex,exponentialize,logarc;
;; ratsimp(%),algebraic
;; -> sqrt(x^2+1)
;;
(sqrt1+x^2 arg))
((eq '%atanh fcn)
;; ex: cosh(atanh(x))
;; radcan(logarc(exponentialize(ex)))
;; -> 1/sqrt(1-x)/sqrt(1+x)
(div 1
(mul (power (sub 1 arg) 1//2)
(power (add 1 arg) 1//2))))))))
((and $trigexpand (trigexpand '%cosh y)))
($exponentialize (exponentialize '%cosh y))
((and $halfangles (halfangle '%cosh y)))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (cons-exp '%cosh (neg y)))
(t (eqtest (list '(%cosh) y) form))))
(defun simp-%tanh (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (zerop1 y) 0)))
((and $%iargs (multiplep y '$%i)) (mul '$%i (cons-exp '%tan (coeff y '$%i 1))))
((and $triginverses (not (atom y))
(let ((fcn (caar y))
(arg (cadr y)))
(cond ((eq '%atanh fcn)
arg)
((eq '%asinh fcn)
;; ratsimp(logarc(exponentialize(tanh(asinh(x))))),algebraic;
;; --> x/sqrt(1+x^2)
(div arg (sqrt1+x^2 arg)))
((eq '%acosh fcn)
;; ratsimp(logarc(exponentialize(tanh(acosh(x))))),algebraic;
;; sqrt(x-1)*sqrt(x+1)/x
(div (mul (power (sub arg 1) 1//2)
(power (add arg 1) 1//2))
arg))))))
((and $trigexpand (trigexpand '%tanh y)))
($exponentialize (exponentialize '%tanh y))
((and $halfangles (halfangle '%tanh y)))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%tanh (neg y))))
(t (eqtest (list '(%tanh) y) form))))
(defun simp-%coth (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (zerop1 y) (domain-error y 'coth))))
((and $%iargs (multiplep y '$%i)) (mul -1 '$%i (cons-exp '%cot (coeff y '$%i 1))))
((and $triginverses (not (atom y)) (if (eq '%acoth (caar y)) (cadr y))))
((and $trigexpand (trigexpand '%coth y)))
($exponentialize (exponentialize '%coth y))
((and $halfangles (halfangle '%coth y)))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%coth (neg y))))
(t (eqtest (list '(%coth) y) form))))
(defun simp-%csch (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (cond ((zerop1 y) (domain-error y 'csch)))))
((and $%iargs (multiplep y '$%i)) (mul -1 '$%i (cons-exp '%csc (coeff y '$%i 1))))
((and $triginverses (not (atom y)) (if (eq '%acsch (caar y)) (cadr y))))
((and $trigexpand (trigexpand '%csch y)))
($exponentialize (exponentialize '%csch y))
((and $halfangles (halfangle '%csch y)))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%csch (neg y))))
(t (eqtest (list '(%csch) y) form))))
(defun simp-%sech (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (zerop1 y)) 1)
((and $%iargs (multiplep y '$%i)) (cons-exp '%sec (coeff y '$%i 1)))
((and $triginverses (not (atom y)) (if (eq '%asech (caar y)) (cadr y))))
((and $trigexpand (trigexpand '%sech y)))
($exponentialize (exponentialize '%sech y))
((and $halfangles (halfangle '%sech y)))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (cons-exp '%sech (neg y)))
(t (eqtest (list '(%sech) y) form))))
(defun simp-%asin (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs
;; Recognize some special values
(cond ((zerop1 y)
0)
((equal 1 y)
(div '$%pi 2))
((equal -1 y)
(div '$%pi -2))
((alike1 y 1//2)
(div '$%pi 6))
((alike1 y -1//2)
(div '$%pi -6))
;; 1/sqrt(2)
((alike1 y (power* 2 -1//2))
(div '$%pi 4))
;; sqrt(3)/2
((alike1 y (div (power* 3 1//2) 2))
(div '$%pi 3))
;; -sqrt(3)/2
((alike1 y (div (power* 3 1//2) -2))
(div '$%pi -3)))))
((and $%iargs (multiplep y '$%i)) (mul '$%i (cons-exp '%asinh (coeff y '$%i 1))))
((and (not (atom y)) (member (caar y) '(%cos %sin))
(if ($constantp (cadr y))
(let ((y-val (mfuncall '$mod
(if (eq (caar y) '%sin) (cadr y) (m- %pi//2 (cadr y)))
(m* 2 '$%pi))))
(cond ((eq (mlsp y-val %pi//2) t) y-val)
((eq (mlsp y-val (m* 3 %pi//2)) t) (m- '$%pi y-val))
((eq (mlsp y-val (m* 2 '$%pi)) t) (m- y-val (m* 2 '$%pi))))))))
((and (eq $triginverses t) (not (atom y)) (eq (caar y) '%sin)
(if (and (member (csign (m- (cadr y) %pi//2)) '($nz $neg) :test #'eq)
(member (csign (m+ (cadr y) %pi//2)) '($pz $pos) :test #'eq))
(cadr y))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%sin (caar y)) (cadr y))))
($logarc (logarc '%asin y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%asin (neg y))))
(t (eqtest (list '(%asin) y) form))))
(defun simp-%acos (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs
;; Recognize some special values
(cond ((zerop1 y)
(div '$%pi 2))
((equal 1 y)
0)
((equal -1 y)
'$%pi)
((alike1 y 1//2)
(div '$%pi 3))
((alike1 y -1//2)
(mul '$%pi (div 2 3)))
;; 1/sqrt(2)
((alike1 y (power* 2 -1//2))
(div '$%pi 4))
;; sqrt(3)/2
((alike1 y (div (power* 3 1//2) 2))
(div '$%pi 6))
;; -sqrt(3)/2
((alike1 y (div (power* 3 1//2) -2))
(mul '$%pi (div 5 6))))))
((and (not (atom y)) (member (caar y) '(%cos %sin))
(if ($constantp (cadr y))
(let ((y-val (mfuncall '$mod
(if (eq (caar y) '%cos) (cadr y) (m- %pi//2 (cadr y)))
(m* 2 '$%pi))))
(cond ((eq (mlsp y-val '$%pi) t) y-val)
((eq (mlsp y-val (m* 2 '$%pi)) t) (m- (m* 2 '$%pi) y-val)))))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%cos (caar y)) (cadr y))))
((and (eq $triginverses t) (not (atom y)) (eq (caar y) '%cos)
(if (and (member (csign (m- (cadr y) '$%pi)) '($nz $neg) :test #'eq)
(member (csign (cadr y)) '($pz $pos) :test #'eq))
(cadr y))))
($logarc (logarc '%acos y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (sub '$%pi (cons-exp '%acos (neg y))))
(t (eqtest (list '(%acos) y) form))))
(defun simp-%acot (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs
(cond ((zerop1 y) (div '$%pi 2))
((equal 1 y) (div '$%pi 4))
((equal -1 y) (div '$%pi -4))
;; 1/sqrt(3)
((alike1 y '((mexpt) 3 ((rat) -1 2))) (div '$%pi 3))
;; sqrt(3)
((alike1 y '((mexpt) 3 ((rat) 1 2))) (div '$%pi 6)))))
((and $%iargs (multiplep y '$%i)) (mul -1 '$%i (cons-exp '%acoth (coeff y '$%i 1))))
((and (not (atom y)) (member (caar y) '(%cot %tan))
(if ($constantp (cadr y))
(let ((y-val (mfuncall '$mod
(if (eq (caar y) '%cot) (cadr y) (m- %pi//2 (cadr y)))
'$%pi)))
(cond ((eq (mlsp y-val %pi//2) t) y-val)
((eq (mlsp y-val '$%pi) t) (m- y-val '$%pi)))))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%cot (caar y)) (cadr y))))
((and (eq $triginverses t) (not (atom y)) (eq (caar y) '%cot)
(if (and (member (csign (m- (cadr y) %pi//2)) '($nz $neg) :test #'eq)
(member (csign (m+ (cadr y) %pi//2)) '($pz $pos) :test #'eq))
(cadr y))))
($logarc (logarc '%acot y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%acot (neg y))))
(t (eqtest (list '(%acot) y) form))))
(defun simp-%acsc (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs
(cond ((equal 1 y) (div '$%pi 2))
((equal -1 y) (div '$%pi -2))
((equal y 2) (div '$%pi 6))
;; sqrt(2)
((alike1 y '((mexpt) 2 ((rat) 1 2))) (div '$%pi 4))
;; 2*sqrt(3)/3
((alike1 y '((mtimes) 2 ((mexpt) 3 ((rat) -1 2))))
(div '$%pi 3)))))
((and $%iargs (multiplep y '$%i)) (mul -1 '$%i (cons-exp '%acsch (coeff y '$%i 1))))
((and (not (atom y)) (eq '%csc (caar y))
(if ($constantp (cadr y))
(let ((y-val (mfuncall '$mod (cadr y) (m* 2 '$%pi))))
(cond ((eq (mlsp y-val %pi//2) t) y-val)
((eq (mlsp y-val (m* 3 %pi//2)) t) (m- '$%pi y-val))
((eq (mlsp y-val (m* 2 '$%pi)) t) (m- y-val (m* 2 '$%pi))))))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%csc (caar y)) (cadr y))))
($logarc (logarc '%acsc y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%acsc (neg y))))
(t (eqtest (list '(%acsc) y) form))))
(defun simp-%asec (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs
(cond ((equal 1 y) 0)
((equal -1 y) '$%pi)
((equal 2 y) (div '$%pi 3))
;; sqrt(2)
((alike1 y '((mexpt) 2 ((rat) 1 2))) (div '$%pi 4))
;; 2/sqrt(3)
((alike1 y '((mtimes) 2 ((mexpt) 3 ((rat) -1 2))))
(div '$%pi 6)))))
((and (not (atom y)) (eq '%sec (caar y))
(if ($constantp (cadr y))
(let ((y-val (mfuncall '$mod (cadr y) (m* 2 '$%pi))))
(cond ((eq (mlsp y-val '$%pi) t) y-val)
((eq (mlsp y-val (m* 2 '$%pi)) t) (m- (m* 2 '$%pi) y-val)))))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%sec (caar y)) (cadr y))))
($logarc (logarc '%asec y))
((apply-reflection-simp (mop form) y $trigsign))
;;((and $trigsign (mminusp* y)) (sub '$%pi (cons-exp '%asec (neg y))))
(t (eqtest (list '(%asec) y) form))))
(defun simp-%asinh (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (zerop1 y) y)))
((and $%iargs (multiplep y '$%i)) (mul '$%i (cons-exp '%asin (coeff y '$%i 1))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%sinh (caar y)) (cadr y))))
($logarc (logarc '%asinh y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%asinh (neg y))))
(t (eqtest (list '(%asinh) y) form))))
(defun simp-%acosh (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (equal y 1) 0)))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%cosh (caar y)) (cadr y))))
($logarc (logarc '%acosh y))
(t (eqtest (list '(%acosh) y) form))))
(defun simp-%atanh (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (cond ((zerop1 y) 0)
((or (equal y 1) (equal y -1)) (domain-error y 'atanh)))))
((and $%iargs (multiplep y '$%i)) (mul '$%i (cons-exp '%atan (coeff y '$%i 1))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%tanh (caar y)) (cadr y))))
($logarc (logarc '%atanh y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%atanh (neg y))))
(t (eqtest (list '(%atanh) y) form))))
(defun simp-%acoth (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (or (equal y 1) (equal y -1)) (domain-error y 'acoth))))
((and $%iargs (multiplep y '$%i)) (mul -1 '$%i (cons-exp '%acot (coeff y '$%i 1))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%coth (caar y)) (cadr y))))
($logarc (logarc '%acoth y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%acoth (neg y))))
(t (eqtest (list '(%acoth) y) form))))
(defun simp-%acsch (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (zerop1 y) (domain-error y 'acsch))))
((and $%iargs (multiplep y '$%i)) (mul -1 '$%i (cons-exp '%acsc (coeff y '$%i 1))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%csch (caar y)) (cadr y))))
($logarc (logarc '%acsch y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%acsch (neg y))))
(t (eqtest (list '(%acsch) y) form))))
(defun simp-%asech (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (cond ((equal y 1) 0)
((zerop1 y) (domain-error y 'asech)))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%sech (caar y)) (cadr y))))
($logarc (logarc '%asech y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (cons-exp '%asech (neg y)))
(t (eqtest (list '(%asech) y) form))))
(declare-top (special $trigexpandplus $trigexpandtimes))
(defmfun $trigexpand (e)
(cond ((atom e) e)
((specrepp e) ($trigexpand (specdisrep e)))
((trigexpand (caar e) (cadr e)))
(t (recur-apply #'$trigexpand e))))
(defun trigexpand (op arg)
(cond ((atom arg) nil)
((and $trigexpandplus (eq 'mplus (caar arg)))
(cond ((eq '%sin op) (sin/cos-plus (cdr arg) 1 '%sin '%cos -1))
((eq '%cos op) (sin/cos-plus (cdr arg) 0 '%sin '%cos -1))
((eq '%tan op) (tan-plus (cdr arg) '%tan -1))
((eq '%cot op) (cot-plus (cdr arg) '%cot -1))
((eq '%csc op) (csc/sec-plus (cdr arg) 1 '%csc '%sec -1))
((eq '%sec op) (csc/sec-plus (cdr arg) 0 '%csc '%sec -1))
((eq '%sinh op) (sin/cos-plus (cdr arg) 1 '%sinh '%cosh 1))
((eq '%cosh op) (sin/cos-plus (cdr arg) 0 '%sinh '%cosh 1))
((eq '%tanh op) (tan-plus (cdr arg) '%tanh 1))
((eq '%coth op) (cot-plus (cdr arg) '%coth 1))
((eq '%csch op) (csc/sec-plus (cdr arg) 1 '%csch '%sech 1))
((eq '%sech op) (csc/sec-plus (cdr arg) 0 '%csch '%sech 1))))
((and $trigexpandtimes (eq 'mtimes (caar arg)) (fixnump (cadr arg)))
(cond ((eq '%sin op) (sin/cos-times (cddr arg) 1 (cadr arg) '%sin '%cos -1))
((eq '%cos op) (sin/cos-times (cddr arg) 0 (cadr arg) '%sin '%cos -1))
((eq '%tan op) (tan-times (cddr arg) (cadr arg) '%tan -1))
((eq '%cot op) (cot-times (cddr arg) (cadr arg) '%cot -1))
((eq '%csc op) (csc/sec-times (cddr arg) 1 (cadr arg) '%csc '%sec -1))
((eq '%sec op) (csc/sec-times (cddr arg) 0 (cadr arg) '%csc '%sec -1))
((eq '%sinh op) (sin/cos-times (cddr arg) 1 (cadr arg) '%sinh '%cosh 1))
((eq '%cosh op) (sin/cos-times (cddr arg) 0 (cadr arg) '%sinh '%cosh 1))
((eq '%tanh op) (tan-times (cddr arg) (cadr arg) '%tanh 1))
((eq '%coth op) (cot-times (cddr arg) (cadr arg) '%coth 1))
((eq '%csch op) (csc/sec-times (cddr arg) 1 (cadr arg) '%csch '%sech 1))
((eq '%sech op) (csc/sec-times (cddr arg) 0 (cadr arg) '%csch '%sech 1))))))
(defun sin/cos-plus (l n f1 f2 flag)
(do ((i n (+ 2 i))
(len (length l))
(sign 1 (* flag sign))
(result))
((> i len) (simplify (cons '(mplus) result)))
(setq result (mpc (cond ((minusp sign) '(-1 (mtimes)))
(t '((mtimes)))) l result f1 f2 len i))))
(defun tan-plus (l f flag)
(do ((i 1 (+ 2 i))
(sign 1 (* flag sign))
(len (length l))
(num)
(den (list 1)))
((> i len) (div* (cons '(mplus) num) (cons '(mplus) den)))
(setq num (mpc1 (list sign '(mtimes)) l num f len i)
den (cond ((= len i) den)
(t (mpc1 (list (* flag sign) '(mtimes)) l den f len (1+ i)))))))
(defun cot-plus (l f flag)
(do ((i (length l) (- i 2)) (len (length l)) (sign 1 (* flag sign)) (num) (den))
((< i 0) (div* (cons '(mplus) num) (cons '(mplus) den)))
(setq num (mpc1 (list sign '(mtimes)) l num f len i)
den (cond ((= 0 i) den)
(t (mpc1 (list sign '(mtimes)) l den f len (1- i)))))))
(defun csc/sec-plus (l n f1 f2 flag)
(div* (do ((l l (cdr l))
(result))
((null l) (cons '(mtimes) result))
(setq result (cons (cons-exp f1 (car l)) (cons (cons-exp f2 (car l)) result))))
(sin/cos-plus l n f2 f1 flag)))
(defun sin/cos-times (l m n f1 f2 flag)
;; Assume m,n < 2^17, but Binom may become big
;; Flag is 1 or -1
(setq f1 (cons-exp f1 (cons '(mtimes) l)) f2 (cons-exp f2 (cons '(mtimes) l)))
(do ((i m (+ 2 i))
(end (abs n))
(result)
(binom (cond ((= 0 m) 1)
(t (abs n)))
(quotient (* flag (- end i 1) (- end i) binom) (* (+ 2 i) (1+ i)))))
((> i end) (setq result (simplify (cons '(mplus) result)))
(cond ((and (= 1 m) (minusp n)) (neg result)) (t result)))
(setq result (cons (mul binom (power f1 i) (power f2 (- end i))) result))))
(defun tan-times (l n f flag)
(setq f (cons-exp f (cons '(mtimes) l)))
(do ((i 1 (+ 2 i))
(end (abs n))
(num)
(den (list 1))
(binom (abs n) (quotient (* (- end i 1) binom) (+ 2 i))))
((> i end) (setq num (div* (cons '(mplus) num) (cons '(mplus) den)))
(cond ((minusp n) (neg num))
(t num)))
(setq num (cons (mul binom (power f i)) num)
den (cond ((= end i) den)
(t (cons (mul (setq binom (truncate (* flag (- end i) binom) (1+ i)))
(power f (1+ i)))
den))))))
(defun cot-times (l n f flag)
(setq f (cons-exp f (cons '(mtimes) l)))
(do ((i (abs n) (- i 2))
(end (abs n))
(num)
(den)
(binom 1 (truncate (* flag (1- i) binom) (- end i -2))))
((< i 0) (setq num (div* (cons '(mplus) num) (cons '(mplus) den)))
(if (minusp n) (neg num) num))
(setq num (cons (mul binom (power f i)) num)
den (if (= 0 i)
den
(cons (mul (setq binom (truncate (* i binom) (- end i -1))) (power f (1- i))) den)))))
(defun csc/sec-times (l m n f1 f2 flag)
(div* (mul (power (cons-exp f1 (cons '(mtimes) l)) (abs n))
(power (cons-exp f2 (cons '(mtimes) l)) (abs n)))
(sin/cos-times l m n f2 f1 flag)))
(defun mpc (dl ul result f1 f2 di ui)
(cond ((= 0 ui)
(cons (revappend dl (mapcar #'(lambda (l) (cons-exp f2 l)) ul)) result))
((= di ui)
(cons (revappend dl (mapcar #'(lambda (l) (cons-exp f1 l)) ul)) result))
(t (mpc (cons (cons-exp f1 (car ul)) dl) (cdr ul)
(mpc (cons (cons-exp f2 (car ul)) dl)
(cdr ul) result f1 f2 (1- di) ui) f1 f2
(1- di) (1- ui)))))
(defun mpc1 (dl ul result f di ui)
(cond ((= 0 ui) (cons (reverse dl) result))
((= di ui)
(cons (revappend dl (mapcar #'(lambda (l) (cons-exp f l)) ul)) result))
(t (mpc1 (cons (cons-exp f (car ul)) dl) (cdr ul)
(mpc1 dl (cdr ul) result f (1- di) ui) f
(1- di) (1- ui)))))
;; Local Modes:
;; Mode: LISP
;; Comment Col: 40
;; End:
|
69232
|
;;; -*- Mode: Lisp; Package: Maxima; Syntax: Common-Lisp; Base: 10 -*- ;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The data in this file contains enhancments. ;;;;;
;;; ;;;;;
;;; Copyright (c) 1984,1987 by <NAME>,University of Texas ;;;;;
;;; All rights reserved ;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; (c) Copyright 1982 Massachusetts Institute of Technology ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :maxima)
(macsyma-module trigo)
(load-macsyma-macros mrgmac)
(defun simp-%sinh (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((big-float-eval (mop form) y))
((taylorize (mop form) (second form)))
((and $%piargs (if (zerop1 y) 0)))
((and $%iargs (multiplep y '$%i)) (mul '$%i (cons-exp '%sin (coeff y '$%i 1))))
((and $triginverses (not (atom y))
(let ((fcn (caar y))
(arg (cadr y)))
(cond ((eq '%asinh fcn)
arg)
((eq '%acosh fcn)
;; ratsimp(logarc(exponentialize(sinh(acosh(x))))),algebraic;
;; -> sqrt(x-1)*sqrt(x+1)
(mul (power (sub arg 1) 1//2)
(power (add arg 1) 1//2)))
((eq '%atanh fcn)
;; radcan(logarc(exponentialize(sinh(atanh(x)))));
;; -> x/(sqrt(1-x)*sqrt(1+x))
(div arg
(mul (power (sub 1 arg) 1//2)
(power (add 1 arg) 1//2))))))))
((and $trigexpand (trigexpand '%sinh y)))
($exponentialize (exponentialize '%sinh y))
((and $halfangles (halfangle '%sinh y)))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%sinh (neg y))))
(t (eqtest (list '(%sinh) y) form))))
(defun simp-%cosh (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (zerop1 y) 1)))
((and $%iargs (multiplep y '$%i)) (cons-exp '%cos (coeff y '$%i 1)))
((and $triginverses (not (atom y))
(let ((fcn (caar y))
(arg (cadr y)))
(cond ((eq '%acosh fcn)
arg)
((eq '%asinh fcn)
;; ex: cosh(asinh(x));
;; ex,exponentialize,logarc;
;; ratsimp(%),algebraic
;; -> sqrt(x^2+1)
;;
(sqrt1+x^2 arg))
((eq '%atanh fcn)
;; ex: cosh(atanh(x))
;; radcan(logarc(exponentialize(ex)))
;; -> 1/sqrt(1-x)/sqrt(1+x)
(div 1
(mul (power (sub 1 arg) 1//2)
(power (add 1 arg) 1//2))))))))
((and $trigexpand (trigexpand '%cosh y)))
($exponentialize (exponentialize '%cosh y))
((and $halfangles (halfangle '%cosh y)))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (cons-exp '%cosh (neg y)))
(t (eqtest (list '(%cosh) y) form))))
(defun simp-%tanh (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (zerop1 y) 0)))
((and $%iargs (multiplep y '$%i)) (mul '$%i (cons-exp '%tan (coeff y '$%i 1))))
((and $triginverses (not (atom y))
(let ((fcn (caar y))
(arg (cadr y)))
(cond ((eq '%atanh fcn)
arg)
((eq '%asinh fcn)
;; ratsimp(logarc(exponentialize(tanh(asinh(x))))),algebraic;
;; --> x/sqrt(1+x^2)
(div arg (sqrt1+x^2 arg)))
((eq '%acosh fcn)
;; ratsimp(logarc(exponentialize(tanh(acosh(x))))),algebraic;
;; sqrt(x-1)*sqrt(x+1)/x
(div (mul (power (sub arg 1) 1//2)
(power (add arg 1) 1//2))
arg))))))
((and $trigexpand (trigexpand '%tanh y)))
($exponentialize (exponentialize '%tanh y))
((and $halfangles (halfangle '%tanh y)))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%tanh (neg y))))
(t (eqtest (list '(%tanh) y) form))))
(defun simp-%coth (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (zerop1 y) (domain-error y 'coth))))
((and $%iargs (multiplep y '$%i)) (mul -1 '$%i (cons-exp '%cot (coeff y '$%i 1))))
((and $triginverses (not (atom y)) (if (eq '%acoth (caar y)) (cadr y))))
((and $trigexpand (trigexpand '%coth y)))
($exponentialize (exponentialize '%coth y))
((and $halfangles (halfangle '%coth y)))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%coth (neg y))))
(t (eqtest (list '(%coth) y) form))))
(defun simp-%csch (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (cond ((zerop1 y) (domain-error y 'csch)))))
((and $%iargs (multiplep y '$%i)) (mul -1 '$%i (cons-exp '%csc (coeff y '$%i 1))))
((and $triginverses (not (atom y)) (if (eq '%acsch (caar y)) (cadr y))))
((and $trigexpand (trigexpand '%csch y)))
($exponentialize (exponentialize '%csch y))
((and $halfangles (halfangle '%csch y)))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%csch (neg y))))
(t (eqtest (list '(%csch) y) form))))
(defun simp-%sech (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (zerop1 y)) 1)
((and $%iargs (multiplep y '$%i)) (cons-exp '%sec (coeff y '$%i 1)))
((and $triginverses (not (atom y)) (if (eq '%asech (caar y)) (cadr y))))
((and $trigexpand (trigexpand '%sech y)))
($exponentialize (exponentialize '%sech y))
((and $halfangles (halfangle '%sech y)))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (cons-exp '%sech (neg y)))
(t (eqtest (list '(%sech) y) form))))
(defun simp-%asin (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs
;; Recognize some special values
(cond ((zerop1 y)
0)
((equal 1 y)
(div '$%pi 2))
((equal -1 y)
(div '$%pi -2))
((alike1 y 1//2)
(div '$%pi 6))
((alike1 y -1//2)
(div '$%pi -6))
;; 1/sqrt(2)
((alike1 y (power* 2 -1//2))
(div '$%pi 4))
;; sqrt(3)/2
((alike1 y (div (power* 3 1//2) 2))
(div '$%pi 3))
;; -sqrt(3)/2
((alike1 y (div (power* 3 1//2) -2))
(div '$%pi -3)))))
((and $%iargs (multiplep y '$%i)) (mul '$%i (cons-exp '%asinh (coeff y '$%i 1))))
((and (not (atom y)) (member (caar y) '(%cos %sin))
(if ($constantp (cadr y))
(let ((y-val (mfuncall '$mod
(if (eq (caar y) '%sin) (cadr y) (m- %pi//2 (cadr y)))
(m* 2 '$%pi))))
(cond ((eq (mlsp y-val %pi//2) t) y-val)
((eq (mlsp y-val (m* 3 %pi//2)) t) (m- '$%pi y-val))
((eq (mlsp y-val (m* 2 '$%pi)) t) (m- y-val (m* 2 '$%pi))))))))
((and (eq $triginverses t) (not (atom y)) (eq (caar y) '%sin)
(if (and (member (csign (m- (cadr y) %pi//2)) '($nz $neg) :test #'eq)
(member (csign (m+ (cadr y) %pi//2)) '($pz $pos) :test #'eq))
(cadr y))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%sin (caar y)) (cadr y))))
($logarc (logarc '%asin y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%asin (neg y))))
(t (eqtest (list '(%asin) y) form))))
(defun simp-%acos (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs
;; Recognize some special values
(cond ((zerop1 y)
(div '$%pi 2))
((equal 1 y)
0)
((equal -1 y)
'$%pi)
((alike1 y 1//2)
(div '$%pi 3))
((alike1 y -1//2)
(mul '$%pi (div 2 3)))
;; 1/sqrt(2)
((alike1 y (power* 2 -1//2))
(div '$%pi 4))
;; sqrt(3)/2
((alike1 y (div (power* 3 1//2) 2))
(div '$%pi 6))
;; -sqrt(3)/2
((alike1 y (div (power* 3 1//2) -2))
(mul '$%pi (div 5 6))))))
((and (not (atom y)) (member (caar y) '(%cos %sin))
(if ($constantp (cadr y))
(let ((y-val (mfuncall '$mod
(if (eq (caar y) '%cos) (cadr y) (m- %pi//2 (cadr y)))
(m* 2 '$%pi))))
(cond ((eq (mlsp y-val '$%pi) t) y-val)
((eq (mlsp y-val (m* 2 '$%pi)) t) (m- (m* 2 '$%pi) y-val)))))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%cos (caar y)) (cadr y))))
((and (eq $triginverses t) (not (atom y)) (eq (caar y) '%cos)
(if (and (member (csign (m- (cadr y) '$%pi)) '($nz $neg) :test #'eq)
(member (csign (cadr y)) '($pz $pos) :test #'eq))
(cadr y))))
($logarc (logarc '%acos y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (sub '$%pi (cons-exp '%acos (neg y))))
(t (eqtest (list '(%acos) y) form))))
(defun simp-%acot (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs
(cond ((zerop1 y) (div '$%pi 2))
((equal 1 y) (div '$%pi 4))
((equal -1 y) (div '$%pi -4))
;; 1/sqrt(3)
((alike1 y '((mexpt) 3 ((rat) -1 2))) (div '$%pi 3))
;; sqrt(3)
((alike1 y '((mexpt) 3 ((rat) 1 2))) (div '$%pi 6)))))
((and $%iargs (multiplep y '$%i)) (mul -1 '$%i (cons-exp '%acoth (coeff y '$%i 1))))
((and (not (atom y)) (member (caar y) '(%cot %tan))
(if ($constantp (cadr y))
(let ((y-val (mfuncall '$mod
(if (eq (caar y) '%cot) (cadr y) (m- %pi//2 (cadr y)))
'$%pi)))
(cond ((eq (mlsp y-val %pi//2) t) y-val)
((eq (mlsp y-val '$%pi) t) (m- y-val '$%pi)))))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%cot (caar y)) (cadr y))))
((and (eq $triginverses t) (not (atom y)) (eq (caar y) '%cot)
(if (and (member (csign (m- (cadr y) %pi//2)) '($nz $neg) :test #'eq)
(member (csign (m+ (cadr y) %pi//2)) '($pz $pos) :test #'eq))
(cadr y))))
($logarc (logarc '%acot y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%acot (neg y))))
(t (eqtest (list '(%acot) y) form))))
(defun simp-%acsc (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs
(cond ((equal 1 y) (div '$%pi 2))
((equal -1 y) (div '$%pi -2))
((equal y 2) (div '$%pi 6))
;; sqrt(2)
((alike1 y '((mexpt) 2 ((rat) 1 2))) (div '$%pi 4))
;; 2*sqrt(3)/3
((alike1 y '((mtimes) 2 ((mexpt) 3 ((rat) -1 2))))
(div '$%pi 3)))))
((and $%iargs (multiplep y '$%i)) (mul -1 '$%i (cons-exp '%acsch (coeff y '$%i 1))))
((and (not (atom y)) (eq '%csc (caar y))
(if ($constantp (cadr y))
(let ((y-val (mfuncall '$mod (cadr y) (m* 2 '$%pi))))
(cond ((eq (mlsp y-val %pi//2) t) y-val)
((eq (mlsp y-val (m* 3 %pi//2)) t) (m- '$%pi y-val))
((eq (mlsp y-val (m* 2 '$%pi)) t) (m- y-val (m* 2 '$%pi))))))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%csc (caar y)) (cadr y))))
($logarc (logarc '%acsc y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%acsc (neg y))))
(t (eqtest (list '(%acsc) y) form))))
(defun simp-%asec (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs
(cond ((equal 1 y) 0)
((equal -1 y) '$%pi)
((equal 2 y) (div '$%pi 3))
;; sqrt(2)
((alike1 y '((mexpt) 2 ((rat) 1 2))) (div '$%pi 4))
;; 2/sqrt(3)
((alike1 y '((mtimes) 2 ((mexpt) 3 ((rat) -1 2))))
(div '$%pi 6)))))
((and (not (atom y)) (eq '%sec (caar y))
(if ($constantp (cadr y))
(let ((y-val (mfuncall '$mod (cadr y) (m* 2 '$%pi))))
(cond ((eq (mlsp y-val '$%pi) t) y-val)
((eq (mlsp y-val (m* 2 '$%pi)) t) (m- (m* 2 '$%pi) y-val)))))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%sec (caar y)) (cadr y))))
($logarc (logarc '%asec y))
((apply-reflection-simp (mop form) y $trigsign))
;;((and $trigsign (mminusp* y)) (sub '$%pi (cons-exp '%asec (neg y))))
(t (eqtest (list '(%asec) y) form))))
(defun simp-%asinh (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (zerop1 y) y)))
((and $%iargs (multiplep y '$%i)) (mul '$%i (cons-exp '%asin (coeff y '$%i 1))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%sinh (caar y)) (cadr y))))
($logarc (logarc '%asinh y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%asinh (neg y))))
(t (eqtest (list '(%asinh) y) form))))
(defun simp-%acosh (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (equal y 1) 0)))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%cosh (caar y)) (cadr y))))
($logarc (logarc '%acosh y))
(t (eqtest (list '(%acosh) y) form))))
(defun simp-%atanh (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (cond ((zerop1 y) 0)
((or (equal y 1) (equal y -1)) (domain-error y 'atanh)))))
((and $%iargs (multiplep y '$%i)) (mul '$%i (cons-exp '%atan (coeff y '$%i 1))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%tanh (caar y)) (cadr y))))
($logarc (logarc '%atanh y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%atanh (neg y))))
(t (eqtest (list '(%atanh) y) form))))
(defun simp-%acoth (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (or (equal y 1) (equal y -1)) (domain-error y 'acoth))))
((and $%iargs (multiplep y '$%i)) (mul -1 '$%i (cons-exp '%acot (coeff y '$%i 1))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%coth (caar y)) (cadr y))))
($logarc (logarc '%acoth y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%acoth (neg y))))
(t (eqtest (list '(%acoth) y) form))))
(defun simp-%acsch (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (zerop1 y) (domain-error y 'acsch))))
((and $%iargs (multiplep y '$%i)) (mul -1 '$%i (cons-exp '%acsc (coeff y '$%i 1))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%csch (caar y)) (cadr y))))
($logarc (logarc '%acsch y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%acsch (neg y))))
(t (eqtest (list '(%acsch) y) form))))
(defun simp-%asech (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (cond ((equal y 1) 0)
((zerop1 y) (domain-error y 'asech)))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%sech (caar y)) (cadr y))))
($logarc (logarc '%asech y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (cons-exp '%asech (neg y)))
(t (eqtest (list '(%asech) y) form))))
(declare-top (special $trigexpandplus $trigexpandtimes))
(defmfun $trigexpand (e)
(cond ((atom e) e)
((specrepp e) ($trigexpand (specdisrep e)))
((trigexpand (caar e) (cadr e)))
(t (recur-apply #'$trigexpand e))))
(defun trigexpand (op arg)
(cond ((atom arg) nil)
((and $trigexpandplus (eq 'mplus (caar arg)))
(cond ((eq '%sin op) (sin/cos-plus (cdr arg) 1 '%sin '%cos -1))
((eq '%cos op) (sin/cos-plus (cdr arg) 0 '%sin '%cos -1))
((eq '%tan op) (tan-plus (cdr arg) '%tan -1))
((eq '%cot op) (cot-plus (cdr arg) '%cot -1))
((eq '%csc op) (csc/sec-plus (cdr arg) 1 '%csc '%sec -1))
((eq '%sec op) (csc/sec-plus (cdr arg) 0 '%csc '%sec -1))
((eq '%sinh op) (sin/cos-plus (cdr arg) 1 '%sinh '%cosh 1))
((eq '%cosh op) (sin/cos-plus (cdr arg) 0 '%sinh '%cosh 1))
((eq '%tanh op) (tan-plus (cdr arg) '%tanh 1))
((eq '%coth op) (cot-plus (cdr arg) '%coth 1))
((eq '%csch op) (csc/sec-plus (cdr arg) 1 '%csch '%sech 1))
((eq '%sech op) (csc/sec-plus (cdr arg) 0 '%csch '%sech 1))))
((and $trigexpandtimes (eq 'mtimes (caar arg)) (fixnump (cadr arg)))
(cond ((eq '%sin op) (sin/cos-times (cddr arg) 1 (cadr arg) '%sin '%cos -1))
((eq '%cos op) (sin/cos-times (cddr arg) 0 (cadr arg) '%sin '%cos -1))
((eq '%tan op) (tan-times (cddr arg) (cadr arg) '%tan -1))
((eq '%cot op) (cot-times (cddr arg) (cadr arg) '%cot -1))
((eq '%csc op) (csc/sec-times (cddr arg) 1 (cadr arg) '%csc '%sec -1))
((eq '%sec op) (csc/sec-times (cddr arg) 0 (cadr arg) '%csc '%sec -1))
((eq '%sinh op) (sin/cos-times (cddr arg) 1 (cadr arg) '%sinh '%cosh 1))
((eq '%cosh op) (sin/cos-times (cddr arg) 0 (cadr arg) '%sinh '%cosh 1))
((eq '%tanh op) (tan-times (cddr arg) (cadr arg) '%tanh 1))
((eq '%coth op) (cot-times (cddr arg) (cadr arg) '%coth 1))
((eq '%csch op) (csc/sec-times (cddr arg) 1 (cadr arg) '%csch '%sech 1))
((eq '%sech op) (csc/sec-times (cddr arg) 0 (cadr arg) '%csch '%sech 1))))))
(defun sin/cos-plus (l n f1 f2 flag)
(do ((i n (+ 2 i))
(len (length l))
(sign 1 (* flag sign))
(result))
((> i len) (simplify (cons '(mplus) result)))
(setq result (mpc (cond ((minusp sign) '(-1 (mtimes)))
(t '((mtimes)))) l result f1 f2 len i))))
(defun tan-plus (l f flag)
(do ((i 1 (+ 2 i))
(sign 1 (* flag sign))
(len (length l))
(num)
(den (list 1)))
((> i len) (div* (cons '(mplus) num) (cons '(mplus) den)))
(setq num (mpc1 (list sign '(mtimes)) l num f len i)
den (cond ((= len i) den)
(t (mpc1 (list (* flag sign) '(mtimes)) l den f len (1+ i)))))))
(defun cot-plus (l f flag)
(do ((i (length l) (- i 2)) (len (length l)) (sign 1 (* flag sign)) (num) (den))
((< i 0) (div* (cons '(mplus) num) (cons '(mplus) den)))
(setq num (mpc1 (list sign '(mtimes)) l num f len i)
den (cond ((= 0 i) den)
(t (mpc1 (list sign '(mtimes)) l den f len (1- i)))))))
(defun csc/sec-plus (l n f1 f2 flag)
(div* (do ((l l (cdr l))
(result))
((null l) (cons '(mtimes) result))
(setq result (cons (cons-exp f1 (car l)) (cons (cons-exp f2 (car l)) result))))
(sin/cos-plus l n f2 f1 flag)))
(defun sin/cos-times (l m n f1 f2 flag)
;; Assume m,n < 2^17, but Binom may become big
;; Flag is 1 or -1
(setq f1 (cons-exp f1 (cons '(mtimes) l)) f2 (cons-exp f2 (cons '(mtimes) l)))
(do ((i m (+ 2 i))
(end (abs n))
(result)
(binom (cond ((= 0 m) 1)
(t (abs n)))
(quotient (* flag (- end i 1) (- end i) binom) (* (+ 2 i) (1+ i)))))
((> i end) (setq result (simplify (cons '(mplus) result)))
(cond ((and (= 1 m) (minusp n)) (neg result)) (t result)))
(setq result (cons (mul binom (power f1 i) (power f2 (- end i))) result))))
(defun tan-times (l n f flag)
(setq f (cons-exp f (cons '(mtimes) l)))
(do ((i 1 (+ 2 i))
(end (abs n))
(num)
(den (list 1))
(binom (abs n) (quotient (* (- end i 1) binom) (+ 2 i))))
((> i end) (setq num (div* (cons '(mplus) num) (cons '(mplus) den)))
(cond ((minusp n) (neg num))
(t num)))
(setq num (cons (mul binom (power f i)) num)
den (cond ((= end i) den)
(t (cons (mul (setq binom (truncate (* flag (- end i) binom) (1+ i)))
(power f (1+ i)))
den))))))
(defun cot-times (l n f flag)
(setq f (cons-exp f (cons '(mtimes) l)))
(do ((i (abs n) (- i 2))
(end (abs n))
(num)
(den)
(binom 1 (truncate (* flag (1- i) binom) (- end i -2))))
((< i 0) (setq num (div* (cons '(mplus) num) (cons '(mplus) den)))
(if (minusp n) (neg num) num))
(setq num (cons (mul binom (power f i)) num)
den (if (= 0 i)
den
(cons (mul (setq binom (truncate (* i binom) (- end i -1))) (power f (1- i))) den)))))
(defun csc/sec-times (l m n f1 f2 flag)
(div* (mul (power (cons-exp f1 (cons '(mtimes) l)) (abs n))
(power (cons-exp f2 (cons '(mtimes) l)) (abs n)))
(sin/cos-times l m n f2 f1 flag)))
(defun mpc (dl ul result f1 f2 di ui)
(cond ((= 0 ui)
(cons (revappend dl (mapcar #'(lambda (l) (cons-exp f2 l)) ul)) result))
((= di ui)
(cons (revappend dl (mapcar #'(lambda (l) (cons-exp f1 l)) ul)) result))
(t (mpc (cons (cons-exp f1 (car ul)) dl) (cdr ul)
(mpc (cons (cons-exp f2 (car ul)) dl)
(cdr ul) result f1 f2 (1- di) ui) f1 f2
(1- di) (1- ui)))))
(defun mpc1 (dl ul result f di ui)
(cond ((= 0 ui) (cons (reverse dl) result))
((= di ui)
(cons (revappend dl (mapcar #'(lambda (l) (cons-exp f l)) ul)) result))
(t (mpc1 (cons (cons-exp f (car ul)) dl) (cdr ul)
(mpc1 dl (cdr ul) result f (1- di) ui) f
(1- di) (1- ui)))))
;; Local Modes:
;; Mode: LISP
;; Comment Col: 40
;; End:
| true |
;;; -*- Mode: Lisp; Package: Maxima; Syntax: Common-Lisp; Base: 10 -*- ;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The data in this file contains enhancments. ;;;;;
;;; ;;;;;
;;; Copyright (c) 1984,1987 by PI:NAME:<NAME>END_PI,University of Texas ;;;;;
;;; All rights reserved ;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; (c) Copyright 1982 Massachusetts Institute of Technology ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :maxima)
(macsyma-module trigo)
(load-macsyma-macros mrgmac)
(defun simp-%sinh (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((big-float-eval (mop form) y))
((taylorize (mop form) (second form)))
((and $%piargs (if (zerop1 y) 0)))
((and $%iargs (multiplep y '$%i)) (mul '$%i (cons-exp '%sin (coeff y '$%i 1))))
((and $triginverses (not (atom y))
(let ((fcn (caar y))
(arg (cadr y)))
(cond ((eq '%asinh fcn)
arg)
((eq '%acosh fcn)
;; ratsimp(logarc(exponentialize(sinh(acosh(x))))),algebraic;
;; -> sqrt(x-1)*sqrt(x+1)
(mul (power (sub arg 1) 1//2)
(power (add arg 1) 1//2)))
((eq '%atanh fcn)
;; radcan(logarc(exponentialize(sinh(atanh(x)))));
;; -> x/(sqrt(1-x)*sqrt(1+x))
(div arg
(mul (power (sub 1 arg) 1//2)
(power (add 1 arg) 1//2))))))))
((and $trigexpand (trigexpand '%sinh y)))
($exponentialize (exponentialize '%sinh y))
((and $halfangles (halfangle '%sinh y)))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%sinh (neg y))))
(t (eqtest (list '(%sinh) y) form))))
(defun simp-%cosh (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (zerop1 y) 1)))
((and $%iargs (multiplep y '$%i)) (cons-exp '%cos (coeff y '$%i 1)))
((and $triginverses (not (atom y))
(let ((fcn (caar y))
(arg (cadr y)))
(cond ((eq '%acosh fcn)
arg)
((eq '%asinh fcn)
;; ex: cosh(asinh(x));
;; ex,exponentialize,logarc;
;; ratsimp(%),algebraic
;; -> sqrt(x^2+1)
;;
(sqrt1+x^2 arg))
((eq '%atanh fcn)
;; ex: cosh(atanh(x))
;; radcan(logarc(exponentialize(ex)))
;; -> 1/sqrt(1-x)/sqrt(1+x)
(div 1
(mul (power (sub 1 arg) 1//2)
(power (add 1 arg) 1//2))))))))
((and $trigexpand (trigexpand '%cosh y)))
($exponentialize (exponentialize '%cosh y))
((and $halfangles (halfangle '%cosh y)))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (cons-exp '%cosh (neg y)))
(t (eqtest (list '(%cosh) y) form))))
(defun simp-%tanh (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (zerop1 y) 0)))
((and $%iargs (multiplep y '$%i)) (mul '$%i (cons-exp '%tan (coeff y '$%i 1))))
((and $triginverses (not (atom y))
(let ((fcn (caar y))
(arg (cadr y)))
(cond ((eq '%atanh fcn)
arg)
((eq '%asinh fcn)
;; ratsimp(logarc(exponentialize(tanh(asinh(x))))),algebraic;
;; --> x/sqrt(1+x^2)
(div arg (sqrt1+x^2 arg)))
((eq '%acosh fcn)
;; ratsimp(logarc(exponentialize(tanh(acosh(x))))),algebraic;
;; sqrt(x-1)*sqrt(x+1)/x
(div (mul (power (sub arg 1) 1//2)
(power (add arg 1) 1//2))
arg))))))
((and $trigexpand (trigexpand '%tanh y)))
($exponentialize (exponentialize '%tanh y))
((and $halfangles (halfangle '%tanh y)))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%tanh (neg y))))
(t (eqtest (list '(%tanh) y) form))))
(defun simp-%coth (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (zerop1 y) (domain-error y 'coth))))
((and $%iargs (multiplep y '$%i)) (mul -1 '$%i (cons-exp '%cot (coeff y '$%i 1))))
((and $triginverses (not (atom y)) (if (eq '%acoth (caar y)) (cadr y))))
((and $trigexpand (trigexpand '%coth y)))
($exponentialize (exponentialize '%coth y))
((and $halfangles (halfangle '%coth y)))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%coth (neg y))))
(t (eqtest (list '(%coth) y) form))))
(defun simp-%csch (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (cond ((zerop1 y) (domain-error y 'csch)))))
((and $%iargs (multiplep y '$%i)) (mul -1 '$%i (cons-exp '%csc (coeff y '$%i 1))))
((and $triginverses (not (atom y)) (if (eq '%acsch (caar y)) (cadr y))))
((and $trigexpand (trigexpand '%csch y)))
($exponentialize (exponentialize '%csch y))
((and $halfangles (halfangle '%csch y)))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%csch (neg y))))
(t (eqtest (list '(%csch) y) form))))
(defun simp-%sech (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (zerop1 y)) 1)
((and $%iargs (multiplep y '$%i)) (cons-exp '%sec (coeff y '$%i 1)))
((and $triginverses (not (atom y)) (if (eq '%asech (caar y)) (cadr y))))
((and $trigexpand (trigexpand '%sech y)))
($exponentialize (exponentialize '%sech y))
((and $halfangles (halfangle '%sech y)))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (cons-exp '%sech (neg y)))
(t (eqtest (list '(%sech) y) form))))
(defun simp-%asin (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs
;; Recognize some special values
(cond ((zerop1 y)
0)
((equal 1 y)
(div '$%pi 2))
((equal -1 y)
(div '$%pi -2))
((alike1 y 1//2)
(div '$%pi 6))
((alike1 y -1//2)
(div '$%pi -6))
;; 1/sqrt(2)
((alike1 y (power* 2 -1//2))
(div '$%pi 4))
;; sqrt(3)/2
((alike1 y (div (power* 3 1//2) 2))
(div '$%pi 3))
;; -sqrt(3)/2
((alike1 y (div (power* 3 1//2) -2))
(div '$%pi -3)))))
((and $%iargs (multiplep y '$%i)) (mul '$%i (cons-exp '%asinh (coeff y '$%i 1))))
((and (not (atom y)) (member (caar y) '(%cos %sin))
(if ($constantp (cadr y))
(let ((y-val (mfuncall '$mod
(if (eq (caar y) '%sin) (cadr y) (m- %pi//2 (cadr y)))
(m* 2 '$%pi))))
(cond ((eq (mlsp y-val %pi//2) t) y-val)
((eq (mlsp y-val (m* 3 %pi//2)) t) (m- '$%pi y-val))
((eq (mlsp y-val (m* 2 '$%pi)) t) (m- y-val (m* 2 '$%pi))))))))
((and (eq $triginverses t) (not (atom y)) (eq (caar y) '%sin)
(if (and (member (csign (m- (cadr y) %pi//2)) '($nz $neg) :test #'eq)
(member (csign (m+ (cadr y) %pi//2)) '($pz $pos) :test #'eq))
(cadr y))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%sin (caar y)) (cadr y))))
($logarc (logarc '%asin y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%asin (neg y))))
(t (eqtest (list '(%asin) y) form))))
(defun simp-%acos (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs
;; Recognize some special values
(cond ((zerop1 y)
(div '$%pi 2))
((equal 1 y)
0)
((equal -1 y)
'$%pi)
((alike1 y 1//2)
(div '$%pi 3))
((alike1 y -1//2)
(mul '$%pi (div 2 3)))
;; 1/sqrt(2)
((alike1 y (power* 2 -1//2))
(div '$%pi 4))
;; sqrt(3)/2
((alike1 y (div (power* 3 1//2) 2))
(div '$%pi 6))
;; -sqrt(3)/2
((alike1 y (div (power* 3 1//2) -2))
(mul '$%pi (div 5 6))))))
((and (not (atom y)) (member (caar y) '(%cos %sin))
(if ($constantp (cadr y))
(let ((y-val (mfuncall '$mod
(if (eq (caar y) '%cos) (cadr y) (m- %pi//2 (cadr y)))
(m* 2 '$%pi))))
(cond ((eq (mlsp y-val '$%pi) t) y-val)
((eq (mlsp y-val (m* 2 '$%pi)) t) (m- (m* 2 '$%pi) y-val)))))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%cos (caar y)) (cadr y))))
((and (eq $triginverses t) (not (atom y)) (eq (caar y) '%cos)
(if (and (member (csign (m- (cadr y) '$%pi)) '($nz $neg) :test #'eq)
(member (csign (cadr y)) '($pz $pos) :test #'eq))
(cadr y))))
($logarc (logarc '%acos y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (sub '$%pi (cons-exp '%acos (neg y))))
(t (eqtest (list '(%acos) y) form))))
(defun simp-%acot (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs
(cond ((zerop1 y) (div '$%pi 2))
((equal 1 y) (div '$%pi 4))
((equal -1 y) (div '$%pi -4))
;; 1/sqrt(3)
((alike1 y '((mexpt) 3 ((rat) -1 2))) (div '$%pi 3))
;; sqrt(3)
((alike1 y '((mexpt) 3 ((rat) 1 2))) (div '$%pi 6)))))
((and $%iargs (multiplep y '$%i)) (mul -1 '$%i (cons-exp '%acoth (coeff y '$%i 1))))
((and (not (atom y)) (member (caar y) '(%cot %tan))
(if ($constantp (cadr y))
(let ((y-val (mfuncall '$mod
(if (eq (caar y) '%cot) (cadr y) (m- %pi//2 (cadr y)))
'$%pi)))
(cond ((eq (mlsp y-val %pi//2) t) y-val)
((eq (mlsp y-val '$%pi) t) (m- y-val '$%pi)))))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%cot (caar y)) (cadr y))))
((and (eq $triginverses t) (not (atom y)) (eq (caar y) '%cot)
(if (and (member (csign (m- (cadr y) %pi//2)) '($nz $neg) :test #'eq)
(member (csign (m+ (cadr y) %pi//2)) '($pz $pos) :test #'eq))
(cadr y))))
($logarc (logarc '%acot y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%acot (neg y))))
(t (eqtest (list '(%acot) y) form))))
(defun simp-%acsc (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs
(cond ((equal 1 y) (div '$%pi 2))
((equal -1 y) (div '$%pi -2))
((equal y 2) (div '$%pi 6))
;; sqrt(2)
((alike1 y '((mexpt) 2 ((rat) 1 2))) (div '$%pi 4))
;; 2*sqrt(3)/3
((alike1 y '((mtimes) 2 ((mexpt) 3 ((rat) -1 2))))
(div '$%pi 3)))))
((and $%iargs (multiplep y '$%i)) (mul -1 '$%i (cons-exp '%acsch (coeff y '$%i 1))))
((and (not (atom y)) (eq '%csc (caar y))
(if ($constantp (cadr y))
(let ((y-val (mfuncall '$mod (cadr y) (m* 2 '$%pi))))
(cond ((eq (mlsp y-val %pi//2) t) y-val)
((eq (mlsp y-val (m* 3 %pi//2)) t) (m- '$%pi y-val))
((eq (mlsp y-val (m* 2 '$%pi)) t) (m- y-val (m* 2 '$%pi))))))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%csc (caar y)) (cadr y))))
($logarc (logarc '%acsc y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%acsc (neg y))))
(t (eqtest (list '(%acsc) y) form))))
(defun simp-%asec (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs
(cond ((equal 1 y) 0)
((equal -1 y) '$%pi)
((equal 2 y) (div '$%pi 3))
;; sqrt(2)
((alike1 y '((mexpt) 2 ((rat) 1 2))) (div '$%pi 4))
;; 2/sqrt(3)
((alike1 y '((mtimes) 2 ((mexpt) 3 ((rat) -1 2))))
(div '$%pi 6)))))
((and (not (atom y)) (eq '%sec (caar y))
(if ($constantp (cadr y))
(let ((y-val (mfuncall '$mod (cadr y) (m* 2 '$%pi))))
(cond ((eq (mlsp y-val '$%pi) t) y-val)
((eq (mlsp y-val (m* 2 '$%pi)) t) (m- (m* 2 '$%pi) y-val)))))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%sec (caar y)) (cadr y))))
($logarc (logarc '%asec y))
((apply-reflection-simp (mop form) y $trigsign))
;;((and $trigsign (mminusp* y)) (sub '$%pi (cons-exp '%asec (neg y))))
(t (eqtest (list '(%asec) y) form))))
(defun simp-%asinh (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (zerop1 y) y)))
((and $%iargs (multiplep y '$%i)) (mul '$%i (cons-exp '%asin (coeff y '$%i 1))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%sinh (caar y)) (cadr y))))
($logarc (logarc '%asinh y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%asinh (neg y))))
(t (eqtest (list '(%asinh) y) form))))
(defun simp-%acosh (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (equal y 1) 0)))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%cosh (caar y)) (cadr y))))
($logarc (logarc '%acosh y))
(t (eqtest (list '(%acosh) y) form))))
(defun simp-%atanh (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (cond ((zerop1 y) 0)
((or (equal y 1) (equal y -1)) (domain-error y 'atanh)))))
((and $%iargs (multiplep y '$%i)) (mul '$%i (cons-exp '%atan (coeff y '$%i 1))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%tanh (caar y)) (cadr y))))
($logarc (logarc '%atanh y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%atanh (neg y))))
(t (eqtest (list '(%atanh) y) form))))
(defun simp-%acoth (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (or (equal y 1) (equal y -1)) (domain-error y 'acoth))))
((and $%iargs (multiplep y '$%i)) (mul -1 '$%i (cons-exp '%acot (coeff y '$%i 1))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%coth (caar y)) (cadr y))))
($logarc (logarc '%acoth y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%acoth (neg y))))
(t (eqtest (list '(%acoth) y) form))))
(defun simp-%acsch (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (if (zerop1 y) (domain-error y 'acsch))))
((and $%iargs (multiplep y '$%i)) (mul -1 '$%i (cons-exp '%acsc (coeff y '$%i 1))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%csch (caar y)) (cadr y))))
($logarc (logarc '%acsch y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (neg (cons-exp '%acsch (neg y))))
(t (eqtest (list '(%acsch) y) form))))
(defun simp-%asech (form y z)
(oneargcheck form)
(setq y (simpcheck (cadr form) z))
(cond ((flonum-eval (mop form) y))
((and (not (member 'simp (car form))) (big-float-eval (mop form) y)))
((taylorize (mop form) (second form)))
((and $%piargs (cond ((equal y 1) 0)
((zerop1 y) (domain-error y 'asech)))))
((and (eq $triginverses '$all) (not (atom y))
(if (eq '%sech (caar y)) (cadr y))))
($logarc (logarc '%asech y))
((apply-reflection-simp (mop form) y $trigsign))
;((and $trigsign (mminusp* y)) (cons-exp '%asech (neg y)))
(t (eqtest (list '(%asech) y) form))))
(declare-top (special $trigexpandplus $trigexpandtimes))
(defmfun $trigexpand (e)
(cond ((atom e) e)
((specrepp e) ($trigexpand (specdisrep e)))
((trigexpand (caar e) (cadr e)))
(t (recur-apply #'$trigexpand e))))
(defun trigexpand (op arg)
(cond ((atom arg) nil)
((and $trigexpandplus (eq 'mplus (caar arg)))
(cond ((eq '%sin op) (sin/cos-plus (cdr arg) 1 '%sin '%cos -1))
((eq '%cos op) (sin/cos-plus (cdr arg) 0 '%sin '%cos -1))
((eq '%tan op) (tan-plus (cdr arg) '%tan -1))
((eq '%cot op) (cot-plus (cdr arg) '%cot -1))
((eq '%csc op) (csc/sec-plus (cdr arg) 1 '%csc '%sec -1))
((eq '%sec op) (csc/sec-plus (cdr arg) 0 '%csc '%sec -1))
((eq '%sinh op) (sin/cos-plus (cdr arg) 1 '%sinh '%cosh 1))
((eq '%cosh op) (sin/cos-plus (cdr arg) 0 '%sinh '%cosh 1))
((eq '%tanh op) (tan-plus (cdr arg) '%tanh 1))
((eq '%coth op) (cot-plus (cdr arg) '%coth 1))
((eq '%csch op) (csc/sec-plus (cdr arg) 1 '%csch '%sech 1))
((eq '%sech op) (csc/sec-plus (cdr arg) 0 '%csch '%sech 1))))
((and $trigexpandtimes (eq 'mtimes (caar arg)) (fixnump (cadr arg)))
(cond ((eq '%sin op) (sin/cos-times (cddr arg) 1 (cadr arg) '%sin '%cos -1))
((eq '%cos op) (sin/cos-times (cddr arg) 0 (cadr arg) '%sin '%cos -1))
((eq '%tan op) (tan-times (cddr arg) (cadr arg) '%tan -1))
((eq '%cot op) (cot-times (cddr arg) (cadr arg) '%cot -1))
((eq '%csc op) (csc/sec-times (cddr arg) 1 (cadr arg) '%csc '%sec -1))
((eq '%sec op) (csc/sec-times (cddr arg) 0 (cadr arg) '%csc '%sec -1))
((eq '%sinh op) (sin/cos-times (cddr arg) 1 (cadr arg) '%sinh '%cosh 1))
((eq '%cosh op) (sin/cos-times (cddr arg) 0 (cadr arg) '%sinh '%cosh 1))
((eq '%tanh op) (tan-times (cddr arg) (cadr arg) '%tanh 1))
((eq '%coth op) (cot-times (cddr arg) (cadr arg) '%coth 1))
((eq '%csch op) (csc/sec-times (cddr arg) 1 (cadr arg) '%csch '%sech 1))
((eq '%sech op) (csc/sec-times (cddr arg) 0 (cadr arg) '%csch '%sech 1))))))
(defun sin/cos-plus (l n f1 f2 flag)
(do ((i n (+ 2 i))
(len (length l))
(sign 1 (* flag sign))
(result))
((> i len) (simplify (cons '(mplus) result)))
(setq result (mpc (cond ((minusp sign) '(-1 (mtimes)))
(t '((mtimes)))) l result f1 f2 len i))))
(defun tan-plus (l f flag)
(do ((i 1 (+ 2 i))
(sign 1 (* flag sign))
(len (length l))
(num)
(den (list 1)))
((> i len) (div* (cons '(mplus) num) (cons '(mplus) den)))
(setq num (mpc1 (list sign '(mtimes)) l num f len i)
den (cond ((= len i) den)
(t (mpc1 (list (* flag sign) '(mtimes)) l den f len (1+ i)))))))
(defun cot-plus (l f flag)
(do ((i (length l) (- i 2)) (len (length l)) (sign 1 (* flag sign)) (num) (den))
((< i 0) (div* (cons '(mplus) num) (cons '(mplus) den)))
(setq num (mpc1 (list sign '(mtimes)) l num f len i)
den (cond ((= 0 i) den)
(t (mpc1 (list sign '(mtimes)) l den f len (1- i)))))))
(defun csc/sec-plus (l n f1 f2 flag)
(div* (do ((l l (cdr l))
(result))
((null l) (cons '(mtimes) result))
(setq result (cons (cons-exp f1 (car l)) (cons (cons-exp f2 (car l)) result))))
(sin/cos-plus l n f2 f1 flag)))
(defun sin/cos-times (l m n f1 f2 flag)
;; Assume m,n < 2^17, but Binom may become big
;; Flag is 1 or -1
(setq f1 (cons-exp f1 (cons '(mtimes) l)) f2 (cons-exp f2 (cons '(mtimes) l)))
(do ((i m (+ 2 i))
(end (abs n))
(result)
(binom (cond ((= 0 m) 1)
(t (abs n)))
(quotient (* flag (- end i 1) (- end i) binom) (* (+ 2 i) (1+ i)))))
((> i end) (setq result (simplify (cons '(mplus) result)))
(cond ((and (= 1 m) (minusp n)) (neg result)) (t result)))
(setq result (cons (mul binom (power f1 i) (power f2 (- end i))) result))))
(defun tan-times (l n f flag)
(setq f (cons-exp f (cons '(mtimes) l)))
(do ((i 1 (+ 2 i))
(end (abs n))
(num)
(den (list 1))
(binom (abs n) (quotient (* (- end i 1) binom) (+ 2 i))))
((> i end) (setq num (div* (cons '(mplus) num) (cons '(mplus) den)))
(cond ((minusp n) (neg num))
(t num)))
(setq num (cons (mul binom (power f i)) num)
den (cond ((= end i) den)
(t (cons (mul (setq binom (truncate (* flag (- end i) binom) (1+ i)))
(power f (1+ i)))
den))))))
(defun cot-times (l n f flag)
(setq f (cons-exp f (cons '(mtimes) l)))
(do ((i (abs n) (- i 2))
(end (abs n))
(num)
(den)
(binom 1 (truncate (* flag (1- i) binom) (- end i -2))))
((< i 0) (setq num (div* (cons '(mplus) num) (cons '(mplus) den)))
(if (minusp n) (neg num) num))
(setq num (cons (mul binom (power f i)) num)
den (if (= 0 i)
den
(cons (mul (setq binom (truncate (* i binom) (- end i -1))) (power f (1- i))) den)))))
(defun csc/sec-times (l m n f1 f2 flag)
(div* (mul (power (cons-exp f1 (cons '(mtimes) l)) (abs n))
(power (cons-exp f2 (cons '(mtimes) l)) (abs n)))
(sin/cos-times l m n f2 f1 flag)))
(defun mpc (dl ul result f1 f2 di ui)
(cond ((= 0 ui)
(cons (revappend dl (mapcar #'(lambda (l) (cons-exp f2 l)) ul)) result))
((= di ui)
(cons (revappend dl (mapcar #'(lambda (l) (cons-exp f1 l)) ul)) result))
(t (mpc (cons (cons-exp f1 (car ul)) dl) (cdr ul)
(mpc (cons (cons-exp f2 (car ul)) dl)
(cdr ul) result f1 f2 (1- di) ui) f1 f2
(1- di) (1- ui)))))
(defun mpc1 (dl ul result f di ui)
(cond ((= 0 ui) (cons (reverse dl) result))
((= di ui)
(cons (revappend dl (mapcar #'(lambda (l) (cons-exp f l)) ul)) result))
(t (mpc1 (cons (cons-exp f (car ul)) dl) (cdr ul)
(mpc1 dl (cdr ul) result f (1- di) ui) f
(1- di) (1- ui)))))
;; Local Modes:
;; Mode: LISP
;; Comment Col: 40
;; End:
|
[
{
"context": "fectively\n(defparameter *heroes*\n '((Superman (Clark Kent))\n (Batman (Bruce Wayne))))\n \n(format t",
"end": 110,
"score": 0.9998413920402527,
"start": 100,
"tag": "NAME",
"value": "Clark Kent"
},
{
"context": "ter *heroes*\n '((Superman (Clark Kent))\n (Batman (Bruce Wayne))))\n \n(format t \"Superman Da",
"end": 123,
"score": 0.7126311659812927,
"start": 120,
"tag": "NAME",
"value": "Bat"
},
{
"context": "oes*\n '((Superman (Clark Kent))\n (Batman (Bruce Wayne))))\n \n(format t \"Superman Data ~a ~%\" (assoc",
"end": 139,
"score": 0.9996476173400879,
"start": 128,
"tag": "NAME",
"value": "Bruce Wayne"
}
] |
src/10_association_lists.lsp
|
James-P-D/LispDump
| 0 |
(setq *print-case* :capitalize)
; Dictionaries effectively
(defparameter *heroes*
'((Superman (Clark Kent))
(Batman (Bruce Wayne))))
(format t "Superman Data ~a ~%" (assoc 'sUpErMaN *heroes*)) ; Note it doesn't care about case of key
(format t "Superman is ~a ~%" (cadr (assoc 'superman *heroes*)))
|
52908
|
(setq *print-case* :capitalize)
; Dictionaries effectively
(defparameter *heroes*
'((Superman (<NAME>))
(<NAME>man (<NAME>))))
(format t "Superman Data ~a ~%" (assoc 'sUpErMaN *heroes*)) ; Note it doesn't care about case of key
(format t "Superman is ~a ~%" (cadr (assoc 'superman *heroes*)))
| true |
(setq *print-case* :capitalize)
; Dictionaries effectively
(defparameter *heroes*
'((Superman (PI:NAME:<NAME>END_PI))
(PI:NAME:<NAME>END_PIman (PI:NAME:<NAME>END_PI))))
(format t "Superman Data ~a ~%" (assoc 'sUpErMaN *heroes*)) ; Note it doesn't care about case of key
(format t "Superman is ~a ~%" (cadr (assoc 'superman *heroes*)))
|
[
{
"context": "ription \"Example lisp app for tsuru\"\n :author \"Nick Ricketts\"\n :license \"\"\n :depends-on (\"alexandria\" \"w",
"end": 130,
"score": 0.9998810291290283,
"start": 117,
"tag": "NAME",
"value": "Nick Ricketts"
}
] |
examples/lisp/example-tsuru-lisp-webapp.asd
|
jblancett/basebuilder
| 26 |
(asdf:defsystem #:example-tsuru-lisp-webapp
:serial t
:description "Example lisp app for tsuru"
:author "Nick Ricketts"
:license ""
:depends-on ("alexandria" "wookie")
:components ((:file "package")
(:file "web")))
|
12524
|
(asdf:defsystem #:example-tsuru-lisp-webapp
:serial t
:description "Example lisp app for tsuru"
:author "<NAME>"
:license ""
:depends-on ("alexandria" "wookie")
:components ((:file "package")
(:file "web")))
| true |
(asdf:defsystem #:example-tsuru-lisp-webapp
:serial t
:description "Example lisp app for tsuru"
:author "PI:NAME:<NAME>END_PI"
:license ""
:depends-on ("alexandria" "wookie")
:components ((:file "package")
(:file "web")))
|
[
{
"context": " core knowledge base.\n;;;\n;;; Author & Maintainer: Scott E. Fahlman\n;;; *********************************************",
"end": 241,
"score": 0.9998767971992493,
"start": 225,
"tag": "NAME",
"value": "Scott E. Fahlman"
}
] |
kb/core-components/simple-person-model.lisp
|
nondejus/scone
| 60 |
;;; -*- Mode:Lisp -*-
;;; ***************************************************************************
;;; Generic knowledge about people and their aspects for the Scone's
;;; core knowledge base.
;;;
;;; Author & Maintainer: Scott E. Fahlman
;;; ***************************************************************************
;;; Copyright (C) 2003-2014, Carnegie Mellon University.
;;;
;;; The Scone software is made available to the public under the
;;; Apache 2.0 open source license. A copy of this license is
;;; distributed with the software. The license can also be found at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0.
;;;
;;; Unless required by applicable law or agreed to in writing,
;;; software distributed under the License is distributed on an "AS
;;; IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
;;; express or implied. See the License for the specific language
;;; governing permissions and limitations under the License.
;;;
;;; Development since February 2013 has been supported in part by the
;;; U.S. Office of Naval Research under award number N000141310224.
;;;
;;; Development of Scone from January, 2012, through August 2013 was
;;; supported in part by the Intelligence Advanced Research Projects
;;; Activity (IARPA) via Department of Defense US Army Research
;;; Laboratory contract number W911NF-12-C-0020.
;;;
;;; Development of Scone from 2003 through 2008 was supported in part
;;; by the Defense Advanced Research Projects Agency (DARPA) under
;;; contract numbers NBCHD030010 and FA8750-07-D-0185.
;;;
;;; Additional support for Scone development has been provided by
;;; research grants from Cisco Systems Inc. and from Google Inc.
;;;
;;; The U.S. Government is authorized to reproduce and distribute
;;; reprints for Governmental purposes notwithstanding any copyright
;;; annotation thereon.
;;;
;;; Disclaimer: The views and conclusions contained herein are those
;;; of the authors and should not be interpreted as necessarily
;;; representing the official policies or endorsements, either
;;; expressed or implied, of IARPA, DoD/ARL, ONR, DARPA, the
;;; U.S. Government, or any of our other sponsors.
;;; ***************************************************************************
;;; General knowledge about people that you would want around for
;;; almost any "common sense" application.
;; Note: The {person} type and some other core knowledge about
;; parent/offspring relations are defined in the "simple-biology"
;; file.
;; Some subtypes of person.
(new-intersection-type {child}
'({person} {immature}))
(new-intersection-type {adult}
'({person} {mature}))
(new-intersection-type {boy}
'({child} {male}))
(new-intersection-type {girl}
'({child} {female}))
(new-intersection-type {man}
'({adult} {male}))
(new-intersection-type {woman}
'({adult} {female}))
(new-intersection-type {male person}
'({person} {male}))
(new-intersection-type {female person}
'({person} {female}))
;; Additional stuff about family relations. For now, we just
;; list relationships we may want to represent, and not all the
;; rules about "sister of parent is aunt", etc.
(new-type-role {relative} {person} {person})
(new-type-role {close relative} {person} {relative})
(new-type-role {medium relative} {person} {relative})
(new-type-role {distant relative} {person} {relative})
(new-type-role {blood relative} {person} {relative})
(new-type-role {relative by marriage} {person} {relative})
(new-intersection-type {close blood relative}
'({close relative} {blood relative}))
(new-intersection-type {medium blood relative}
'({medium relative} {blood relative}))
(new-is-a {parent} {close blood relative})
(new-is-a {offspring} {close blood relative})
(new-type-role {sibling} {person} {close blood relative} :may-have t)
(new-type-role {brother} {person} {sibling} :may-have t)
(new-is-a {brother} {male})
(new-type-role {sister} {person} {sibling} :may-have t)
(new-is-a {sister} {female})
(new-type-role {grandparent} {person} {close blood relative} :n 4)
(new-type-role {grandfather} {person} {grandparent} :n 2)
(new-is-a {grandfather} {man})
(new-type-role {grandmother} {person} {grandparent} :n 2)
(new-is-a {grandmother} {woman})
(new-type-role {grandchild} {person} {close blood relative} :may-have t)
(new-type-role {granddaughter} {person} {grandchild} :may-have t)
(new-is-a {granddaughter} {female})
(new-type-role {grandson} {person} {grandchild} :may-have t)
(new-is-a {grandson} {male})
(new-type-role {cousin} {person} {medium blood relative})
(new-type-role {aunt} {person} {medium blood relative})
(new-is-a {aunt} {female})
(new-type-role {uncle} {person} {medium blood relative})
(new-is-a {uncle} {male})
;; NOTE: The following stuff was initially developed for the RADAR
;; project at CMU, circa 2006, updated and re-formatted to match the
;; current Scone engine.
;; Parts of the person's name. For now, this is specific to
;; Anglo-American culture. So we really should put this into a
;; culture-specific context.
(new-indv-role {person full name} {person} {string}
:english '(:role "name" "full name"))
(new-indv-role {first name} {person}
{string}
:english '(:role "given name" "Christian name"))
(new-indv-role {last name} {person}
{string}
:english '(:role "family name" "surname"))
(new-indv-role {middle name} {person}
{string} :may-have t)
;; This is for stuff like "Sr.", "Jr.", "III", etc.
(new-indv-role {name suffix} {person}
{string} :may-have t
:english '(:role "suffix"))
;; This is for honorific titles such as "Professor" or
;; "Emperor". For now, this is just a string field, but we
;; probably should enumerate the common ones.
(new-indv-role {person title} {person}
{string}
:may-have t
:english '(:role "title" "honorific title"))
;; A person may have any number of alternative names. We
;; distinguish between nicknames and aliases, though the
;; difference depends on intent and can be fuzzy.
(new-type-role {alternative name} {person}
{string} :may-have t)
(new-type-role {nickname} {person}
{alternative name} :may-have t)
(new-type-role {alias} {person}
{alternative name} :may-have t)
;; A person may have an employer, which can be any legal entity --
;; that is, an organization or a person.
(new-indv-role {employer} {person}
{legal entity}
:may-have t)
;;; Addresses, home and business.
;;; Add functions to parse an address and relate to geographic
;;; regions or entities. For now it's just an uninterpreted string.
(new-type-role {person address} {person} {street address}
:english '(:role "address" "street address"
"mailing address" "physical mail address"
"postal address"))
(new-indv-role {home address} {person} {person address})
(new-indv-role {business address} {person} {person address})
;; Phone numbers.
(new-type-role {person phone number} {person}
{phone number}
:english '("phone number" "telephone number"))
(new-indv-role {primary phone number} {person}
{person phone number})
(new-indv-role {home phone number} {person}
{person phone number}
:may-have t)
(new-indv-role {cell phone number} {person}
{person phone number}
:may-have t
:english '("mobile phonbe number"))
(new-indv-role {business phone number} {person}
{person phone number}
:may-have t
:english '("office phone number"))
(new-indv-role {fax phone number} {person}
{person phone number} :may-have t
:english '("fax number"))
;;; Email address
(new-indv-role {person email address} {person}
{email address}
:english '(:role "Email address" "E-mail address"
"Email" "E-mail"))
;;; Personal web page.
(new-indv-role {personal web page} {person}
{url}
:english '(:role "url" "web page" "personal web page"
"home page"))
;;; Bio is some kind of text object, proibably a file or string.
(new-indv-role {biographical note} {person}
{text object} :may-have t
:english '(:role "bio" "biography" "biographical note"))
;;; A person may have one or more pictures.
(new-type-role {person picture} {person}
{image file} :may-have t
:english '(:role "picture" "photo" "mug shot"))
;;; Contact information is a collection of other roles.
(new-type-role {contact information} {person}
{string})
(new-is-a {person phone number} {contact information})
(new-is-a {person email address} {contact information})
(new-is-a {personal web page} {contact information})
(new-is-a {person address} {contact information})
;;; ------------------------------------------------------------------------
;;; Inter-Personal Relations
(new-relation {friend of}
:a-inst-of {person}
:b-inst-of {person}
:symmetric t)
(new-relation {co-worker of}
:a-inst-of {person}
:b-inst-of {person}
:symmetric t)
(new-relation {family member of}
:a-inst-of {person}
:b-inst-of {person}
:symmetric t)
;;; This may be either formal or informal status.
(new-relation {higher status than}
:a-inst-of {person}
:b-inst-of {person}
:transitive t
:english '(:relation
:inverse-relation "lower status than"))
;;; This is meant to be a formal ranking according to the rules of some
;;; hierarchical organization, such as the military or a university. It
;;; implies higher status.
(new-relation {higher rank than}
:parent {higher status than}
:a-inst-of {person}
:b-inst-of {person}
:transitive t)
(new-relation {reports to}
:parent {higher rank than}
:a-inst-of {person}
:b-inst-of {person})
;;; ------------------------------------------------------------------------
;;; Subtypes of Person
;; Some types of people you find around a university. (This is not
;; really core stuff, since it is only useful for certain specialized
;; applications, but we keep it here for now as an illustration of complex ranks
;; and positions within an organization.)
(new-type {university person} {person}
:english '(:adj-noun "academic"))
(new-split-subtypes
{university person}
'(({faculty member} :noun :adj "faculty")
({post-doc} "post-doctoral fellow" "post-doctoral research associate")
{visitor}
{student}
({staff member} :noun :adj "staff")))
;;; This type may overlap with faculty or staff.
(new-type {university administrator} {university person})
;;; Types of staff.
(new-split-subtypes {staff member}
'({technical staff member}
{administrative staff member}))
(new-split-subtypes
{technical staff member}
'(({staff programmer} "research programmer" "programmer")
{technical writer}
{data wrangler}
{user studies assistant}))
(new-split-subtypes
{administrative staff member}
'({departmental administrator}
({secretary} "executive assistant" "assistant")
{student coordinator}
{business manager}))
(new-split-subtypes
{student}
'(({undergraduate student} :adj-noun "undergradaute" "undergrad")
({graduate student} "grad student")
{special student}))
;;; Hierarchy of professitude.
(new-split-subtypes
{faculty member}
'(({professor-rank} :adj)
({associate-professor-rank} :adj)
({assistant-professor-rank} :adj)))
(new-statement {professor-rank}
{higher rank than}
{associate-professor-rank})
(new-statement {associate-professor-rank}
{higher rank than}
{assistant-professor-rank})
(new-statement {assistant-professor-rank}
{higher rank than}
{post-doc})
(new-statement {post-doc}
{higher rank than}
{graduate student})
(new-statement {graduate student}
{higher rank than}
{undergraduate student})
;;; NOTE: Some of the below is CMU-specific. Leave it that way for now.
;;; Ultimately this should be in a CMU context.
(new-split-subtypes {faculty member}
'({tenure-track faculty member}
{research faculty member}
{teaching faculty member}
{systems faculty member}))
(english {tenure-track faculty member}
:adj "tenure-track")
(english {research faculty member}
:adj "research" "research-track" :noun "research scientist")
(english {teaching faculty member}
:adj "teaching" "teaching-track" :noun "lecturer" )
(english {systems faculty member}
:adj "systems" "systems-track" :noun "systems scientist")
(new-intersection-type
{professor}
'({tenure-track faculty member} {professor-rank})
:english '("full professor"))
(new-intersection-type
{associate professor}
'({tenure-track faculty member} {associate-professor-rank}))
(new-intersection-type
{assistant professor}
'({tenure-track faculty member} {assistant-professor-rank}))
(new-intersection-type
{research professor}
'({research faculty member} {professor-rank})
:english '("resarch full professor" "full research professor"))
(new-intersection-type
{research associate professor}
'({research faculty member} {associate-professor-rank})
:english '("associate research professor"))
(new-intersection-type
{research scientist}
'({research faculty member} {assistant-professor-rank}))
(new-intersection-type
{teaching professor}
'({teaching faculty member} {professor-rank})
:english '("teaching full professor" "full teaching professor"))
(new-intersection-type
{teaching associate professor}
'({teaching faculty member} {associate-professor-rank})
:english '("associate teaching professor"))
(new-intersection-type
{lecturer}
'({teaching faculty member} {assistant-professor-rank}))
(new-intersection-type
{principal systems scientist}
'({systems faculty member} {professor-rank}))
(new-intersection-type
{senior systems scientist}
'({systems faculty member} {associate-professor-rank}))
(new-intersection-type
{systems scientist}
'({systems faculty member} {assistant-professor-rank}))
;;; End of RADAR-derived ontology.
|
4736
|
;;; -*- Mode:Lisp -*-
;;; ***************************************************************************
;;; Generic knowledge about people and their aspects for the Scone's
;;; core knowledge base.
;;;
;;; Author & Maintainer: <NAME>
;;; ***************************************************************************
;;; Copyright (C) 2003-2014, Carnegie Mellon University.
;;;
;;; The Scone software is made available to the public under the
;;; Apache 2.0 open source license. A copy of this license is
;;; distributed with the software. The license can also be found at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0.
;;;
;;; Unless required by applicable law or agreed to in writing,
;;; software distributed under the License is distributed on an "AS
;;; IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
;;; express or implied. See the License for the specific language
;;; governing permissions and limitations under the License.
;;;
;;; Development since February 2013 has been supported in part by the
;;; U.S. Office of Naval Research under award number N000141310224.
;;;
;;; Development of Scone from January, 2012, through August 2013 was
;;; supported in part by the Intelligence Advanced Research Projects
;;; Activity (IARPA) via Department of Defense US Army Research
;;; Laboratory contract number W911NF-12-C-0020.
;;;
;;; Development of Scone from 2003 through 2008 was supported in part
;;; by the Defense Advanced Research Projects Agency (DARPA) under
;;; contract numbers NBCHD030010 and FA8750-07-D-0185.
;;;
;;; Additional support for Scone development has been provided by
;;; research grants from Cisco Systems Inc. and from Google Inc.
;;;
;;; The U.S. Government is authorized to reproduce and distribute
;;; reprints for Governmental purposes notwithstanding any copyright
;;; annotation thereon.
;;;
;;; Disclaimer: The views and conclusions contained herein are those
;;; of the authors and should not be interpreted as necessarily
;;; representing the official policies or endorsements, either
;;; expressed or implied, of IARPA, DoD/ARL, ONR, DARPA, the
;;; U.S. Government, or any of our other sponsors.
;;; ***************************************************************************
;;; General knowledge about people that you would want around for
;;; almost any "common sense" application.
;; Note: The {person} type and some other core knowledge about
;; parent/offspring relations are defined in the "simple-biology"
;; file.
;; Some subtypes of person.
(new-intersection-type {child}
'({person} {immature}))
(new-intersection-type {adult}
'({person} {mature}))
(new-intersection-type {boy}
'({child} {male}))
(new-intersection-type {girl}
'({child} {female}))
(new-intersection-type {man}
'({adult} {male}))
(new-intersection-type {woman}
'({adult} {female}))
(new-intersection-type {male person}
'({person} {male}))
(new-intersection-type {female person}
'({person} {female}))
;; Additional stuff about family relations. For now, we just
;; list relationships we may want to represent, and not all the
;; rules about "sister of parent is aunt", etc.
(new-type-role {relative} {person} {person})
(new-type-role {close relative} {person} {relative})
(new-type-role {medium relative} {person} {relative})
(new-type-role {distant relative} {person} {relative})
(new-type-role {blood relative} {person} {relative})
(new-type-role {relative by marriage} {person} {relative})
(new-intersection-type {close blood relative}
'({close relative} {blood relative}))
(new-intersection-type {medium blood relative}
'({medium relative} {blood relative}))
(new-is-a {parent} {close blood relative})
(new-is-a {offspring} {close blood relative})
(new-type-role {sibling} {person} {close blood relative} :may-have t)
(new-type-role {brother} {person} {sibling} :may-have t)
(new-is-a {brother} {male})
(new-type-role {sister} {person} {sibling} :may-have t)
(new-is-a {sister} {female})
(new-type-role {grandparent} {person} {close blood relative} :n 4)
(new-type-role {grandfather} {person} {grandparent} :n 2)
(new-is-a {grandfather} {man})
(new-type-role {grandmother} {person} {grandparent} :n 2)
(new-is-a {grandmother} {woman})
(new-type-role {grandchild} {person} {close blood relative} :may-have t)
(new-type-role {granddaughter} {person} {grandchild} :may-have t)
(new-is-a {granddaughter} {female})
(new-type-role {grandson} {person} {grandchild} :may-have t)
(new-is-a {grandson} {male})
(new-type-role {cousin} {person} {medium blood relative})
(new-type-role {aunt} {person} {medium blood relative})
(new-is-a {aunt} {female})
(new-type-role {uncle} {person} {medium blood relative})
(new-is-a {uncle} {male})
;; NOTE: The following stuff was initially developed for the RADAR
;; project at CMU, circa 2006, updated and re-formatted to match the
;; current Scone engine.
;; Parts of the person's name. For now, this is specific to
;; Anglo-American culture. So we really should put this into a
;; culture-specific context.
(new-indv-role {person full name} {person} {string}
:english '(:role "name" "full name"))
(new-indv-role {first name} {person}
{string}
:english '(:role "given name" "Christian name"))
(new-indv-role {last name} {person}
{string}
:english '(:role "family name" "surname"))
(new-indv-role {middle name} {person}
{string} :may-have t)
;; This is for stuff like "Sr.", "Jr.", "III", etc.
(new-indv-role {name suffix} {person}
{string} :may-have t
:english '(:role "suffix"))
;; This is for honorific titles such as "Professor" or
;; "Emperor". For now, this is just a string field, but we
;; probably should enumerate the common ones.
(new-indv-role {person title} {person}
{string}
:may-have t
:english '(:role "title" "honorific title"))
;; A person may have any number of alternative names. We
;; distinguish between nicknames and aliases, though the
;; difference depends on intent and can be fuzzy.
(new-type-role {alternative name} {person}
{string} :may-have t)
(new-type-role {nickname} {person}
{alternative name} :may-have t)
(new-type-role {alias} {person}
{alternative name} :may-have t)
;; A person may have an employer, which can be any legal entity --
;; that is, an organization or a person.
(new-indv-role {employer} {person}
{legal entity}
:may-have t)
;;; Addresses, home and business.
;;; Add functions to parse an address and relate to geographic
;;; regions or entities. For now it's just an uninterpreted string.
(new-type-role {person address} {person} {street address}
:english '(:role "address" "street address"
"mailing address" "physical mail address"
"postal address"))
(new-indv-role {home address} {person} {person address})
(new-indv-role {business address} {person} {person address})
;; Phone numbers.
(new-type-role {person phone number} {person}
{phone number}
:english '("phone number" "telephone number"))
(new-indv-role {primary phone number} {person}
{person phone number})
(new-indv-role {home phone number} {person}
{person phone number}
:may-have t)
(new-indv-role {cell phone number} {person}
{person phone number}
:may-have t
:english '("mobile phonbe number"))
(new-indv-role {business phone number} {person}
{person phone number}
:may-have t
:english '("office phone number"))
(new-indv-role {fax phone number} {person}
{person phone number} :may-have t
:english '("fax number"))
;;; Email address
(new-indv-role {person email address} {person}
{email address}
:english '(:role "Email address" "E-mail address"
"Email" "E-mail"))
;;; Personal web page.
(new-indv-role {personal web page} {person}
{url}
:english '(:role "url" "web page" "personal web page"
"home page"))
;;; Bio is some kind of text object, proibably a file or string.
(new-indv-role {biographical note} {person}
{text object} :may-have t
:english '(:role "bio" "biography" "biographical note"))
;;; A person may have one or more pictures.
(new-type-role {person picture} {person}
{image file} :may-have t
:english '(:role "picture" "photo" "mug shot"))
;;; Contact information is a collection of other roles.
(new-type-role {contact information} {person}
{string})
(new-is-a {person phone number} {contact information})
(new-is-a {person email address} {contact information})
(new-is-a {personal web page} {contact information})
(new-is-a {person address} {contact information})
;;; ------------------------------------------------------------------------
;;; Inter-Personal Relations
(new-relation {friend of}
:a-inst-of {person}
:b-inst-of {person}
:symmetric t)
(new-relation {co-worker of}
:a-inst-of {person}
:b-inst-of {person}
:symmetric t)
(new-relation {family member of}
:a-inst-of {person}
:b-inst-of {person}
:symmetric t)
;;; This may be either formal or informal status.
(new-relation {higher status than}
:a-inst-of {person}
:b-inst-of {person}
:transitive t
:english '(:relation
:inverse-relation "lower status than"))
;;; This is meant to be a formal ranking according to the rules of some
;;; hierarchical organization, such as the military or a university. It
;;; implies higher status.
(new-relation {higher rank than}
:parent {higher status than}
:a-inst-of {person}
:b-inst-of {person}
:transitive t)
(new-relation {reports to}
:parent {higher rank than}
:a-inst-of {person}
:b-inst-of {person})
;;; ------------------------------------------------------------------------
;;; Subtypes of Person
;; Some types of people you find around a university. (This is not
;; really core stuff, since it is only useful for certain specialized
;; applications, but we keep it here for now as an illustration of complex ranks
;; and positions within an organization.)
(new-type {university person} {person}
:english '(:adj-noun "academic"))
(new-split-subtypes
{university person}
'(({faculty member} :noun :adj "faculty")
({post-doc} "post-doctoral fellow" "post-doctoral research associate")
{visitor}
{student}
({staff member} :noun :adj "staff")))
;;; This type may overlap with faculty or staff.
(new-type {university administrator} {university person})
;;; Types of staff.
(new-split-subtypes {staff member}
'({technical staff member}
{administrative staff member}))
(new-split-subtypes
{technical staff member}
'(({staff programmer} "research programmer" "programmer")
{technical writer}
{data wrangler}
{user studies assistant}))
(new-split-subtypes
{administrative staff member}
'({departmental administrator}
({secretary} "executive assistant" "assistant")
{student coordinator}
{business manager}))
(new-split-subtypes
{student}
'(({undergraduate student} :adj-noun "undergradaute" "undergrad")
({graduate student} "grad student")
{special student}))
;;; Hierarchy of professitude.
(new-split-subtypes
{faculty member}
'(({professor-rank} :adj)
({associate-professor-rank} :adj)
({assistant-professor-rank} :adj)))
(new-statement {professor-rank}
{higher rank than}
{associate-professor-rank})
(new-statement {associate-professor-rank}
{higher rank than}
{assistant-professor-rank})
(new-statement {assistant-professor-rank}
{higher rank than}
{post-doc})
(new-statement {post-doc}
{higher rank than}
{graduate student})
(new-statement {graduate student}
{higher rank than}
{undergraduate student})
;;; NOTE: Some of the below is CMU-specific. Leave it that way for now.
;;; Ultimately this should be in a CMU context.
(new-split-subtypes {faculty member}
'({tenure-track faculty member}
{research faculty member}
{teaching faculty member}
{systems faculty member}))
(english {tenure-track faculty member}
:adj "tenure-track")
(english {research faculty member}
:adj "research" "research-track" :noun "research scientist")
(english {teaching faculty member}
:adj "teaching" "teaching-track" :noun "lecturer" )
(english {systems faculty member}
:adj "systems" "systems-track" :noun "systems scientist")
(new-intersection-type
{professor}
'({tenure-track faculty member} {professor-rank})
:english '("full professor"))
(new-intersection-type
{associate professor}
'({tenure-track faculty member} {associate-professor-rank}))
(new-intersection-type
{assistant professor}
'({tenure-track faculty member} {assistant-professor-rank}))
(new-intersection-type
{research professor}
'({research faculty member} {professor-rank})
:english '("resarch full professor" "full research professor"))
(new-intersection-type
{research associate professor}
'({research faculty member} {associate-professor-rank})
:english '("associate research professor"))
(new-intersection-type
{research scientist}
'({research faculty member} {assistant-professor-rank}))
(new-intersection-type
{teaching professor}
'({teaching faculty member} {professor-rank})
:english '("teaching full professor" "full teaching professor"))
(new-intersection-type
{teaching associate professor}
'({teaching faculty member} {associate-professor-rank})
:english '("associate teaching professor"))
(new-intersection-type
{lecturer}
'({teaching faculty member} {assistant-professor-rank}))
(new-intersection-type
{principal systems scientist}
'({systems faculty member} {professor-rank}))
(new-intersection-type
{senior systems scientist}
'({systems faculty member} {associate-professor-rank}))
(new-intersection-type
{systems scientist}
'({systems faculty member} {assistant-professor-rank}))
;;; End of RADAR-derived ontology.
| true |
;;; -*- Mode:Lisp -*-
;;; ***************************************************************************
;;; Generic knowledge about people and their aspects for the Scone's
;;; core knowledge base.
;;;
;;; Author & Maintainer: PI:NAME:<NAME>END_PI
;;; ***************************************************************************
;;; Copyright (C) 2003-2014, Carnegie Mellon University.
;;;
;;; The Scone software is made available to the public under the
;;; Apache 2.0 open source license. A copy of this license is
;;; distributed with the software. The license can also be found at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0.
;;;
;;; Unless required by applicable law or agreed to in writing,
;;; software distributed under the License is distributed on an "AS
;;; IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
;;; express or implied. See the License for the specific language
;;; governing permissions and limitations under the License.
;;;
;;; Development since February 2013 has been supported in part by the
;;; U.S. Office of Naval Research under award number N000141310224.
;;;
;;; Development of Scone from January, 2012, through August 2013 was
;;; supported in part by the Intelligence Advanced Research Projects
;;; Activity (IARPA) via Department of Defense US Army Research
;;; Laboratory contract number W911NF-12-C-0020.
;;;
;;; Development of Scone from 2003 through 2008 was supported in part
;;; by the Defense Advanced Research Projects Agency (DARPA) under
;;; contract numbers NBCHD030010 and FA8750-07-D-0185.
;;;
;;; Additional support for Scone development has been provided by
;;; research grants from Cisco Systems Inc. and from Google Inc.
;;;
;;; The U.S. Government is authorized to reproduce and distribute
;;; reprints for Governmental purposes notwithstanding any copyright
;;; annotation thereon.
;;;
;;; Disclaimer: The views and conclusions contained herein are those
;;; of the authors and should not be interpreted as necessarily
;;; representing the official policies or endorsements, either
;;; expressed or implied, of IARPA, DoD/ARL, ONR, DARPA, the
;;; U.S. Government, or any of our other sponsors.
;;; ***************************************************************************
;;; General knowledge about people that you would want around for
;;; almost any "common sense" application.
;; Note: The {person} type and some other core knowledge about
;; parent/offspring relations are defined in the "simple-biology"
;; file.
;; Some subtypes of person.
(new-intersection-type {child}
'({person} {immature}))
(new-intersection-type {adult}
'({person} {mature}))
(new-intersection-type {boy}
'({child} {male}))
(new-intersection-type {girl}
'({child} {female}))
(new-intersection-type {man}
'({adult} {male}))
(new-intersection-type {woman}
'({adult} {female}))
(new-intersection-type {male person}
'({person} {male}))
(new-intersection-type {female person}
'({person} {female}))
;; Additional stuff about family relations. For now, we just
;; list relationships we may want to represent, and not all the
;; rules about "sister of parent is aunt", etc.
(new-type-role {relative} {person} {person})
(new-type-role {close relative} {person} {relative})
(new-type-role {medium relative} {person} {relative})
(new-type-role {distant relative} {person} {relative})
(new-type-role {blood relative} {person} {relative})
(new-type-role {relative by marriage} {person} {relative})
(new-intersection-type {close blood relative}
'({close relative} {blood relative}))
(new-intersection-type {medium blood relative}
'({medium relative} {blood relative}))
(new-is-a {parent} {close blood relative})
(new-is-a {offspring} {close blood relative})
(new-type-role {sibling} {person} {close blood relative} :may-have t)
(new-type-role {brother} {person} {sibling} :may-have t)
(new-is-a {brother} {male})
(new-type-role {sister} {person} {sibling} :may-have t)
(new-is-a {sister} {female})
(new-type-role {grandparent} {person} {close blood relative} :n 4)
(new-type-role {grandfather} {person} {grandparent} :n 2)
(new-is-a {grandfather} {man})
(new-type-role {grandmother} {person} {grandparent} :n 2)
(new-is-a {grandmother} {woman})
(new-type-role {grandchild} {person} {close blood relative} :may-have t)
(new-type-role {granddaughter} {person} {grandchild} :may-have t)
(new-is-a {granddaughter} {female})
(new-type-role {grandson} {person} {grandchild} :may-have t)
(new-is-a {grandson} {male})
(new-type-role {cousin} {person} {medium blood relative})
(new-type-role {aunt} {person} {medium blood relative})
(new-is-a {aunt} {female})
(new-type-role {uncle} {person} {medium blood relative})
(new-is-a {uncle} {male})
;; NOTE: The following stuff was initially developed for the RADAR
;; project at CMU, circa 2006, updated and re-formatted to match the
;; current Scone engine.
;; Parts of the person's name. For now, this is specific to
;; Anglo-American culture. So we really should put this into a
;; culture-specific context.
(new-indv-role {person full name} {person} {string}
:english '(:role "name" "full name"))
(new-indv-role {first name} {person}
{string}
:english '(:role "given name" "Christian name"))
(new-indv-role {last name} {person}
{string}
:english '(:role "family name" "surname"))
(new-indv-role {middle name} {person}
{string} :may-have t)
;; This is for stuff like "Sr.", "Jr.", "III", etc.
(new-indv-role {name suffix} {person}
{string} :may-have t
:english '(:role "suffix"))
;; This is for honorific titles such as "Professor" or
;; "Emperor". For now, this is just a string field, but we
;; probably should enumerate the common ones.
(new-indv-role {person title} {person}
{string}
:may-have t
:english '(:role "title" "honorific title"))
;; A person may have any number of alternative names. We
;; distinguish between nicknames and aliases, though the
;; difference depends on intent and can be fuzzy.
(new-type-role {alternative name} {person}
{string} :may-have t)
(new-type-role {nickname} {person}
{alternative name} :may-have t)
(new-type-role {alias} {person}
{alternative name} :may-have t)
;; A person may have an employer, which can be any legal entity --
;; that is, an organization or a person.
(new-indv-role {employer} {person}
{legal entity}
:may-have t)
;;; Addresses, home and business.
;;; Add functions to parse an address and relate to geographic
;;; regions or entities. For now it's just an uninterpreted string.
(new-type-role {person address} {person} {street address}
:english '(:role "address" "street address"
"mailing address" "physical mail address"
"postal address"))
(new-indv-role {home address} {person} {person address})
(new-indv-role {business address} {person} {person address})
;; Phone numbers.
(new-type-role {person phone number} {person}
{phone number}
:english '("phone number" "telephone number"))
(new-indv-role {primary phone number} {person}
{person phone number})
(new-indv-role {home phone number} {person}
{person phone number}
:may-have t)
(new-indv-role {cell phone number} {person}
{person phone number}
:may-have t
:english '("mobile phonbe number"))
(new-indv-role {business phone number} {person}
{person phone number}
:may-have t
:english '("office phone number"))
(new-indv-role {fax phone number} {person}
{person phone number} :may-have t
:english '("fax number"))
;;; Email address
(new-indv-role {person email address} {person}
{email address}
:english '(:role "Email address" "E-mail address"
"Email" "E-mail"))
;;; Personal web page.
(new-indv-role {personal web page} {person}
{url}
:english '(:role "url" "web page" "personal web page"
"home page"))
;;; Bio is some kind of text object, proibably a file or string.
(new-indv-role {biographical note} {person}
{text object} :may-have t
:english '(:role "bio" "biography" "biographical note"))
;;; A person may have one or more pictures.
(new-type-role {person picture} {person}
{image file} :may-have t
:english '(:role "picture" "photo" "mug shot"))
;;; Contact information is a collection of other roles.
(new-type-role {contact information} {person}
{string})
(new-is-a {person phone number} {contact information})
(new-is-a {person email address} {contact information})
(new-is-a {personal web page} {contact information})
(new-is-a {person address} {contact information})
;;; ------------------------------------------------------------------------
;;; Inter-Personal Relations
(new-relation {friend of}
:a-inst-of {person}
:b-inst-of {person}
:symmetric t)
(new-relation {co-worker of}
:a-inst-of {person}
:b-inst-of {person}
:symmetric t)
(new-relation {family member of}
:a-inst-of {person}
:b-inst-of {person}
:symmetric t)
;;; This may be either formal or informal status.
(new-relation {higher status than}
:a-inst-of {person}
:b-inst-of {person}
:transitive t
:english '(:relation
:inverse-relation "lower status than"))
;;; This is meant to be a formal ranking according to the rules of some
;;; hierarchical organization, such as the military or a university. It
;;; implies higher status.
(new-relation {higher rank than}
:parent {higher status than}
:a-inst-of {person}
:b-inst-of {person}
:transitive t)
(new-relation {reports to}
:parent {higher rank than}
:a-inst-of {person}
:b-inst-of {person})
;;; ------------------------------------------------------------------------
;;; Subtypes of Person
;; Some types of people you find around a university. (This is not
;; really core stuff, since it is only useful for certain specialized
;; applications, but we keep it here for now as an illustration of complex ranks
;; and positions within an organization.)
(new-type {university person} {person}
:english '(:adj-noun "academic"))
(new-split-subtypes
{university person}
'(({faculty member} :noun :adj "faculty")
({post-doc} "post-doctoral fellow" "post-doctoral research associate")
{visitor}
{student}
({staff member} :noun :adj "staff")))
;;; This type may overlap with faculty or staff.
(new-type {university administrator} {university person})
;;; Types of staff.
(new-split-subtypes {staff member}
'({technical staff member}
{administrative staff member}))
(new-split-subtypes
{technical staff member}
'(({staff programmer} "research programmer" "programmer")
{technical writer}
{data wrangler}
{user studies assistant}))
(new-split-subtypes
{administrative staff member}
'({departmental administrator}
({secretary} "executive assistant" "assistant")
{student coordinator}
{business manager}))
(new-split-subtypes
{student}
'(({undergraduate student} :adj-noun "undergradaute" "undergrad")
({graduate student} "grad student")
{special student}))
;;; Hierarchy of professitude.
(new-split-subtypes
{faculty member}
'(({professor-rank} :adj)
({associate-professor-rank} :adj)
({assistant-professor-rank} :adj)))
(new-statement {professor-rank}
{higher rank than}
{associate-professor-rank})
(new-statement {associate-professor-rank}
{higher rank than}
{assistant-professor-rank})
(new-statement {assistant-professor-rank}
{higher rank than}
{post-doc})
(new-statement {post-doc}
{higher rank than}
{graduate student})
(new-statement {graduate student}
{higher rank than}
{undergraduate student})
;;; NOTE: Some of the below is CMU-specific. Leave it that way for now.
;;; Ultimately this should be in a CMU context.
(new-split-subtypes {faculty member}
'({tenure-track faculty member}
{research faculty member}
{teaching faculty member}
{systems faculty member}))
(english {tenure-track faculty member}
:adj "tenure-track")
(english {research faculty member}
:adj "research" "research-track" :noun "research scientist")
(english {teaching faculty member}
:adj "teaching" "teaching-track" :noun "lecturer" )
(english {systems faculty member}
:adj "systems" "systems-track" :noun "systems scientist")
(new-intersection-type
{professor}
'({tenure-track faculty member} {professor-rank})
:english '("full professor"))
(new-intersection-type
{associate professor}
'({tenure-track faculty member} {associate-professor-rank}))
(new-intersection-type
{assistant professor}
'({tenure-track faculty member} {assistant-professor-rank}))
(new-intersection-type
{research professor}
'({research faculty member} {professor-rank})
:english '("resarch full professor" "full research professor"))
(new-intersection-type
{research associate professor}
'({research faculty member} {associate-professor-rank})
:english '("associate research professor"))
(new-intersection-type
{research scientist}
'({research faculty member} {assistant-professor-rank}))
(new-intersection-type
{teaching professor}
'({teaching faculty member} {professor-rank})
:english '("teaching full professor" "full teaching professor"))
(new-intersection-type
{teaching associate professor}
'({teaching faculty member} {associate-professor-rank})
:english '("associate teaching professor"))
(new-intersection-type
{lecturer}
'({teaching faculty member} {assistant-professor-rank}))
(new-intersection-type
{principal systems scientist}
'({systems faculty member} {professor-rank}))
(new-intersection-type
{senior systems scientist}
'({systems faculty member} {associate-professor-rank}))
(new-intersection-type
{systems scientist}
'({systems faculty member} {assistant-professor-rank}))
;;; End of RADAR-derived ontology.
|
[
{
"context": "; DEALINGS IN THE SOFTWARE.\n;\n; Original author: Jared Davis <[email protected]>\n\n(in-package \"VL\")\n(include-",
"end": 1390,
"score": 0.9995430111885071,
"start": 1379,
"tag": "NAME",
"value": "Jared Davis"
},
{
"context": "N THE SOFTWARE.\n;\n; Original author: Jared Davis <[email protected]>\n\n(in-package \"VL\")\n(include-book \"../mlib/clean-",
"end": 1410,
"score": 0.9999338984489441,
"start": 1392,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/centaur/vl/transforms/xf-clean-selects.lisp
|
ragerdl/acl2-defthm-rc2
| 0 |
; VL Verilog Toolkit
; Copyright (C) 2008-2014 Centaur Technology
;
; Contact:
; Centaur Technology Formal Verification Group
; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA.
; http://www.centtech.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: Jared Davis <[email protected]>
(in-package "VL")
(include-book "../mlib/clean-concats")
(include-book "../mlib/stmt-tools")
(local (include-book "../util/arithmetic"))
(local (std::add-default-post-define-hook :fix))
(defxdoc clean-selects
:parents (transforms)
:short "Simplify concatenations and selects throughout a module."
:long "<p>This is a mainly aesthetic transform that applies @(see
vl-expr-clean-selects) throughout modules. This may help to make certain
concatenation and select expressions more readable.</p>
<p>Implementation-wise, this is the usual boilerplate to extend @(see
vl-expr-clean-selects) through the parse tree, except that we aren't going to
go through ranges: we only do this in assignments, instances, and statements,
where we expect to see wires.</p>")
(local (xdoc::set-default-parents clean-selects))
(defmacro def-vl-clean-selects (name &key type body)
`(define ,name ((x ,type)
(mod vl-module-p)
(ialist (equal ialist (vl-moditem-alist mod))))
:returns (new-x ,type)
(declare (ignorable x mod ialist))
,body))
(defmacro def-vl-clean-selects-list (name &key type element)
`(defprojection ,name ((x ,type)
(mod vl-module-p)
(ialist (equal ialist (vl-moditem-alist mod))))
:returns (new-x ,type)
(,element x mod ialist)))
(def-vl-clean-selects vl-maybe-expr-clean-selects
:type vl-maybe-expr-p
:body (and x (vl-expr-clean-selects x mod ialist)))
(def-vl-clean-selects vl-port-clean-selects
:type vl-port-p
:body (b* (((vl-port x) x))
(change-vl-port x :expr (vl-maybe-expr-clean-selects x.expr mod ialist))))
(def-vl-clean-selects-list vl-portlist-clean-selects
:type vl-portlist-p
:element vl-port-clean-selects)
(def-vl-clean-selects vl-assign-clean-selects
:type vl-assign-p
:body (b* (((vl-assign x) x))
(change-vl-assign x
:lvalue (vl-expr-clean-selects x.lvalue mod ialist)
:expr (vl-expr-clean-selects x.expr mod ialist))))
(def-vl-clean-selects-list vl-assignlist-clean-selects
:type vl-assignlist-p
:element vl-assign-clean-selects)
(def-vl-clean-selects vl-plainarg-clean-selects
:type vl-plainarg-p
:body (b* (((vl-plainarg x) x))
(change-vl-plainarg x
:expr (vl-maybe-expr-clean-selects x.expr mod ialist))))
(def-vl-clean-selects-list vl-plainarglist-clean-selects
:type vl-plainarglist-p
:element vl-plainarg-clean-selects)
(def-vl-clean-selects vl-namedarg-clean-selects
:type vl-namedarg-p
:body (b* (((vl-namedarg x) x))
(change-vl-namedarg x
:expr (vl-maybe-expr-clean-selects x.expr mod ialist))))
(def-vl-clean-selects-list vl-namedarglist-clean-selects
:type vl-namedarglist-p
:element vl-namedarg-clean-selects)
(def-vl-clean-selects vl-arguments-clean-selects
:type vl-arguments-p
:body (vl-arguments-case x
:vl-arguments-named
(make-vl-arguments-named :args (vl-namedarglist-clean-selects x.args mod ialist))
:vl-arguments-plain
(make-vl-arguments-plain :args (vl-plainarglist-clean-selects x.args mod ialist))))
(def-vl-clean-selects vl-modinst-clean-selects
:type vl-modinst-p
:body (b* (((vl-modinst x) x))
(change-vl-modinst x
:portargs (vl-arguments-clean-selects x.portargs mod ialist))))
(def-vl-clean-selects-list vl-modinstlist-clean-selects
:type vl-modinstlist-p
:element vl-modinst-clean-selects)
(def-vl-clean-selects vl-gateinst-clean-selects
:type vl-gateinst-p
:body (b* (((vl-gateinst x) x))
(change-vl-gateinst x
:args (vl-plainarglist-clean-selects x.args mod ialist))))
(def-vl-clean-selects-list vl-gateinstlist-clean-selects
:type vl-gateinstlist-p
:element vl-gateinst-clean-selects)
(defines vl-stmt-clean-selects
:parents (clean-selects)
(define vl-stmt-clean-selects ((x vl-stmt-p)
(mod vl-module-p)
(ialist (equal ialist (vl-moditem-alist mod))))
:returns (new-x vl-stmt-p)
:measure (vl-stmt-count x)
:verify-guards nil
(b* ((x (vl-stmt-fix x))
((when (vl-atomicstmt-p x))
(case (vl-stmt-kind x)
(:vl-nullstmt
x)
(:vl-assignstmt
(b* (((vl-assignstmt x) x))
(change-vl-assignstmt x
:lvalue (vl-expr-clean-selects x.lvalue mod ialist)
:expr (vl-expr-clean-selects x.expr mod ialist))))
(:vl-deassignstmt
(b* (((vl-deassignstmt x) x))
(change-vl-deassignstmt x
:lvalue (vl-expr-clean-selects x.lvalue mod ialist))))
(:vl-enablestmt
(b* (((vl-enablestmt x) x))
(change-vl-enablestmt x
:args (vl-exprlist-clean-selects x.args mod ialist))))
(:vl-disablestmt
x)
(otherwise
;; event trigger statement
x)))
(exprs (vl-exprlist-clean-selects (vl-compoundstmt->exprs x) mod ialist))
(stmts (vl-stmtlist-clean-selects (vl-compoundstmt->stmts x) mod ialist)))
(change-vl-compoundstmt x :exprs exprs :stmts stmts)))
(define vl-stmtlist-clean-selects ((x vl-stmtlist-p)
(mod vl-module-p)
(ialist (equal ialist (vl-moditem-alist mod))))
:returns (new-x (and (vl-stmtlist-p new-x)
(equal (len new-x) (len x))))
:measure (vl-stmtlist-count x)
(if (consp x)
(cons (vl-stmt-clean-selects (car x) mod ialist)
(vl-stmtlist-clean-selects (cdr x) mod ialist))
nil))
///
(verify-guards vl-stmt-clean-selects)
(deffixequiv-mutual vl-stmt-clean-selects)
(defprojection vl-stmtlist-clean-selects (x mod ialist)
(vl-stmt-clean-selects x mod ialist)
:already-definedp t))
(def-vl-clean-selects vl-always-clean-selects
:type vl-always-p
:body (b* (((vl-always x) x))
(change-vl-always x
:stmt (vl-stmt-clean-selects x.stmt mod ialist))))
(def-vl-clean-selects-list vl-alwayslist-clean-selects
:type vl-alwayslist-p
:element vl-always-clean-selects)
(def-vl-clean-selects vl-initial-clean-selects
:type vl-initial-p
:body (b* (((vl-initial x) x))
(change-vl-initial x
:stmt (vl-stmt-clean-selects x.stmt mod ialist))))
(def-vl-clean-selects-list vl-initiallist-clean-selects
:type vl-initiallist-p
:element vl-initial-clean-selects)
(define vl-module-clean-selects ((x vl-module-p))
:returns (new-x vl-module-p)
(b* ((x (vl-module-fix x))
((vl-module x) x)
((when (vl-module->hands-offp x))
x)
(ialist (vl-moditem-alist x))
(ans (change-vl-module
x
:ports (vl-portlist-clean-selects x.ports x ialist)
:assigns (vl-assignlist-clean-selects x.assigns x ialist)
:modinsts (vl-modinstlist-clean-selects x.modinsts x ialist)
:gateinsts (vl-gateinstlist-clean-selects x.gateinsts x ialist)
:alwayses (vl-alwayslist-clean-selects x.alwayses x ialist)
:initials (vl-initiallist-clean-selects x.initials x ialist))))
(fast-alist-free ialist)
ans))
(defprojection vl-modulelist-clean-selects ((x vl-modulelist-p))
:returns (new-x vl-modulelist-p)
(vl-module-clean-selects x))
(define vl-design-clean-selects ((x vl-design-p))
:short "Top-level @(see clean-selects) transform."
(b* (((vl-design x) x))
(change-vl-design x :mods (vl-modulelist-clean-selects x.mods))))
|
65406
|
; VL Verilog Toolkit
; Copyright (C) 2008-2014 Centaur Technology
;
; Contact:
; Centaur Technology Formal Verification Group
; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA.
; http://www.centtech.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: <NAME> <<EMAIL>>
(in-package "VL")
(include-book "../mlib/clean-concats")
(include-book "../mlib/stmt-tools")
(local (include-book "../util/arithmetic"))
(local (std::add-default-post-define-hook :fix))
(defxdoc clean-selects
:parents (transforms)
:short "Simplify concatenations and selects throughout a module."
:long "<p>This is a mainly aesthetic transform that applies @(see
vl-expr-clean-selects) throughout modules. This may help to make certain
concatenation and select expressions more readable.</p>
<p>Implementation-wise, this is the usual boilerplate to extend @(see
vl-expr-clean-selects) through the parse tree, except that we aren't going to
go through ranges: we only do this in assignments, instances, and statements,
where we expect to see wires.</p>")
(local (xdoc::set-default-parents clean-selects))
(defmacro def-vl-clean-selects (name &key type body)
`(define ,name ((x ,type)
(mod vl-module-p)
(ialist (equal ialist (vl-moditem-alist mod))))
:returns (new-x ,type)
(declare (ignorable x mod ialist))
,body))
(defmacro def-vl-clean-selects-list (name &key type element)
`(defprojection ,name ((x ,type)
(mod vl-module-p)
(ialist (equal ialist (vl-moditem-alist mod))))
:returns (new-x ,type)
(,element x mod ialist)))
(def-vl-clean-selects vl-maybe-expr-clean-selects
:type vl-maybe-expr-p
:body (and x (vl-expr-clean-selects x mod ialist)))
(def-vl-clean-selects vl-port-clean-selects
:type vl-port-p
:body (b* (((vl-port x) x))
(change-vl-port x :expr (vl-maybe-expr-clean-selects x.expr mod ialist))))
(def-vl-clean-selects-list vl-portlist-clean-selects
:type vl-portlist-p
:element vl-port-clean-selects)
(def-vl-clean-selects vl-assign-clean-selects
:type vl-assign-p
:body (b* (((vl-assign x) x))
(change-vl-assign x
:lvalue (vl-expr-clean-selects x.lvalue mod ialist)
:expr (vl-expr-clean-selects x.expr mod ialist))))
(def-vl-clean-selects-list vl-assignlist-clean-selects
:type vl-assignlist-p
:element vl-assign-clean-selects)
(def-vl-clean-selects vl-plainarg-clean-selects
:type vl-plainarg-p
:body (b* (((vl-plainarg x) x))
(change-vl-plainarg x
:expr (vl-maybe-expr-clean-selects x.expr mod ialist))))
(def-vl-clean-selects-list vl-plainarglist-clean-selects
:type vl-plainarglist-p
:element vl-plainarg-clean-selects)
(def-vl-clean-selects vl-namedarg-clean-selects
:type vl-namedarg-p
:body (b* (((vl-namedarg x) x))
(change-vl-namedarg x
:expr (vl-maybe-expr-clean-selects x.expr mod ialist))))
(def-vl-clean-selects-list vl-namedarglist-clean-selects
:type vl-namedarglist-p
:element vl-namedarg-clean-selects)
(def-vl-clean-selects vl-arguments-clean-selects
:type vl-arguments-p
:body (vl-arguments-case x
:vl-arguments-named
(make-vl-arguments-named :args (vl-namedarglist-clean-selects x.args mod ialist))
:vl-arguments-plain
(make-vl-arguments-plain :args (vl-plainarglist-clean-selects x.args mod ialist))))
(def-vl-clean-selects vl-modinst-clean-selects
:type vl-modinst-p
:body (b* (((vl-modinst x) x))
(change-vl-modinst x
:portargs (vl-arguments-clean-selects x.portargs mod ialist))))
(def-vl-clean-selects-list vl-modinstlist-clean-selects
:type vl-modinstlist-p
:element vl-modinst-clean-selects)
(def-vl-clean-selects vl-gateinst-clean-selects
:type vl-gateinst-p
:body (b* (((vl-gateinst x) x))
(change-vl-gateinst x
:args (vl-plainarglist-clean-selects x.args mod ialist))))
(def-vl-clean-selects-list vl-gateinstlist-clean-selects
:type vl-gateinstlist-p
:element vl-gateinst-clean-selects)
(defines vl-stmt-clean-selects
:parents (clean-selects)
(define vl-stmt-clean-selects ((x vl-stmt-p)
(mod vl-module-p)
(ialist (equal ialist (vl-moditem-alist mod))))
:returns (new-x vl-stmt-p)
:measure (vl-stmt-count x)
:verify-guards nil
(b* ((x (vl-stmt-fix x))
((when (vl-atomicstmt-p x))
(case (vl-stmt-kind x)
(:vl-nullstmt
x)
(:vl-assignstmt
(b* (((vl-assignstmt x) x))
(change-vl-assignstmt x
:lvalue (vl-expr-clean-selects x.lvalue mod ialist)
:expr (vl-expr-clean-selects x.expr mod ialist))))
(:vl-deassignstmt
(b* (((vl-deassignstmt x) x))
(change-vl-deassignstmt x
:lvalue (vl-expr-clean-selects x.lvalue mod ialist))))
(:vl-enablestmt
(b* (((vl-enablestmt x) x))
(change-vl-enablestmt x
:args (vl-exprlist-clean-selects x.args mod ialist))))
(:vl-disablestmt
x)
(otherwise
;; event trigger statement
x)))
(exprs (vl-exprlist-clean-selects (vl-compoundstmt->exprs x) mod ialist))
(stmts (vl-stmtlist-clean-selects (vl-compoundstmt->stmts x) mod ialist)))
(change-vl-compoundstmt x :exprs exprs :stmts stmts)))
(define vl-stmtlist-clean-selects ((x vl-stmtlist-p)
(mod vl-module-p)
(ialist (equal ialist (vl-moditem-alist mod))))
:returns (new-x (and (vl-stmtlist-p new-x)
(equal (len new-x) (len x))))
:measure (vl-stmtlist-count x)
(if (consp x)
(cons (vl-stmt-clean-selects (car x) mod ialist)
(vl-stmtlist-clean-selects (cdr x) mod ialist))
nil))
///
(verify-guards vl-stmt-clean-selects)
(deffixequiv-mutual vl-stmt-clean-selects)
(defprojection vl-stmtlist-clean-selects (x mod ialist)
(vl-stmt-clean-selects x mod ialist)
:already-definedp t))
(def-vl-clean-selects vl-always-clean-selects
:type vl-always-p
:body (b* (((vl-always x) x))
(change-vl-always x
:stmt (vl-stmt-clean-selects x.stmt mod ialist))))
(def-vl-clean-selects-list vl-alwayslist-clean-selects
:type vl-alwayslist-p
:element vl-always-clean-selects)
(def-vl-clean-selects vl-initial-clean-selects
:type vl-initial-p
:body (b* (((vl-initial x) x))
(change-vl-initial x
:stmt (vl-stmt-clean-selects x.stmt mod ialist))))
(def-vl-clean-selects-list vl-initiallist-clean-selects
:type vl-initiallist-p
:element vl-initial-clean-selects)
(define vl-module-clean-selects ((x vl-module-p))
:returns (new-x vl-module-p)
(b* ((x (vl-module-fix x))
((vl-module x) x)
((when (vl-module->hands-offp x))
x)
(ialist (vl-moditem-alist x))
(ans (change-vl-module
x
:ports (vl-portlist-clean-selects x.ports x ialist)
:assigns (vl-assignlist-clean-selects x.assigns x ialist)
:modinsts (vl-modinstlist-clean-selects x.modinsts x ialist)
:gateinsts (vl-gateinstlist-clean-selects x.gateinsts x ialist)
:alwayses (vl-alwayslist-clean-selects x.alwayses x ialist)
:initials (vl-initiallist-clean-selects x.initials x ialist))))
(fast-alist-free ialist)
ans))
(defprojection vl-modulelist-clean-selects ((x vl-modulelist-p))
:returns (new-x vl-modulelist-p)
(vl-module-clean-selects x))
(define vl-design-clean-selects ((x vl-design-p))
:short "Top-level @(see clean-selects) transform."
(b* (((vl-design x) x))
(change-vl-design x :mods (vl-modulelist-clean-selects x.mods))))
| true |
; VL Verilog Toolkit
; Copyright (C) 2008-2014 Centaur Technology
;
; Contact:
; Centaur Technology Formal Verification Group
; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA.
; http://www.centtech.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
(in-package "VL")
(include-book "../mlib/clean-concats")
(include-book "../mlib/stmt-tools")
(local (include-book "../util/arithmetic"))
(local (std::add-default-post-define-hook :fix))
(defxdoc clean-selects
:parents (transforms)
:short "Simplify concatenations and selects throughout a module."
:long "<p>This is a mainly aesthetic transform that applies @(see
vl-expr-clean-selects) throughout modules. This may help to make certain
concatenation and select expressions more readable.</p>
<p>Implementation-wise, this is the usual boilerplate to extend @(see
vl-expr-clean-selects) through the parse tree, except that we aren't going to
go through ranges: we only do this in assignments, instances, and statements,
where we expect to see wires.</p>")
(local (xdoc::set-default-parents clean-selects))
(defmacro def-vl-clean-selects (name &key type body)
`(define ,name ((x ,type)
(mod vl-module-p)
(ialist (equal ialist (vl-moditem-alist mod))))
:returns (new-x ,type)
(declare (ignorable x mod ialist))
,body))
(defmacro def-vl-clean-selects-list (name &key type element)
`(defprojection ,name ((x ,type)
(mod vl-module-p)
(ialist (equal ialist (vl-moditem-alist mod))))
:returns (new-x ,type)
(,element x mod ialist)))
(def-vl-clean-selects vl-maybe-expr-clean-selects
:type vl-maybe-expr-p
:body (and x (vl-expr-clean-selects x mod ialist)))
(def-vl-clean-selects vl-port-clean-selects
:type vl-port-p
:body (b* (((vl-port x) x))
(change-vl-port x :expr (vl-maybe-expr-clean-selects x.expr mod ialist))))
(def-vl-clean-selects-list vl-portlist-clean-selects
:type vl-portlist-p
:element vl-port-clean-selects)
(def-vl-clean-selects vl-assign-clean-selects
:type vl-assign-p
:body (b* (((vl-assign x) x))
(change-vl-assign x
:lvalue (vl-expr-clean-selects x.lvalue mod ialist)
:expr (vl-expr-clean-selects x.expr mod ialist))))
(def-vl-clean-selects-list vl-assignlist-clean-selects
:type vl-assignlist-p
:element vl-assign-clean-selects)
(def-vl-clean-selects vl-plainarg-clean-selects
:type vl-plainarg-p
:body (b* (((vl-plainarg x) x))
(change-vl-plainarg x
:expr (vl-maybe-expr-clean-selects x.expr mod ialist))))
(def-vl-clean-selects-list vl-plainarglist-clean-selects
:type vl-plainarglist-p
:element vl-plainarg-clean-selects)
(def-vl-clean-selects vl-namedarg-clean-selects
:type vl-namedarg-p
:body (b* (((vl-namedarg x) x))
(change-vl-namedarg x
:expr (vl-maybe-expr-clean-selects x.expr mod ialist))))
(def-vl-clean-selects-list vl-namedarglist-clean-selects
:type vl-namedarglist-p
:element vl-namedarg-clean-selects)
(def-vl-clean-selects vl-arguments-clean-selects
:type vl-arguments-p
:body (vl-arguments-case x
:vl-arguments-named
(make-vl-arguments-named :args (vl-namedarglist-clean-selects x.args mod ialist))
:vl-arguments-plain
(make-vl-arguments-plain :args (vl-plainarglist-clean-selects x.args mod ialist))))
(def-vl-clean-selects vl-modinst-clean-selects
:type vl-modinst-p
:body (b* (((vl-modinst x) x))
(change-vl-modinst x
:portargs (vl-arguments-clean-selects x.portargs mod ialist))))
(def-vl-clean-selects-list vl-modinstlist-clean-selects
:type vl-modinstlist-p
:element vl-modinst-clean-selects)
(def-vl-clean-selects vl-gateinst-clean-selects
:type vl-gateinst-p
:body (b* (((vl-gateinst x) x))
(change-vl-gateinst x
:args (vl-plainarglist-clean-selects x.args mod ialist))))
(def-vl-clean-selects-list vl-gateinstlist-clean-selects
:type vl-gateinstlist-p
:element vl-gateinst-clean-selects)
(defines vl-stmt-clean-selects
:parents (clean-selects)
(define vl-stmt-clean-selects ((x vl-stmt-p)
(mod vl-module-p)
(ialist (equal ialist (vl-moditem-alist mod))))
:returns (new-x vl-stmt-p)
:measure (vl-stmt-count x)
:verify-guards nil
(b* ((x (vl-stmt-fix x))
((when (vl-atomicstmt-p x))
(case (vl-stmt-kind x)
(:vl-nullstmt
x)
(:vl-assignstmt
(b* (((vl-assignstmt x) x))
(change-vl-assignstmt x
:lvalue (vl-expr-clean-selects x.lvalue mod ialist)
:expr (vl-expr-clean-selects x.expr mod ialist))))
(:vl-deassignstmt
(b* (((vl-deassignstmt x) x))
(change-vl-deassignstmt x
:lvalue (vl-expr-clean-selects x.lvalue mod ialist))))
(:vl-enablestmt
(b* (((vl-enablestmt x) x))
(change-vl-enablestmt x
:args (vl-exprlist-clean-selects x.args mod ialist))))
(:vl-disablestmt
x)
(otherwise
;; event trigger statement
x)))
(exprs (vl-exprlist-clean-selects (vl-compoundstmt->exprs x) mod ialist))
(stmts (vl-stmtlist-clean-selects (vl-compoundstmt->stmts x) mod ialist)))
(change-vl-compoundstmt x :exprs exprs :stmts stmts)))
(define vl-stmtlist-clean-selects ((x vl-stmtlist-p)
(mod vl-module-p)
(ialist (equal ialist (vl-moditem-alist mod))))
:returns (new-x (and (vl-stmtlist-p new-x)
(equal (len new-x) (len x))))
:measure (vl-stmtlist-count x)
(if (consp x)
(cons (vl-stmt-clean-selects (car x) mod ialist)
(vl-stmtlist-clean-selects (cdr x) mod ialist))
nil))
///
(verify-guards vl-stmt-clean-selects)
(deffixequiv-mutual vl-stmt-clean-selects)
(defprojection vl-stmtlist-clean-selects (x mod ialist)
(vl-stmt-clean-selects x mod ialist)
:already-definedp t))
(def-vl-clean-selects vl-always-clean-selects
:type vl-always-p
:body (b* (((vl-always x) x))
(change-vl-always x
:stmt (vl-stmt-clean-selects x.stmt mod ialist))))
(def-vl-clean-selects-list vl-alwayslist-clean-selects
:type vl-alwayslist-p
:element vl-always-clean-selects)
(def-vl-clean-selects vl-initial-clean-selects
:type vl-initial-p
:body (b* (((vl-initial x) x))
(change-vl-initial x
:stmt (vl-stmt-clean-selects x.stmt mod ialist))))
(def-vl-clean-selects-list vl-initiallist-clean-selects
:type vl-initiallist-p
:element vl-initial-clean-selects)
(define vl-module-clean-selects ((x vl-module-p))
:returns (new-x vl-module-p)
(b* ((x (vl-module-fix x))
((vl-module x) x)
((when (vl-module->hands-offp x))
x)
(ialist (vl-moditem-alist x))
(ans (change-vl-module
x
:ports (vl-portlist-clean-selects x.ports x ialist)
:assigns (vl-assignlist-clean-selects x.assigns x ialist)
:modinsts (vl-modinstlist-clean-selects x.modinsts x ialist)
:gateinsts (vl-gateinstlist-clean-selects x.gateinsts x ialist)
:alwayses (vl-alwayslist-clean-selects x.alwayses x ialist)
:initials (vl-initiallist-clean-selects x.initials x ialist))))
(fast-alist-free ialist)
ans))
(defprojection vl-modulelist-clean-selects ((x vl-modulelist-p))
:returns (new-x vl-modulelist-p)
(vl-module-clean-selects x))
(define vl-design-clean-selects ((x vl-design-p))
:short "Top-level @(see clean-selects) transform."
(b* (((vl-design x) x))
(change-vl-design x :mods (vl-modulelist-clean-selects x.mods))))
|
[
{
"context": ";;;; -*- Mode: LISP -*-\n(defsystem jss\n :author \"Alan Ruttenberg, Mark Evenson\"\n :long-description \"<urn:abcl.org",
"end": 65,
"score": 0.999871015548706,
"start": 50,
"tag": "NAME",
"value": "Alan Ruttenberg"
},
{
"context": "ISP -*-\n(defsystem jss\n :author \"Alan Ruttenberg, Mark Evenson\"\n :long-description \"<urn:abcl.org/release/1.6.0",
"end": 79,
"score": 0.9998177886009216,
"start": 67,
"tag": "NAME",
"value": "Mark Evenson"
}
] |
abcl/contrib/jss/jss.asd
|
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD
| 10 |
;;;; -*- Mode: LISP -*-
(defsystem jss
:author "Alan Ruttenberg, Mark Evenson"
:long-description "<urn:abcl.org/release/1.6.0/contrib/jss#>"
:version "3.5.0"
:components ((:module base :pathname "" :serial t
:components ((:file "packages")
(:file "invoke")
(:file "collections")
(:file "optimize-java-call")
(:file "classpath")
(:file "transform-to-field")
(:file "compat")
(:file "jtypecase"))))
:perform (asdf:test-op (op c)
(asdf:test-system :jss-tests)))
|
40284
|
;;;; -*- Mode: LISP -*-
(defsystem jss
:author "<NAME>, <NAME>"
:long-description "<urn:abcl.org/release/1.6.0/contrib/jss#>"
:version "3.5.0"
:components ((:module base :pathname "" :serial t
:components ((:file "packages")
(:file "invoke")
(:file "collections")
(:file "optimize-java-call")
(:file "classpath")
(:file "transform-to-field")
(:file "compat")
(:file "jtypecase"))))
:perform (asdf:test-op (op c)
(asdf:test-system :jss-tests)))
| true |
;;;; -*- Mode: LISP -*-
(defsystem jss
:author "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI"
:long-description "<urn:abcl.org/release/1.6.0/contrib/jss#>"
:version "3.5.0"
:components ((:module base :pathname "" :serial t
:components ((:file "packages")
(:file "invoke")
(:file "collections")
(:file "optimize-java-call")
(:file "classpath")
(:file "transform-to-field")
(:file "compat")
(:file "jtypecase"))))
:perform (asdf:test-op (op c)
(asdf:test-system :jss-tests)))
|
[
{
"context": "ronclad:ascii-string-to-byte-array \"01234567890abcde\"))\n (nonce (make-array 16\n ",
"end": 360,
"score": 0.6056174635887146,
"start": 358,
"tag": "KEY",
"value": "de"
}
] |
tests/authenticated-encryption.lisp
|
kkazuo/authenticated-encryption
| 2 |
(defpackage authenticated-encryption-test
(:use :cl
:authenticated-encryption
:ironclad
:1am))
(in-package :authenticated-encryption-test)
;; NOTE: To run this test file, execute `(asdf:test-system :authenticated-encryption)' in your Lisp.
(test encrypt-decrypt
(let ((secret (ironclad:ascii-string-to-byte-array "01234567890abcde"))
(nonce (make-array 16
:element-type '(unsigned-byte 8)
:initial-contents #(254 105 255 23 133 125 163 190 72 25 186 247 13 73 5 185)))
(plain1 (ironclad:ascii-string-to-byte-array "ab00000000000009"))
(enc1 (make-array 66
:element-type '(unsigned-byte 8)
:initial-contents #(0 16 254 105 255 23 133 125 163 190 72 25 186 247
13 73 5 185 229 167 95 55 239 235 243 131 125 125
147 244 45 77 34 229 111 145 189 134 176 175 46 6 126
50 193 244 61 204 101 166 219 179 94 228 114 225 94 21
194 126 47 22 149 27 80 199)))
(plain2 (ironclad:ascii-string-to-byte-array "ab0000000000000"))
(enc2 (make-array 50
:element-type '(unsigned-byte 8)
:initial-contents #(0 16 254 105 255 23 133 125 163 190 72 25 186 247
13 73 5 185 229 167 95 55 239 235 243 131 125 125
147 244 45 77 34 221 231 96 10 121 199 183 67 196 55
246 98 234 23 230 43 40))))
(is (equalp
(authenticated-encrypt plain1 :secret secret :nonce nonce)
enc1))
(is (equalp
(authenticated-decrypt enc1 :secret secret)
plain1))
(is (equalp
(authenticated-encrypt plain2 :secret secret :nonce nonce)
enc2))
(is (equalp
(authenticated-decrypt enc2 :secret secret)
plain2))))
|
46243
|
(defpackage authenticated-encryption-test
(:use :cl
:authenticated-encryption
:ironclad
:1am))
(in-package :authenticated-encryption-test)
;; NOTE: To run this test file, execute `(asdf:test-system :authenticated-encryption)' in your Lisp.
(test encrypt-decrypt
(let ((secret (ironclad:ascii-string-to-byte-array "01234567890abc<KEY>"))
(nonce (make-array 16
:element-type '(unsigned-byte 8)
:initial-contents #(254 105 255 23 133 125 163 190 72 25 186 247 13 73 5 185)))
(plain1 (ironclad:ascii-string-to-byte-array "ab00000000000009"))
(enc1 (make-array 66
:element-type '(unsigned-byte 8)
:initial-contents #(0 16 254 105 255 23 133 125 163 190 72 25 186 247
13 73 5 185 229 167 95 55 239 235 243 131 125 125
147 244 45 77 34 229 111 145 189 134 176 175 46 6 126
50 193 244 61 204 101 166 219 179 94 228 114 225 94 21
194 126 47 22 149 27 80 199)))
(plain2 (ironclad:ascii-string-to-byte-array "ab0000000000000"))
(enc2 (make-array 50
:element-type '(unsigned-byte 8)
:initial-contents #(0 16 254 105 255 23 133 125 163 190 72 25 186 247
13 73 5 185 229 167 95 55 239 235 243 131 125 125
147 244 45 77 34 221 231 96 10 121 199 183 67 196 55
246 98 234 23 230 43 40))))
(is (equalp
(authenticated-encrypt plain1 :secret secret :nonce nonce)
enc1))
(is (equalp
(authenticated-decrypt enc1 :secret secret)
plain1))
(is (equalp
(authenticated-encrypt plain2 :secret secret :nonce nonce)
enc2))
(is (equalp
(authenticated-decrypt enc2 :secret secret)
plain2))))
| true |
(defpackage authenticated-encryption-test
(:use :cl
:authenticated-encryption
:ironclad
:1am))
(in-package :authenticated-encryption-test)
;; NOTE: To run this test file, execute `(asdf:test-system :authenticated-encryption)' in your Lisp.
(test encrypt-decrypt
(let ((secret (ironclad:ascii-string-to-byte-array "01234567890abcPI:KEY:<KEY>END_PI"))
(nonce (make-array 16
:element-type '(unsigned-byte 8)
:initial-contents #(254 105 255 23 133 125 163 190 72 25 186 247 13 73 5 185)))
(plain1 (ironclad:ascii-string-to-byte-array "ab00000000000009"))
(enc1 (make-array 66
:element-type '(unsigned-byte 8)
:initial-contents #(0 16 254 105 255 23 133 125 163 190 72 25 186 247
13 73 5 185 229 167 95 55 239 235 243 131 125 125
147 244 45 77 34 229 111 145 189 134 176 175 46 6 126
50 193 244 61 204 101 166 219 179 94 228 114 225 94 21
194 126 47 22 149 27 80 199)))
(plain2 (ironclad:ascii-string-to-byte-array "ab0000000000000"))
(enc2 (make-array 50
:element-type '(unsigned-byte 8)
:initial-contents #(0 16 254 105 255 23 133 125 163 190 72 25 186 247
13 73 5 185 229 167 95 55 239 235 243 131 125 125
147 244 45 77 34 221 231 96 10 121 199 183 67 196 55
246 98 234 23 230 43 40))))
(is (equalp
(authenticated-encrypt plain1 :secret secret :nonce nonce)
enc1))
(is (equalp
(authenticated-decrypt enc1 :secret secret)
plain1))
(is (equalp
(authenticated-encrypt plain2 :secret secret :nonce nonce)
enc2))
(is (equalp
(authenticated-decrypt enc2 :secret secret)
plain2))))
|
[
{
"context": "isp\n\n;;;; Copyright (c) 2012 -- 2013 \"the Phoeron\" Colin J.E. Lupton <//thephoeron.com>\n;;;; See LICENSE for additiona",
"end": 167,
"score": 0.9998700618743896,
"start": 150,
"tag": "NAME",
"value": "Colin J.E. Lupton"
},
{
"context": " \"user \"\n (:a :href \"#\" \"ManningP\")\n \" changed password on u",
"end": 9654,
"score": 0.9992827773094177,
"start": 9646,
"tag": "USERNAME",
"value": "ManningP"
},
{
"context": " on user \"\n (:a :href \"#\" \"NonnyA\"))\n (:span :class \"ago\" \"10 ",
"end": 9755,
"score": 0.8793129920959473,
"start": 9749,
"tag": "USERNAME",
"value": "NonnyA"
}
] |
admin/admin-requests.lisp
|
thephoeron/REDSHIFTNET
| 2 |
;;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: REDSHIFTNET; Base: 10 -*- file: admin-requests.lisp
;;;; Copyright (c) 2012 -- 2013 "the Phoeron" Colin J.E. Lupton <//thephoeron.com>
;;;; See LICENSE for additional information.
(in-package :redshiftnet)
(defun admin-login (logo)
"Login page for admin section."
(cl-who:with-html-output (hunchentoot::*standard-output*)
(:div :class "container-fluid"
(:div :id "login"
(:div :class "login-wrapper" :data-active "log"
(:a :class "navbar-brand" :href "#"
(:img :class "image-responsive" :alt "REDSHIFTNET Admin" :src (str (format nil "~A" logo))))
(:div :id "log"
(:div :class "page-header"
(:h3 :class "center" "Please Login"))
(show-rsn-form admin-login-form))
(:div :id "forgot"
(:div :class "page-header"
(:h3 :class "center" "Forgot Password"))
(show-rsn-form admin-forgot-password-form)))
(:div :id "bar" :data-active "log"
(:div :class "btn-group btn-group-vertical"
(:a :id "log" :href "#" :class "btn tipR" :title "Login"
(:i :class "icon16 i-key"))
(:a :id "forgot" :href "#" :class "btn tipR" :title "Forgot Password"
(:i :class "icon16 i-question"))))
(:div :class "clearfix")))))
(defmacro admin-page ((title login-page-fun &key (styles nil) (scripts nil)) &body body)
"Admin site page generator macro."
`(%auth-page (title ,login-page-fun)
(%app-page (:title ,title :header #'admin-header
:menu #'admin-menu :footer #'admin-footer
:scripts ,scripts :styles ,styles)
(cl-who:with-html-output (hunchentoot::*standard-output*)
,@body))))
;; Admin Dashboard
(defun admin-dashboard ()
"Admin site dashboard widget generator function."
(cl-who:with-html-output (hunchentoot::*standard-output*)
(:div :id "heading" :class "page-header"
(:h1 (:i :class "icon20 i-dashboard") " Dashboard"))
(:div :class "row"
(:p :class "lead"
"Welcome to REDSHIFTNET Admin. This is a good place to put your favourite dashboard widgets. There should probably be a list somewhere that is built through the interface, so users can customize it... Some dependencies need to be rebuilt."))))
(defrequest rsn-admin (:vhost vhost-admin)
(admin-page ("REDSHIFTNET Admin :: Admin" #'admin-login
:styles admin-dashboard-styles
:scripts admin-dashboard-scripts)
(hunchentoot:redirect "/admin/dashboard/")))
(defrequest rsn-admin/dashboard (:vhost vhost-admin)
(admin-page ("REDSHIFTNET Admin :: Dashboard" #'admin-login
:styles admin-dashboard-styles
:scripts admin-dashboard-scripts)
(admin-dashboard)))
(defrequest rsn-admin/webmail (:vhost vhost-admin)
(admin-page ("REDSHIFTNET Admin :: Webmail" #'admin-login
:styles admin-dashboard-styles
:scripts admin-dashboard-scripts)
(html-to-stout
(:div :id "heading" :class "page-header"
(:h1 (:i :class "icon20 i-envelop-2") " Webmail"))
(:div :class "row"
(:div :id "email" :class "col-lg-12"
(:div :class "email-bar")
(:div :class "email-nav well")
(:div :class "email-wrapper"))))))
(defrequest rsn-admin/calendar (:vhost vhost-admin)
(admin-page ("REDSHIFTNET Admin :: Calendar" #'admin-login
:styles admin-calendar-styles
:scripts admin-calendar-scripts)
(html-to-stout
(:div :id "heading" :class "page-header"
(:h1 (:i :class "icon20 i-calendar") " Calendar"))
(:div :class "row"
(:div :class "col-lg-8"
(:div :class "panel plain"
(:div :class "panel-heading"
(:i :class "icon20 i-calendar-3")
(:h4 "Calendar")
(:a :href "#" :class "minimize"))
(:div :class "panel-body noPadding"
(:div :id "calendar"))))
(:div :class "col-lg-4"
(:div :class "page-header"
(:h4 "Events " (:small "drop events to calendar")))
(:div :id "external-events"
(:div :class "external-event" "Meeting with client")
(:div :class "external-event" "Telephone interview")
(:div :class "external-event" "Face-to-face")))))))
;; Edit page for database record
(defun generate-edit-page-for-database-record (table-name record-id)
"Accepts a table name and record id, and creates a new request object with an auto-generated form that allows you to edit the record."
)
(defun output-named-database-table-as-html (table-name)
"Outputs the named database table as html."
(postmodern:with-connection *db*
(let* ((all-records
(postmodern:query
(format nil "SELECT * FROM ~A" (normalize-for-sql table-name))
:alists)))
(html-to-stout
(:div :id "heading" :class "page-header"
(:h1 (:i :class "icon20 i-table"
" " (string-symbol-to-label table-name))))
(:div :class "row"
(:div :class "col-lg-12"
(:table :class "table table-striped table-bordered table-hover" :id "dataTable"
(:thead (:tr
(loop for a in all-records
for i upto 0
do (loop for b in a
unless (eq (car b) :password)
do (htm (:th (str (string-symbol-to-label (format nil "~A" (car b))))))))))
(:tbody
(loop for x in all-records
do (htm (:tr (loop for y in x
unless (eq (car y) :password)
do (htm (:td (str (format nil "~A" (cdr y)))))))))))))))))
;; Output all database tables as html
(defun output-all-database-tables-as-html ()
"Introspects on the current toplevel database and generates an admin page that lists all tables grouped by app, following the PostgreSQL naming convention 'appname_tablename'."
(postmodern:with-connection *db*
(let* ((all-tables (loop for table in (list-database-tables)
collect (split-sequence #\_ table)))
(parsed-tables (loop for (x y) in all-tables
collect x))
(table-group-names (remove-duplicates parsed-tables :test #'string=))
(table-group-lists (loop for z in table-group-names
collect (list z (loop for x in all-tables
when (string= (car x) z)
collect x))))
(final-table-list (loop for (x . y) in table-group-lists
collect (list x (lol:flatten
(loop for i in y
collect (loop for j in i
collect (format nil "~{~a~^-~}" j))))))))
(html-to-stout
(loop for (x . y) in final-table-list
do (htm
(:div :class "panel panel-default"
(:div :class "panel-heading"
(:div :class "icon" (:i :class "icon20 i-table-2"))
(:h4 (str (string-symbol-to-label x)) (:small " app tables"))
(:a :href "#" :class "minimize"))
(:div :class "panel-body noPadding"
(:table :class "table table-bordered"
(:tbody
(loop for i in y
do (loop for j in i
do (progn
(htm
(:tr
(:td
(:i :class "icon20 i-table")
" "
(:a :href (str (format nil "/admin/tables/?name=~a" j))
(str (string-symbol-to-label j)))))))))))))
(:div :class "clearfix" " ")))))))
;; All Tables request
;; Accepts get-parameter 'name' to display specific table
;; Otherwise it lists all tables in current db grouped by app
(defrequest rsn-admin/tables (:vhost vhost-admin)
(admin-page ("REDSHIFTNET Admin :: All Tables" #'admin-login
:styles admin-dashboard-styles
:scripts admin-dashboard-scripts)
(if (hunchentoot:get-parameter "name")
(output-named-database-table-as-html (hunchentoot:get-parameter "name"))
; else
(cl-who:with-html-output (hunchentoot::*standard-output*)
(:div :id "heading" :class "page-header"
(:h1 (:i :class "icon20 i-dashboard") " All Tables"))
(:div :class "row"
(:div :class "col-lg-8"
(output-all-database-tables-as-html))
(:div :class "col-lg-4"
(:div :class "panel panel-default"
(:div :class "panel-heading"
(:div :class "icon" (:i :class "icon20 i-power"))
(:h4 "Recent activity")
(:a :href "#" :class "minimize"))
(:div :class "panel-body noPadding"
(:ul :class "recent-activity"
(:li :class "item"
(:span :class "icon green" (:i :class "icon16 i-user"))
(:span :class "text"
"user "
(:a :href "#" "ManningP")
" changed password on user "
(:a :href "#" "NonnyA"))
(:span :class "ago" "10 min ago"))
(:li :class "item"
(:span :class "icon blue" (:i :class "icon16 i-notification"))
(:span :class "text"
(:a :href "#" "5 callbacks")
" were automatically closed")
(:span :class "ago" "1 day ago"))
(:li :class "item"
(:span :class "icon red" (:i :class "icon16 i-key"))
(:span :class "text"
"user "
(:a :href "#" "DarkoD")
" has "
(:a :href "#" "5 failed login attempts"))
(:span :class "ago" "2 days ago")))))))))))
;; EOF
|
74874
|
;;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: REDSHIFTNET; Base: 10 -*- file: admin-requests.lisp
;;;; Copyright (c) 2012 -- 2013 "the Phoeron" <NAME> <//thephoeron.com>
;;;; See LICENSE for additional information.
(in-package :redshiftnet)
(defun admin-login (logo)
"Login page for admin section."
(cl-who:with-html-output (hunchentoot::*standard-output*)
(:div :class "container-fluid"
(:div :id "login"
(:div :class "login-wrapper" :data-active "log"
(:a :class "navbar-brand" :href "#"
(:img :class "image-responsive" :alt "REDSHIFTNET Admin" :src (str (format nil "~A" logo))))
(:div :id "log"
(:div :class "page-header"
(:h3 :class "center" "Please Login"))
(show-rsn-form admin-login-form))
(:div :id "forgot"
(:div :class "page-header"
(:h3 :class "center" "Forgot Password"))
(show-rsn-form admin-forgot-password-form)))
(:div :id "bar" :data-active "log"
(:div :class "btn-group btn-group-vertical"
(:a :id "log" :href "#" :class "btn tipR" :title "Login"
(:i :class "icon16 i-key"))
(:a :id "forgot" :href "#" :class "btn tipR" :title "Forgot Password"
(:i :class "icon16 i-question"))))
(:div :class "clearfix")))))
(defmacro admin-page ((title login-page-fun &key (styles nil) (scripts nil)) &body body)
"Admin site page generator macro."
`(%auth-page (title ,login-page-fun)
(%app-page (:title ,title :header #'admin-header
:menu #'admin-menu :footer #'admin-footer
:scripts ,scripts :styles ,styles)
(cl-who:with-html-output (hunchentoot::*standard-output*)
,@body))))
;; Admin Dashboard
(defun admin-dashboard ()
"Admin site dashboard widget generator function."
(cl-who:with-html-output (hunchentoot::*standard-output*)
(:div :id "heading" :class "page-header"
(:h1 (:i :class "icon20 i-dashboard") " Dashboard"))
(:div :class "row"
(:p :class "lead"
"Welcome to REDSHIFTNET Admin. This is a good place to put your favourite dashboard widgets. There should probably be a list somewhere that is built through the interface, so users can customize it... Some dependencies need to be rebuilt."))))
(defrequest rsn-admin (:vhost vhost-admin)
(admin-page ("REDSHIFTNET Admin :: Admin" #'admin-login
:styles admin-dashboard-styles
:scripts admin-dashboard-scripts)
(hunchentoot:redirect "/admin/dashboard/")))
(defrequest rsn-admin/dashboard (:vhost vhost-admin)
(admin-page ("REDSHIFTNET Admin :: Dashboard" #'admin-login
:styles admin-dashboard-styles
:scripts admin-dashboard-scripts)
(admin-dashboard)))
(defrequest rsn-admin/webmail (:vhost vhost-admin)
(admin-page ("REDSHIFTNET Admin :: Webmail" #'admin-login
:styles admin-dashboard-styles
:scripts admin-dashboard-scripts)
(html-to-stout
(:div :id "heading" :class "page-header"
(:h1 (:i :class "icon20 i-envelop-2") " Webmail"))
(:div :class "row"
(:div :id "email" :class "col-lg-12"
(:div :class "email-bar")
(:div :class "email-nav well")
(:div :class "email-wrapper"))))))
(defrequest rsn-admin/calendar (:vhost vhost-admin)
(admin-page ("REDSHIFTNET Admin :: Calendar" #'admin-login
:styles admin-calendar-styles
:scripts admin-calendar-scripts)
(html-to-stout
(:div :id "heading" :class "page-header"
(:h1 (:i :class "icon20 i-calendar") " Calendar"))
(:div :class "row"
(:div :class "col-lg-8"
(:div :class "panel plain"
(:div :class "panel-heading"
(:i :class "icon20 i-calendar-3")
(:h4 "Calendar")
(:a :href "#" :class "minimize"))
(:div :class "panel-body noPadding"
(:div :id "calendar"))))
(:div :class "col-lg-4"
(:div :class "page-header"
(:h4 "Events " (:small "drop events to calendar")))
(:div :id "external-events"
(:div :class "external-event" "Meeting with client")
(:div :class "external-event" "Telephone interview")
(:div :class "external-event" "Face-to-face")))))))
;; Edit page for database record
(defun generate-edit-page-for-database-record (table-name record-id)
"Accepts a table name and record id, and creates a new request object with an auto-generated form that allows you to edit the record."
)
(defun output-named-database-table-as-html (table-name)
"Outputs the named database table as html."
(postmodern:with-connection *db*
(let* ((all-records
(postmodern:query
(format nil "SELECT * FROM ~A" (normalize-for-sql table-name))
:alists)))
(html-to-stout
(:div :id "heading" :class "page-header"
(:h1 (:i :class "icon20 i-table"
" " (string-symbol-to-label table-name))))
(:div :class "row"
(:div :class "col-lg-12"
(:table :class "table table-striped table-bordered table-hover" :id "dataTable"
(:thead (:tr
(loop for a in all-records
for i upto 0
do (loop for b in a
unless (eq (car b) :password)
do (htm (:th (str (string-symbol-to-label (format nil "~A" (car b))))))))))
(:tbody
(loop for x in all-records
do (htm (:tr (loop for y in x
unless (eq (car y) :password)
do (htm (:td (str (format nil "~A" (cdr y)))))))))))))))))
;; Output all database tables as html
(defun output-all-database-tables-as-html ()
"Introspects on the current toplevel database and generates an admin page that lists all tables grouped by app, following the PostgreSQL naming convention 'appname_tablename'."
(postmodern:with-connection *db*
(let* ((all-tables (loop for table in (list-database-tables)
collect (split-sequence #\_ table)))
(parsed-tables (loop for (x y) in all-tables
collect x))
(table-group-names (remove-duplicates parsed-tables :test #'string=))
(table-group-lists (loop for z in table-group-names
collect (list z (loop for x in all-tables
when (string= (car x) z)
collect x))))
(final-table-list (loop for (x . y) in table-group-lists
collect (list x (lol:flatten
(loop for i in y
collect (loop for j in i
collect (format nil "~{~a~^-~}" j))))))))
(html-to-stout
(loop for (x . y) in final-table-list
do (htm
(:div :class "panel panel-default"
(:div :class "panel-heading"
(:div :class "icon" (:i :class "icon20 i-table-2"))
(:h4 (str (string-symbol-to-label x)) (:small " app tables"))
(:a :href "#" :class "minimize"))
(:div :class "panel-body noPadding"
(:table :class "table table-bordered"
(:tbody
(loop for i in y
do (loop for j in i
do (progn
(htm
(:tr
(:td
(:i :class "icon20 i-table")
" "
(:a :href (str (format nil "/admin/tables/?name=~a" j))
(str (string-symbol-to-label j)))))))))))))
(:div :class "clearfix" " ")))))))
;; All Tables request
;; Accepts get-parameter 'name' to display specific table
;; Otherwise it lists all tables in current db grouped by app
(defrequest rsn-admin/tables (:vhost vhost-admin)
(admin-page ("REDSHIFTNET Admin :: All Tables" #'admin-login
:styles admin-dashboard-styles
:scripts admin-dashboard-scripts)
(if (hunchentoot:get-parameter "name")
(output-named-database-table-as-html (hunchentoot:get-parameter "name"))
; else
(cl-who:with-html-output (hunchentoot::*standard-output*)
(:div :id "heading" :class "page-header"
(:h1 (:i :class "icon20 i-dashboard") " All Tables"))
(:div :class "row"
(:div :class "col-lg-8"
(output-all-database-tables-as-html))
(:div :class "col-lg-4"
(:div :class "panel panel-default"
(:div :class "panel-heading"
(:div :class "icon" (:i :class "icon20 i-power"))
(:h4 "Recent activity")
(:a :href "#" :class "minimize"))
(:div :class "panel-body noPadding"
(:ul :class "recent-activity"
(:li :class "item"
(:span :class "icon green" (:i :class "icon16 i-user"))
(:span :class "text"
"user "
(:a :href "#" "ManningP")
" changed password on user "
(:a :href "#" "NonnyA"))
(:span :class "ago" "10 min ago"))
(:li :class "item"
(:span :class "icon blue" (:i :class "icon16 i-notification"))
(:span :class "text"
(:a :href "#" "5 callbacks")
" were automatically closed")
(:span :class "ago" "1 day ago"))
(:li :class "item"
(:span :class "icon red" (:i :class "icon16 i-key"))
(:span :class "text"
"user "
(:a :href "#" "DarkoD")
" has "
(:a :href "#" "5 failed login attempts"))
(:span :class "ago" "2 days ago")))))))))))
;; EOF
| true |
;;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: REDSHIFTNET; Base: 10 -*- file: admin-requests.lisp
;;;; Copyright (c) 2012 -- 2013 "the Phoeron" PI:NAME:<NAME>END_PI <//thephoeron.com>
;;;; See LICENSE for additional information.
(in-package :redshiftnet)
(defun admin-login (logo)
"Login page for admin section."
(cl-who:with-html-output (hunchentoot::*standard-output*)
(:div :class "container-fluid"
(:div :id "login"
(:div :class "login-wrapper" :data-active "log"
(:a :class "navbar-brand" :href "#"
(:img :class "image-responsive" :alt "REDSHIFTNET Admin" :src (str (format nil "~A" logo))))
(:div :id "log"
(:div :class "page-header"
(:h3 :class "center" "Please Login"))
(show-rsn-form admin-login-form))
(:div :id "forgot"
(:div :class "page-header"
(:h3 :class "center" "Forgot Password"))
(show-rsn-form admin-forgot-password-form)))
(:div :id "bar" :data-active "log"
(:div :class "btn-group btn-group-vertical"
(:a :id "log" :href "#" :class "btn tipR" :title "Login"
(:i :class "icon16 i-key"))
(:a :id "forgot" :href "#" :class "btn tipR" :title "Forgot Password"
(:i :class "icon16 i-question"))))
(:div :class "clearfix")))))
(defmacro admin-page ((title login-page-fun &key (styles nil) (scripts nil)) &body body)
"Admin site page generator macro."
`(%auth-page (title ,login-page-fun)
(%app-page (:title ,title :header #'admin-header
:menu #'admin-menu :footer #'admin-footer
:scripts ,scripts :styles ,styles)
(cl-who:with-html-output (hunchentoot::*standard-output*)
,@body))))
;; Admin Dashboard
(defun admin-dashboard ()
"Admin site dashboard widget generator function."
(cl-who:with-html-output (hunchentoot::*standard-output*)
(:div :id "heading" :class "page-header"
(:h1 (:i :class "icon20 i-dashboard") " Dashboard"))
(:div :class "row"
(:p :class "lead"
"Welcome to REDSHIFTNET Admin. This is a good place to put your favourite dashboard widgets. There should probably be a list somewhere that is built through the interface, so users can customize it... Some dependencies need to be rebuilt."))))
(defrequest rsn-admin (:vhost vhost-admin)
(admin-page ("REDSHIFTNET Admin :: Admin" #'admin-login
:styles admin-dashboard-styles
:scripts admin-dashboard-scripts)
(hunchentoot:redirect "/admin/dashboard/")))
(defrequest rsn-admin/dashboard (:vhost vhost-admin)
(admin-page ("REDSHIFTNET Admin :: Dashboard" #'admin-login
:styles admin-dashboard-styles
:scripts admin-dashboard-scripts)
(admin-dashboard)))
(defrequest rsn-admin/webmail (:vhost vhost-admin)
(admin-page ("REDSHIFTNET Admin :: Webmail" #'admin-login
:styles admin-dashboard-styles
:scripts admin-dashboard-scripts)
(html-to-stout
(:div :id "heading" :class "page-header"
(:h1 (:i :class "icon20 i-envelop-2") " Webmail"))
(:div :class "row"
(:div :id "email" :class "col-lg-12"
(:div :class "email-bar")
(:div :class "email-nav well")
(:div :class "email-wrapper"))))))
(defrequest rsn-admin/calendar (:vhost vhost-admin)
(admin-page ("REDSHIFTNET Admin :: Calendar" #'admin-login
:styles admin-calendar-styles
:scripts admin-calendar-scripts)
(html-to-stout
(:div :id "heading" :class "page-header"
(:h1 (:i :class "icon20 i-calendar") " Calendar"))
(:div :class "row"
(:div :class "col-lg-8"
(:div :class "panel plain"
(:div :class "panel-heading"
(:i :class "icon20 i-calendar-3")
(:h4 "Calendar")
(:a :href "#" :class "minimize"))
(:div :class "panel-body noPadding"
(:div :id "calendar"))))
(:div :class "col-lg-4"
(:div :class "page-header"
(:h4 "Events " (:small "drop events to calendar")))
(:div :id "external-events"
(:div :class "external-event" "Meeting with client")
(:div :class "external-event" "Telephone interview")
(:div :class "external-event" "Face-to-face")))))))
;; Edit page for database record
(defun generate-edit-page-for-database-record (table-name record-id)
"Accepts a table name and record id, and creates a new request object with an auto-generated form that allows you to edit the record."
)
(defun output-named-database-table-as-html (table-name)
"Outputs the named database table as html."
(postmodern:with-connection *db*
(let* ((all-records
(postmodern:query
(format nil "SELECT * FROM ~A" (normalize-for-sql table-name))
:alists)))
(html-to-stout
(:div :id "heading" :class "page-header"
(:h1 (:i :class "icon20 i-table"
" " (string-symbol-to-label table-name))))
(:div :class "row"
(:div :class "col-lg-12"
(:table :class "table table-striped table-bordered table-hover" :id "dataTable"
(:thead (:tr
(loop for a in all-records
for i upto 0
do (loop for b in a
unless (eq (car b) :password)
do (htm (:th (str (string-symbol-to-label (format nil "~A" (car b))))))))))
(:tbody
(loop for x in all-records
do (htm (:tr (loop for y in x
unless (eq (car y) :password)
do (htm (:td (str (format nil "~A" (cdr y)))))))))))))))))
;; Output all database tables as html
(defun output-all-database-tables-as-html ()
"Introspects on the current toplevel database and generates an admin page that lists all tables grouped by app, following the PostgreSQL naming convention 'appname_tablename'."
(postmodern:with-connection *db*
(let* ((all-tables (loop for table in (list-database-tables)
collect (split-sequence #\_ table)))
(parsed-tables (loop for (x y) in all-tables
collect x))
(table-group-names (remove-duplicates parsed-tables :test #'string=))
(table-group-lists (loop for z in table-group-names
collect (list z (loop for x in all-tables
when (string= (car x) z)
collect x))))
(final-table-list (loop for (x . y) in table-group-lists
collect (list x (lol:flatten
(loop for i in y
collect (loop for j in i
collect (format nil "~{~a~^-~}" j))))))))
(html-to-stout
(loop for (x . y) in final-table-list
do (htm
(:div :class "panel panel-default"
(:div :class "panel-heading"
(:div :class "icon" (:i :class "icon20 i-table-2"))
(:h4 (str (string-symbol-to-label x)) (:small " app tables"))
(:a :href "#" :class "minimize"))
(:div :class "panel-body noPadding"
(:table :class "table table-bordered"
(:tbody
(loop for i in y
do (loop for j in i
do (progn
(htm
(:tr
(:td
(:i :class "icon20 i-table")
" "
(:a :href (str (format nil "/admin/tables/?name=~a" j))
(str (string-symbol-to-label j)))))))))))))
(:div :class "clearfix" " ")))))))
;; All Tables request
;; Accepts get-parameter 'name' to display specific table
;; Otherwise it lists all tables in current db grouped by app
(defrequest rsn-admin/tables (:vhost vhost-admin)
(admin-page ("REDSHIFTNET Admin :: All Tables" #'admin-login
:styles admin-dashboard-styles
:scripts admin-dashboard-scripts)
(if (hunchentoot:get-parameter "name")
(output-named-database-table-as-html (hunchentoot:get-parameter "name"))
; else
(cl-who:with-html-output (hunchentoot::*standard-output*)
(:div :id "heading" :class "page-header"
(:h1 (:i :class "icon20 i-dashboard") " All Tables"))
(:div :class "row"
(:div :class "col-lg-8"
(output-all-database-tables-as-html))
(:div :class "col-lg-4"
(:div :class "panel panel-default"
(:div :class "panel-heading"
(:div :class "icon" (:i :class "icon20 i-power"))
(:h4 "Recent activity")
(:a :href "#" :class "minimize"))
(:div :class "panel-body noPadding"
(:ul :class "recent-activity"
(:li :class "item"
(:span :class "icon green" (:i :class "icon16 i-user"))
(:span :class "text"
"user "
(:a :href "#" "ManningP")
" changed password on user "
(:a :href "#" "NonnyA"))
(:span :class "ago" "10 min ago"))
(:li :class "item"
(:span :class "icon blue" (:i :class "icon16 i-notification"))
(:span :class "text"
(:a :href "#" "5 callbacks")
" were automatically closed")
(:span :class "ago" "1 day ago"))
(:li :class "item"
(:span :class "icon red" (:i :class "icon16 i-key"))
(:span :class "text"
"user "
(:a :href "#" "DarkoD")
" has "
(:a :href "#" "5 failed login attempts"))
(:span :class "ago" "2 days ago")))))))))))
;; EOF
|
[
{
"context": " theorems about packbv\n;\n; Copyright (C) 2008-2011 Eric Smith and Stanford University\n; Copyright (C) 2013-2020",
"end": 80,
"score": 0.9996841549873352,
"start": 70,
"tag": "NAME",
"value": "Eric Smith"
},
{
"context": "ense. See the file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;",
"end": 241,
"score": 0.9995967149734497,
"start": 231,
"tag": "NAME",
"value": "Eric Smith"
},
{
"context": " file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 265,
"score": 0.9999340176582336,
"start": 243,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/kestrel/bv-lists/packbv.lisp
|
nzt/acl2
| 1 |
; BV Lists Library: theorems about packbv
;
; Copyright (C) 2008-2011 Eric Smith and Stanford University
; Copyright (C) 2013-2020 Kestrel Institute
;
; License: A 3-clause BSD license. See the file books/3BSD-mod.txt.
;
; Author: Eric Smith ([email protected])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(include-book "packbv-def")
(include-book "all-unsigned-byte-p")
(include-book "../bv/bvcat-def")
(include-book "../bv/getbit")
(include-book "../lists-light/repeat")
(local (include-book "../bv/bvcat"))
(local (include-book "../bv/unsigned-byte-p"))
(local (include-book "../../ihs/ihs-lemmas")) ;why? for <-*-left-cancel
(local (include-book "../lists-light/butlast"))
(local (include-book "../../meta/meta-plus-lessp"))
(local (in-theory (disable mod-x-y-=-x+y-for-rationals))) ;bad
(defthm <-cancel-hack
(implies (and (posp size)
(rationalp count)
(rationalp n))
(equal (< (+ (- size) (* count size)) (* n size))
(< (+ -1 count) n)))
:hints (("Goal" :use (:instance <-*-left-cancel (z size) (x (+ -1 count)) (y n)))))
(defthmd packbv-base
(implies (zp itemcount)
(equal (packbv itemcount itemsize items)
0))
:hints (("Goal" :in-theory (enable packbv))))
(defthmd packbv-opener
(implies (not (zp itemcount))
(equal (packbv itemcount itemsize items)
(bvcat itemsize
(car items)
(* itemsize (+ -1 itemcount))
(packbv (+ -1 itemcount) itemsize (cdr items)))))
:hints (("Goal" :in-theory (enable packbv))))
(defthm packbv-of-0
(equal (packbv 0 size bvs)
0)
:hints (("Goal" :in-theory (enable packbv))))
(defthm unsigned-byte-p-of-packbv
(implies (and (natp size)
(natp num))
(unsigned-byte-p (* size num)
(packbv num size items)))
:hints (("Goal" :in-theory (enable packbv))))
(defthm unsigned-byte-p-of-packbv-gen
(implies (and (<= (* size num) n)
(natp size)
(natp n)
(natp num))
(unsigned-byte-p n (packbv num size items)))
:hints (("Goal" :use (:instance unsigned-byte-p-of-packbv)
:in-theory (disable unsigned-byte-p-of-packbv))))
;gen the 1
(defthm bvchop-of-packbv-1-helper
(implies (and (<= n count)
(natp n)
(natp count))
(equal (bvchop n (packbv count 1 bvs))
(packbv n 1 (nthcdr (- count n) bvs))))
:hints (("Goal" :in-theory (enable packbv))))
;gen the 1?
(defthm bvchop-of-packbv-1
(implies (and (<= n count)
(natp count))
(equal (bvchop n (packbv count 1 bvs))
(packbv n 1 (nthcdr (- count n) bvs))))
:hints (("Goal" :use (:instance bvchop-of-packbv-1-helper)
:in-theory (e/d (packbv-base) (bvchop-of-packbv-1-helper)))))
;gen the 1
(defthm getbit-of-packbv-1
(implies (and (natp n)
(integerp count)
(< n count))
(equal (getbit n (packbv count 1 bvs))
(getbit 0 (nth (+ count -1 (- n)) bvs))))
:hints (("Goal" ;:induct (packbv-induct count n bvs)
:do-not '(generalize eliminate-destructors)
:in-theory (enable packbv nth zp))))
(defthm bvchop-of-packbv-helper
(implies (and (<= n count)
(natp n)
(posp size)
(natp count))
(equal (bvchop (* n size) (packbv count size bvs))
(packbv n size (nthcdr (- count n) bvs))))
:hints (("Goal" :do-not '(generalize eliminate-destructors)
:in-theory (e/d (packbv posp nthcdr natp)
(bvcat-equal-rewrite-alt bvcat-equal-rewrite)))))
;gen to non multiples of size?
(defthm bvchop-of-packbv
(implies (and (<= (floor k size) count)
(equal 0 (mod k size))
(natp k)
(posp size)
(natp count))
(equal (bvchop k (packbv count size bvs))
(packbv (floor k size) size (nthcdr (- count (floor k size)) bvs))))
:hints (("Goal" :use (:instance bvchop-of-packbv-helper (n (floor k size)))
:in-theory (disable bvchop-of-packbv-helper))))
(defthm packbv-of-nil
(equal (packbv itemcount itemsize nil)
0)
:hints (("Goal" :in-theory (enable packbv))))
(defthm logtail-of-packbv-gen2
(implies (and (natp n)
(equal len (len vals)))
(equal (logtail (* 8 n) (packbv len 8 vals))
(packbv (- len n) 8 (butlast vals n))))
:hints (("Goal" :induct (packbv len 8 vals)
:in-theory (enable packbv))))
(defthm logtail-8-of-packbv
(implies (equal len (len vals))
(equal (logtail 8 (packbv len 8 vals))
(packbv (- len 1) 8 (butlast vals 1))))
:hints (("Goal" :use (:instance logtail-of-packbv-gen2 (n 1))
:in-theory (disable logtail-of-packbv-gen2))))
(defthm packbv-of-1
(equal (packbv 1 size items)
(bvchop size (first items)))
:hints (("Goal" :in-theory (enable packbv))))
;might not need this if the syntax functions knew the size of packbv
(defthm getbit-of-packbv-too-high
(equal (getbit num (packbv num 1 items))
0)
:hints (("Goal" :in-theory (enable packbv))))
(defthm packbv-of-repeat-of-0
(equal (packbv num 1 (repeat num 0))
0)
:hints (("Goal" :in-theory (enable packbv repeat))))
(defthm packbv-of-true-list-fix
(equal (packbv count size (true-list-fix items))
(packbv count size items))
:hints (("Goal" :in-theory (enable packbv))))
|
77566
|
; BV Lists Library: theorems about packbv
;
; Copyright (C) 2008-2011 <NAME> and Stanford University
; Copyright (C) 2013-2020 Kestrel Institute
;
; License: A 3-clause BSD license. See the file books/3BSD-mod.txt.
;
; Author: <NAME> (<EMAIL>)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(include-book "packbv-def")
(include-book "all-unsigned-byte-p")
(include-book "../bv/bvcat-def")
(include-book "../bv/getbit")
(include-book "../lists-light/repeat")
(local (include-book "../bv/bvcat"))
(local (include-book "../bv/unsigned-byte-p"))
(local (include-book "../../ihs/ihs-lemmas")) ;why? for <-*-left-cancel
(local (include-book "../lists-light/butlast"))
(local (include-book "../../meta/meta-plus-lessp"))
(local (in-theory (disable mod-x-y-=-x+y-for-rationals))) ;bad
(defthm <-cancel-hack
(implies (and (posp size)
(rationalp count)
(rationalp n))
(equal (< (+ (- size) (* count size)) (* n size))
(< (+ -1 count) n)))
:hints (("Goal" :use (:instance <-*-left-cancel (z size) (x (+ -1 count)) (y n)))))
(defthmd packbv-base
(implies (zp itemcount)
(equal (packbv itemcount itemsize items)
0))
:hints (("Goal" :in-theory (enable packbv))))
(defthmd packbv-opener
(implies (not (zp itemcount))
(equal (packbv itemcount itemsize items)
(bvcat itemsize
(car items)
(* itemsize (+ -1 itemcount))
(packbv (+ -1 itemcount) itemsize (cdr items)))))
:hints (("Goal" :in-theory (enable packbv))))
(defthm packbv-of-0
(equal (packbv 0 size bvs)
0)
:hints (("Goal" :in-theory (enable packbv))))
(defthm unsigned-byte-p-of-packbv
(implies (and (natp size)
(natp num))
(unsigned-byte-p (* size num)
(packbv num size items)))
:hints (("Goal" :in-theory (enable packbv))))
(defthm unsigned-byte-p-of-packbv-gen
(implies (and (<= (* size num) n)
(natp size)
(natp n)
(natp num))
(unsigned-byte-p n (packbv num size items)))
:hints (("Goal" :use (:instance unsigned-byte-p-of-packbv)
:in-theory (disable unsigned-byte-p-of-packbv))))
;gen the 1
(defthm bvchop-of-packbv-1-helper
(implies (and (<= n count)
(natp n)
(natp count))
(equal (bvchop n (packbv count 1 bvs))
(packbv n 1 (nthcdr (- count n) bvs))))
:hints (("Goal" :in-theory (enable packbv))))
;gen the 1?
(defthm bvchop-of-packbv-1
(implies (and (<= n count)
(natp count))
(equal (bvchop n (packbv count 1 bvs))
(packbv n 1 (nthcdr (- count n) bvs))))
:hints (("Goal" :use (:instance bvchop-of-packbv-1-helper)
:in-theory (e/d (packbv-base) (bvchop-of-packbv-1-helper)))))
;gen the 1
(defthm getbit-of-packbv-1
(implies (and (natp n)
(integerp count)
(< n count))
(equal (getbit n (packbv count 1 bvs))
(getbit 0 (nth (+ count -1 (- n)) bvs))))
:hints (("Goal" ;:induct (packbv-induct count n bvs)
:do-not '(generalize eliminate-destructors)
:in-theory (enable packbv nth zp))))
(defthm bvchop-of-packbv-helper
(implies (and (<= n count)
(natp n)
(posp size)
(natp count))
(equal (bvchop (* n size) (packbv count size bvs))
(packbv n size (nthcdr (- count n) bvs))))
:hints (("Goal" :do-not '(generalize eliminate-destructors)
:in-theory (e/d (packbv posp nthcdr natp)
(bvcat-equal-rewrite-alt bvcat-equal-rewrite)))))
;gen to non multiples of size?
(defthm bvchop-of-packbv
(implies (and (<= (floor k size) count)
(equal 0 (mod k size))
(natp k)
(posp size)
(natp count))
(equal (bvchop k (packbv count size bvs))
(packbv (floor k size) size (nthcdr (- count (floor k size)) bvs))))
:hints (("Goal" :use (:instance bvchop-of-packbv-helper (n (floor k size)))
:in-theory (disable bvchop-of-packbv-helper))))
(defthm packbv-of-nil
(equal (packbv itemcount itemsize nil)
0)
:hints (("Goal" :in-theory (enable packbv))))
(defthm logtail-of-packbv-gen2
(implies (and (natp n)
(equal len (len vals)))
(equal (logtail (* 8 n) (packbv len 8 vals))
(packbv (- len n) 8 (butlast vals n))))
:hints (("Goal" :induct (packbv len 8 vals)
:in-theory (enable packbv))))
(defthm logtail-8-of-packbv
(implies (equal len (len vals))
(equal (logtail 8 (packbv len 8 vals))
(packbv (- len 1) 8 (butlast vals 1))))
:hints (("Goal" :use (:instance logtail-of-packbv-gen2 (n 1))
:in-theory (disable logtail-of-packbv-gen2))))
(defthm packbv-of-1
(equal (packbv 1 size items)
(bvchop size (first items)))
:hints (("Goal" :in-theory (enable packbv))))
;might not need this if the syntax functions knew the size of packbv
(defthm getbit-of-packbv-too-high
(equal (getbit num (packbv num 1 items))
0)
:hints (("Goal" :in-theory (enable packbv))))
(defthm packbv-of-repeat-of-0
(equal (packbv num 1 (repeat num 0))
0)
:hints (("Goal" :in-theory (enable packbv repeat))))
(defthm packbv-of-true-list-fix
(equal (packbv count size (true-list-fix items))
(packbv count size items))
:hints (("Goal" :in-theory (enable packbv))))
| true |
; BV Lists Library: theorems about packbv
;
; Copyright (C) 2008-2011 PI:NAME:<NAME>END_PI and Stanford University
; Copyright (C) 2013-2020 Kestrel Institute
;
; License: A 3-clause BSD license. See the file books/3BSD-mod.txt.
;
; Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(include-book "packbv-def")
(include-book "all-unsigned-byte-p")
(include-book "../bv/bvcat-def")
(include-book "../bv/getbit")
(include-book "../lists-light/repeat")
(local (include-book "../bv/bvcat"))
(local (include-book "../bv/unsigned-byte-p"))
(local (include-book "../../ihs/ihs-lemmas")) ;why? for <-*-left-cancel
(local (include-book "../lists-light/butlast"))
(local (include-book "../../meta/meta-plus-lessp"))
(local (in-theory (disable mod-x-y-=-x+y-for-rationals))) ;bad
(defthm <-cancel-hack
(implies (and (posp size)
(rationalp count)
(rationalp n))
(equal (< (+ (- size) (* count size)) (* n size))
(< (+ -1 count) n)))
:hints (("Goal" :use (:instance <-*-left-cancel (z size) (x (+ -1 count)) (y n)))))
(defthmd packbv-base
(implies (zp itemcount)
(equal (packbv itemcount itemsize items)
0))
:hints (("Goal" :in-theory (enable packbv))))
(defthmd packbv-opener
(implies (not (zp itemcount))
(equal (packbv itemcount itemsize items)
(bvcat itemsize
(car items)
(* itemsize (+ -1 itemcount))
(packbv (+ -1 itemcount) itemsize (cdr items)))))
:hints (("Goal" :in-theory (enable packbv))))
(defthm packbv-of-0
(equal (packbv 0 size bvs)
0)
:hints (("Goal" :in-theory (enable packbv))))
(defthm unsigned-byte-p-of-packbv
(implies (and (natp size)
(natp num))
(unsigned-byte-p (* size num)
(packbv num size items)))
:hints (("Goal" :in-theory (enable packbv))))
(defthm unsigned-byte-p-of-packbv-gen
(implies (and (<= (* size num) n)
(natp size)
(natp n)
(natp num))
(unsigned-byte-p n (packbv num size items)))
:hints (("Goal" :use (:instance unsigned-byte-p-of-packbv)
:in-theory (disable unsigned-byte-p-of-packbv))))
;gen the 1
(defthm bvchop-of-packbv-1-helper
(implies (and (<= n count)
(natp n)
(natp count))
(equal (bvchop n (packbv count 1 bvs))
(packbv n 1 (nthcdr (- count n) bvs))))
:hints (("Goal" :in-theory (enable packbv))))
;gen the 1?
(defthm bvchop-of-packbv-1
(implies (and (<= n count)
(natp count))
(equal (bvchop n (packbv count 1 bvs))
(packbv n 1 (nthcdr (- count n) bvs))))
:hints (("Goal" :use (:instance bvchop-of-packbv-1-helper)
:in-theory (e/d (packbv-base) (bvchop-of-packbv-1-helper)))))
;gen the 1
(defthm getbit-of-packbv-1
(implies (and (natp n)
(integerp count)
(< n count))
(equal (getbit n (packbv count 1 bvs))
(getbit 0 (nth (+ count -1 (- n)) bvs))))
:hints (("Goal" ;:induct (packbv-induct count n bvs)
:do-not '(generalize eliminate-destructors)
:in-theory (enable packbv nth zp))))
(defthm bvchop-of-packbv-helper
(implies (and (<= n count)
(natp n)
(posp size)
(natp count))
(equal (bvchop (* n size) (packbv count size bvs))
(packbv n size (nthcdr (- count n) bvs))))
:hints (("Goal" :do-not '(generalize eliminate-destructors)
:in-theory (e/d (packbv posp nthcdr natp)
(bvcat-equal-rewrite-alt bvcat-equal-rewrite)))))
;gen to non multiples of size?
(defthm bvchop-of-packbv
(implies (and (<= (floor k size) count)
(equal 0 (mod k size))
(natp k)
(posp size)
(natp count))
(equal (bvchop k (packbv count size bvs))
(packbv (floor k size) size (nthcdr (- count (floor k size)) bvs))))
:hints (("Goal" :use (:instance bvchop-of-packbv-helper (n (floor k size)))
:in-theory (disable bvchop-of-packbv-helper))))
(defthm packbv-of-nil
(equal (packbv itemcount itemsize nil)
0)
:hints (("Goal" :in-theory (enable packbv))))
(defthm logtail-of-packbv-gen2
(implies (and (natp n)
(equal len (len vals)))
(equal (logtail (* 8 n) (packbv len 8 vals))
(packbv (- len n) 8 (butlast vals n))))
:hints (("Goal" :induct (packbv len 8 vals)
:in-theory (enable packbv))))
(defthm logtail-8-of-packbv
(implies (equal len (len vals))
(equal (logtail 8 (packbv len 8 vals))
(packbv (- len 1) 8 (butlast vals 1))))
:hints (("Goal" :use (:instance logtail-of-packbv-gen2 (n 1))
:in-theory (disable logtail-of-packbv-gen2))))
(defthm packbv-of-1
(equal (packbv 1 size items)
(bvchop size (first items)))
:hints (("Goal" :in-theory (enable packbv))))
;might not need this if the syntax functions knew the size of packbv
(defthm getbit-of-packbv-too-high
(equal (getbit num (packbv num 1 items))
0)
:hints (("Goal" :in-theory (enable packbv))))
(defthm packbv-of-repeat-of-0
(equal (packbv num 1 (repeat num 0))
0)
:hints (("Goal" :in-theory (enable packbv repeat))))
(defthm packbv-of-true-list-fix
(equal (packbv count size (true-list-fix items))
(packbv count size items))
:hints (("Goal" :in-theory (enable packbv))))
|
[
{
"context": "(defsystem asdf-linguist-test\n :author \"Fernando Borretti\"\n :mailto \"[email protected]\"\n :license \"MIT\"",
"end": 58,
"score": 0.9998354911804199,
"start": 41,
"tag": "NAME",
"value": "Fernando Borretti"
},
{
"context": "ist-test\n :author \"Fernando Borretti\"\n :mailto \"[email protected]\"\n :license \"MIT\"\n :defsystem-depends-on (:asdf-",
"end": 90,
"score": 0.9999266862869263,
"start": 71,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
asdf-linguist-test.asd
|
eudoxia0/asdf-linguist
| 27 |
(defsystem asdf-linguist-test
:author "Fernando Borretti"
:mailto "[email protected]"
:license "MIT"
:defsystem-depends-on (:asdf-linguist)
:components ((:module "t"
:components
((:module "www"
:components
((:module "css"
:components
((:less "less-input")
(:myth "myth-input")
(:sass "sass-input")
(:sass-strict "sass-strict-input")))))
(:module "build-systems"
:components
((:make "Makefile")))
(:module "tools"
:components
((:module "graphics"
:components
((:dot "dot-input")
(:ditaa "ditaa-input")))
(:module "text"
:components
((:pandoc "test"
:type "md"
:input-type "markdown"
:output-type "html5"
:output-extension "html"
:options "-S")))))))))
|
36143
|
(defsystem asdf-linguist-test
:author "<NAME>"
:mailto "<EMAIL>"
:license "MIT"
:defsystem-depends-on (:asdf-linguist)
:components ((:module "t"
:components
((:module "www"
:components
((:module "css"
:components
((:less "less-input")
(:myth "myth-input")
(:sass "sass-input")
(:sass-strict "sass-strict-input")))))
(:module "build-systems"
:components
((:make "Makefile")))
(:module "tools"
:components
((:module "graphics"
:components
((:dot "dot-input")
(:ditaa "ditaa-input")))
(:module "text"
:components
((:pandoc "test"
:type "md"
:input-type "markdown"
:output-type "html5"
:output-extension "html"
:options "-S")))))))))
| true |
(defsystem asdf-linguist-test
:author "PI:NAME:<NAME>END_PI"
:mailto "PI:EMAIL:<EMAIL>END_PI"
:license "MIT"
:defsystem-depends-on (:asdf-linguist)
:components ((:module "t"
:components
((:module "www"
:components
((:module "css"
:components
((:less "less-input")
(:myth "myth-input")
(:sass "sass-input")
(:sass-strict "sass-strict-input")))))
(:module "build-systems"
:components
((:make "Makefile")))
(:module "tools"
:components
((:module "graphics"
:components
((:dot "dot-input")
(:ditaa "ditaa-input")))
(:module "text"
:components
((:pandoc "test"
:type "md"
:input-type "markdown"
:output-type "html5"
:output-extension "html"
:options "-S")))))))))
|
[
{
"context": "; DEALINGS IN THE SOFTWARE.\n;\n; Original author: Jared Davis <[email protected]>\n\n(in-package \"ACL2\")\n\n(incl",
"end": 1354,
"score": 0.9997519254684448,
"start": 1343,
"tag": "NAME",
"value": "Jared Davis"
},
{
"context": "N THE SOFTWARE.\n;\n; Original author: Jared Davis <[email protected]>\n\n(in-package \"ACL2\")\n\n(include-book \"std/lists/f",
"end": 1375,
"score": 0.999934732913971,
"start": 1356,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/unicode/partition.lisp
|
mayankmanj/acl2
| 305 |
; Processing Unicode Files with ACL2
; Copyright (C) 2005-2006 Kookamara LLC
;
; Contact:
;
; Kookamara LLC
; 11410 Windermere Meadows
; Austin, TX 78759, USA
; http://www.kookamara.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: Jared Davis <[email protected]>
(in-package "ACL2")
(include-book "std/lists/flatten" :dir :system)
(include-book "sum-list")
(local (include-book "std/lists/take" :dir :system))
(local (include-book "z-listp"))
(local (include-book "arithmetic/top-with-meta" :dir :system))
(local (include-book "std/lists/nthcdr" :dir :system))
(defund partition (sizes x)
(declare (xargs :guard (and (nat-listp sizes)
(true-listp x))))
(if (consp sizes)
(cons (take (car sizes) x)
(partition (cdr sizes)
(nthcdr (car sizes) x)))
nil))
(defthm partition-when-not-consp
(implies (not (consp sizes))
(equal (partition sizes x)
nil))
:hints(("Goal" :in-theory (enable partition))))
(defthm partition-of-cons
(equal (partition (cons size sizes) x)
(cons (take size x)
(partition sizes (nthcdr size x))))
:hints(("Goal" :in-theory (enable partition))))
(defthm consp-of-partition-under-iff
(equal (consp (partition sizes x))
(if (partition sizes x)
t
nil))
:hints(("Goal" :in-theory (enable partition))))
(local (defthm sum-list-when-nat-listp-and-z-listp
(implies (and (nat-listp x)
(z-listp x))
(equal (sum-list x)
0))
:hints(("Goal" :induct (len x)))))
(local (defthm reassemble-lemma
(implies (<= (nfix n) (len x))
(equal (append (take n x)
(list-fix (nthcdr n x)))
(list-fix x)))))
(defthm flatten-of-partition
(implies (and (nat-listp sizes)
(equal (sum-list sizes) (len x)))
(equal (flatten (partition sizes x))
(list-fix x)))
:hints(("Goal" :in-theory (enable partition))))
(defthm len-of-car-of-partition
(equal (len (car (partition sizes x)))
(nfix (car sizes))))
|
43044
|
; Processing Unicode Files with ACL2
; Copyright (C) 2005-2006 Kookamara LLC
;
; Contact:
;
; Kookamara LLC
; 11410 Windermere Meadows
; Austin, TX 78759, USA
; http://www.kookamara.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: <NAME> <<EMAIL>>
(in-package "ACL2")
(include-book "std/lists/flatten" :dir :system)
(include-book "sum-list")
(local (include-book "std/lists/take" :dir :system))
(local (include-book "z-listp"))
(local (include-book "arithmetic/top-with-meta" :dir :system))
(local (include-book "std/lists/nthcdr" :dir :system))
(defund partition (sizes x)
(declare (xargs :guard (and (nat-listp sizes)
(true-listp x))))
(if (consp sizes)
(cons (take (car sizes) x)
(partition (cdr sizes)
(nthcdr (car sizes) x)))
nil))
(defthm partition-when-not-consp
(implies (not (consp sizes))
(equal (partition sizes x)
nil))
:hints(("Goal" :in-theory (enable partition))))
(defthm partition-of-cons
(equal (partition (cons size sizes) x)
(cons (take size x)
(partition sizes (nthcdr size x))))
:hints(("Goal" :in-theory (enable partition))))
(defthm consp-of-partition-under-iff
(equal (consp (partition sizes x))
(if (partition sizes x)
t
nil))
:hints(("Goal" :in-theory (enable partition))))
(local (defthm sum-list-when-nat-listp-and-z-listp
(implies (and (nat-listp x)
(z-listp x))
(equal (sum-list x)
0))
:hints(("Goal" :induct (len x)))))
(local (defthm reassemble-lemma
(implies (<= (nfix n) (len x))
(equal (append (take n x)
(list-fix (nthcdr n x)))
(list-fix x)))))
(defthm flatten-of-partition
(implies (and (nat-listp sizes)
(equal (sum-list sizes) (len x)))
(equal (flatten (partition sizes x))
(list-fix x)))
:hints(("Goal" :in-theory (enable partition))))
(defthm len-of-car-of-partition
(equal (len (car (partition sizes x)))
(nfix (car sizes))))
| true |
; Processing Unicode Files with ACL2
; Copyright (C) 2005-2006 Kookamara LLC
;
; Contact:
;
; Kookamara LLC
; 11410 Windermere Meadows
; Austin, TX 78759, USA
; http://www.kookamara.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
(in-package "ACL2")
(include-book "std/lists/flatten" :dir :system)
(include-book "sum-list")
(local (include-book "std/lists/take" :dir :system))
(local (include-book "z-listp"))
(local (include-book "arithmetic/top-with-meta" :dir :system))
(local (include-book "std/lists/nthcdr" :dir :system))
(defund partition (sizes x)
(declare (xargs :guard (and (nat-listp sizes)
(true-listp x))))
(if (consp sizes)
(cons (take (car sizes) x)
(partition (cdr sizes)
(nthcdr (car sizes) x)))
nil))
(defthm partition-when-not-consp
(implies (not (consp sizes))
(equal (partition sizes x)
nil))
:hints(("Goal" :in-theory (enable partition))))
(defthm partition-of-cons
(equal (partition (cons size sizes) x)
(cons (take size x)
(partition sizes (nthcdr size x))))
:hints(("Goal" :in-theory (enable partition))))
(defthm consp-of-partition-under-iff
(equal (consp (partition sizes x))
(if (partition sizes x)
t
nil))
:hints(("Goal" :in-theory (enable partition))))
(local (defthm sum-list-when-nat-listp-and-z-listp
(implies (and (nat-listp x)
(z-listp x))
(equal (sum-list x)
0))
:hints(("Goal" :induct (len x)))))
(local (defthm reassemble-lemma
(implies (<= (nfix n) (len x))
(equal (append (take n x)
(list-fix (nthcdr n x)))
(list-fix x)))))
(defthm flatten-of-partition
(implies (and (nat-listp sizes)
(equal (sum-list sizes) (len x)))
(equal (flatten (partition sizes x))
(list-fix x)))
:hints(("Goal" :in-theory (enable partition))))
(defthm len-of-car-of-partition
(equal (len (car (partition sizes x)))
(nfix (car sizes))))
|
[
{
"context": "; DEALINGS IN THE SOFTWARE.\n;\n; Original author: Jared Davis <[email protected]>\n\n(in-package \"MILAWA\")\n(inc",
"end": 1356,
"score": 0.9994359612464905,
"start": 1345,
"tag": "NAME",
"value": "Jared Davis"
},
{
"context": "N THE SOFTWARE.\n;\n; Original author: Jared Davis <[email protected]>\n\n(in-package \"MILAWA\")\n(include-book \"conditiona",
"end": 1377,
"score": 0.9999352693557739,
"start": 1358,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/projects/milawa/ACL2/bootstrap/level11/elim.lisp
|
mayankmanj/acl2
| 305 |
; Milawa - A Reflective Theorem Prover
; Copyright (C) 2005-2009 Kookamara LLC
;
; Contact:
;
; Kookamara LLC
; 11410 Windermere Meadows
; Austin, TX 78759, USA
; http://www.kookamara.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: Jared Davis <[email protected]>
(in-package "MILAWA")
(include-book "conditional-eqsubst")
(%interactive)
(defthm logic.strip-conclusions-of-restn
;; BOZO this seems to address some of the firstn/restn issues. Move it where it
;; belongs and try using it globally.
(equal (logic.strip-conclusions (restn n x))
(restn n (logic.strip-conclusions x))))
(in-theory (disable restn-of-logic.strip-conclusions))
(ACL2::theory-invariant (ACL2::incompatible (:rewrite logic.strip-conclusions-of-restn)
(:rewrite restn-of-logic.strip-conclusions)))
(%autoprove logic.strip-conclusions-of-restn)
(%disable default
restn-of-logic.strip-conclusions
[outside]restn-of-logic.strip-conclusions)
(defthm logic.strip-conclusions-of-firstn
;; BOZO this seems to address some of the firstn/restn issues. Move it where it
;; belongs and try using it globally.
(equal (logic.strip-conclusions (firstn n x))
(firstn n (logic.strip-conclusions x))))
(in-theory (disable firstn-of-logic.strip-conclusions))
(ACL2::theory-invariant (ACL2::incompatible (:rewrite logic.strip-conclusions-of-firstn)
(:rewrite firstn-of-logic.strip-conclusions)))
(%autoprove logic.strip-conclusions-of-firstn)
(%disable default
firstn-of-logic.strip-conclusions
[outside]firstn-of-logic.strip-conclusions)
(%autoprove logic.substitute-formula-of-logic.disjoin-formulas-free)
(%autoprove lemma-for-aggressive-forcing-logic.substitute-of-logic.replace-subterm
(%logic.term-induction flag x)
(%restrict default definition-of-logic.replace-subterm (equal x 'x)))
(%autoprove aggressive-forcing-logic.substitute-of-logic.replace-subterm
(%use (%instance (%thm lemma-for-aggressive-forcing-logic.substitute-of-logic.replace-subterm)
(flag 'term))))
(%autoprove aggressive-forcing-logic.substitute-list-of-logic.replace-subterm-list
(%use (%instance (%thm lemma-for-aggressive-forcing-logic.substitute-of-logic.replace-subterm)
(flag 'list))))
(%autoprove lemma-for-equal-of-logic.replace-subterm-and-logic.replace-subterm-when-same-term-and-old
(%logic.term-induction flag x)
(%restrict default definition-of-logic.replace-subterm (equal x 'x))
(%restrict default definition-of-logic.subtermp (equal y 'x)))
(%autoprove equal-of-logic.replace-subterm-and-logic.replace-subterm-when-same-term-and-old
(%use (%instance (%thm lemma-for-equal-of-logic.replace-subterm-and-logic.replace-subterm-when-same-term-and-old)
(flag 'term))))
(%autoprove equal-of-logic.replace-subterm-list-and-logic.replace-subterm-list-when-same-term-and-old
(%use (%instance (%thm lemma-for-equal-of-logic.replace-subterm-and-logic.replace-subterm-when-same-term-and-old)
(flag 'list))))
(%autoprove forcing-logic.substitute-of-var-when-first-in-sigma
(%restrict default definition-of-logic.substitute (equal x 'var)))
(%autoprove forcing-logic.substitute-of-var-when-second-in-sigma
(%restrict default definition-of-logic.substitute (equal x 'var)))
(%autoprove equal-of-first-and-second-when-uniquep)
(%autoprove equal-of-second-and-first-when-uniquep) ;; probably unnecessary via term order??
(%autoprove memberp-of-first-of-difference-in-removed
(%disable default
memberp-of-car
[outside]memberp-of-car)
(%use (%instance (%thm memberp-of-car)
(x (difference x y)))))
(%autoprove memberp-of-second-of-difference-in-removed
(%disable default memberp-of-second)
(%use (%instance (%thm memberp-of-second)
(x (difference x y)))))
(%autoadmit elim.flag-collect-destructed-variables)
(%autoadmit elim.flag-slow-collect-destructed-variables)
(%autoadmit elim.collect-destructed-variables)
(%autoadmit elim.collect-destructed-variables-list)
(%autoprove true-listp-of-elim.flag-collect-destructed-variables
(%autoinduct elim.flag-collect-destructed-variables flag x acc)
(%restrict default elim.flag-collect-destructed-variables (equal x 'x)))
(%autoprove elim.flag-slow-collect-destructed-variables-equiv
(%autoinduct elim.flag-collect-destructed-variables flag x acc)
(%restrict default elim.flag-collect-destructed-variables (equal x 'x))
(%restrict default elim.flag-slow-collect-destructed-variables (equal x 'x)))
(%autoprove definition-of-elim.collect-destructed-variables
(%forcingp nil)
(%restrict default elim.flag-slow-collect-destructed-variables (equal x 'x))
(%enable default
elim.collect-destructed-variables
elim.collect-destructed-variables-list))
(%autoprove definition-of-elim.collect-destructed-variables-list
(%restrict default elim.flag-slow-collect-destructed-variables (equal x 'x))
(%enable default
elim.collect-destructed-variables
elim.collect-destructed-variables-list))
(%autoprove lemma-for-logic.variable-listp-of-elim.collect-destructed-variables
(%logic.term-induction flag x)
(%restrict default definition-of-elim.collect-destructed-variables (equal x 'x))
(%restrict default definition-of-elim.collect-destructed-variables-list (equal x 'x)))
(%autoprove logic.variable-listp-of-elim.collect-destructed-variables
(%use (%instance (%thm lemma-for-logic.variable-listp-of-elim.collect-destructed-variables)
(flag 'term))))
(%autoprove logic.variable-listp-of-elim.collect-destructed-variables-list
(%use (%instance (%thm lemma-for-logic.variable-listp-of-elim.collect-destructed-variables)
(flag 'list))))
;; BOZO stupid name, should be called duplicity
(%autoadmit fast-count)
(%autoadmit slow-count)
(%autoadmit count)
(%autoprove fast-count-as-slow-count
(%autoinduct fast-count a x acc)
(%restrict default fast-count (equal x 'x))
(%restrict default slow-count (equal x 'x)))
(%autoprove definition-of-count
(%enable default count)
(%restrict default slow-count (equal x 'x))
(%enable default fast-count-as-slow-count))
(%autoprove count-when-not-consp
(%restrict default definition-of-count (equal x 'x)))
(%autoprove count-of-cons
(%restrict default definition-of-count (equal x '(cons b x))))
(%autoprove natp-of-count
(%cdr-induction x))
(%autoprove count-of-zero
(%cdr-induction x))
(%autoprove count-of-list-fix
(%cdr-induction x))
(%autoprove count-of-app
(%cdr-induction x))
(%autoprove count-of-rev
(%cdr-induction x))
(%autoprove count-when-not-memberp
(%cdr-induction x))
(%autoadmit aux-maximal-count)
(%autoprove memberp-of-aux-maximal-count
(%autoinduct aux-maximal-count best best-count domain x)
(%restrict default aux-maximal-count (equal domain 'domain)))
(%autoprove aux-maximal-count-when-not-consp-of-x
(%autoinduct aux-maximal-count best best-count domain x)
(%restrict default aux-maximal-count (equal domain 'domain)))
(%autoadmit maximal-count)
(%autoprove maximal-count-when-not-consp
(%enable default maximal-count))
(%autoprove memberp-of-maximal-count
(%enable default maximal-count))
(%autoadmit elim.find-backup-var)
(%autoprove logic.variablep-of-elim.find-backup-var
(%autoinduct elim.find-backup-var)
(%restrict default elim.find-backup-var (equal x 'x)))
(%autoadmit elim.choose-var-to-eliminate)
(%autoprove lemma-for-logic.variablep-of-elim.choose-var-to-eliminate
(%disable default logic.variablep-when-memberp-of-logic.variable-listp)
(%use (%instance (%thm logic.variablep-when-memberp-of-logic.variable-listp)
(a (maximal-count x))
(x x))))
(%autoprove logic.variablep-of-elim.choose-var-to-eliminate
(%enable default
elim.choose-var-to-eliminate
lemma-for-logic.variablep-of-elim.choose-var-to-eliminate))
(%deflist logic.variable-list-listp (x)
(logic.variable-listp x))
(%defmap :map (elim.namesp x)
:key (logic.variablep x)
:val (logic.variable-listp x)
:key-list (logic.variable-listp x)
:val-list (logic.variable-list-listp x)
:val-of-nil t)
(%autoadmit elim.pick-fresh-vars)
(encapsulate
()
(local (%disable default
unusual-consp-rules
unusual-memberp-rules
unusual-subsetp-rules
expensive-term/formula-inference
type-set-like-rules
list-of-first-and-second-when-len-2
))
(local (%enable default elim.pick-fresh-vars))
(%autoprove forcing-logic.variablep-of-first-of-elim.pick-fresh-vars)
(%autoprove forcing-logic.variablep-of-second-of-elim.pick-fresh-vars)
(%autoprove forcing-logic.memberp-of-first-of-elim.pick-fresh-vars)
(%autoprove forcing-logic.memberp-of-second-of-elim.pick-fresh-vars)
(%autoprove forcing-equal-of-first-and-second-of-elim.pick-fresh-vars)
(%autoprove forcing-equal-of-second-and-first-of-elim.pick-fresh-vars))
(%autoadmit elim.elim-clause)
(encapsulate
()
(local (%enable default elim.elim-clause))
(%autoprove forcing-logic.term-list-listp-of-elim.elim-clause)
(%autoprove forcing-cons-listp-of-elim.elim-clause)
(%autoprove forcing-logic.term-list-list-atblp-of-elim.elim-clause))
(%autoadmit elim.elim-clause-bldr)
(encapsulate
()
(local (%enable default
axiom-cons-of-car-and-cdr
elim.elim-clause
logic.term-formula
redefinition-of-logic.term-list-formulas
elim.elim-clause-bldr))
(%autoprove forcing-logic.appealp-of-elim.elim-clause-bldr)
(%autoprove forcing-logic.conclusion-of-elim.elim-clause-bldr)
(%autoprove forcing-logic.proofp-of-elim.elim-clause-bldr))
(%autoadmit elim.elim-clause-list)
(%autoprove true-listp-of-elim.elim-clause-list
(%cdr-induction x)
(%restrict default elim.elim-clause-list (equal x 'x)))
(%autoprove forcing-logic.term-list-listp-of-elim.elim-clause-list
(%cdr-induction x)
(%restrict default elim.elim-clause-list (equal x 'x)))
(%autoprove forcing-logic.term-list-list-atblp-of-elim.elim-clause-list
(%cdr-induction x)
(%restrict default elim.elim-clause-list (equal x 'x)))
(%autoprove forcing-cons-listp-of-elim.elim-clause-list
(%cdr-induction x)
(%restrict default elim.elim-clause-list (equal x 'x)))
(%autoadmit elim.elim-clause-list-bldr)
(encapsulate
()
(%autoprove dangerous-decomposition-of-app
(%cdr-cdr-induction x a)
(%restrict default firstn (equal n '(len a)))
(%restrict default restn (equal n '(len a))))
(local (%enable default dangerous-decomposition-of-app))
(%autoprove forcing-logic.appeal-listp-of-elim.elim-clause-list-bldr
(%autoinduct elim.elim-clause-list-bldr)
(%restrict default elim.elim-clause-list-bldr (equal x 'x))
(%restrict default elim.elim-clause-list (equal x 'x)))
(%autoprove forcing-logic.strip-conclusions-of-elim.elim-clause-list-bldr
(%autoinduct elim.elim-clause-list-bldr)
(%restrict default elim.elim-clause-list-bldr (equal x 'x))
(%restrict default elim.elim-clause-list (equal x 'x)))
(%autoprove forcing-logic.proof-listp-of-elim.elim-clause-list-bldr
(%autoinduct elim.elim-clause-list-bldr)
(%restrict default elim.elim-clause-list-bldr (equal x 'x))
(%restrict default elim.elim-clause-list (equal x 'x))))
(%autoadmit tactic.elim-first-okp)
(%autoprove booleanp-of-tactic.elim-first-okp
(%enable default tactic.elim-first-okp))
(%autoadmit tactic.elim-first-tac)
(%autoprove forcing-tactic.skeletonp-of-tactic.elim-first-tac
(%enable default tactic.elim-first-tac))
(%autoprove forcing-tactic.elim-first-okp-of-tactic.elim-first-tac
(%enable default tactic.elim-first-tac tactic.elim-first-okp))
(%autoadmit tactic.elim-first-compile)
(encapsulate
()
(local (%enable default
tactic.elim-first-okp
tactic.elim-first-compile))
(local (%enable default dangerous-decomposition-of-app))
(%autoprove forcing-logic.appeal-listp-of-tactic.elim-first-compile
(%auto :strategy (cleanup split urewrite crewrite))
(%fertilize (LOGIC.STRIP-CONCLUSIONS PROOFS)
(LOGIC.DISJOIN-EACH-FORMULA-LIST
(LOGIC.TERM-LIST-LIST-FORMULAS (TACTIC.SKELETON->GOALS X)))))
(%autoprove forcing-logic.strip-conclusions-of-tactic.elim-first-compile
(%auto :strategy (cleanup split urewrite crewrite))
(%fertilize (LOGIC.STRIP-CONCLUSIONS PROOFS)
(LOGIC.DISJOIN-EACH-FORMULA-LIST
(LOGIC.TERM-LIST-LIST-FORMULAS (TACTIC.SKELETON->GOALS X))))
(%auto :strategy (cleanup split urewrite crewrite))
(%fertilize (LOGIC.STRIP-CONCLUSIONS PROOFS)
(LOGIC.DISJOIN-EACH-FORMULA-LIST
(LOGIC.TERM-LIST-LIST-FORMULAS (TACTIC.SKELETON->GOALS X)))))
(%autoprove forcing-logic.proof-listp-of-tactic.elim-first-compile
(%auto :strategy (cleanup split urewrite crewrite))
(%fertilize (LOGIC.STRIP-CONCLUSIONS PROOFS)
(LOGIC.DISJOIN-EACH-FORMULA-LIST
(LOGIC.TERM-LIST-LIST-FORMULAS (TACTIC.SKELETON->GOALS X))))))
(%autoadmit tactic.elim-all-okp)
(%autoprove booleanp-of-tactic.elim-all-okp
(%enable default tactic.elim-all-okp))
(%autoadmit tactic.elim-all-tac)
(%autoprove forcing-tactic.skeletonp-of-tactic.elim-all-tac
(%enable default tactic.elim-all-tac))
(%autoprove forcing-tactic.elim-all-okp-of-tactic.elim-all-tac
(%enable default tactic.elim-all-tac tactic.elim-all-okp))
(%autoadmit tactic.elim-all-compile)
(encapsulate
()
(local (%enable default tactic.elim-all-okp tactic.elim-all-compile))
(%autoprove forcing-logic.appeal-listp-of-tactic.elim-all-compile)
(%autoprove forcing-logic.strip-conclusions-of-tactic.elim-all-compile)
(%autoprove forcing-logic.proof-listp-of-tactic.elim-all-compile))
(%ensure-exactly-these-rules-are-missing "../../tactics/elim")
|
51210
|
; Milawa - A Reflective Theorem Prover
; Copyright (C) 2005-2009 Kookamara LLC
;
; Contact:
;
; Kookamara LLC
; 11410 Windermere Meadows
; Austin, TX 78759, USA
; http://www.kookamara.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: <NAME> <<EMAIL>>
(in-package "MILAWA")
(include-book "conditional-eqsubst")
(%interactive)
(defthm logic.strip-conclusions-of-restn
;; BOZO this seems to address some of the firstn/restn issues. Move it where it
;; belongs and try using it globally.
(equal (logic.strip-conclusions (restn n x))
(restn n (logic.strip-conclusions x))))
(in-theory (disable restn-of-logic.strip-conclusions))
(ACL2::theory-invariant (ACL2::incompatible (:rewrite logic.strip-conclusions-of-restn)
(:rewrite restn-of-logic.strip-conclusions)))
(%autoprove logic.strip-conclusions-of-restn)
(%disable default
restn-of-logic.strip-conclusions
[outside]restn-of-logic.strip-conclusions)
(defthm logic.strip-conclusions-of-firstn
;; BOZO this seems to address some of the firstn/restn issues. Move it where it
;; belongs and try using it globally.
(equal (logic.strip-conclusions (firstn n x))
(firstn n (logic.strip-conclusions x))))
(in-theory (disable firstn-of-logic.strip-conclusions))
(ACL2::theory-invariant (ACL2::incompatible (:rewrite logic.strip-conclusions-of-firstn)
(:rewrite firstn-of-logic.strip-conclusions)))
(%autoprove logic.strip-conclusions-of-firstn)
(%disable default
firstn-of-logic.strip-conclusions
[outside]firstn-of-logic.strip-conclusions)
(%autoprove logic.substitute-formula-of-logic.disjoin-formulas-free)
(%autoprove lemma-for-aggressive-forcing-logic.substitute-of-logic.replace-subterm
(%logic.term-induction flag x)
(%restrict default definition-of-logic.replace-subterm (equal x 'x)))
(%autoprove aggressive-forcing-logic.substitute-of-logic.replace-subterm
(%use (%instance (%thm lemma-for-aggressive-forcing-logic.substitute-of-logic.replace-subterm)
(flag 'term))))
(%autoprove aggressive-forcing-logic.substitute-list-of-logic.replace-subterm-list
(%use (%instance (%thm lemma-for-aggressive-forcing-logic.substitute-of-logic.replace-subterm)
(flag 'list))))
(%autoprove lemma-for-equal-of-logic.replace-subterm-and-logic.replace-subterm-when-same-term-and-old
(%logic.term-induction flag x)
(%restrict default definition-of-logic.replace-subterm (equal x 'x))
(%restrict default definition-of-logic.subtermp (equal y 'x)))
(%autoprove equal-of-logic.replace-subterm-and-logic.replace-subterm-when-same-term-and-old
(%use (%instance (%thm lemma-for-equal-of-logic.replace-subterm-and-logic.replace-subterm-when-same-term-and-old)
(flag 'term))))
(%autoprove equal-of-logic.replace-subterm-list-and-logic.replace-subterm-list-when-same-term-and-old
(%use (%instance (%thm lemma-for-equal-of-logic.replace-subterm-and-logic.replace-subterm-when-same-term-and-old)
(flag 'list))))
(%autoprove forcing-logic.substitute-of-var-when-first-in-sigma
(%restrict default definition-of-logic.substitute (equal x 'var)))
(%autoprove forcing-logic.substitute-of-var-when-second-in-sigma
(%restrict default definition-of-logic.substitute (equal x 'var)))
(%autoprove equal-of-first-and-second-when-uniquep)
(%autoprove equal-of-second-and-first-when-uniquep) ;; probably unnecessary via term order??
(%autoprove memberp-of-first-of-difference-in-removed
(%disable default
memberp-of-car
[outside]memberp-of-car)
(%use (%instance (%thm memberp-of-car)
(x (difference x y)))))
(%autoprove memberp-of-second-of-difference-in-removed
(%disable default memberp-of-second)
(%use (%instance (%thm memberp-of-second)
(x (difference x y)))))
(%autoadmit elim.flag-collect-destructed-variables)
(%autoadmit elim.flag-slow-collect-destructed-variables)
(%autoadmit elim.collect-destructed-variables)
(%autoadmit elim.collect-destructed-variables-list)
(%autoprove true-listp-of-elim.flag-collect-destructed-variables
(%autoinduct elim.flag-collect-destructed-variables flag x acc)
(%restrict default elim.flag-collect-destructed-variables (equal x 'x)))
(%autoprove elim.flag-slow-collect-destructed-variables-equiv
(%autoinduct elim.flag-collect-destructed-variables flag x acc)
(%restrict default elim.flag-collect-destructed-variables (equal x 'x))
(%restrict default elim.flag-slow-collect-destructed-variables (equal x 'x)))
(%autoprove definition-of-elim.collect-destructed-variables
(%forcingp nil)
(%restrict default elim.flag-slow-collect-destructed-variables (equal x 'x))
(%enable default
elim.collect-destructed-variables
elim.collect-destructed-variables-list))
(%autoprove definition-of-elim.collect-destructed-variables-list
(%restrict default elim.flag-slow-collect-destructed-variables (equal x 'x))
(%enable default
elim.collect-destructed-variables
elim.collect-destructed-variables-list))
(%autoprove lemma-for-logic.variable-listp-of-elim.collect-destructed-variables
(%logic.term-induction flag x)
(%restrict default definition-of-elim.collect-destructed-variables (equal x 'x))
(%restrict default definition-of-elim.collect-destructed-variables-list (equal x 'x)))
(%autoprove logic.variable-listp-of-elim.collect-destructed-variables
(%use (%instance (%thm lemma-for-logic.variable-listp-of-elim.collect-destructed-variables)
(flag 'term))))
(%autoprove logic.variable-listp-of-elim.collect-destructed-variables-list
(%use (%instance (%thm lemma-for-logic.variable-listp-of-elim.collect-destructed-variables)
(flag 'list))))
;; BOZO stupid name, should be called duplicity
(%autoadmit fast-count)
(%autoadmit slow-count)
(%autoadmit count)
(%autoprove fast-count-as-slow-count
(%autoinduct fast-count a x acc)
(%restrict default fast-count (equal x 'x))
(%restrict default slow-count (equal x 'x)))
(%autoprove definition-of-count
(%enable default count)
(%restrict default slow-count (equal x 'x))
(%enable default fast-count-as-slow-count))
(%autoprove count-when-not-consp
(%restrict default definition-of-count (equal x 'x)))
(%autoprove count-of-cons
(%restrict default definition-of-count (equal x '(cons b x))))
(%autoprove natp-of-count
(%cdr-induction x))
(%autoprove count-of-zero
(%cdr-induction x))
(%autoprove count-of-list-fix
(%cdr-induction x))
(%autoprove count-of-app
(%cdr-induction x))
(%autoprove count-of-rev
(%cdr-induction x))
(%autoprove count-when-not-memberp
(%cdr-induction x))
(%autoadmit aux-maximal-count)
(%autoprove memberp-of-aux-maximal-count
(%autoinduct aux-maximal-count best best-count domain x)
(%restrict default aux-maximal-count (equal domain 'domain)))
(%autoprove aux-maximal-count-when-not-consp-of-x
(%autoinduct aux-maximal-count best best-count domain x)
(%restrict default aux-maximal-count (equal domain 'domain)))
(%autoadmit maximal-count)
(%autoprove maximal-count-when-not-consp
(%enable default maximal-count))
(%autoprove memberp-of-maximal-count
(%enable default maximal-count))
(%autoadmit elim.find-backup-var)
(%autoprove logic.variablep-of-elim.find-backup-var
(%autoinduct elim.find-backup-var)
(%restrict default elim.find-backup-var (equal x 'x)))
(%autoadmit elim.choose-var-to-eliminate)
(%autoprove lemma-for-logic.variablep-of-elim.choose-var-to-eliminate
(%disable default logic.variablep-when-memberp-of-logic.variable-listp)
(%use (%instance (%thm logic.variablep-when-memberp-of-logic.variable-listp)
(a (maximal-count x))
(x x))))
(%autoprove logic.variablep-of-elim.choose-var-to-eliminate
(%enable default
elim.choose-var-to-eliminate
lemma-for-logic.variablep-of-elim.choose-var-to-eliminate))
(%deflist logic.variable-list-listp (x)
(logic.variable-listp x))
(%defmap :map (elim.namesp x)
:key (logic.variablep x)
:val (logic.variable-listp x)
:key-list (logic.variable-listp x)
:val-list (logic.variable-list-listp x)
:val-of-nil t)
(%autoadmit elim.pick-fresh-vars)
(encapsulate
()
(local (%disable default
unusual-consp-rules
unusual-memberp-rules
unusual-subsetp-rules
expensive-term/formula-inference
type-set-like-rules
list-of-first-and-second-when-len-2
))
(local (%enable default elim.pick-fresh-vars))
(%autoprove forcing-logic.variablep-of-first-of-elim.pick-fresh-vars)
(%autoprove forcing-logic.variablep-of-second-of-elim.pick-fresh-vars)
(%autoprove forcing-logic.memberp-of-first-of-elim.pick-fresh-vars)
(%autoprove forcing-logic.memberp-of-second-of-elim.pick-fresh-vars)
(%autoprove forcing-equal-of-first-and-second-of-elim.pick-fresh-vars)
(%autoprove forcing-equal-of-second-and-first-of-elim.pick-fresh-vars))
(%autoadmit elim.elim-clause)
(encapsulate
()
(local (%enable default elim.elim-clause))
(%autoprove forcing-logic.term-list-listp-of-elim.elim-clause)
(%autoprove forcing-cons-listp-of-elim.elim-clause)
(%autoprove forcing-logic.term-list-list-atblp-of-elim.elim-clause))
(%autoadmit elim.elim-clause-bldr)
(encapsulate
()
(local (%enable default
axiom-cons-of-car-and-cdr
elim.elim-clause
logic.term-formula
redefinition-of-logic.term-list-formulas
elim.elim-clause-bldr))
(%autoprove forcing-logic.appealp-of-elim.elim-clause-bldr)
(%autoprove forcing-logic.conclusion-of-elim.elim-clause-bldr)
(%autoprove forcing-logic.proofp-of-elim.elim-clause-bldr))
(%autoadmit elim.elim-clause-list)
(%autoprove true-listp-of-elim.elim-clause-list
(%cdr-induction x)
(%restrict default elim.elim-clause-list (equal x 'x)))
(%autoprove forcing-logic.term-list-listp-of-elim.elim-clause-list
(%cdr-induction x)
(%restrict default elim.elim-clause-list (equal x 'x)))
(%autoprove forcing-logic.term-list-list-atblp-of-elim.elim-clause-list
(%cdr-induction x)
(%restrict default elim.elim-clause-list (equal x 'x)))
(%autoprove forcing-cons-listp-of-elim.elim-clause-list
(%cdr-induction x)
(%restrict default elim.elim-clause-list (equal x 'x)))
(%autoadmit elim.elim-clause-list-bldr)
(encapsulate
()
(%autoprove dangerous-decomposition-of-app
(%cdr-cdr-induction x a)
(%restrict default firstn (equal n '(len a)))
(%restrict default restn (equal n '(len a))))
(local (%enable default dangerous-decomposition-of-app))
(%autoprove forcing-logic.appeal-listp-of-elim.elim-clause-list-bldr
(%autoinduct elim.elim-clause-list-bldr)
(%restrict default elim.elim-clause-list-bldr (equal x 'x))
(%restrict default elim.elim-clause-list (equal x 'x)))
(%autoprove forcing-logic.strip-conclusions-of-elim.elim-clause-list-bldr
(%autoinduct elim.elim-clause-list-bldr)
(%restrict default elim.elim-clause-list-bldr (equal x 'x))
(%restrict default elim.elim-clause-list (equal x 'x)))
(%autoprove forcing-logic.proof-listp-of-elim.elim-clause-list-bldr
(%autoinduct elim.elim-clause-list-bldr)
(%restrict default elim.elim-clause-list-bldr (equal x 'x))
(%restrict default elim.elim-clause-list (equal x 'x))))
(%autoadmit tactic.elim-first-okp)
(%autoprove booleanp-of-tactic.elim-first-okp
(%enable default tactic.elim-first-okp))
(%autoadmit tactic.elim-first-tac)
(%autoprove forcing-tactic.skeletonp-of-tactic.elim-first-tac
(%enable default tactic.elim-first-tac))
(%autoprove forcing-tactic.elim-first-okp-of-tactic.elim-first-tac
(%enable default tactic.elim-first-tac tactic.elim-first-okp))
(%autoadmit tactic.elim-first-compile)
(encapsulate
()
(local (%enable default
tactic.elim-first-okp
tactic.elim-first-compile))
(local (%enable default dangerous-decomposition-of-app))
(%autoprove forcing-logic.appeal-listp-of-tactic.elim-first-compile
(%auto :strategy (cleanup split urewrite crewrite))
(%fertilize (LOGIC.STRIP-CONCLUSIONS PROOFS)
(LOGIC.DISJOIN-EACH-FORMULA-LIST
(LOGIC.TERM-LIST-LIST-FORMULAS (TACTIC.SKELETON->GOALS X)))))
(%autoprove forcing-logic.strip-conclusions-of-tactic.elim-first-compile
(%auto :strategy (cleanup split urewrite crewrite))
(%fertilize (LOGIC.STRIP-CONCLUSIONS PROOFS)
(LOGIC.DISJOIN-EACH-FORMULA-LIST
(LOGIC.TERM-LIST-LIST-FORMULAS (TACTIC.SKELETON->GOALS X))))
(%auto :strategy (cleanup split urewrite crewrite))
(%fertilize (LOGIC.STRIP-CONCLUSIONS PROOFS)
(LOGIC.DISJOIN-EACH-FORMULA-LIST
(LOGIC.TERM-LIST-LIST-FORMULAS (TACTIC.SKELETON->GOALS X)))))
(%autoprove forcing-logic.proof-listp-of-tactic.elim-first-compile
(%auto :strategy (cleanup split urewrite crewrite))
(%fertilize (LOGIC.STRIP-CONCLUSIONS PROOFS)
(LOGIC.DISJOIN-EACH-FORMULA-LIST
(LOGIC.TERM-LIST-LIST-FORMULAS (TACTIC.SKELETON->GOALS X))))))
(%autoadmit tactic.elim-all-okp)
(%autoprove booleanp-of-tactic.elim-all-okp
(%enable default tactic.elim-all-okp))
(%autoadmit tactic.elim-all-tac)
(%autoprove forcing-tactic.skeletonp-of-tactic.elim-all-tac
(%enable default tactic.elim-all-tac))
(%autoprove forcing-tactic.elim-all-okp-of-tactic.elim-all-tac
(%enable default tactic.elim-all-tac tactic.elim-all-okp))
(%autoadmit tactic.elim-all-compile)
(encapsulate
()
(local (%enable default tactic.elim-all-okp tactic.elim-all-compile))
(%autoprove forcing-logic.appeal-listp-of-tactic.elim-all-compile)
(%autoprove forcing-logic.strip-conclusions-of-tactic.elim-all-compile)
(%autoprove forcing-logic.proof-listp-of-tactic.elim-all-compile))
(%ensure-exactly-these-rules-are-missing "../../tactics/elim")
| true |
; Milawa - A Reflective Theorem Prover
; Copyright (C) 2005-2009 Kookamara LLC
;
; Contact:
;
; Kookamara LLC
; 11410 Windermere Meadows
; Austin, TX 78759, USA
; http://www.kookamara.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
(in-package "MILAWA")
(include-book "conditional-eqsubst")
(%interactive)
(defthm logic.strip-conclusions-of-restn
;; BOZO this seems to address some of the firstn/restn issues. Move it where it
;; belongs and try using it globally.
(equal (logic.strip-conclusions (restn n x))
(restn n (logic.strip-conclusions x))))
(in-theory (disable restn-of-logic.strip-conclusions))
(ACL2::theory-invariant (ACL2::incompatible (:rewrite logic.strip-conclusions-of-restn)
(:rewrite restn-of-logic.strip-conclusions)))
(%autoprove logic.strip-conclusions-of-restn)
(%disable default
restn-of-logic.strip-conclusions
[outside]restn-of-logic.strip-conclusions)
(defthm logic.strip-conclusions-of-firstn
;; BOZO this seems to address some of the firstn/restn issues. Move it where it
;; belongs and try using it globally.
(equal (logic.strip-conclusions (firstn n x))
(firstn n (logic.strip-conclusions x))))
(in-theory (disable firstn-of-logic.strip-conclusions))
(ACL2::theory-invariant (ACL2::incompatible (:rewrite logic.strip-conclusions-of-firstn)
(:rewrite firstn-of-logic.strip-conclusions)))
(%autoprove logic.strip-conclusions-of-firstn)
(%disable default
firstn-of-logic.strip-conclusions
[outside]firstn-of-logic.strip-conclusions)
(%autoprove logic.substitute-formula-of-logic.disjoin-formulas-free)
(%autoprove lemma-for-aggressive-forcing-logic.substitute-of-logic.replace-subterm
(%logic.term-induction flag x)
(%restrict default definition-of-logic.replace-subterm (equal x 'x)))
(%autoprove aggressive-forcing-logic.substitute-of-logic.replace-subterm
(%use (%instance (%thm lemma-for-aggressive-forcing-logic.substitute-of-logic.replace-subterm)
(flag 'term))))
(%autoprove aggressive-forcing-logic.substitute-list-of-logic.replace-subterm-list
(%use (%instance (%thm lemma-for-aggressive-forcing-logic.substitute-of-logic.replace-subterm)
(flag 'list))))
(%autoprove lemma-for-equal-of-logic.replace-subterm-and-logic.replace-subterm-when-same-term-and-old
(%logic.term-induction flag x)
(%restrict default definition-of-logic.replace-subterm (equal x 'x))
(%restrict default definition-of-logic.subtermp (equal y 'x)))
(%autoprove equal-of-logic.replace-subterm-and-logic.replace-subterm-when-same-term-and-old
(%use (%instance (%thm lemma-for-equal-of-logic.replace-subterm-and-logic.replace-subterm-when-same-term-and-old)
(flag 'term))))
(%autoprove equal-of-logic.replace-subterm-list-and-logic.replace-subterm-list-when-same-term-and-old
(%use (%instance (%thm lemma-for-equal-of-logic.replace-subterm-and-logic.replace-subterm-when-same-term-and-old)
(flag 'list))))
(%autoprove forcing-logic.substitute-of-var-when-first-in-sigma
(%restrict default definition-of-logic.substitute (equal x 'var)))
(%autoprove forcing-logic.substitute-of-var-when-second-in-sigma
(%restrict default definition-of-logic.substitute (equal x 'var)))
(%autoprove equal-of-first-and-second-when-uniquep)
(%autoprove equal-of-second-and-first-when-uniquep) ;; probably unnecessary via term order??
(%autoprove memberp-of-first-of-difference-in-removed
(%disable default
memberp-of-car
[outside]memberp-of-car)
(%use (%instance (%thm memberp-of-car)
(x (difference x y)))))
(%autoprove memberp-of-second-of-difference-in-removed
(%disable default memberp-of-second)
(%use (%instance (%thm memberp-of-second)
(x (difference x y)))))
(%autoadmit elim.flag-collect-destructed-variables)
(%autoadmit elim.flag-slow-collect-destructed-variables)
(%autoadmit elim.collect-destructed-variables)
(%autoadmit elim.collect-destructed-variables-list)
(%autoprove true-listp-of-elim.flag-collect-destructed-variables
(%autoinduct elim.flag-collect-destructed-variables flag x acc)
(%restrict default elim.flag-collect-destructed-variables (equal x 'x)))
(%autoprove elim.flag-slow-collect-destructed-variables-equiv
(%autoinduct elim.flag-collect-destructed-variables flag x acc)
(%restrict default elim.flag-collect-destructed-variables (equal x 'x))
(%restrict default elim.flag-slow-collect-destructed-variables (equal x 'x)))
(%autoprove definition-of-elim.collect-destructed-variables
(%forcingp nil)
(%restrict default elim.flag-slow-collect-destructed-variables (equal x 'x))
(%enable default
elim.collect-destructed-variables
elim.collect-destructed-variables-list))
(%autoprove definition-of-elim.collect-destructed-variables-list
(%restrict default elim.flag-slow-collect-destructed-variables (equal x 'x))
(%enable default
elim.collect-destructed-variables
elim.collect-destructed-variables-list))
(%autoprove lemma-for-logic.variable-listp-of-elim.collect-destructed-variables
(%logic.term-induction flag x)
(%restrict default definition-of-elim.collect-destructed-variables (equal x 'x))
(%restrict default definition-of-elim.collect-destructed-variables-list (equal x 'x)))
(%autoprove logic.variable-listp-of-elim.collect-destructed-variables
(%use (%instance (%thm lemma-for-logic.variable-listp-of-elim.collect-destructed-variables)
(flag 'term))))
(%autoprove logic.variable-listp-of-elim.collect-destructed-variables-list
(%use (%instance (%thm lemma-for-logic.variable-listp-of-elim.collect-destructed-variables)
(flag 'list))))
;; BOZO stupid name, should be called duplicity
(%autoadmit fast-count)
(%autoadmit slow-count)
(%autoadmit count)
(%autoprove fast-count-as-slow-count
(%autoinduct fast-count a x acc)
(%restrict default fast-count (equal x 'x))
(%restrict default slow-count (equal x 'x)))
(%autoprove definition-of-count
(%enable default count)
(%restrict default slow-count (equal x 'x))
(%enable default fast-count-as-slow-count))
(%autoprove count-when-not-consp
(%restrict default definition-of-count (equal x 'x)))
(%autoprove count-of-cons
(%restrict default definition-of-count (equal x '(cons b x))))
(%autoprove natp-of-count
(%cdr-induction x))
(%autoprove count-of-zero
(%cdr-induction x))
(%autoprove count-of-list-fix
(%cdr-induction x))
(%autoprove count-of-app
(%cdr-induction x))
(%autoprove count-of-rev
(%cdr-induction x))
(%autoprove count-when-not-memberp
(%cdr-induction x))
(%autoadmit aux-maximal-count)
(%autoprove memberp-of-aux-maximal-count
(%autoinduct aux-maximal-count best best-count domain x)
(%restrict default aux-maximal-count (equal domain 'domain)))
(%autoprove aux-maximal-count-when-not-consp-of-x
(%autoinduct aux-maximal-count best best-count domain x)
(%restrict default aux-maximal-count (equal domain 'domain)))
(%autoadmit maximal-count)
(%autoprove maximal-count-when-not-consp
(%enable default maximal-count))
(%autoprove memberp-of-maximal-count
(%enable default maximal-count))
(%autoadmit elim.find-backup-var)
(%autoprove logic.variablep-of-elim.find-backup-var
(%autoinduct elim.find-backup-var)
(%restrict default elim.find-backup-var (equal x 'x)))
(%autoadmit elim.choose-var-to-eliminate)
(%autoprove lemma-for-logic.variablep-of-elim.choose-var-to-eliminate
(%disable default logic.variablep-when-memberp-of-logic.variable-listp)
(%use (%instance (%thm logic.variablep-when-memberp-of-logic.variable-listp)
(a (maximal-count x))
(x x))))
(%autoprove logic.variablep-of-elim.choose-var-to-eliminate
(%enable default
elim.choose-var-to-eliminate
lemma-for-logic.variablep-of-elim.choose-var-to-eliminate))
(%deflist logic.variable-list-listp (x)
(logic.variable-listp x))
(%defmap :map (elim.namesp x)
:key (logic.variablep x)
:val (logic.variable-listp x)
:key-list (logic.variable-listp x)
:val-list (logic.variable-list-listp x)
:val-of-nil t)
(%autoadmit elim.pick-fresh-vars)
(encapsulate
()
(local (%disable default
unusual-consp-rules
unusual-memberp-rules
unusual-subsetp-rules
expensive-term/formula-inference
type-set-like-rules
list-of-first-and-second-when-len-2
))
(local (%enable default elim.pick-fresh-vars))
(%autoprove forcing-logic.variablep-of-first-of-elim.pick-fresh-vars)
(%autoprove forcing-logic.variablep-of-second-of-elim.pick-fresh-vars)
(%autoprove forcing-logic.memberp-of-first-of-elim.pick-fresh-vars)
(%autoprove forcing-logic.memberp-of-second-of-elim.pick-fresh-vars)
(%autoprove forcing-equal-of-first-and-second-of-elim.pick-fresh-vars)
(%autoprove forcing-equal-of-second-and-first-of-elim.pick-fresh-vars))
(%autoadmit elim.elim-clause)
(encapsulate
()
(local (%enable default elim.elim-clause))
(%autoprove forcing-logic.term-list-listp-of-elim.elim-clause)
(%autoprove forcing-cons-listp-of-elim.elim-clause)
(%autoprove forcing-logic.term-list-list-atblp-of-elim.elim-clause))
(%autoadmit elim.elim-clause-bldr)
(encapsulate
()
(local (%enable default
axiom-cons-of-car-and-cdr
elim.elim-clause
logic.term-formula
redefinition-of-logic.term-list-formulas
elim.elim-clause-bldr))
(%autoprove forcing-logic.appealp-of-elim.elim-clause-bldr)
(%autoprove forcing-logic.conclusion-of-elim.elim-clause-bldr)
(%autoprove forcing-logic.proofp-of-elim.elim-clause-bldr))
(%autoadmit elim.elim-clause-list)
(%autoprove true-listp-of-elim.elim-clause-list
(%cdr-induction x)
(%restrict default elim.elim-clause-list (equal x 'x)))
(%autoprove forcing-logic.term-list-listp-of-elim.elim-clause-list
(%cdr-induction x)
(%restrict default elim.elim-clause-list (equal x 'x)))
(%autoprove forcing-logic.term-list-list-atblp-of-elim.elim-clause-list
(%cdr-induction x)
(%restrict default elim.elim-clause-list (equal x 'x)))
(%autoprove forcing-cons-listp-of-elim.elim-clause-list
(%cdr-induction x)
(%restrict default elim.elim-clause-list (equal x 'x)))
(%autoadmit elim.elim-clause-list-bldr)
(encapsulate
()
(%autoprove dangerous-decomposition-of-app
(%cdr-cdr-induction x a)
(%restrict default firstn (equal n '(len a)))
(%restrict default restn (equal n '(len a))))
(local (%enable default dangerous-decomposition-of-app))
(%autoprove forcing-logic.appeal-listp-of-elim.elim-clause-list-bldr
(%autoinduct elim.elim-clause-list-bldr)
(%restrict default elim.elim-clause-list-bldr (equal x 'x))
(%restrict default elim.elim-clause-list (equal x 'x)))
(%autoprove forcing-logic.strip-conclusions-of-elim.elim-clause-list-bldr
(%autoinduct elim.elim-clause-list-bldr)
(%restrict default elim.elim-clause-list-bldr (equal x 'x))
(%restrict default elim.elim-clause-list (equal x 'x)))
(%autoprove forcing-logic.proof-listp-of-elim.elim-clause-list-bldr
(%autoinduct elim.elim-clause-list-bldr)
(%restrict default elim.elim-clause-list-bldr (equal x 'x))
(%restrict default elim.elim-clause-list (equal x 'x))))
(%autoadmit tactic.elim-first-okp)
(%autoprove booleanp-of-tactic.elim-first-okp
(%enable default tactic.elim-first-okp))
(%autoadmit tactic.elim-first-tac)
(%autoprove forcing-tactic.skeletonp-of-tactic.elim-first-tac
(%enable default tactic.elim-first-tac))
(%autoprove forcing-tactic.elim-first-okp-of-tactic.elim-first-tac
(%enable default tactic.elim-first-tac tactic.elim-first-okp))
(%autoadmit tactic.elim-first-compile)
(encapsulate
()
(local (%enable default
tactic.elim-first-okp
tactic.elim-first-compile))
(local (%enable default dangerous-decomposition-of-app))
(%autoprove forcing-logic.appeal-listp-of-tactic.elim-first-compile
(%auto :strategy (cleanup split urewrite crewrite))
(%fertilize (LOGIC.STRIP-CONCLUSIONS PROOFS)
(LOGIC.DISJOIN-EACH-FORMULA-LIST
(LOGIC.TERM-LIST-LIST-FORMULAS (TACTIC.SKELETON->GOALS X)))))
(%autoprove forcing-logic.strip-conclusions-of-tactic.elim-first-compile
(%auto :strategy (cleanup split urewrite crewrite))
(%fertilize (LOGIC.STRIP-CONCLUSIONS PROOFS)
(LOGIC.DISJOIN-EACH-FORMULA-LIST
(LOGIC.TERM-LIST-LIST-FORMULAS (TACTIC.SKELETON->GOALS X))))
(%auto :strategy (cleanup split urewrite crewrite))
(%fertilize (LOGIC.STRIP-CONCLUSIONS PROOFS)
(LOGIC.DISJOIN-EACH-FORMULA-LIST
(LOGIC.TERM-LIST-LIST-FORMULAS (TACTIC.SKELETON->GOALS X)))))
(%autoprove forcing-logic.proof-listp-of-tactic.elim-first-compile
(%auto :strategy (cleanup split urewrite crewrite))
(%fertilize (LOGIC.STRIP-CONCLUSIONS PROOFS)
(LOGIC.DISJOIN-EACH-FORMULA-LIST
(LOGIC.TERM-LIST-LIST-FORMULAS (TACTIC.SKELETON->GOALS X))))))
(%autoadmit tactic.elim-all-okp)
(%autoprove booleanp-of-tactic.elim-all-okp
(%enable default tactic.elim-all-okp))
(%autoadmit tactic.elim-all-tac)
(%autoprove forcing-tactic.skeletonp-of-tactic.elim-all-tac
(%enable default tactic.elim-all-tac))
(%autoprove forcing-tactic.elim-all-okp-of-tactic.elim-all-tac
(%enable default tactic.elim-all-tac tactic.elim-all-okp))
(%autoadmit tactic.elim-all-compile)
(encapsulate
()
(local (%enable default tactic.elim-all-okp tactic.elim-all-compile))
(%autoprove forcing-logic.appeal-listp-of-tactic.elim-all-compile)
(%autoprove forcing-logic.strip-conclusions-of-tactic.elim-all-compile)
(%autoprove forcing-logic.proof-listp-of-tactic.elim-all-compile))
(%ensure-exactly-these-rules-are-missing "../../tactics/elim")
|
[
{
"context": "ile is a part of avm project.\n Copyright (c) 2016 Masayuki Takagi ([email protected])\n|#\n\n(in-package :cl-user)\n(d",
"end": 77,
"score": 0.9998269081115723,
"start": 62,
"tag": "NAME",
"value": "Masayuki Takagi"
},
{
"context": "vm project.\n Copyright (c) 2016 Masayuki Takagi ([email protected])\n|#\n\n(in-package :cl-user)\n(defpackage avm.lang.c",
"end": 97,
"score": 0.9999260306358337,
"start": 79,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
src/lang/compiler/cuda/k-normal.lisp
|
JMC-design/avm
| 45 |
#|
This file is a part of avm project.
Copyright (c) 2016 Masayuki Takagi ([email protected])
|#
(in-package :cl-user)
(defpackage avm.lang.compiler.cuda.k-normal
(:use :cl
:avm
:avm.lang.syntax)
(:export :k-normal
:*gentmp-counter*))
(in-package :avm.lang.compiler.cuda.k-normal)
;;
;; Gentmp
(defvar *gentmp-counter* 0)
(defun gentmp ()
(prog1 (intern (format nil "T~A" *gentmp-counter*))
(incf *gentmp-counter*)))
;;
;; K-normalization
(defun k-normal (form)
(cond
((literal-p form) (k-normal-literal form))
((reference-p form) (k-normal-reference form))
((accessor-p form) (k-normal-accessor form))
((the-p form) (k-normal-the form))
((if-p form) (k-normal-if form))
((let-p form) (k-normal-let form))
((flet-p form) (k-normal-flet form))
((labels-p form) (k-normal-labels form))
((setf-p form) (k-normal-setf form))
((apply-p form) (k-normal-apply form))
(t (error "The value ~S is an invalid form." form))))
(defun k-normal-literal (form)
form)
(defun k-normal-reference (form)
form)
(defun k-normal-accessor (form)
(k-normal-apply form))
(defun k-normal-the (form)
(let ((type (the-type form))
(value (the-value form)))
(if (or (literal-p value) (reference-p value))
`(the ,type ,value)
(let ((tmp (gentmp))
(value1 (k-normal value)))
`(let ((,tmp ,value1))
(the ,type ,tmp))))))
(defun k-normal-if (form)
(let ((test-form (if-test-form form))
(then-form (if-then-form form))
(else-form (if-else-form form)))
(let ((tmp (gentmp))
(test-form1 (k-normal test-form))
(then-form1 (k-normal then-form))
(else-form1 (k-normal else-form)))
(if (or (literal-p test-form) (reference-p test-form))
`(if ,test-form ,then-form1 ,else-form1)
`(let ((,tmp ,test-form1))
(if ,tmp ,then-form1 ,else-form1))))))
(defun k-normal-let (form)
(flet ((aux (binding)
(destructuring-bind (var value) binding
(let ((value1 (k-normal value)))
`(,var ,value1)))))
(let ((bindings (let-bindings form))
(body (let-body form)))
(let ((bindings1 (mapcar #'aux bindings))
(body1 (k-normal body)))
`(let ,bindings1 ,body1)))))
(defun k-normal-flet (form)
(let ((bindings (flet-bindings form))
(body (flet-body form)))
(%k-normal-flet 'flet bindings body)))
(defun %k-normal-flet (op bindings body)
(flet ((aux (binding)
(destructuring-bind (name args body) binding
(let ((body1 (k-normal body)))
`(,name ,args ,body1)))))
(let ((bindings1 (mapcar #'aux bindings))
(body1 (k-normal body)))
`(,op ,bindings1 ,body1))))
(defun k-normal-labels (form)
(let ((bindings (labels-bindings form))
(body (labels-body form)))
(%k-normal-flet 'labels bindings body)))
(defun k-normal-setf (form)
(let ((place (setf-place form))
(value (setf-value form)))
(multiple-value-bind (fn place1) (k-normal-place place)
(if (or (literal-p value)
(reference-p value))
(funcall fn `(setf ,place1 ,value))
(let ((tmp (gentmp))
(value1 (k-normal value)))
`(let ((,tmp ,value1))
,(funcall fn `(setf ,place1 ,tmp))))))))
(defun k-normal-place (place)
(cond
((reference-place-p place) (k-normal-reference-place place))
((vector-place-p place) (k-normal-vector-place place))
((array-place-p place) (k-normal-array-place place))
(t (error "Must not be reached."))))
(defun k-normal-reference-place (place)
(values #'identity place))
(defun k-normal-vector-place (place)
(let ((operator (vector-place-operator place))
(value (vector-place-value place)))
(multiple-value-bind (fn value1) (k-normal-place value)
(values fn `(,operator ,value1)))))
(defun k-normal-array-place (place)
(let ((value (array-place-value place))
(index (array-place-index place)))
(multiple-value-bind (fn value1) (k-normal-place value)
(if (or (literal-p index)
(reference-p index))
(values fn `(aref ,value1 ,index))
(let ((tmp (gentmp))
(index1 (k-normal index)))
(values #'(lambda (form)
`(let ((,tmp ,index1))
,(funcall fn form)))
`(aref ,value1 ,tmp)))))))
(defun k-normal-apply (form)
(let ((operator (apply-operator form))
(operands (apply-operands form)))
(%k-normal-apply operator operands nil)))
(defun %k-normal-apply (operator operands tmps)
(if operands
(destructuring-bind (operand . operands1) operands
(if (or (literal-p operand) (reference-p operand))
(%k-normal-apply operator operands1 (cons operand tmps))
(let ((tmp (gentmp))
(operand1 (k-normal operand)))
`(let ((,tmp ,operand1))
,(%k-normal-apply operator operands1 (cons tmp tmps))))))
`(,operator ,@(nreverse tmps))))
|
7814
|
#|
This file is a part of avm project.
Copyright (c) 2016 <NAME> (<EMAIL>)
|#
(in-package :cl-user)
(defpackage avm.lang.compiler.cuda.k-normal
(:use :cl
:avm
:avm.lang.syntax)
(:export :k-normal
:*gentmp-counter*))
(in-package :avm.lang.compiler.cuda.k-normal)
;;
;; Gentmp
(defvar *gentmp-counter* 0)
(defun gentmp ()
(prog1 (intern (format nil "T~A" *gentmp-counter*))
(incf *gentmp-counter*)))
;;
;; K-normalization
(defun k-normal (form)
(cond
((literal-p form) (k-normal-literal form))
((reference-p form) (k-normal-reference form))
((accessor-p form) (k-normal-accessor form))
((the-p form) (k-normal-the form))
((if-p form) (k-normal-if form))
((let-p form) (k-normal-let form))
((flet-p form) (k-normal-flet form))
((labels-p form) (k-normal-labels form))
((setf-p form) (k-normal-setf form))
((apply-p form) (k-normal-apply form))
(t (error "The value ~S is an invalid form." form))))
(defun k-normal-literal (form)
form)
(defun k-normal-reference (form)
form)
(defun k-normal-accessor (form)
(k-normal-apply form))
(defun k-normal-the (form)
(let ((type (the-type form))
(value (the-value form)))
(if (or (literal-p value) (reference-p value))
`(the ,type ,value)
(let ((tmp (gentmp))
(value1 (k-normal value)))
`(let ((,tmp ,value1))
(the ,type ,tmp))))))
(defun k-normal-if (form)
(let ((test-form (if-test-form form))
(then-form (if-then-form form))
(else-form (if-else-form form)))
(let ((tmp (gentmp))
(test-form1 (k-normal test-form))
(then-form1 (k-normal then-form))
(else-form1 (k-normal else-form)))
(if (or (literal-p test-form) (reference-p test-form))
`(if ,test-form ,then-form1 ,else-form1)
`(let ((,tmp ,test-form1))
(if ,tmp ,then-form1 ,else-form1))))))
(defun k-normal-let (form)
(flet ((aux (binding)
(destructuring-bind (var value) binding
(let ((value1 (k-normal value)))
`(,var ,value1)))))
(let ((bindings (let-bindings form))
(body (let-body form)))
(let ((bindings1 (mapcar #'aux bindings))
(body1 (k-normal body)))
`(let ,bindings1 ,body1)))))
(defun k-normal-flet (form)
(let ((bindings (flet-bindings form))
(body (flet-body form)))
(%k-normal-flet 'flet bindings body)))
(defun %k-normal-flet (op bindings body)
(flet ((aux (binding)
(destructuring-bind (name args body) binding
(let ((body1 (k-normal body)))
`(,name ,args ,body1)))))
(let ((bindings1 (mapcar #'aux bindings))
(body1 (k-normal body)))
`(,op ,bindings1 ,body1))))
(defun k-normal-labels (form)
(let ((bindings (labels-bindings form))
(body (labels-body form)))
(%k-normal-flet 'labels bindings body)))
(defun k-normal-setf (form)
(let ((place (setf-place form))
(value (setf-value form)))
(multiple-value-bind (fn place1) (k-normal-place place)
(if (or (literal-p value)
(reference-p value))
(funcall fn `(setf ,place1 ,value))
(let ((tmp (gentmp))
(value1 (k-normal value)))
`(let ((,tmp ,value1))
,(funcall fn `(setf ,place1 ,tmp))))))))
(defun k-normal-place (place)
(cond
((reference-place-p place) (k-normal-reference-place place))
((vector-place-p place) (k-normal-vector-place place))
((array-place-p place) (k-normal-array-place place))
(t (error "Must not be reached."))))
(defun k-normal-reference-place (place)
(values #'identity place))
(defun k-normal-vector-place (place)
(let ((operator (vector-place-operator place))
(value (vector-place-value place)))
(multiple-value-bind (fn value1) (k-normal-place value)
(values fn `(,operator ,value1)))))
(defun k-normal-array-place (place)
(let ((value (array-place-value place))
(index (array-place-index place)))
(multiple-value-bind (fn value1) (k-normal-place value)
(if (or (literal-p index)
(reference-p index))
(values fn `(aref ,value1 ,index))
(let ((tmp (gentmp))
(index1 (k-normal index)))
(values #'(lambda (form)
`(let ((,tmp ,index1))
,(funcall fn form)))
`(aref ,value1 ,tmp)))))))
(defun k-normal-apply (form)
(let ((operator (apply-operator form))
(operands (apply-operands form)))
(%k-normal-apply operator operands nil)))
(defun %k-normal-apply (operator operands tmps)
(if operands
(destructuring-bind (operand . operands1) operands
(if (or (literal-p operand) (reference-p operand))
(%k-normal-apply operator operands1 (cons operand tmps))
(let ((tmp (gentmp))
(operand1 (k-normal operand)))
`(let ((,tmp ,operand1))
,(%k-normal-apply operator operands1 (cons tmp tmps))))))
`(,operator ,@(nreverse tmps))))
| true |
#|
This file is a part of avm project.
Copyright (c) 2016 PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
|#
(in-package :cl-user)
(defpackage avm.lang.compiler.cuda.k-normal
(:use :cl
:avm
:avm.lang.syntax)
(:export :k-normal
:*gentmp-counter*))
(in-package :avm.lang.compiler.cuda.k-normal)
;;
;; Gentmp
(defvar *gentmp-counter* 0)
(defun gentmp ()
(prog1 (intern (format nil "T~A" *gentmp-counter*))
(incf *gentmp-counter*)))
;;
;; K-normalization
(defun k-normal (form)
(cond
((literal-p form) (k-normal-literal form))
((reference-p form) (k-normal-reference form))
((accessor-p form) (k-normal-accessor form))
((the-p form) (k-normal-the form))
((if-p form) (k-normal-if form))
((let-p form) (k-normal-let form))
((flet-p form) (k-normal-flet form))
((labels-p form) (k-normal-labels form))
((setf-p form) (k-normal-setf form))
((apply-p form) (k-normal-apply form))
(t (error "The value ~S is an invalid form." form))))
(defun k-normal-literal (form)
form)
(defun k-normal-reference (form)
form)
(defun k-normal-accessor (form)
(k-normal-apply form))
(defun k-normal-the (form)
(let ((type (the-type form))
(value (the-value form)))
(if (or (literal-p value) (reference-p value))
`(the ,type ,value)
(let ((tmp (gentmp))
(value1 (k-normal value)))
`(let ((,tmp ,value1))
(the ,type ,tmp))))))
(defun k-normal-if (form)
(let ((test-form (if-test-form form))
(then-form (if-then-form form))
(else-form (if-else-form form)))
(let ((tmp (gentmp))
(test-form1 (k-normal test-form))
(then-form1 (k-normal then-form))
(else-form1 (k-normal else-form)))
(if (or (literal-p test-form) (reference-p test-form))
`(if ,test-form ,then-form1 ,else-form1)
`(let ((,tmp ,test-form1))
(if ,tmp ,then-form1 ,else-form1))))))
(defun k-normal-let (form)
(flet ((aux (binding)
(destructuring-bind (var value) binding
(let ((value1 (k-normal value)))
`(,var ,value1)))))
(let ((bindings (let-bindings form))
(body (let-body form)))
(let ((bindings1 (mapcar #'aux bindings))
(body1 (k-normal body)))
`(let ,bindings1 ,body1)))))
(defun k-normal-flet (form)
(let ((bindings (flet-bindings form))
(body (flet-body form)))
(%k-normal-flet 'flet bindings body)))
(defun %k-normal-flet (op bindings body)
(flet ((aux (binding)
(destructuring-bind (name args body) binding
(let ((body1 (k-normal body)))
`(,name ,args ,body1)))))
(let ((bindings1 (mapcar #'aux bindings))
(body1 (k-normal body)))
`(,op ,bindings1 ,body1))))
(defun k-normal-labels (form)
(let ((bindings (labels-bindings form))
(body (labels-body form)))
(%k-normal-flet 'labels bindings body)))
(defun k-normal-setf (form)
(let ((place (setf-place form))
(value (setf-value form)))
(multiple-value-bind (fn place1) (k-normal-place place)
(if (or (literal-p value)
(reference-p value))
(funcall fn `(setf ,place1 ,value))
(let ((tmp (gentmp))
(value1 (k-normal value)))
`(let ((,tmp ,value1))
,(funcall fn `(setf ,place1 ,tmp))))))))
(defun k-normal-place (place)
(cond
((reference-place-p place) (k-normal-reference-place place))
((vector-place-p place) (k-normal-vector-place place))
((array-place-p place) (k-normal-array-place place))
(t (error "Must not be reached."))))
(defun k-normal-reference-place (place)
(values #'identity place))
(defun k-normal-vector-place (place)
(let ((operator (vector-place-operator place))
(value (vector-place-value place)))
(multiple-value-bind (fn value1) (k-normal-place value)
(values fn `(,operator ,value1)))))
(defun k-normal-array-place (place)
(let ((value (array-place-value place))
(index (array-place-index place)))
(multiple-value-bind (fn value1) (k-normal-place value)
(if (or (literal-p index)
(reference-p index))
(values fn `(aref ,value1 ,index))
(let ((tmp (gentmp))
(index1 (k-normal index)))
(values #'(lambda (form)
`(let ((,tmp ,index1))
,(funcall fn form)))
`(aref ,value1 ,tmp)))))))
(defun k-normal-apply (form)
(let ((operator (apply-operator form))
(operands (apply-operands form)))
(%k-normal-apply operator operands nil)))
(defun %k-normal-apply (operator operands tmps)
(if operands
(destructuring-bind (operand . operands1) operands
(if (or (literal-p operand) (reference-p operand))
(%k-normal-apply operator operands1 (cons operand tmps))
(let ((tmp (gentmp))
(operand1 (k-normal operand)))
`(let ((,tmp ,operand1))
,(%k-normal-apply operator operands1 (cons tmp tmps))))))
`(,operator ,@(nreverse tmps))))
|
[
{
"context": " srfi-60.lisp\n\n(cl:in-package \"https://github.com/g000001/srfi-60#internals\")\n\n;;;; \"logical.scm\", bit acce",
"end": 61,
"score": 0.9981808662414551,
"start": 54,
"tag": "USERNAME",
"value": "g000001"
},
{
"context": "eme\n;;; Copyright (C) 1991, 1993, 2001, 2003, 2005 Aubrey Jaffer\n;\n;Permission to copy this software, to modify it",
"end": 213,
"score": 0.999883234500885,
"start": 200,
"tag": "NAME",
"value": "Aubrey Jaffer"
}
] |
srfi-60.lisp
|
g000001/srfi-60
| 1 |
;;;; srfi-60.lisp
(cl:in-package "https://github.com/g000001/srfi-60#internals")
;;;; "logical.scm", bit access and operations for integers for Scheme
;;; Copyright (C) 1991, 1993, 2001, 2003, 2005 Aubrey Jaffer
;
;Permission to copy this software, to modify it, to redistribute it,
;to distribute modified versions, and to use it for any purpose is
;granted, subject to the following restrictions and understandings.
;
;1. Any copy made of this software must include this copyright notice
;in full.
;
;2. I have made no warranty or representation that the operation of
;this software will be error-free, and I am under no obligation to
;provide any services, by way of maintenance, update, or otherwise.
;
;3. In conjunction with products arising from the use of this
;material, there shall be no use of my name in any advertising,
;promotional, or sales literature without prior written consent in
;each case.
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (symbol-function 'arithmetic-shift)
#'cl:ash))
(define-symbol-macro |LOGICAL:BOOLE-XOR|
'#(#(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15)
#(1 0 3 2 5 4 7 6 9 8 11 10 13 12 15 14)
#(2 3 0 1 6 7 4 5 10 11 8 9 14 15 12 13)
#(3 2 1 0 7 6 5 4 11 10 9 8 15 14 13 12)
#(4 5 6 7 0 1 2 3 12 13 14 15 8 9 10 11)
#(5 4 7 6 1 0 3 2 13 12 15 14 9 8 11 10)
#(6 7 4 5 2 3 0 1 14 15 12 13 10 11 8 9)
#(7 6 5 4 3 2 1 0 15 14 13 12 11 10 9 8)
#(8 9 10 11 12 13 14 15 0 1 2 3 4 5 6 7)
#(9 8 11 10 13 12 15 14 1 0 3 2 5 4 7 6)
#(10 11 8 9 14 15 12 13 2 3 0 1 6 7 4 5)
#(11 10 9 8 15 14 13 12 3 2 1 0 7 6 5 4)
#(12 13 14 15 8 9 10 11 4 5 6 7 0 1 2 3)
#(13 12 15 14 9 8 11 10 5 4 7 6 1 0 3 2)
#(14 15 12 13 10 11 8 9 6 7 4 5 2 3 0 1)
#(15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0)))
(define-symbol-macro |LOGICAL:BOOLE-AND|
'#(#(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
#(0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1)
#(0 0 2 2 0 0 2 2 0 0 2 2 0 0 2 2)
#(0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3)
#(0 0 0 0 4 4 4 4 0 0 0 0 4 4 4 4)
#(0 1 0 1 4 5 4 5 0 1 0 1 4 5 4 5)
#(0 0 2 2 4 4 6 6 0 0 2 2 4 4 6 6)
#(0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7)
#(0 0 0 0 0 0 0 0 8 8 8 8 8 8 8 8)
#(0 1 0 1 0 1 0 1 8 9 8 9 8 9 8 9)
#(0 0 2 2 0 0 2 2 8 8 10 10 8 8 10 10)
#(0 1 2 3 0 1 2 3 8 9 10 11 8 9 10 11)
#(0 0 0 0 4 4 4 4 8 8 8 8 12 12 12 12)
#(0 1 0 1 4 5 4 5 8 9 8 9 12 13 12 13)
#(0 0 2 2 4 4 6 6 8 8 10 10 12 12 14 14)
#(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15)))
(defun |LOGICAL:ASH-4| (x)
(if (minusp x)
(+ -1 (truncate (+ 1 x) 16))
(truncate x 16)))
(declaim (ftype (function (function integer) function)
|LOGICAL:REDUCE|))
(defun |LOGICAL:REDUCE| (op4 ident)
(declare (optimize (safety 0) (speed 3) (space 3)))
(lambda (&rest args)
(do ((res ident (funcall op4 res (car rgs) 1 0))
(rgs args (cdr rgs)))
((null rgs) res))))
;@
#+sbcl
(defun logand (&rest args)
(declare (optimize (space 3))
(inline |LOGICAL:REDUCE|))
(labels ((lgand (n2 n1 scl acc)
(declare (integer n2 n1))
(cond ((= n1 n2) (+ acc (* scl n1)))
((zerop n2) acc)
((zerop n1) acc)
(:else (lgand (|LOGICAL:ASH-4| n2)
(|LOGICAL:ASH-4| n1)
(* 16 scl)
(+ (* (svref (svref |LOGICAL:BOOLE-AND|
(mod n1 16) )
(mod n2 16) )
scl )
acc ))))))
(apply (|LOGICAL:REDUCE| #'lgand -1)
args) ))
#-sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (symbol-function 'logand) #'cl:logand))
;@
#+sbcl
(defun logior (&rest args)
(declare (inline |LOGICAL:REDUCE|))
(labels ((lgior (n2 n1 scl acc)
(cond ((= n1 n2) (+ acc (* scl n1)))
((zerop n2) (+ acc (* scl n1)))
((zerop n1) (+ acc (* scl n2)))
(:else (lgior (|LOGICAL:ASH-4| n2)
(|LOGICAL:ASH-4| n1)
(* 16 scl)
(+ (* (- 15 (svref
(svref |LOGICAL:BOOLE-AND|
(- 15 (mod n1 16)))
(- 15 (mod n2 16))))
scl)
acc))))))
(apply (|LOGICAL:REDUCE| #'lgior 0)
args )))
#-sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (symbol-function 'logior) #'cl:logior))
;@
#+sbcl
(defun logxor (&rest args)
(labels ((lgxor (n2 n1 scl acc)
(cond ((= n1 n2) acc)
((zerop n2) (+ acc (* scl n1)))
((zerop n1) (+ acc (* scl n2)))
(:else (lgxor (|LOGICAL:ASH-4| n2)
(|LOGICAL:ASH-4| n1)
(* 16 scl)
(+ (* (svref (svref |LOGICAL:BOOLE-XOR|
(mod n1 16) )
(mod n2 16) )
scl )
acc ))))))
(apply (|LOGICAL:REDUCE| #'lgxor 0)
args)) )
#-sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (symbol-function 'logxor) #'cl:logxor))
;@
(defun lognot (n) (- -1 n))
;@
(defun logtest (n1 n2)
(not (zerop (logand n1 n2))))
;@
(defun logbit? (index n)
(logtest (expt 2 index) n))
;@
(defun copy-bit (index to bool)
(if bool
(logior to (arithmetic-shift 1 index))
(logand to (lognot (arithmetic-shift 1 index)))))
;@
(defun bitwise-if (mask n0 n1)
(logior (logand mask n0)
(logand (lognot mask) n1)))
;@
(defun bit-field (n start end)
(logand (lognot (arithmetic-shift -1 (- end start)))
(arithmetic-shift n (- start))))
;@
(defun copy-bit-field (to from start end)
(bitwise-if (arithmetic-shift (lognot (arithmetic-shift -1 (- end start))) start)
(arithmetic-shift from start)
to))
;@
(defun rotate-bit-field (n count start end)
(let ((width (- end start)))
(setq count (mod count width))
(let ((mask (lognot (arithmetic-shift -1 width))))
(let ((zn (logand mask (arithmetic-shift n (- start)))))
(logior (arithmetic-shift
(logior (logand mask (arithmetic-shift zn count))
(arithmetic-shift zn (- count width)) )
start )
(logand (lognot (arithmetic-shift mask start)) n) )))))
;@
(defun ash (n count)
(if (minusp count)
(let ((k (expt 2 (- count))))
(if (minusp n)
(+ -1 (floor (+ 1 n) k))
(floor n k)))
(* (expt 2 count) n)))
;@
(defun integer-length (n)
(labels ((intlen (n tot)
(case n
((0 -1) (+ 0 tot))
((1 -2) (+ 1 tot))
((2 3 -3 -4) (+ 2 tot))
((4 5 6 7 -5 -6 -7 -8) (+ 3 tot))
(otherwise (intlen (|LOGICAL:ASH-4| n) (+ 4 tot))))))
(intlen n 0)))
;@
(defun bitwise-bit-count (n)
(labels ((logcnt (n tot)
(if (zerop n)
tot
(logcnt (floor n 16)
(+ (svref
'#(0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4)
(mod n 16))
tot)))))
(cond ((minusp n) (lognot (logcnt (lognot n) 0)))
((plusp n) (logcnt n 0))
(:else 0))))
;@
(defun logcount (n)
(cond ((minusp n) (bitwise-bit-count (lognot n)))
(:else (bitwise-bit-count n))))
;@
(defun log2-binary-factors (n)
(+ -1 (integer-length (logand n (- n)))))
(defun bit-reverse (k n)
(do ((m (if (minusp n) (lognot n) n) (ash m -1))
(k (+ -1 k) (+ -1 k))
(rvs 0 (logior (ash rvs 1) (logand 1 m))))
((minusp k) (if (minusp n) (lognot rvs) rvs))))
;@
(defun reverse-bit-field (n start end)
(let ((width (- end start)))
(let ((mask (lognot (ash -1 width))))
(let ((zn (logand mask (ash n (- start)))))
(logior (ash (bit-reverse width zn) start)
(logand (lognot (ash mask start)) n) )))))
;@
(defun integer->list (k &rest len)
(if (null len)
(do ((k k (ash k -1))
(lst '() (cons (oddp k) lst)) )
((<= k 0) lst) )
(do ((idx (+ -1 (car len)) (+ -1 idx))
(k k (ash k -1))
(lst '() (cons (oddp k) lst)) )
((minusp idx) lst) )))
;@
(defun list->integer (bools)
(do ((bs bools (cdr bs))
(acc 0 (+ acc acc (if (car bs) 1 0))))
((null bs) acc)))
(defun booleans->integer (&rest bools)
(list->integer bools))
;;;;@ SRFI-60 aliases
(macrolet ((define (new old)
`(setf (symbol-function ',new)
(function ,old))))
(define arithmetic-shift ash)
(define bitwise-ior logior)
(define bitwise-xor logxor)
(define bitwise-and logand)
(define bitwise-not lognot)
(define bit-count logcount)
(define bit-set? logbit?)
(define any-bits-set? logtest)
(define first-set-bit log2-binary-factors)
(define bitwise-merge bitwise-if))
;;; Legacy
;;(define (logical:rotate k count len) (rotate-bit-field k count 0 len))
;;(define (logical:ones deg) (lognot (ash -1 deg)))
;;(define integer-expt expt) ; legacy name
|
2760
|
;;;; srfi-60.lisp
(cl:in-package "https://github.com/g000001/srfi-60#internals")
;;;; "logical.scm", bit access and operations for integers for Scheme
;;; Copyright (C) 1991, 1993, 2001, 2003, 2005 <NAME>
;
;Permission to copy this software, to modify it, to redistribute it,
;to distribute modified versions, and to use it for any purpose is
;granted, subject to the following restrictions and understandings.
;
;1. Any copy made of this software must include this copyright notice
;in full.
;
;2. I have made no warranty or representation that the operation of
;this software will be error-free, and I am under no obligation to
;provide any services, by way of maintenance, update, or otherwise.
;
;3. In conjunction with products arising from the use of this
;material, there shall be no use of my name in any advertising,
;promotional, or sales literature without prior written consent in
;each case.
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (symbol-function 'arithmetic-shift)
#'cl:ash))
(define-symbol-macro |LOGICAL:BOOLE-XOR|
'#(#(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15)
#(1 0 3 2 5 4 7 6 9 8 11 10 13 12 15 14)
#(2 3 0 1 6 7 4 5 10 11 8 9 14 15 12 13)
#(3 2 1 0 7 6 5 4 11 10 9 8 15 14 13 12)
#(4 5 6 7 0 1 2 3 12 13 14 15 8 9 10 11)
#(5 4 7 6 1 0 3 2 13 12 15 14 9 8 11 10)
#(6 7 4 5 2 3 0 1 14 15 12 13 10 11 8 9)
#(7 6 5 4 3 2 1 0 15 14 13 12 11 10 9 8)
#(8 9 10 11 12 13 14 15 0 1 2 3 4 5 6 7)
#(9 8 11 10 13 12 15 14 1 0 3 2 5 4 7 6)
#(10 11 8 9 14 15 12 13 2 3 0 1 6 7 4 5)
#(11 10 9 8 15 14 13 12 3 2 1 0 7 6 5 4)
#(12 13 14 15 8 9 10 11 4 5 6 7 0 1 2 3)
#(13 12 15 14 9 8 11 10 5 4 7 6 1 0 3 2)
#(14 15 12 13 10 11 8 9 6 7 4 5 2 3 0 1)
#(15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0)))
(define-symbol-macro |LOGICAL:BOOLE-AND|
'#(#(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
#(0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1)
#(0 0 2 2 0 0 2 2 0 0 2 2 0 0 2 2)
#(0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3)
#(0 0 0 0 4 4 4 4 0 0 0 0 4 4 4 4)
#(0 1 0 1 4 5 4 5 0 1 0 1 4 5 4 5)
#(0 0 2 2 4 4 6 6 0 0 2 2 4 4 6 6)
#(0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7)
#(0 0 0 0 0 0 0 0 8 8 8 8 8 8 8 8)
#(0 1 0 1 0 1 0 1 8 9 8 9 8 9 8 9)
#(0 0 2 2 0 0 2 2 8 8 10 10 8 8 10 10)
#(0 1 2 3 0 1 2 3 8 9 10 11 8 9 10 11)
#(0 0 0 0 4 4 4 4 8 8 8 8 12 12 12 12)
#(0 1 0 1 4 5 4 5 8 9 8 9 12 13 12 13)
#(0 0 2 2 4 4 6 6 8 8 10 10 12 12 14 14)
#(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15)))
(defun |LOGICAL:ASH-4| (x)
(if (minusp x)
(+ -1 (truncate (+ 1 x) 16))
(truncate x 16)))
(declaim (ftype (function (function integer) function)
|LOGICAL:REDUCE|))
(defun |LOGICAL:REDUCE| (op4 ident)
(declare (optimize (safety 0) (speed 3) (space 3)))
(lambda (&rest args)
(do ((res ident (funcall op4 res (car rgs) 1 0))
(rgs args (cdr rgs)))
((null rgs) res))))
;@
#+sbcl
(defun logand (&rest args)
(declare (optimize (space 3))
(inline |LOGICAL:REDUCE|))
(labels ((lgand (n2 n1 scl acc)
(declare (integer n2 n1))
(cond ((= n1 n2) (+ acc (* scl n1)))
((zerop n2) acc)
((zerop n1) acc)
(:else (lgand (|LOGICAL:ASH-4| n2)
(|LOGICAL:ASH-4| n1)
(* 16 scl)
(+ (* (svref (svref |LOGICAL:BOOLE-AND|
(mod n1 16) )
(mod n2 16) )
scl )
acc ))))))
(apply (|LOGICAL:REDUCE| #'lgand -1)
args) ))
#-sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (symbol-function 'logand) #'cl:logand))
;@
#+sbcl
(defun logior (&rest args)
(declare (inline |LOGICAL:REDUCE|))
(labels ((lgior (n2 n1 scl acc)
(cond ((= n1 n2) (+ acc (* scl n1)))
((zerop n2) (+ acc (* scl n1)))
((zerop n1) (+ acc (* scl n2)))
(:else (lgior (|LOGICAL:ASH-4| n2)
(|LOGICAL:ASH-4| n1)
(* 16 scl)
(+ (* (- 15 (svref
(svref |LOGICAL:BOOLE-AND|
(- 15 (mod n1 16)))
(- 15 (mod n2 16))))
scl)
acc))))))
(apply (|LOGICAL:REDUCE| #'lgior 0)
args )))
#-sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (symbol-function 'logior) #'cl:logior))
;@
#+sbcl
(defun logxor (&rest args)
(labels ((lgxor (n2 n1 scl acc)
(cond ((= n1 n2) acc)
((zerop n2) (+ acc (* scl n1)))
((zerop n1) (+ acc (* scl n2)))
(:else (lgxor (|LOGICAL:ASH-4| n2)
(|LOGICAL:ASH-4| n1)
(* 16 scl)
(+ (* (svref (svref |LOGICAL:BOOLE-XOR|
(mod n1 16) )
(mod n2 16) )
scl )
acc ))))))
(apply (|LOGICAL:REDUCE| #'lgxor 0)
args)) )
#-sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (symbol-function 'logxor) #'cl:logxor))
;@
(defun lognot (n) (- -1 n))
;@
(defun logtest (n1 n2)
(not (zerop (logand n1 n2))))
;@
(defun logbit? (index n)
(logtest (expt 2 index) n))
;@
(defun copy-bit (index to bool)
(if bool
(logior to (arithmetic-shift 1 index))
(logand to (lognot (arithmetic-shift 1 index)))))
;@
(defun bitwise-if (mask n0 n1)
(logior (logand mask n0)
(logand (lognot mask) n1)))
;@
(defun bit-field (n start end)
(logand (lognot (arithmetic-shift -1 (- end start)))
(arithmetic-shift n (- start))))
;@
(defun copy-bit-field (to from start end)
(bitwise-if (arithmetic-shift (lognot (arithmetic-shift -1 (- end start))) start)
(arithmetic-shift from start)
to))
;@
(defun rotate-bit-field (n count start end)
(let ((width (- end start)))
(setq count (mod count width))
(let ((mask (lognot (arithmetic-shift -1 width))))
(let ((zn (logand mask (arithmetic-shift n (- start)))))
(logior (arithmetic-shift
(logior (logand mask (arithmetic-shift zn count))
(arithmetic-shift zn (- count width)) )
start )
(logand (lognot (arithmetic-shift mask start)) n) )))))
;@
(defun ash (n count)
(if (minusp count)
(let ((k (expt 2 (- count))))
(if (minusp n)
(+ -1 (floor (+ 1 n) k))
(floor n k)))
(* (expt 2 count) n)))
;@
(defun integer-length (n)
(labels ((intlen (n tot)
(case n
((0 -1) (+ 0 tot))
((1 -2) (+ 1 tot))
((2 3 -3 -4) (+ 2 tot))
((4 5 6 7 -5 -6 -7 -8) (+ 3 tot))
(otherwise (intlen (|LOGICAL:ASH-4| n) (+ 4 tot))))))
(intlen n 0)))
;@
(defun bitwise-bit-count (n)
(labels ((logcnt (n tot)
(if (zerop n)
tot
(logcnt (floor n 16)
(+ (svref
'#(0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4)
(mod n 16))
tot)))))
(cond ((minusp n) (lognot (logcnt (lognot n) 0)))
((plusp n) (logcnt n 0))
(:else 0))))
;@
(defun logcount (n)
(cond ((minusp n) (bitwise-bit-count (lognot n)))
(:else (bitwise-bit-count n))))
;@
(defun log2-binary-factors (n)
(+ -1 (integer-length (logand n (- n)))))
(defun bit-reverse (k n)
(do ((m (if (minusp n) (lognot n) n) (ash m -1))
(k (+ -1 k) (+ -1 k))
(rvs 0 (logior (ash rvs 1) (logand 1 m))))
((minusp k) (if (minusp n) (lognot rvs) rvs))))
;@
(defun reverse-bit-field (n start end)
(let ((width (- end start)))
(let ((mask (lognot (ash -1 width))))
(let ((zn (logand mask (ash n (- start)))))
(logior (ash (bit-reverse width zn) start)
(logand (lognot (ash mask start)) n) )))))
;@
(defun integer->list (k &rest len)
(if (null len)
(do ((k k (ash k -1))
(lst '() (cons (oddp k) lst)) )
((<= k 0) lst) )
(do ((idx (+ -1 (car len)) (+ -1 idx))
(k k (ash k -1))
(lst '() (cons (oddp k) lst)) )
((minusp idx) lst) )))
;@
(defun list->integer (bools)
(do ((bs bools (cdr bs))
(acc 0 (+ acc acc (if (car bs) 1 0))))
((null bs) acc)))
(defun booleans->integer (&rest bools)
(list->integer bools))
;;;;@ SRFI-60 aliases
(macrolet ((define (new old)
`(setf (symbol-function ',new)
(function ,old))))
(define arithmetic-shift ash)
(define bitwise-ior logior)
(define bitwise-xor logxor)
(define bitwise-and logand)
(define bitwise-not lognot)
(define bit-count logcount)
(define bit-set? logbit?)
(define any-bits-set? logtest)
(define first-set-bit log2-binary-factors)
(define bitwise-merge bitwise-if))
;;; Legacy
;;(define (logical:rotate k count len) (rotate-bit-field k count 0 len))
;;(define (logical:ones deg) (lognot (ash -1 deg)))
;;(define integer-expt expt) ; legacy name
| true |
;;;; srfi-60.lisp
(cl:in-package "https://github.com/g000001/srfi-60#internals")
;;;; "logical.scm", bit access and operations for integers for Scheme
;;; Copyright (C) 1991, 1993, 2001, 2003, 2005 PI:NAME:<NAME>END_PI
;
;Permission to copy this software, to modify it, to redistribute it,
;to distribute modified versions, and to use it for any purpose is
;granted, subject to the following restrictions and understandings.
;
;1. Any copy made of this software must include this copyright notice
;in full.
;
;2. I have made no warranty or representation that the operation of
;this software will be error-free, and I am under no obligation to
;provide any services, by way of maintenance, update, or otherwise.
;
;3. In conjunction with products arising from the use of this
;material, there shall be no use of my name in any advertising,
;promotional, or sales literature without prior written consent in
;each case.
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (symbol-function 'arithmetic-shift)
#'cl:ash))
(define-symbol-macro |LOGICAL:BOOLE-XOR|
'#(#(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15)
#(1 0 3 2 5 4 7 6 9 8 11 10 13 12 15 14)
#(2 3 0 1 6 7 4 5 10 11 8 9 14 15 12 13)
#(3 2 1 0 7 6 5 4 11 10 9 8 15 14 13 12)
#(4 5 6 7 0 1 2 3 12 13 14 15 8 9 10 11)
#(5 4 7 6 1 0 3 2 13 12 15 14 9 8 11 10)
#(6 7 4 5 2 3 0 1 14 15 12 13 10 11 8 9)
#(7 6 5 4 3 2 1 0 15 14 13 12 11 10 9 8)
#(8 9 10 11 12 13 14 15 0 1 2 3 4 5 6 7)
#(9 8 11 10 13 12 15 14 1 0 3 2 5 4 7 6)
#(10 11 8 9 14 15 12 13 2 3 0 1 6 7 4 5)
#(11 10 9 8 15 14 13 12 3 2 1 0 7 6 5 4)
#(12 13 14 15 8 9 10 11 4 5 6 7 0 1 2 3)
#(13 12 15 14 9 8 11 10 5 4 7 6 1 0 3 2)
#(14 15 12 13 10 11 8 9 6 7 4 5 2 3 0 1)
#(15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0)))
(define-symbol-macro |LOGICAL:BOOLE-AND|
'#(#(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
#(0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1)
#(0 0 2 2 0 0 2 2 0 0 2 2 0 0 2 2)
#(0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3)
#(0 0 0 0 4 4 4 4 0 0 0 0 4 4 4 4)
#(0 1 0 1 4 5 4 5 0 1 0 1 4 5 4 5)
#(0 0 2 2 4 4 6 6 0 0 2 2 4 4 6 6)
#(0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7)
#(0 0 0 0 0 0 0 0 8 8 8 8 8 8 8 8)
#(0 1 0 1 0 1 0 1 8 9 8 9 8 9 8 9)
#(0 0 2 2 0 0 2 2 8 8 10 10 8 8 10 10)
#(0 1 2 3 0 1 2 3 8 9 10 11 8 9 10 11)
#(0 0 0 0 4 4 4 4 8 8 8 8 12 12 12 12)
#(0 1 0 1 4 5 4 5 8 9 8 9 12 13 12 13)
#(0 0 2 2 4 4 6 6 8 8 10 10 12 12 14 14)
#(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15)))
(defun |LOGICAL:ASH-4| (x)
(if (minusp x)
(+ -1 (truncate (+ 1 x) 16))
(truncate x 16)))
(declaim (ftype (function (function integer) function)
|LOGICAL:REDUCE|))
(defun |LOGICAL:REDUCE| (op4 ident)
(declare (optimize (safety 0) (speed 3) (space 3)))
(lambda (&rest args)
(do ((res ident (funcall op4 res (car rgs) 1 0))
(rgs args (cdr rgs)))
((null rgs) res))))
;@
#+sbcl
(defun logand (&rest args)
(declare (optimize (space 3))
(inline |LOGICAL:REDUCE|))
(labels ((lgand (n2 n1 scl acc)
(declare (integer n2 n1))
(cond ((= n1 n2) (+ acc (* scl n1)))
((zerop n2) acc)
((zerop n1) acc)
(:else (lgand (|LOGICAL:ASH-4| n2)
(|LOGICAL:ASH-4| n1)
(* 16 scl)
(+ (* (svref (svref |LOGICAL:BOOLE-AND|
(mod n1 16) )
(mod n2 16) )
scl )
acc ))))))
(apply (|LOGICAL:REDUCE| #'lgand -1)
args) ))
#-sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (symbol-function 'logand) #'cl:logand))
;@
#+sbcl
(defun logior (&rest args)
(declare (inline |LOGICAL:REDUCE|))
(labels ((lgior (n2 n1 scl acc)
(cond ((= n1 n2) (+ acc (* scl n1)))
((zerop n2) (+ acc (* scl n1)))
((zerop n1) (+ acc (* scl n2)))
(:else (lgior (|LOGICAL:ASH-4| n2)
(|LOGICAL:ASH-4| n1)
(* 16 scl)
(+ (* (- 15 (svref
(svref |LOGICAL:BOOLE-AND|
(- 15 (mod n1 16)))
(- 15 (mod n2 16))))
scl)
acc))))))
(apply (|LOGICAL:REDUCE| #'lgior 0)
args )))
#-sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (symbol-function 'logior) #'cl:logior))
;@
#+sbcl
(defun logxor (&rest args)
(labels ((lgxor (n2 n1 scl acc)
(cond ((= n1 n2) acc)
((zerop n2) (+ acc (* scl n1)))
((zerop n1) (+ acc (* scl n2)))
(:else (lgxor (|LOGICAL:ASH-4| n2)
(|LOGICAL:ASH-4| n1)
(* 16 scl)
(+ (* (svref (svref |LOGICAL:BOOLE-XOR|
(mod n1 16) )
(mod n2 16) )
scl )
acc ))))))
(apply (|LOGICAL:REDUCE| #'lgxor 0)
args)) )
#-sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (symbol-function 'logxor) #'cl:logxor))
;@
(defun lognot (n) (- -1 n))
;@
(defun logtest (n1 n2)
(not (zerop (logand n1 n2))))
;@
(defun logbit? (index n)
(logtest (expt 2 index) n))
;@
(defun copy-bit (index to bool)
(if bool
(logior to (arithmetic-shift 1 index))
(logand to (lognot (arithmetic-shift 1 index)))))
;@
(defun bitwise-if (mask n0 n1)
(logior (logand mask n0)
(logand (lognot mask) n1)))
;@
(defun bit-field (n start end)
(logand (lognot (arithmetic-shift -1 (- end start)))
(arithmetic-shift n (- start))))
;@
(defun copy-bit-field (to from start end)
(bitwise-if (arithmetic-shift (lognot (arithmetic-shift -1 (- end start))) start)
(arithmetic-shift from start)
to))
;@
(defun rotate-bit-field (n count start end)
(let ((width (- end start)))
(setq count (mod count width))
(let ((mask (lognot (arithmetic-shift -1 width))))
(let ((zn (logand mask (arithmetic-shift n (- start)))))
(logior (arithmetic-shift
(logior (logand mask (arithmetic-shift zn count))
(arithmetic-shift zn (- count width)) )
start )
(logand (lognot (arithmetic-shift mask start)) n) )))))
;@
(defun ash (n count)
(if (minusp count)
(let ((k (expt 2 (- count))))
(if (minusp n)
(+ -1 (floor (+ 1 n) k))
(floor n k)))
(* (expt 2 count) n)))
;@
(defun integer-length (n)
(labels ((intlen (n tot)
(case n
((0 -1) (+ 0 tot))
((1 -2) (+ 1 tot))
((2 3 -3 -4) (+ 2 tot))
((4 5 6 7 -5 -6 -7 -8) (+ 3 tot))
(otherwise (intlen (|LOGICAL:ASH-4| n) (+ 4 tot))))))
(intlen n 0)))
;@
(defun bitwise-bit-count (n)
(labels ((logcnt (n tot)
(if (zerop n)
tot
(logcnt (floor n 16)
(+ (svref
'#(0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4)
(mod n 16))
tot)))))
(cond ((minusp n) (lognot (logcnt (lognot n) 0)))
((plusp n) (logcnt n 0))
(:else 0))))
;@
(defun logcount (n)
(cond ((minusp n) (bitwise-bit-count (lognot n)))
(:else (bitwise-bit-count n))))
;@
(defun log2-binary-factors (n)
(+ -1 (integer-length (logand n (- n)))))
(defun bit-reverse (k n)
(do ((m (if (minusp n) (lognot n) n) (ash m -1))
(k (+ -1 k) (+ -1 k))
(rvs 0 (logior (ash rvs 1) (logand 1 m))))
((minusp k) (if (minusp n) (lognot rvs) rvs))))
;@
(defun reverse-bit-field (n start end)
(let ((width (- end start)))
(let ((mask (lognot (ash -1 width))))
(let ((zn (logand mask (ash n (- start)))))
(logior (ash (bit-reverse width zn) start)
(logand (lognot (ash mask start)) n) )))))
;@
(defun integer->list (k &rest len)
(if (null len)
(do ((k k (ash k -1))
(lst '() (cons (oddp k) lst)) )
((<= k 0) lst) )
(do ((idx (+ -1 (car len)) (+ -1 idx))
(k k (ash k -1))
(lst '() (cons (oddp k) lst)) )
((minusp idx) lst) )))
;@
(defun list->integer (bools)
(do ((bs bools (cdr bs))
(acc 0 (+ acc acc (if (car bs) 1 0))))
((null bs) acc)))
(defun booleans->integer (&rest bools)
(list->integer bools))
;;;;@ SRFI-60 aliases
(macrolet ((define (new old)
`(setf (symbol-function ',new)
(function ,old))))
(define arithmetic-shift ash)
(define bitwise-ior logior)
(define bitwise-xor logxor)
(define bitwise-and logand)
(define bitwise-not lognot)
(define bit-count logcount)
(define bit-set? logbit?)
(define any-bits-set? logtest)
(define first-set-bit log2-binary-factors)
(define bitwise-merge bitwise-if))
;;; Legacy
;;(define (logical:rotate k count len) (rotate-bit-field k count 0 len))
;;(define (logical:ones deg) (lognot (ash -1 deg)))
;;(define integer-expt expt) ; legacy name
|
[
{
"context": "ense. See the file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;",
"end": 174,
"score": 0.9992576837539673,
"start": 164,
"tag": "NAME",
"value": "Eric Smith"
},
{
"context": " file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 198,
"score": 0.9999305009841919,
"start": 176,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/kestrel/crypto/hmac/top.lisp
|
mayankmanj/acl2
| 305 |
; Formal specifications of HMAC variants
;
; Copyright (C) 2019 Kestrel Institute
;
; License: A 3-clause BSD license. See the file books/3BSD-mod.txt.
;
; Author: Eric Smith ([email protected])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(include-book "hmac-sha-256")
(include-book "hmac-sha-512")
(include-book "doc")
|
82944
|
; Formal specifications of HMAC variants
;
; Copyright (C) 2019 Kestrel Institute
;
; License: A 3-clause BSD license. See the file books/3BSD-mod.txt.
;
; Author: <NAME> (<EMAIL>)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(include-book "hmac-sha-256")
(include-book "hmac-sha-512")
(include-book "doc")
| true |
; Formal specifications of HMAC variants
;
; Copyright (C) 2019 Kestrel Institute
;
; License: A 3-clause BSD license. See the file books/3BSD-mod.txt.
;
; Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(include-book "hmac-sha-256")
(include-book "hmac-sha-512")
(include-book "doc")
|
[
{
"context": "m a string\"\n (let ((str \"1 2 \\\"My parrot is named Brady.\\\" (11 22)\"))\n (with-input-from-string\n (i",
"end": 129,
"score": 0.9994361996650696,
"start": 124,
"tag": "NAME",
"value": "Brady"
}
] |
src/code_snippets_for_book/read-from-string-test.lisp
|
metayan/loving-common-lisp
| 170 |
(defun read-from-string-test ()
"read a maximum of 1000 expressions from a string"
(let ((str "1 2 \"My parrot is named Brady.\" (11 22)"))
(with-input-from-string
(input-stream str)
(dotimes (i 1000)
(let ((x (read input-stream nil nil)))
(if (null x) (return)) ;; break out of the 'dotimes' loop
(format t "next expression in string: ~S~%" x))))))
|
46328
|
(defun read-from-string-test ()
"read a maximum of 1000 expressions from a string"
(let ((str "1 2 \"My parrot is named <NAME>.\" (11 22)"))
(with-input-from-string
(input-stream str)
(dotimes (i 1000)
(let ((x (read input-stream nil nil)))
(if (null x) (return)) ;; break out of the 'dotimes' loop
(format t "next expression in string: ~S~%" x))))))
| true |
(defun read-from-string-test ()
"read a maximum of 1000 expressions from a string"
(let ((str "1 2 \"My parrot is named PI:NAME:<NAME>END_PI.\" (11 22)"))
(with-input-from-string
(input-stream str)
(dotimes (i 1000)
(let ((x (read input-stream nil nil)))
(if (null x) (return)) ;; break out of the 'dotimes' loop
(format t "next expression in string: ~S~%" x))))))
|
[
{
"context": "#|\n This file is a part of Clip\n (c) 2014 Shirakumo http://tymoon.eu ([email protected])\n Author: N",
"end": 50,
"score": 0.6711733341217041,
"start": 44,
"tag": "NAME",
"value": "irakum"
},
{
"context": "art of Clip\n (c) 2014 Shirakumo http://tymoon.eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n",
"end": 88,
"score": 0.9999215602874756,
"start": 70,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "umo http://tymoon.eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(in-package #:org.tymoon",
"end": 113,
"score": 0.9998942017555237,
"start": 99,
"tag": "NAME",
"value": "Nicolas Hafner"
},
{
"context": ".eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(in-package #:org.tymoonnext.clip)\n\n(defvar ",
"end": 133,
"score": 0.9999306201934814,
"start": 115,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
attr-processors.lisp
|
Shinmera/clip
| 19 |
#|
This file is a part of Clip
(c) 2014 Shirakumo http://tymoon.eu ([email protected])
Author: Nicolas Hafner <[email protected]>
|#
(in-package #:org.tymoonnext.clip)
(defvar *attribute-processors* (make-hash-table :test 'equalp)
"Global registry of attribute processors.
This has to be an EQUALP hash-table with the attribute name as keys
and functions that accept two arguments (node attribute-value) as
values. Binding this variable can be useful to establish local
attributes.")
(defvar *target* NIL
"This variable is bound to whatever node is currently being processed.")
(defvar *target-counter* 0
"This counter is upped whenever process-node is called.")
(defun attribute-processor (attribute)
"Returns the processor function for the requested attribute if one is registered.
Otherwise returns NIL. See *ATTRIBUTE-PROCESSORS*."
(gethash attribute *attribute-processors*))
(defun (setf attribute-processor) (func attribute)
"Sets the attribute-processor bound to the given attribute to the specified function.
See *ATTRIBUTE-PROCESSORS*."
(setf (gethash attribute *attribute-processors*) func))
(defun process-attribute (node attribute value)
"Processes the specified attribute using the given value.
If no attribute processor can be found, nothing is done.
See *ATTRIBUTE-PROCESSORS*."
(let ((func (attribute-processor attribute)))
(when func (funcall func node value))))
(defmacro define-attribute-processor (attribute (node value) &body body)
"Defines a new attribute processor.
ATTRIBTUE --- A symbol or string that matches the attribute to process (case-insensitive)
NODE --- The current node is bound to this symbol.
VALUE --- The value of the attribute is bound to this symbol.
BODY ::= form*"
`(setf (attribute-processor ,(string attribute))
#'(lambda (,node ,value) ,@body)))
(defun process-attributes (node)
"Processes all attributes on the node.
See PROCESS-ATTRIBUTE."
(maphash #'(lambda (attr val) (process-attribute node attr val))
(plump:attributes node)))
(define-attribute-processor lquery (node value)
(let ((actions (typecase value
(list value)
(string (read-from-string (format NIL "(~a)" value))))))
(plump:remove-attribute node "lquery")
(loop with node = (make-proper-vector :size 1 :initial-element node :fill-pointer T)
for (func . args) in actions
do (apply (or (find-symbol (string func) :lquery-funcs) func)
node (mapcar #'resolve-value args)))))
(define-attribute-processor eval (node value)
(eval (read-from-string value))
(plump:remove-attribute node "eval"))
(define-attribute-processor iterate (node value)
(let ((val (parse-and-resolve value))
(new-children (plump:make-child-array))
(target node))
(flet ((process (item)
(with-clipboard-bound (item)
(let ((clone (plump:clone-node target T)))
(loop for node across (plump:children clone)
do (process-node node))
(array-utils:vector-append new-children (plump:children clone))))))
(etypecase val
(list (loop for item in val do (process item)))
(vector (loop for item across val do (process item)))))
(setf (plump:children node) new-children)
(plump:remove-attribute node "iterate")))
(define-attribute-processor as (node value)
(setf (plump:tag-name node) value)
(plump:remove-attribute node "as"))
(define-attribute-processor count (node value)
(declare (ignore value))
(setf (plump:attribute node "count") (princ-to-string *target-counter*)))
(defun replace-region (string start end replacer)
(with-output-to-string (output)
(loop with filler = (make-string-output-stream)
with target = output
for char across string
do (cond
((char= char start)
(setf target filler))
((char= char end)
(unless (eql target filler)
(error "Unmatched closing."))
(princ (funcall replacer (get-output-stream-string filler)) output)
(close filler)
(setf target output)
(setf filler (make-string-output-stream)))
(T (write-char char target)))
finally (if (eql target filler)
(error "Unmatched opening.")
(close filler)))))
(define-attribute-processor fill (node value)
(loop for (attribute object) on (read-from-string (format NIL "(~a)" value))
for attr = (string attribute)
do (let ((value (plump:attribute node attr)))
(when value
(setf (plump:attribute node attr)
(replace-region
value #\{ #\}
#'(lambda (value)
(clip (resolve-value object) value)))))))
(plump:remove-attribute node "fill"))
|
89587
|
#|
This file is a part of Clip
(c) 2014 Sh<NAME>o http://tymoon.eu (<EMAIL>)
Author: <NAME> <<EMAIL>>
|#
(in-package #:org.tymoonnext.clip)
(defvar *attribute-processors* (make-hash-table :test 'equalp)
"Global registry of attribute processors.
This has to be an EQUALP hash-table with the attribute name as keys
and functions that accept two arguments (node attribute-value) as
values. Binding this variable can be useful to establish local
attributes.")
(defvar *target* NIL
"This variable is bound to whatever node is currently being processed.")
(defvar *target-counter* 0
"This counter is upped whenever process-node is called.")
(defun attribute-processor (attribute)
"Returns the processor function for the requested attribute if one is registered.
Otherwise returns NIL. See *ATTRIBUTE-PROCESSORS*."
(gethash attribute *attribute-processors*))
(defun (setf attribute-processor) (func attribute)
"Sets the attribute-processor bound to the given attribute to the specified function.
See *ATTRIBUTE-PROCESSORS*."
(setf (gethash attribute *attribute-processors*) func))
(defun process-attribute (node attribute value)
"Processes the specified attribute using the given value.
If no attribute processor can be found, nothing is done.
See *ATTRIBUTE-PROCESSORS*."
(let ((func (attribute-processor attribute)))
(when func (funcall func node value))))
(defmacro define-attribute-processor (attribute (node value) &body body)
"Defines a new attribute processor.
ATTRIBTUE --- A symbol or string that matches the attribute to process (case-insensitive)
NODE --- The current node is bound to this symbol.
VALUE --- The value of the attribute is bound to this symbol.
BODY ::= form*"
`(setf (attribute-processor ,(string attribute))
#'(lambda (,node ,value) ,@body)))
(defun process-attributes (node)
"Processes all attributes on the node.
See PROCESS-ATTRIBUTE."
(maphash #'(lambda (attr val) (process-attribute node attr val))
(plump:attributes node)))
(define-attribute-processor lquery (node value)
(let ((actions (typecase value
(list value)
(string (read-from-string (format NIL "(~a)" value))))))
(plump:remove-attribute node "lquery")
(loop with node = (make-proper-vector :size 1 :initial-element node :fill-pointer T)
for (func . args) in actions
do (apply (or (find-symbol (string func) :lquery-funcs) func)
node (mapcar #'resolve-value args)))))
(define-attribute-processor eval (node value)
(eval (read-from-string value))
(plump:remove-attribute node "eval"))
(define-attribute-processor iterate (node value)
(let ((val (parse-and-resolve value))
(new-children (plump:make-child-array))
(target node))
(flet ((process (item)
(with-clipboard-bound (item)
(let ((clone (plump:clone-node target T)))
(loop for node across (plump:children clone)
do (process-node node))
(array-utils:vector-append new-children (plump:children clone))))))
(etypecase val
(list (loop for item in val do (process item)))
(vector (loop for item across val do (process item)))))
(setf (plump:children node) new-children)
(plump:remove-attribute node "iterate")))
(define-attribute-processor as (node value)
(setf (plump:tag-name node) value)
(plump:remove-attribute node "as"))
(define-attribute-processor count (node value)
(declare (ignore value))
(setf (plump:attribute node "count") (princ-to-string *target-counter*)))
(defun replace-region (string start end replacer)
(with-output-to-string (output)
(loop with filler = (make-string-output-stream)
with target = output
for char across string
do (cond
((char= char start)
(setf target filler))
((char= char end)
(unless (eql target filler)
(error "Unmatched closing."))
(princ (funcall replacer (get-output-stream-string filler)) output)
(close filler)
(setf target output)
(setf filler (make-string-output-stream)))
(T (write-char char target)))
finally (if (eql target filler)
(error "Unmatched opening.")
(close filler)))))
(define-attribute-processor fill (node value)
(loop for (attribute object) on (read-from-string (format NIL "(~a)" value))
for attr = (string attribute)
do (let ((value (plump:attribute node attr)))
(when value
(setf (plump:attribute node attr)
(replace-region
value #\{ #\}
#'(lambda (value)
(clip (resolve-value object) value)))))))
(plump:remove-attribute node "fill"))
| true |
#|
This file is a part of Clip
(c) 2014 ShPI:NAME:<NAME>END_PIo http://tymoon.eu (PI:EMAIL:<EMAIL>END_PI)
Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
|#
(in-package #:org.tymoonnext.clip)
(defvar *attribute-processors* (make-hash-table :test 'equalp)
"Global registry of attribute processors.
This has to be an EQUALP hash-table with the attribute name as keys
and functions that accept two arguments (node attribute-value) as
values. Binding this variable can be useful to establish local
attributes.")
(defvar *target* NIL
"This variable is bound to whatever node is currently being processed.")
(defvar *target-counter* 0
"This counter is upped whenever process-node is called.")
(defun attribute-processor (attribute)
"Returns the processor function for the requested attribute if one is registered.
Otherwise returns NIL. See *ATTRIBUTE-PROCESSORS*."
(gethash attribute *attribute-processors*))
(defun (setf attribute-processor) (func attribute)
"Sets the attribute-processor bound to the given attribute to the specified function.
See *ATTRIBUTE-PROCESSORS*."
(setf (gethash attribute *attribute-processors*) func))
(defun process-attribute (node attribute value)
"Processes the specified attribute using the given value.
If no attribute processor can be found, nothing is done.
See *ATTRIBUTE-PROCESSORS*."
(let ((func (attribute-processor attribute)))
(when func (funcall func node value))))
(defmacro define-attribute-processor (attribute (node value) &body body)
"Defines a new attribute processor.
ATTRIBTUE --- A symbol or string that matches the attribute to process (case-insensitive)
NODE --- The current node is bound to this symbol.
VALUE --- The value of the attribute is bound to this symbol.
BODY ::= form*"
`(setf (attribute-processor ,(string attribute))
#'(lambda (,node ,value) ,@body)))
(defun process-attributes (node)
"Processes all attributes on the node.
See PROCESS-ATTRIBUTE."
(maphash #'(lambda (attr val) (process-attribute node attr val))
(plump:attributes node)))
(define-attribute-processor lquery (node value)
(let ((actions (typecase value
(list value)
(string (read-from-string (format NIL "(~a)" value))))))
(plump:remove-attribute node "lquery")
(loop with node = (make-proper-vector :size 1 :initial-element node :fill-pointer T)
for (func . args) in actions
do (apply (or (find-symbol (string func) :lquery-funcs) func)
node (mapcar #'resolve-value args)))))
(define-attribute-processor eval (node value)
(eval (read-from-string value))
(plump:remove-attribute node "eval"))
(define-attribute-processor iterate (node value)
(let ((val (parse-and-resolve value))
(new-children (plump:make-child-array))
(target node))
(flet ((process (item)
(with-clipboard-bound (item)
(let ((clone (plump:clone-node target T)))
(loop for node across (plump:children clone)
do (process-node node))
(array-utils:vector-append new-children (plump:children clone))))))
(etypecase val
(list (loop for item in val do (process item)))
(vector (loop for item across val do (process item)))))
(setf (plump:children node) new-children)
(plump:remove-attribute node "iterate")))
(define-attribute-processor as (node value)
(setf (plump:tag-name node) value)
(plump:remove-attribute node "as"))
(define-attribute-processor count (node value)
(declare (ignore value))
(setf (plump:attribute node "count") (princ-to-string *target-counter*)))
(defun replace-region (string start end replacer)
(with-output-to-string (output)
(loop with filler = (make-string-output-stream)
with target = output
for char across string
do (cond
((char= char start)
(setf target filler))
((char= char end)
(unless (eql target filler)
(error "Unmatched closing."))
(princ (funcall replacer (get-output-stream-string filler)) output)
(close filler)
(setf target output)
(setf filler (make-string-output-stream)))
(T (write-char char target)))
finally (if (eql target filler)
(error "Unmatched opening.")
(close filler)))))
(define-attribute-processor fill (node value)
(loop for (attribute object) on (read-from-string (format NIL "(~a)" value))
for attr = (string attribute)
do (let ((value (plump:attribute node attr)))
(when value
(setf (plump:attribute node attr)
(replace-region
value #\{ #\}
#'(lambda (value)
(clip (resolve-value object) value)))))))
(plump:remove-attribute node "fill"))
|
[
{
"context": "is a part of cl-cuda project.\n Copyright (c) 2012 Masayuki Takagi ([email protected])\n|#\n\n(in-package :cl-user)\n(d",
"end": 81,
"score": 0.9998303055763245,
"start": 66,
"tag": "NAME",
"value": "Masayuki Takagi"
},
{
"context": "da project.\n Copyright (c) 2012 Masayuki Takagi ([email protected])\n|#\n\n(in-package :cl-user)\n(defpackage cl-cuda-te",
"end": 101,
"score": 0.9999242424964905,
"start": 83,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
t/lang/type.lisp
|
digikar99/cl-cuda
| 222 |
#|
This file is a part of cl-cuda project.
Copyright (c) 2012 Masayuki Takagi ([email protected])
|#
(in-package :cl-user)
(defpackage cl-cuda-test.lang.type
(:use :cl :prove
:cl-cuda.driver-api
:cl-cuda.lang.data
:cl-cuda.lang.type))
(in-package :cl-cuda-test.lang.type)
(plan nil)
;;;
;;; test CL-CUDA-TYPE-P function
;;;
(diag "CL-CUDA-TYPE-P")
(is (cl-cuda-type-p 'int) t "basic case 1")
(is (cl-cuda-type-p 'float3) t "basic case 2")
(is (cl-cuda-type-p 'float3*) t "basic case 3")
(is (cl-cuda-type-p '*float*) nil "basic case 4")
;;;
;;; test CFFI-TYPE function
;;;
(diag "CFFI-TYPE")
(is (cffi-type 'int) :int "basic case 1")
(is (cffi-type 'float3) '(:struct float3) "basic case 2")
(is (cffi-type 'float3*) 'cu-device-ptr "basic case 3")
;;;
;;; test CFFI-TYPE-SIZE function
;;;
(diag "CFFI-TYPE-SIZE")
(is (cffi-type-size 'int) 4 "basic case 1")
(is (cffi-type-size 'float3) 12 "basic case 2")
(is (cffi-type-size 'float3*) (cffi:foreign-type-size 'cu-device-ptr)
"basic case 3")
;;;
;;; test CUDA-TYPE function
;;;
(diag "CUDA-TYPE")
(is (cuda-type 'int) "int" "basic case 1")
(is (cuda-type 'float3) "float3" "basic case 2")
(is (cuda-type 'float3*) "float3*" "basic case 3")
;;;
;;; test STRUCTURE-ACCESSOR-P function
;;;
(diag "STRUCTURE-ACCESSOR-P")
(is (structure-accessor-p 'float3-x) t "basic case 1")
(is (structure-accessor-p 'float4-w) t "basic case 2")
(is (structure-accessor-p 'float3-w) nil "basic case 3")
;;;
;;; test STRUCTURE-ACCESSOR-CUDA-ACCESSOR function
;;;
(diag "STRUCTURE-ACCESSOR-CUDA-ACCESSOR")
(is (structure-accessor-cuda-accessor 'float3-x) "x" "basic case 1")
(is (structure-accessor-cuda-accessor 'float4-w) "w" "basic case 2")
(is-error (structure-accessor-cuda-accessor 'float3-w) simple-error
"ACCESSOR which is not an invalid accessor.")
;;;
;;; test STRUCTURE-ACCESSOR-RETURN-TYPE function
;;;
(diag "STRUCTURE-ACCESSOR-RETURN-TYPE")
(is (structure-accessor-return-type 'float3-x) 'float "basic case 1")
(is (structure-accessor-return-type 'double4-w) 'double "basic case 2")
(is-error (structure-accessor-return-type 'float3-w) simple-error
"ACCESSOR which is not an invalid accessor.")
;;;
;;; test ARRAY-TYPE-BASE function
;;;
(diag "ARRAY-TYPE-BASE")
(is (array-type-base 'int*) 'int
"basic case 1")
(is (array-type-base 'int**) 'int
"basic case 2")
;;;
;;; test ARRAY-TYPE-DIMENSION function
;;;
(diag "ARRAY-TYPE-DIMENSION")
(is (array-type-dimension 'int*) 1
"basic case 1")
(is (array-type-dimension 'int**) 2
"basic case 2")
(finalize)
|
43420
|
#|
This file is a part of cl-cuda project.
Copyright (c) 2012 <NAME> (<EMAIL>)
|#
(in-package :cl-user)
(defpackage cl-cuda-test.lang.type
(:use :cl :prove
:cl-cuda.driver-api
:cl-cuda.lang.data
:cl-cuda.lang.type))
(in-package :cl-cuda-test.lang.type)
(plan nil)
;;;
;;; test CL-CUDA-TYPE-P function
;;;
(diag "CL-CUDA-TYPE-P")
(is (cl-cuda-type-p 'int) t "basic case 1")
(is (cl-cuda-type-p 'float3) t "basic case 2")
(is (cl-cuda-type-p 'float3*) t "basic case 3")
(is (cl-cuda-type-p '*float*) nil "basic case 4")
;;;
;;; test CFFI-TYPE function
;;;
(diag "CFFI-TYPE")
(is (cffi-type 'int) :int "basic case 1")
(is (cffi-type 'float3) '(:struct float3) "basic case 2")
(is (cffi-type 'float3*) 'cu-device-ptr "basic case 3")
;;;
;;; test CFFI-TYPE-SIZE function
;;;
(diag "CFFI-TYPE-SIZE")
(is (cffi-type-size 'int) 4 "basic case 1")
(is (cffi-type-size 'float3) 12 "basic case 2")
(is (cffi-type-size 'float3*) (cffi:foreign-type-size 'cu-device-ptr)
"basic case 3")
;;;
;;; test CUDA-TYPE function
;;;
(diag "CUDA-TYPE")
(is (cuda-type 'int) "int" "basic case 1")
(is (cuda-type 'float3) "float3" "basic case 2")
(is (cuda-type 'float3*) "float3*" "basic case 3")
;;;
;;; test STRUCTURE-ACCESSOR-P function
;;;
(diag "STRUCTURE-ACCESSOR-P")
(is (structure-accessor-p 'float3-x) t "basic case 1")
(is (structure-accessor-p 'float4-w) t "basic case 2")
(is (structure-accessor-p 'float3-w) nil "basic case 3")
;;;
;;; test STRUCTURE-ACCESSOR-CUDA-ACCESSOR function
;;;
(diag "STRUCTURE-ACCESSOR-CUDA-ACCESSOR")
(is (structure-accessor-cuda-accessor 'float3-x) "x" "basic case 1")
(is (structure-accessor-cuda-accessor 'float4-w) "w" "basic case 2")
(is-error (structure-accessor-cuda-accessor 'float3-w) simple-error
"ACCESSOR which is not an invalid accessor.")
;;;
;;; test STRUCTURE-ACCESSOR-RETURN-TYPE function
;;;
(diag "STRUCTURE-ACCESSOR-RETURN-TYPE")
(is (structure-accessor-return-type 'float3-x) 'float "basic case 1")
(is (structure-accessor-return-type 'double4-w) 'double "basic case 2")
(is-error (structure-accessor-return-type 'float3-w) simple-error
"ACCESSOR which is not an invalid accessor.")
;;;
;;; test ARRAY-TYPE-BASE function
;;;
(diag "ARRAY-TYPE-BASE")
(is (array-type-base 'int*) 'int
"basic case 1")
(is (array-type-base 'int**) 'int
"basic case 2")
;;;
;;; test ARRAY-TYPE-DIMENSION function
;;;
(diag "ARRAY-TYPE-DIMENSION")
(is (array-type-dimension 'int*) 1
"basic case 1")
(is (array-type-dimension 'int**) 2
"basic case 2")
(finalize)
| true |
#|
This file is a part of cl-cuda project.
Copyright (c) 2012 PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
|#
(in-package :cl-user)
(defpackage cl-cuda-test.lang.type
(:use :cl :prove
:cl-cuda.driver-api
:cl-cuda.lang.data
:cl-cuda.lang.type))
(in-package :cl-cuda-test.lang.type)
(plan nil)
;;;
;;; test CL-CUDA-TYPE-P function
;;;
(diag "CL-CUDA-TYPE-P")
(is (cl-cuda-type-p 'int) t "basic case 1")
(is (cl-cuda-type-p 'float3) t "basic case 2")
(is (cl-cuda-type-p 'float3*) t "basic case 3")
(is (cl-cuda-type-p '*float*) nil "basic case 4")
;;;
;;; test CFFI-TYPE function
;;;
(diag "CFFI-TYPE")
(is (cffi-type 'int) :int "basic case 1")
(is (cffi-type 'float3) '(:struct float3) "basic case 2")
(is (cffi-type 'float3*) 'cu-device-ptr "basic case 3")
;;;
;;; test CFFI-TYPE-SIZE function
;;;
(diag "CFFI-TYPE-SIZE")
(is (cffi-type-size 'int) 4 "basic case 1")
(is (cffi-type-size 'float3) 12 "basic case 2")
(is (cffi-type-size 'float3*) (cffi:foreign-type-size 'cu-device-ptr)
"basic case 3")
;;;
;;; test CUDA-TYPE function
;;;
(diag "CUDA-TYPE")
(is (cuda-type 'int) "int" "basic case 1")
(is (cuda-type 'float3) "float3" "basic case 2")
(is (cuda-type 'float3*) "float3*" "basic case 3")
;;;
;;; test STRUCTURE-ACCESSOR-P function
;;;
(diag "STRUCTURE-ACCESSOR-P")
(is (structure-accessor-p 'float3-x) t "basic case 1")
(is (structure-accessor-p 'float4-w) t "basic case 2")
(is (structure-accessor-p 'float3-w) nil "basic case 3")
;;;
;;; test STRUCTURE-ACCESSOR-CUDA-ACCESSOR function
;;;
(diag "STRUCTURE-ACCESSOR-CUDA-ACCESSOR")
(is (structure-accessor-cuda-accessor 'float3-x) "x" "basic case 1")
(is (structure-accessor-cuda-accessor 'float4-w) "w" "basic case 2")
(is-error (structure-accessor-cuda-accessor 'float3-w) simple-error
"ACCESSOR which is not an invalid accessor.")
;;;
;;; test STRUCTURE-ACCESSOR-RETURN-TYPE function
;;;
(diag "STRUCTURE-ACCESSOR-RETURN-TYPE")
(is (structure-accessor-return-type 'float3-x) 'float "basic case 1")
(is (structure-accessor-return-type 'double4-w) 'double "basic case 2")
(is-error (structure-accessor-return-type 'float3-w) simple-error
"ACCESSOR which is not an invalid accessor.")
;;;
;;; test ARRAY-TYPE-BASE function
;;;
(diag "ARRAY-TYPE-BASE")
(is (array-type-base 'int*) 'int
"basic case 1")
(is (array-type-base 'int**) 'int
"basic case 2")
;;;
;;; test ARRAY-TYPE-DIMENSION function
;;;
(diag "ARRAY-TYPE-DIMENSION")
(is (array-type-dimension 'int*) 1
"basic case 1")
(is (array-type-dimension 'int**) 2
"basic case 2")
(finalize)
|
[
{
"context": "6, Regents of the University of Texas\n; Written by Matt Kaufmann\n; License: A 3-clause BSD license. See the LICEN",
"end": 83,
"score": 0.9997615218162537,
"start": 70,
"tag": "NAME",
"value": "Matt Kaufmann"
}
] |
books/kestrel/utilities/minimize-ruler-extenders.lisp
|
nadezhin/acl2
| 0 |
; Copyright (C) 2016, Regents of the University of Texas
; Written by Matt Kaufmann
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
(in-package "ACL2")
(include-book "xdoc/top" :dir :system)
(program)
(set-state-ok t)
(include-book "tools/remove-hyps" :dir :system) ; for event-steps
(include-book "world-queries") ; for ruler-extenders
(defun not-none (r)
; Coerces :none to nil.
(and (not (eq r :none))
r))
(mutual-recursion
(defun possible-ruler-extenders (fns term)
; Normally returns a list of possible ruler-extenders, where term is a subterm
; of the body of a definition of one of the functions in fns, defined together
; with mutual-recursion. However, return :none if there is a call in term of
; some function in fns but there are no ruler-extenders.
(cond
((variablep term) nil)
((fquotep term) nil)
((eq (ffn-symb term) 'if)
(let* ((r1 (possible-ruler-extenders fns (fargn term 1)))
(r2 (possible-ruler-extenders fns (fargn term 2)))
(r3 (possible-ruler-extenders fns (fargn term 3))))
(and (or r1 r2 r3)
(or (union$ (and r1
(cons 'if (not-none r1)))
(not-none r2)
(not-none r3)
:test 'eq)
:none))))
(t (let ((rs (possible-ruler-extenders-lst fns (fargs term))))
(cond (rs (add-to-set-eq (if (flambdap (ffn-symb term))
:lambdas
(ffn-symb term))
(not-none rs)))
((member-eq (ffn-symb term) fns)
:none)
(t nil))))))
(defun possible-ruler-extenders-lst (fns termlist)
(cond ((endp termlist) nil)
((endp (cdr termlist))
(possible-ruler-extenders fns (car termlist)))
(t (let ((r1 (possible-ruler-extenders fns (car termlist)))
(r2 (possible-ruler-extenders-lst fns (cdr termlist))))
(and (or r1 r2)
(or (union-eq (not-none r1)
(not-none r2))
:none))))))
)
(defun init-ruler-extenders (fn ruler-extenders term)
(let ((re (possible-ruler-extenders (list fn) term)))
(if (eq ruler-extenders :all)
re
(intersection-eq re ruler-extenders))))
(defconst *default-def-types*
; We expect some variant of defun here: (defxxx name args (decls/strings)* body).
'(defun defund))
(defun minimal-ruler-extenders-steps (steps)
; This is quite arbitrary, but has worked well for remove-hyps.
(+ 1000 (* 3 steps)))
(defun add-ruler-extenders (form ruler-extenders)
(case-match form
((defxxx name formals . rest)
`(,defxxx ,name ,formals
(declare (xargs :ruler-extenders ,ruler-extenders))
,@rest))
(& (er hard 'add-ruler-extenders
"Unexpected form: ~x0"
form))))
(defun strip-ruler-extenders (form)
(case-match form
((defxxx name formals . rest)
`(,defxxx ,name ,formals
,@(strip-dcls '(:ruler-extenders) (butlast rest 1))
,(car (last rest))))
(& (er hard 'strip-ruler-extenders
"Unexpected form: ~x0"
form))))
(defun minimal-ruler-extenders (form ruler-extenders steps acc verbose-p state)
(cond
((endp ruler-extenders) (value (reverse acc)))
(t (let ((form2 `(with-prover-step-limit
,steps
,(add-ruler-extenders
form
(append (cdr ruler-extenders) acc)))))
(er-let* ((success (event-steps form2 verbose-p nil state)))
(minimal-ruler-extenders form
(cdr ruler-extenders)
steps
(if success
acc
(cons (car ruler-extenders) acc))
verbose-p
state))))))
(defun min-old-ruler-extenders-1 (fns body
ruler-extenders-1
ruler-extenders-2
induction-machine)
; Fns is a list containing a single function symbol, fn, whose translated
; (hence unnormalized) body is body. Let ruler-extenders be the union of the
; sets represented by the lists ruler-extenders-1 and ruler-extenders-2. The
; induction machine for fn with respect to ruler-extenders is
; induction-machine. We return a minimal sublist S of ruler-extenders-1 for
; which the union of the lists represented by S and ruler-extenders-2) still
; produces induction-machine.
(cond
((endp ruler-extenders-1)
ruler-extenders-2)
(t
(min-old-ruler-extenders-1
fns body
(cdr ruler-extenders-1)
(if (equal (induction-machine-for-fn fns body
(revappend (cdr ruler-extenders-1)
ruler-extenders-2))
induction-machine)
ruler-extenders-2
(cons (car ruler-extenders-1)
ruler-extenders-2))
induction-machine))))
(defun min-old-ruler-extenders (fn ctx state)
(declare (xargs :guard (symbolp fn)))
(let* ((wrld (w state))
(recursivep (getpropc fn 'recursivep nil wrld)))
(cond
((not (function-symbolp fn wrld))
(er hard ctx
"The symbol ~x0 is not a known function symbol in the current ACL2 ~
logical world."
fn))
((null recursivep)
(er hard ctx
"The function symbol ~x0 is not recursive."
fn))
((cdr recursivep)
(er hard ctx
"The function symbol ~x0 is part of a mutual-recursion nest, ~x1."
fn recursivep))
(t (let* ((fns (list fn))
(body (body fn nil wrld))
(ruler-extenders
(init-ruler-extenders fn (ruler-extenders fn wrld) body)))
(min-old-ruler-extenders-1 fns
body
ruler-extenders
nil
(induction-machine-for-fn
fns
body
ruler-extenders)))))))
(defmacro minimize-ruler-extenders (form &key verbose-p)
(cond
((symbolp form)
`(min-old-ruler-extenders ',form 'minimize-ruler-extenders state))
(t
`(make-event
(let* ((verbose-p ,verbose-p)
(def-types *default-def-types*)
(form ',form)
(form0 (strip-ruler-extenders form))
(ctx 'minimize-ruler-extenders))
(cond
((not (and (consp form)
(true-listp form)
(member-eq (car form) def-types)))
(er soft ctx
"Illegal call of ~x0 on form:~|~x1~|A non-symbol form must be a ~
true-list that is a call of ~v2."
'minimal-ruler-extenders form def-types))
(t
(assert$
(symbolp (cadr form)) ; name
(er-let* ((ruler-extenders-p
(value (member-eq :ruler-extenders
(dcl-fields (butlast (nthcdr 3 form) 1)))))
(steps
(event-steps (if ruler-extenders-p
form
(add-ruler-extenders form0 :all))
verbose-p
`((f-put-global 'minimal-r-e-body
(body ',(cadr form)
nil
(w state))
state)
(f-put-global
'minimal-r-e-ruler-extenders
(ruler-extenders ',(cadr form)
(w state))
state))
state)))
(cond
((null steps)
(er soft ctx
"Original defun failed!"))
(t (er-let* ((ruler-extenders
(minimal-ruler-extenders
form0
(init-ruler-extenders (cadr form)
(f-get-global
'minimal-r-e-ruler-extenders
state)
(f-get-global
'minimal-r-e-body
state))
(minimal-ruler-extenders-steps steps)
nil
verbose-p
state)))
(value (add-ruler-extenders form ruler-extenders))))))))))))))
; Example of MIN_NEW (so named in the :doc):
(local
(encapsulate
()
(minimize-ruler-extenders
(defun foo (x)
(car (if (endp x)
x
(cons (foo (cdr x))
(evens (if (consp (cdr x))
(foo (cddr x))
nil)))))))
(assert-event (equal (ruler-extenders 'foo (w state))
'(car)))
(defun bar (x)
(declare (xargs :ruler-extenders :all))
(mod (if (consp x)
(* (bar (car x))
(if (consp (cdr x))
(ifix (cadr x))
17))
3)
23))
(assert-event (equal (minimize-ruler-extenders bar)
'(mod)))))
(defxdoc minimize-ruler-extenders
:parents (kestrel-utilities system-utilities-non-built-in)
:short "Minimize the ruler-extenders necessary to admit a definition."
:long "<p>@('Minimize-ruler-extenders') is really two utilities. The first,
which we call MIN_NEW below, admits a proposed @(tsee defun) or @(tsee defund)
form by declaring a minimal set of @(see ruler-extenders). This MIN_NEW
utility uses proof to eliminate ruler-extenders as completely as possible,
while still permitting the termination proof to succeed. The second utility,
which we call MIN_OLD below, is applied to a function symbol that already has
a recursive (but not mutually recursive) definition. Here are examples that
illustrate each of these two respective utilities.</p>
@({
; MIN_NEW (to admit a proposed definition):
(minimize-ruler-extenders
(defun foo (x)
(car (if (endp x)
x
(cons (foo (cdr x))
(evens (if (consp (cdr x))
(foo (cddr x))
nil)))))))
; MIN_OLD (to compute minimal ruler-extenders for an existing definition):
(defun bar (x)
(declare (xargs :ruler-extenders :all))
(mod (if (consp x)
(* (bar (car x))
(if (consp (cdr x))
(ifix (cadr x))
17))
3)
23))
(minimize-ruler-extenders bar) ; returns (MOD)
})
<p>In the first (MIN_NEW) example above, a minimal set of @(see
ruler-extenders) — in fact, THE minimal set — is the set
@('{car}'). So the definition that is actually submitted, successfully, to
ACL2 is obtained by making that explicit:</p>
@({
ACL2 !>:pe foo
L 2:x(MINIMIZE-RULER-EXTENDERS (DEFUN FOO # ...))
\\
>L (DEFUN FOO (X)
(DECLARE (XARGS :RULER-EXTENDERS (CAR)))
(CAR (IF (ENDP X)
X
(CONS (FOO (CDR X))
(EVENS (IF (CONSP (CDR X))
(FOO (CDDR X))
NIL))))))
ACL2 !>
})
<p>The input form for the MIN_NEW utility should be a call of @(tsee defun) or
@(tsee defund) that defines a function symbol that is not already defined. If
that form specifies @(':ruler-extenders lst'), then ACL2 will look for a
minimal subsequence of @('lst') that can serve as the ruler-extenders.
Otherwise, ACL2 will start by additing an @(tsee xargs) declaration,
@(':ruler-extenders lst'), where @('lst') contains every plausible
ruler-extender, and then will try to find a minimal subsequence of
@('lst').</p>
<p>Now we turn to the MIN_OLD utility. This utility is applied to a function
symbol @('F') that already has a (singly) recursive definition. It returns a
subset of the ruler-extenders @('R') of @('F') that is minimal in the
following sense: it provides the same induction-machine as @('R'). (The
``induction-machine'' is an ACL2 data structure representing the scheme used
when doing induction based on the recursion in @('F').)</p>")
|
66723
|
; Copyright (C) 2016, Regents of the University of Texas
; Written by <NAME>
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
(in-package "ACL2")
(include-book "xdoc/top" :dir :system)
(program)
(set-state-ok t)
(include-book "tools/remove-hyps" :dir :system) ; for event-steps
(include-book "world-queries") ; for ruler-extenders
(defun not-none (r)
; Coerces :none to nil.
(and (not (eq r :none))
r))
(mutual-recursion
(defun possible-ruler-extenders (fns term)
; Normally returns a list of possible ruler-extenders, where term is a subterm
; of the body of a definition of one of the functions in fns, defined together
; with mutual-recursion. However, return :none if there is a call in term of
; some function in fns but there are no ruler-extenders.
(cond
((variablep term) nil)
((fquotep term) nil)
((eq (ffn-symb term) 'if)
(let* ((r1 (possible-ruler-extenders fns (fargn term 1)))
(r2 (possible-ruler-extenders fns (fargn term 2)))
(r3 (possible-ruler-extenders fns (fargn term 3))))
(and (or r1 r2 r3)
(or (union$ (and r1
(cons 'if (not-none r1)))
(not-none r2)
(not-none r3)
:test 'eq)
:none))))
(t (let ((rs (possible-ruler-extenders-lst fns (fargs term))))
(cond (rs (add-to-set-eq (if (flambdap (ffn-symb term))
:lambdas
(ffn-symb term))
(not-none rs)))
((member-eq (ffn-symb term) fns)
:none)
(t nil))))))
(defun possible-ruler-extenders-lst (fns termlist)
(cond ((endp termlist) nil)
((endp (cdr termlist))
(possible-ruler-extenders fns (car termlist)))
(t (let ((r1 (possible-ruler-extenders fns (car termlist)))
(r2 (possible-ruler-extenders-lst fns (cdr termlist))))
(and (or r1 r2)
(or (union-eq (not-none r1)
(not-none r2))
:none))))))
)
(defun init-ruler-extenders (fn ruler-extenders term)
(let ((re (possible-ruler-extenders (list fn) term)))
(if (eq ruler-extenders :all)
re
(intersection-eq re ruler-extenders))))
(defconst *default-def-types*
; We expect some variant of defun here: (defxxx name args (decls/strings)* body).
'(defun defund))
(defun minimal-ruler-extenders-steps (steps)
; This is quite arbitrary, but has worked well for remove-hyps.
(+ 1000 (* 3 steps)))
(defun add-ruler-extenders (form ruler-extenders)
(case-match form
((defxxx name formals . rest)
`(,defxxx ,name ,formals
(declare (xargs :ruler-extenders ,ruler-extenders))
,@rest))
(& (er hard 'add-ruler-extenders
"Unexpected form: ~x0"
form))))
(defun strip-ruler-extenders (form)
(case-match form
((defxxx name formals . rest)
`(,defxxx ,name ,formals
,@(strip-dcls '(:ruler-extenders) (butlast rest 1))
,(car (last rest))))
(& (er hard 'strip-ruler-extenders
"Unexpected form: ~x0"
form))))
(defun minimal-ruler-extenders (form ruler-extenders steps acc verbose-p state)
(cond
((endp ruler-extenders) (value (reverse acc)))
(t (let ((form2 `(with-prover-step-limit
,steps
,(add-ruler-extenders
form
(append (cdr ruler-extenders) acc)))))
(er-let* ((success (event-steps form2 verbose-p nil state)))
(minimal-ruler-extenders form
(cdr ruler-extenders)
steps
(if success
acc
(cons (car ruler-extenders) acc))
verbose-p
state))))))
(defun min-old-ruler-extenders-1 (fns body
ruler-extenders-1
ruler-extenders-2
induction-machine)
; Fns is a list containing a single function symbol, fn, whose translated
; (hence unnormalized) body is body. Let ruler-extenders be the union of the
; sets represented by the lists ruler-extenders-1 and ruler-extenders-2. The
; induction machine for fn with respect to ruler-extenders is
; induction-machine. We return a minimal sublist S of ruler-extenders-1 for
; which the union of the lists represented by S and ruler-extenders-2) still
; produces induction-machine.
(cond
((endp ruler-extenders-1)
ruler-extenders-2)
(t
(min-old-ruler-extenders-1
fns body
(cdr ruler-extenders-1)
(if (equal (induction-machine-for-fn fns body
(revappend (cdr ruler-extenders-1)
ruler-extenders-2))
induction-machine)
ruler-extenders-2
(cons (car ruler-extenders-1)
ruler-extenders-2))
induction-machine))))
(defun min-old-ruler-extenders (fn ctx state)
(declare (xargs :guard (symbolp fn)))
(let* ((wrld (w state))
(recursivep (getpropc fn 'recursivep nil wrld)))
(cond
((not (function-symbolp fn wrld))
(er hard ctx
"The symbol ~x0 is not a known function symbol in the current ACL2 ~
logical world."
fn))
((null recursivep)
(er hard ctx
"The function symbol ~x0 is not recursive."
fn))
((cdr recursivep)
(er hard ctx
"The function symbol ~x0 is part of a mutual-recursion nest, ~x1."
fn recursivep))
(t (let* ((fns (list fn))
(body (body fn nil wrld))
(ruler-extenders
(init-ruler-extenders fn (ruler-extenders fn wrld) body)))
(min-old-ruler-extenders-1 fns
body
ruler-extenders
nil
(induction-machine-for-fn
fns
body
ruler-extenders)))))))
(defmacro minimize-ruler-extenders (form &key verbose-p)
(cond
((symbolp form)
`(min-old-ruler-extenders ',form 'minimize-ruler-extenders state))
(t
`(make-event
(let* ((verbose-p ,verbose-p)
(def-types *default-def-types*)
(form ',form)
(form0 (strip-ruler-extenders form))
(ctx 'minimize-ruler-extenders))
(cond
((not (and (consp form)
(true-listp form)
(member-eq (car form) def-types)))
(er soft ctx
"Illegal call of ~x0 on form:~|~x1~|A non-symbol form must be a ~
true-list that is a call of ~v2."
'minimal-ruler-extenders form def-types))
(t
(assert$
(symbolp (cadr form)) ; name
(er-let* ((ruler-extenders-p
(value (member-eq :ruler-extenders
(dcl-fields (butlast (nthcdr 3 form) 1)))))
(steps
(event-steps (if ruler-extenders-p
form
(add-ruler-extenders form0 :all))
verbose-p
`((f-put-global 'minimal-r-e-body
(body ',(cadr form)
nil
(w state))
state)
(f-put-global
'minimal-r-e-ruler-extenders
(ruler-extenders ',(cadr form)
(w state))
state))
state)))
(cond
((null steps)
(er soft ctx
"Original defun failed!"))
(t (er-let* ((ruler-extenders
(minimal-ruler-extenders
form0
(init-ruler-extenders (cadr form)
(f-get-global
'minimal-r-e-ruler-extenders
state)
(f-get-global
'minimal-r-e-body
state))
(minimal-ruler-extenders-steps steps)
nil
verbose-p
state)))
(value (add-ruler-extenders form ruler-extenders))))))))))))))
; Example of MIN_NEW (so named in the :doc):
(local
(encapsulate
()
(minimize-ruler-extenders
(defun foo (x)
(car (if (endp x)
x
(cons (foo (cdr x))
(evens (if (consp (cdr x))
(foo (cddr x))
nil)))))))
(assert-event (equal (ruler-extenders 'foo (w state))
'(car)))
(defun bar (x)
(declare (xargs :ruler-extenders :all))
(mod (if (consp x)
(* (bar (car x))
(if (consp (cdr x))
(ifix (cadr x))
17))
3)
23))
(assert-event (equal (minimize-ruler-extenders bar)
'(mod)))))
(defxdoc minimize-ruler-extenders
:parents (kestrel-utilities system-utilities-non-built-in)
:short "Minimize the ruler-extenders necessary to admit a definition."
:long "<p>@('Minimize-ruler-extenders') is really two utilities. The first,
which we call MIN_NEW below, admits a proposed @(tsee defun) or @(tsee defund)
form by declaring a minimal set of @(see ruler-extenders). This MIN_NEW
utility uses proof to eliminate ruler-extenders as completely as possible,
while still permitting the termination proof to succeed. The second utility,
which we call MIN_OLD below, is applied to a function symbol that already has
a recursive (but not mutually recursive) definition. Here are examples that
illustrate each of these two respective utilities.</p>
@({
; MIN_NEW (to admit a proposed definition):
(minimize-ruler-extenders
(defun foo (x)
(car (if (endp x)
x
(cons (foo (cdr x))
(evens (if (consp (cdr x))
(foo (cddr x))
nil)))))))
; MIN_OLD (to compute minimal ruler-extenders for an existing definition):
(defun bar (x)
(declare (xargs :ruler-extenders :all))
(mod (if (consp x)
(* (bar (car x))
(if (consp (cdr x))
(ifix (cadr x))
17))
3)
23))
(minimize-ruler-extenders bar) ; returns (MOD)
})
<p>In the first (MIN_NEW) example above, a minimal set of @(see
ruler-extenders) — in fact, THE minimal set — is the set
@('{car}'). So the definition that is actually submitted, successfully, to
ACL2 is obtained by making that explicit:</p>
@({
ACL2 !>:pe foo
L 2:x(MINIMIZE-RULER-EXTENDERS (DEFUN FOO # ...))
\\
>L (DEFUN FOO (X)
(DECLARE (XARGS :RULER-EXTENDERS (CAR)))
(CAR (IF (ENDP X)
X
(CONS (FOO (CDR X))
(EVENS (IF (CONSP (CDR X))
(FOO (CDDR X))
NIL))))))
ACL2 !>
})
<p>The input form for the MIN_NEW utility should be a call of @(tsee defun) or
@(tsee defund) that defines a function symbol that is not already defined. If
that form specifies @(':ruler-extenders lst'), then ACL2 will look for a
minimal subsequence of @('lst') that can serve as the ruler-extenders.
Otherwise, ACL2 will start by additing an @(tsee xargs) declaration,
@(':ruler-extenders lst'), where @('lst') contains every plausible
ruler-extender, and then will try to find a minimal subsequence of
@('lst').</p>
<p>Now we turn to the MIN_OLD utility. This utility is applied to a function
symbol @('F') that already has a (singly) recursive definition. It returns a
subset of the ruler-extenders @('R') of @('F') that is minimal in the
following sense: it provides the same induction-machine as @('R'). (The
``induction-machine'' is an ACL2 data structure representing the scheme used
when doing induction based on the recursion in @('F').)</p>")
| true |
; Copyright (C) 2016, Regents of the University of Texas
; Written by PI:NAME:<NAME>END_PI
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
(in-package "ACL2")
(include-book "xdoc/top" :dir :system)
(program)
(set-state-ok t)
(include-book "tools/remove-hyps" :dir :system) ; for event-steps
(include-book "world-queries") ; for ruler-extenders
(defun not-none (r)
; Coerces :none to nil.
(and (not (eq r :none))
r))
(mutual-recursion
(defun possible-ruler-extenders (fns term)
; Normally returns a list of possible ruler-extenders, where term is a subterm
; of the body of a definition of one of the functions in fns, defined together
; with mutual-recursion. However, return :none if there is a call in term of
; some function in fns but there are no ruler-extenders.
(cond
((variablep term) nil)
((fquotep term) nil)
((eq (ffn-symb term) 'if)
(let* ((r1 (possible-ruler-extenders fns (fargn term 1)))
(r2 (possible-ruler-extenders fns (fargn term 2)))
(r3 (possible-ruler-extenders fns (fargn term 3))))
(and (or r1 r2 r3)
(or (union$ (and r1
(cons 'if (not-none r1)))
(not-none r2)
(not-none r3)
:test 'eq)
:none))))
(t (let ((rs (possible-ruler-extenders-lst fns (fargs term))))
(cond (rs (add-to-set-eq (if (flambdap (ffn-symb term))
:lambdas
(ffn-symb term))
(not-none rs)))
((member-eq (ffn-symb term) fns)
:none)
(t nil))))))
(defun possible-ruler-extenders-lst (fns termlist)
(cond ((endp termlist) nil)
((endp (cdr termlist))
(possible-ruler-extenders fns (car termlist)))
(t (let ((r1 (possible-ruler-extenders fns (car termlist)))
(r2 (possible-ruler-extenders-lst fns (cdr termlist))))
(and (or r1 r2)
(or (union-eq (not-none r1)
(not-none r2))
:none))))))
)
(defun init-ruler-extenders (fn ruler-extenders term)
(let ((re (possible-ruler-extenders (list fn) term)))
(if (eq ruler-extenders :all)
re
(intersection-eq re ruler-extenders))))
(defconst *default-def-types*
; We expect some variant of defun here: (defxxx name args (decls/strings)* body).
'(defun defund))
(defun minimal-ruler-extenders-steps (steps)
; This is quite arbitrary, but has worked well for remove-hyps.
(+ 1000 (* 3 steps)))
(defun add-ruler-extenders (form ruler-extenders)
(case-match form
((defxxx name formals . rest)
`(,defxxx ,name ,formals
(declare (xargs :ruler-extenders ,ruler-extenders))
,@rest))
(& (er hard 'add-ruler-extenders
"Unexpected form: ~x0"
form))))
(defun strip-ruler-extenders (form)
(case-match form
((defxxx name formals . rest)
`(,defxxx ,name ,formals
,@(strip-dcls '(:ruler-extenders) (butlast rest 1))
,(car (last rest))))
(& (er hard 'strip-ruler-extenders
"Unexpected form: ~x0"
form))))
(defun minimal-ruler-extenders (form ruler-extenders steps acc verbose-p state)
(cond
((endp ruler-extenders) (value (reverse acc)))
(t (let ((form2 `(with-prover-step-limit
,steps
,(add-ruler-extenders
form
(append (cdr ruler-extenders) acc)))))
(er-let* ((success (event-steps form2 verbose-p nil state)))
(minimal-ruler-extenders form
(cdr ruler-extenders)
steps
(if success
acc
(cons (car ruler-extenders) acc))
verbose-p
state))))))
(defun min-old-ruler-extenders-1 (fns body
ruler-extenders-1
ruler-extenders-2
induction-machine)
; Fns is a list containing a single function symbol, fn, whose translated
; (hence unnormalized) body is body. Let ruler-extenders be the union of the
; sets represented by the lists ruler-extenders-1 and ruler-extenders-2. The
; induction machine for fn with respect to ruler-extenders is
; induction-machine. We return a minimal sublist S of ruler-extenders-1 for
; which the union of the lists represented by S and ruler-extenders-2) still
; produces induction-machine.
(cond
((endp ruler-extenders-1)
ruler-extenders-2)
(t
(min-old-ruler-extenders-1
fns body
(cdr ruler-extenders-1)
(if (equal (induction-machine-for-fn fns body
(revappend (cdr ruler-extenders-1)
ruler-extenders-2))
induction-machine)
ruler-extenders-2
(cons (car ruler-extenders-1)
ruler-extenders-2))
induction-machine))))
(defun min-old-ruler-extenders (fn ctx state)
(declare (xargs :guard (symbolp fn)))
(let* ((wrld (w state))
(recursivep (getpropc fn 'recursivep nil wrld)))
(cond
((not (function-symbolp fn wrld))
(er hard ctx
"The symbol ~x0 is not a known function symbol in the current ACL2 ~
logical world."
fn))
((null recursivep)
(er hard ctx
"The function symbol ~x0 is not recursive."
fn))
((cdr recursivep)
(er hard ctx
"The function symbol ~x0 is part of a mutual-recursion nest, ~x1."
fn recursivep))
(t (let* ((fns (list fn))
(body (body fn nil wrld))
(ruler-extenders
(init-ruler-extenders fn (ruler-extenders fn wrld) body)))
(min-old-ruler-extenders-1 fns
body
ruler-extenders
nil
(induction-machine-for-fn
fns
body
ruler-extenders)))))))
(defmacro minimize-ruler-extenders (form &key verbose-p)
(cond
((symbolp form)
`(min-old-ruler-extenders ',form 'minimize-ruler-extenders state))
(t
`(make-event
(let* ((verbose-p ,verbose-p)
(def-types *default-def-types*)
(form ',form)
(form0 (strip-ruler-extenders form))
(ctx 'minimize-ruler-extenders))
(cond
((not (and (consp form)
(true-listp form)
(member-eq (car form) def-types)))
(er soft ctx
"Illegal call of ~x0 on form:~|~x1~|A non-symbol form must be a ~
true-list that is a call of ~v2."
'minimal-ruler-extenders form def-types))
(t
(assert$
(symbolp (cadr form)) ; name
(er-let* ((ruler-extenders-p
(value (member-eq :ruler-extenders
(dcl-fields (butlast (nthcdr 3 form) 1)))))
(steps
(event-steps (if ruler-extenders-p
form
(add-ruler-extenders form0 :all))
verbose-p
`((f-put-global 'minimal-r-e-body
(body ',(cadr form)
nil
(w state))
state)
(f-put-global
'minimal-r-e-ruler-extenders
(ruler-extenders ',(cadr form)
(w state))
state))
state)))
(cond
((null steps)
(er soft ctx
"Original defun failed!"))
(t (er-let* ((ruler-extenders
(minimal-ruler-extenders
form0
(init-ruler-extenders (cadr form)
(f-get-global
'minimal-r-e-ruler-extenders
state)
(f-get-global
'minimal-r-e-body
state))
(minimal-ruler-extenders-steps steps)
nil
verbose-p
state)))
(value (add-ruler-extenders form ruler-extenders))))))))))))))
; Example of MIN_NEW (so named in the :doc):
(local
(encapsulate
()
(minimize-ruler-extenders
(defun foo (x)
(car (if (endp x)
x
(cons (foo (cdr x))
(evens (if (consp (cdr x))
(foo (cddr x))
nil)))))))
(assert-event (equal (ruler-extenders 'foo (w state))
'(car)))
(defun bar (x)
(declare (xargs :ruler-extenders :all))
(mod (if (consp x)
(* (bar (car x))
(if (consp (cdr x))
(ifix (cadr x))
17))
3)
23))
(assert-event (equal (minimize-ruler-extenders bar)
'(mod)))))
(defxdoc minimize-ruler-extenders
:parents (kestrel-utilities system-utilities-non-built-in)
:short "Minimize the ruler-extenders necessary to admit a definition."
:long "<p>@('Minimize-ruler-extenders') is really two utilities. The first,
which we call MIN_NEW below, admits a proposed @(tsee defun) or @(tsee defund)
form by declaring a minimal set of @(see ruler-extenders). This MIN_NEW
utility uses proof to eliminate ruler-extenders as completely as possible,
while still permitting the termination proof to succeed. The second utility,
which we call MIN_OLD below, is applied to a function symbol that already has
a recursive (but not mutually recursive) definition. Here are examples that
illustrate each of these two respective utilities.</p>
@({
; MIN_NEW (to admit a proposed definition):
(minimize-ruler-extenders
(defun foo (x)
(car (if (endp x)
x
(cons (foo (cdr x))
(evens (if (consp (cdr x))
(foo (cddr x))
nil)))))))
; MIN_OLD (to compute minimal ruler-extenders for an existing definition):
(defun bar (x)
(declare (xargs :ruler-extenders :all))
(mod (if (consp x)
(* (bar (car x))
(if (consp (cdr x))
(ifix (cadr x))
17))
3)
23))
(minimize-ruler-extenders bar) ; returns (MOD)
})
<p>In the first (MIN_NEW) example above, a minimal set of @(see
ruler-extenders) — in fact, THE minimal set — is the set
@('{car}'). So the definition that is actually submitted, successfully, to
ACL2 is obtained by making that explicit:</p>
@({
ACL2 !>:pe foo
L 2:x(MINIMIZE-RULER-EXTENDERS (DEFUN FOO # ...))
\\
>L (DEFUN FOO (X)
(DECLARE (XARGS :RULER-EXTENDERS (CAR)))
(CAR (IF (ENDP X)
X
(CONS (FOO (CDR X))
(EVENS (IF (CONSP (CDR X))
(FOO (CDDR X))
NIL))))))
ACL2 !>
})
<p>The input form for the MIN_NEW utility should be a call of @(tsee defun) or
@(tsee defund) that defines a function symbol that is not already defined. If
that form specifies @(':ruler-extenders lst'), then ACL2 will look for a
minimal subsequence of @('lst') that can serve as the ruler-extenders.
Otherwise, ACL2 will start by additing an @(tsee xargs) declaration,
@(':ruler-extenders lst'), where @('lst') contains every plausible
ruler-extender, and then will try to find a minimal subsequence of
@('lst').</p>
<p>Now we turn to the MIN_OLD utility. This utility is applied to a function
symbol @('F') that already has a (singly) recursive definition. It returns a
subset of the ruler-extenders @('R') of @('F') that is minimal in the
following sense: it provides the same induction-machine as @('R'). (The
``induction-machine'' is an ACL2 data structure representing the scheme used
when doing induction based on the recursion in @('F').)</p>")
|
[
{
"context": "s #-capi :com :wt.com :wt.component)\n (:use :cl :alexandria)\n (:export\n :define-component\n :component\n ",
"end": 118,
"score": 0.9684632420539856,
"start": 108,
"tag": "NAME",
"value": "alexandria"
}
] |
component/package.lisp
|
xh4/web-toolk
| 81 |
(in-package :cl-user)
(defpackage :component
(:nicknames #-capi :com :wt.com :wt.component)
(:use :cl :alexandria)
(:export
:define-component
:component
:render
:render-all
:diff
:component-class-style)
(:import-from :html
:serialize)
(:import-from :dom
:append-child
:children)
(:import-from :utility
:rewrite-class-option
:function-lambda-list)
(:import-from :reactive
:reactive-object
:reactive-class
:variable-value
:with-variable-capturing
:object-propagation
:add-dependency
:react
:with-propagation
:without-propagation)
(:shadowing-import-from :reactive
:variable)
(:import-from :uri
:uri-path)
(:import-from :closer-mop
:allocate-instance
:validate-superclass
:class-slots
:class-direct-slots
:class-direct-subclasses
:slot-definition
:slot-definition-name
:slot-definition-initargs
:compute-class-precedence-list
:ensure-finalized
:slot-value-using-class)
(:import-from :split-sequence
:split-sequence))
|
40461
|
(in-package :cl-user)
(defpackage :component
(:nicknames #-capi :com :wt.com :wt.component)
(:use :cl :<NAME>)
(:export
:define-component
:component
:render
:render-all
:diff
:component-class-style)
(:import-from :html
:serialize)
(:import-from :dom
:append-child
:children)
(:import-from :utility
:rewrite-class-option
:function-lambda-list)
(:import-from :reactive
:reactive-object
:reactive-class
:variable-value
:with-variable-capturing
:object-propagation
:add-dependency
:react
:with-propagation
:without-propagation)
(:shadowing-import-from :reactive
:variable)
(:import-from :uri
:uri-path)
(:import-from :closer-mop
:allocate-instance
:validate-superclass
:class-slots
:class-direct-slots
:class-direct-subclasses
:slot-definition
:slot-definition-name
:slot-definition-initargs
:compute-class-precedence-list
:ensure-finalized
:slot-value-using-class)
(:import-from :split-sequence
:split-sequence))
| true |
(in-package :cl-user)
(defpackage :component
(:nicknames #-capi :com :wt.com :wt.component)
(:use :cl :PI:NAME:<NAME>END_PI)
(:export
:define-component
:component
:render
:render-all
:diff
:component-class-style)
(:import-from :html
:serialize)
(:import-from :dom
:append-child
:children)
(:import-from :utility
:rewrite-class-option
:function-lambda-list)
(:import-from :reactive
:reactive-object
:reactive-class
:variable-value
:with-variable-capturing
:object-propagation
:add-dependency
:react
:with-propagation
:without-propagation)
(:shadowing-import-from :reactive
:variable)
(:import-from :uri
:uri-path)
(:import-from :closer-mop
:allocate-instance
:validate-superclass
:class-slots
:class-direct-slots
:class-direct-subclasses
:slot-definition
:slot-definition-name
:slot-definition-initargs
:compute-class-precedence-list
:ensure-finalized
:slot-value-using-class)
(:import-from :split-sequence
:split-sequence))
|
[
{
"context": "-----------\n#|\nThe MIT License\n\nCopyright (c) 2018 Emotiq AG\n\nPermission is hereby granted, free of charge, to",
"end": 207,
"score": 0.7928413152694702,
"start": 198,
"tag": "NAME",
"value": "Emotiq AG"
}
] |
src/Crypto/vec-repr.lisp
|
easye/emotiq
| 109 |
;; vec-repr.lisp -- Uniform and varied representation of UB8 Vectors
;;
;; DM/Emotiq 02/18
;; ----------------------------------------------------------------
#|
The MIT License
Copyright (c) 2018 Emotiq AG
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
|#
(in-package :vec-repr)
;; ---------------------------------------------------------
;; This package describes interchangeable representations of vectors
;; of (unsigned-byte 8) values.
;;
;; Class Hierarchy
;; ---------------
;;
;; UB8V
;; |
;; +-----+------+--------+-------+
;; | | | | |
;; LEV BEV BASE58 BASE64 HEX
;;
;; Class UB8V serves as an abstract superclass for all of these
;; parallel sub-classes. Any object of one of the subclasses can be
;; instantly converted into another parallel representation.
;;
;; Additionlly we make provision for conversion from bignum integers
;; to/from these vector representations.
;;
;; Finally, the Class UB8V-REPR is a mixin for future classes to use,
;; to indicate that they have the ability to produce a UB8V
;; representation, e.g., public keys, secret keys, compressed points
;; of Elliptic Curves, etc. This representation may be requested from
;; them with the UB8V-REPR method call.
;;
;; Type UB8 represents '(UNSIGNED-BYTE 8). Type UB8-VECTOR is defined
;; to represent any vector of actual UB8 values. Endian interpretation
;; is in the eye of the beholder.
;;
;; Each of the subclasses also has methods defined with the same name
;; as their class name, to perform conversions to their specific form
;; of representation. For example:
;;
;; (base58 (lev #(1 2 3 4)))
;; ==>
;; #<BASE58 1111156wxj2 >
;;
;; These conversion operators may be applied to objects of any of the
;; parallel subclasses, as well as to INTEGER, LIST, and VECTOR. The
;; latter two must contain only elements of type UB8.
;;
;; The operators can also be applied to any class that inherits from
;; the mixin class UB8V-REPR and which implements a method by that
;; same name to return an instance of one of these parallel
;; subclasses. (c.f., PBC.LISP)
;;
;; NOTE: Items of these types should be considered inviolable atomic
;; values, just like bignums. Modification of their internal contents
;; may have unpredictable consequences.
;;
;; ----------------------------------------------------------
;; Declare Types UB8 and UB8-VECTOR
(deftype ub8 ()
'(unsigned-byte 8))
(deftype ub8-vector (&optional nel)
`(array ub8 (,nel)))
(defun make-ub8-vector (nel &rest args)
(apply 'make-array nel
:element-type 'ub8
args))
;; ----------------------------------------------------------
;; from https://bitcointalk.org/index.php?topic=1026.0
(um:defconstant+ +alphabet-58+
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
(um:defconstant+ +len-58+
(length +alphabet-58+)) ;; should be 58
(defun make-inverse-alphabet (alphabet)
(let ((arr (make-ub8-vector 256
:initial-element 0)))
(loop for c across alphabet
for ix from 1
do
(setf (aref arr (char-code c)) ix))
arr))
(defvar +inv-alphabet-58+
(make-inverse-alphabet +alphabet-58+))
;; ----------------------------------------------------------
(um:defconstant+ +alphabet-64+
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
(defvar +inv-alphabet-64+
(make-inverse-alphabet +alphabet-64+))
;; ---------------------------------------------------------
;; UB8V - the top abstract class of objects which represent
;; UB8-VECTORs. Declare a single slot to hold the data. Object of
;; these classes are intended to be immuatable. All subclasses share
;; this same slot.
(defclass ub8v ()
((val :reader ub8v-vec
:initarg :vec)))
;; ---------------------------------------------------------
;; Declare a useful mixin class to allow future classes to show a UB8V
;; representation
(defclass ub8v-repr ()
())
(defgeneric ub8v-repr (x)
;; subclasses of the mixin should return whatever representation
;; they need
(:method ((x ub8v-repr))
(error "Subclass responsibility")))
;; -----------------------------------------------
(defmethod print-object ((obj ub8v) out-stream)
(if *print-readably*
(with-standard-io-syntax
(princ "#." out-stream)
(prin1 `(,(class-name (class-of obj)) (hex ,(hex-str (hex obj))))
out-stream))
;; else
(print-unreadable-object (obj out-stream :type t)
(princ (short-str (ub8v-vec obj)) out-stream))
))
(defmethod print-object ((obj ub8v-repr) out-stream)
;; subclasses of UB8V-REPR mixin should feel free to override this
(if *print-readably*
(format out-stream "#.(make-instance '~W :value ~A)"
(class-name (class-of obj))
(ub8v-repr obj))
;; else
(print-unreadable-object (obj out-stream :type t)
(princ (short-str (ub8v-repr obj)) out-stream))
))
(defun short-str (str)
(let ((len (length str)))
(if (< len 17)
str
(format nil "~A..~A"
(subseq str 0 7)
(subseq str (- len 7)))
)))
;; ----------------------------------------------------------
;; Base58 encodes integers into character strings of the restricted
;; alphabet.
(defclass base58 (ub8v)
((val :reader base58-str
:initarg :str)
))
(defgeneric base58 (x))
(defmethod base58-str (x)
(base58-str (base58 x)))
;; ----------------------------------------------------------
;; Base64 encodes UB8 vectors and integers into character strings of
;; the restricted alphabet. Encoding has a 6-character prefix that
;; represents the total number of bytes in the vector, up to 2^32
;; elements.
(defclass base64 (ub8v)
((val :reader base64-str
:initarg :str)
))
(defgeneric base64 (x))
(defmethod base64-str (x)
(base64-str (base64 x)))
;; -----------------------------------------------------------
;; Hex-string representation, 1 char per 4-bit nibble
(defclass hex (ub8v)
((val :reader hex-str
:initarg :str)))
(defgeneric hex (x))
(defmethod hex-str (x)
(hex-str (hex x)))
;; -----------------------------------------------------------
;; LEV-UB8 are little-endian vectors of UB8 elements
(defclass lev (ub8v)
((val :reader lev-vec
:initarg :vec)
))
(defgeneric lev (x))
(defmethod lev-vec (x)
(lev-vec (lev x)))
;; -----------------------------------------------------------
;; BEV-UB8 are big-endian vectors of UB8 elements
(defclass bev (ub8v)
((val :reader bev-vec
:initarg :vec)
))
(defgeneric bev (x))
(defmethod bev-vec (x)
(bev-vec (bev x)))
;; ---------------------------------------------------------
;; Integer to/from vector form - conversion starts at LSB and works
;; toward MSB. So FROR-END should be true for big-endian vectors, and
;; false for little-endian vectors.
(defun convert-vec-to-int (vec &key
(start 0)
(end (length vec))
(from-end t))
;; from-end t is suitable for big-endian format
(let ((val 0))
(if from-end
(do ((ix (1- end) (1- ix))
(pos 0 (+ pos 8)))
((< ix start) val)
(setf val (dpb (aref vec ix) (byte 8 pos) val)))
;; else
(do ((ix start (1+ ix))
(pos 0 (+ 8 pos)))
((>= ix end) val)
(setf val (dpb (aref vec ix) (byte 8 pos) val)))
)))
(defun convert-int-to-vec (val &key
(from-end t)
(nb (max 1 (ceiling (integer-length val) 8))))
;; convert val to little-endian vector of UB8
(let ((v (make-ub8-vector nb
:initial-element 0)))
(if from-end
(do ((ix (1- nb) (1- ix))
(pos 0 (+ 8 pos)))
((minusp ix) v)
(setf (aref v ix) (ldb (byte 8 pos) val)))
;; else
(do ((ix 0 (1+ ix))
(pos 0 (+ 8 pos)))
((>= ix nb) v)
(setf (aref v ix) (ldb (byte 8 pos) val)))
)))
;; --------------------------------------------------------------
;; Integer conversions - these produce raw integers without any type
;; context
(defmethod int ((x integer))
x)
(defmethod int ((x lev))
(convert-vec-to-int (lev-vec x)
:from-end nil))
(defmethod int ((x bev))
(convert-vec-to-int (bev-vec x)))
(defmethod int ((x base58))
(let* ((str (base58-str x))
(limit (length str)))
(um:nlet-tail iter ((pos 0)
(val 0))
(if (>= pos limit)
val
(let* ((c (char str pos))
(v (aref +inv-alphabet-58+ (char-code c))))
(when (zerop v)
(error "Invalid Base58 string: ~A" str))
(iter (1+ pos) (+ (1- v) (* 58 val)))
))
)))
(defmethod int ((x base64))
(let* ((str (base64-str x))
(limit (length str)))
(um:nlet-tail iter ((pos 0)
(val 0))
(if (>= pos limit)
val
(let* ((c (char str pos)))
(if (char= c #\=)
val
(let ((v (aref +inv-alphabet-64+ (char-code c))))
(when (zerop v)
(error "Invalid Base64 string: ~A" str))
(iter (1+ pos) (+ (1- v) (ash val 6)))
)))
))))
(defmethod int ((x hex))
(let ((str (hex-str x)))
(if (string= "" str)
0
(let ((*read-eval* nil)
(*read-base* 16))
(read-from-string str)))
))
(defmethod int (x)
(int (bev x)))
;; --------------------------------------------------------------
;; Base58 -- Integer value as Base58 string
;;
;; NOTE: The rules followed in this package try to preserve the byte
;; vector as the fundamental unit of importance. So if a byte vector
;; (BEV or LEV) is converted into a Base58, Base64, or HEX
;; representation, that representation will have at least the same
;; overall bit-length as the underlying byte vector.
;;
;; This means, e.g., suppose we have a byte vector with 32 bytes. That
;; is 256 bits.
;;
;; In Base58, each character accounts for 5.86 bits, so
;; the Base58 representation will have 44 (= (ceiling 256 5.86))
;; chars, for a bit length of 257.84 bits.
;;
;; A Base64 representation of the same 256 bit value will have 43
;; chars, for a bit length of 258 bits.
;;
;; With this understanding, on conversion back to byte vector form,
;; the underlying byte vector will end up with (FLOOR nbits 8) bytes,
;; where nbits is the number of bits represented by the string. In the
;; case of Base58 this will be (floor (* 5.86 (length str)) 8) bits.
;; In the case of Base64 it will be (floor (* 6 (length str)) 8).
;;
;; For Hex encodings, every byte vector will produce an even number of
;; hex digits. But if a Hex value with an odd number of digits is
;; converted back to a byte vector, we round upward. So HEX "012" will
;; produce a BEV vector of #(0 #x12).
;;
;; For now, if this departs from Bitcoin standards, too bad.
;; ------------------------------------------------------------------
(defun validate-base58-string (str)
(every (lambda (c)
(plusp (aref +alphabet-58+ (char-code c))))
str))
(defun convert-int-to-base58-string (val vec)
;; vec is byte vector from which val was computed
(declare (integer val))
(let* ((nbytes (length vec))
(n58 (ceiling (* nbytes #.(log 256 58))))
(cs nil))
(declare (fixnum nbytes n58))
(um:nlet-tail iter ((val val)
(ct n58))
(declare (integer val)
(fixnum ct))
(when (plusp ct)
(multiple-value-bind (vw vf) (floor val 58)
(declare (integer vw)
(fixnum vf))
(let ((c (aref +alphabet-58+ vf)))
(push c cs)
(iter vw (1- ct)))))
(coerce cs 'string))
))
;; ---
(defmethod base58 ((x base58))
x)
(defmethod base58 ((x string))
(assert (every (um:rcurry 'find +alphabet-58+) x))
(make-instance 'base58
:str x))
(defmethod base58 ((x vector))
;; this code assumes x is big-endian...
(make-instance 'base58
:str (convert-int-to-base58-string (convert-vec-to-int x) x)))
(defmethod base58 ((x bev))
(base58 (bev-vec x)))
(defmethod base58 ((x lev))
(make-instance 'base58
:str (convert-int-to-base58-string (int x) (lev-vec x))))
(defmethod base58 (x)
;; preserve leading zeros
(base58 (bev x)))
;; -------------------------------------------------------------
;; Base64 Conversions
(defun convert-int-to-base64-string (val vec)
;; vec is byte vector from which val was computed
(declare (integer val))
(let* ((nbytes (length vec))
(n64 (ceiling (* nbytes #.(log 256 64))))
(ntail (logand n64 3))
(cs nil))
(declare (fixnum nbytes n64 ntail))
(unless (zerop ntail)
(loop repeat (- 4 ntail) do (push #\= cs)))
(um:nlet-tail iter ((val val)
(ct n64))
(declare (integer val)
(fixnum ct))
(when (plusp ct)
(let* ((bits (ldb (byte 6 0) val))
(c (aref +alphabet-64+ bits)))
(declare (fixnum bits))
(push c cs)
(iter (ash val -6) (1- ct)))))
(coerce cs 'string)))
(defmethod base64 ((x bev))
(make-instance 'base64
:str (convert-int-to-base64-string (int x) (bev-vec x))))
(defmethod base64 ((x lev))
(make-instance 'base64
:str (convert-int-to-base64-string (int x) (lev-vec x))))
(defmethod base64 ((x string))
(assert (every (um:rcurry 'find +alphabet-64+) (string-right-trim '(#\=) x)))
(make-instance 'base64
:str x))
(defmethod base64 ((x base64))
x)
(defmethod base64 (x)
(base64 (bev x)))
;; -------------------------------------------------------------
;; HEX Conversions
(defun convert-int-to-hex-string (val vec)
;; convert int val to hex string of length sufficient to cover vec
;; from which val was derived.
(declare (integer val))
(let ((nc (* 2 (length vec))))
(declare (fixnum nc))
(format nil "~@?" (format nil "~~~A,'0x" nc) val)))
(defmethod hex ((x bev))
(make-instance 'hex
:str (convert-int-to-hex-string (int x) (bev-vec x))))
(defmethod hex ((x lev))
(make-instance 'hex
:str (convert-int-to-hex-string (int x) (lev-vec x))))
(defmethod hex ((x hex))
x)
(defmethod hex ((x string))
(assert (every (um:rcurry 'digit-char-p 16) x))
(make-instance 'hex
:str x))
(defmethod hex (x)
(hex (bev x)))
;; ------------------------------------------------------
;; LEV -- encode vector as little-endian (LSB first)
(defmethod lev ((x lev))
x)
(defmethod lev ((x bev))
(make-instance 'lev
:vec (reverse (bev-vec x))))
(defmethod lev ((val integer))
(make-instance 'lev
:vec (convert-int-to-vec val :from-end nil)))
(defmethod lev ((x sequence))
;; LIST and VECTOR when can be coerced to UB8-VECTOR
(make-instance 'lev
:vec (coerce x 'ub8-vector)))
(defmethod lev ((x ub8v-repr))
(lev (ub8v-repr x)))
(defmethod lev ((x base58))
;; convert Base58 to LEV, respecting leading zeros
(let* ((str (base58-str x))
(val (int x))
(nel (floor (* (length str) #.(log 58 256)))))
(levn val nel)))
(defmethod lev ((x base64))
;; convert Base64 to LEV, respecting leading zeros
(let* ((str (string-right-trim "=" (base64-str x)))
(val (int x))
(nel (floor (* (length str) #.(log 64 256)))))
(levn val nel)))
(defmethod lev ((x hex))
;; convert HEX to LEV, respecting leading zeros
(let* ((str (hex-str x))
(val (int x))
(nel (floor (1+ (length str)) 2)))
(levn val nel)))
(defmethod lev (x)
(make-instance 'lev
:vec (nreverse
(bev-vec (bev x)))))
(defun levn (x nb)
;; create a LEV with a specified number of UB8 bytes
(let* ((lev (lev x))
(nel (length (lev-vec lev))))
(cond ((< nel nb)
;; extend with zero filled tail
(let* ((diff (- nb nel))
(tail (make-ub8-vector diff
:initial-element 0)))
(make-instance 'lev
:vec (concatenate 'ub8-vector (lev-vec lev) tail))))
((> nel nb)
;; take from the LSB side
(make-instance 'lev
:vec (subseq (lev-vec lev) 0 nb)))
(t
lev)
)))
;; -----------------------------------------------------------
;; BEV -- encode vector as big-endian (MSB first)
(defmethod bev ((x bev))
x)
(defmethod bev ((x ub8v-repr))
(bev (ub8v-repr x)))
(defmethod bev ((x lev))
;; conversion of LEV to BEV
(make-instance 'bev
:vec (reverse (lev-vec x))))
(defmethod bev ((x sequence))
;; LIST and VECTOR when can be coerced to UB8-VECTOR
(make-instance 'bev
:vec (coerce x 'ub8-vector)))
(defmethod bev ((x string))
(bev (hex x)))
(defmethod bev ((x integer))
;; convert integer to BEV vector
(make-instance 'bev
:vec (convert-int-to-vec x :from-end t)))
(defmethod bev ((x base58))
;; convert Base58 to BEV, respecting leading zeros
(let* ((str (base58-str x))
(val (int x))
(nel (floor (* (length str) #.(log 58 256)))))
(bevn val nel)))
(defmethod bev ((x base64))
;; convert Base64 to BEV respecting leading zeros
(let* ((str (string-right-trim "=" (base64-str x)))
(val (int x))
(nel (floor (* (length str) #.(log 64 256)))))
(bevn val nel)))
(defmethod bev ((x hex))
;; convert HEX to BEV, respecting leading zeros
(let* ((str (hex-str x))
(val (int x))
(nel (ash (1+ (length str)) -1)))
(bevn val nel)))
(defun bevn (x nb)
;; construct a BEV with a specified number of UB8 bytes
(let* ((bev (bev x))
(nel (length (bev-vec bev))))
(cond ((< nel nb)
;; prepend with zero filled prefix
(let* ((diff (- nb nel))
(pref (make-ub8-vector diff
:initial-element 0)))
(make-instance 'bev
:vec (concatenate 'ub8-vector pref (bev-vec bev)))))
((> nel nb)
;; take a portion from the LSB side
(make-instance 'bev
:vec (subseq (bev-vec bev) (- nel nb))))
(t
bev)
)))
;; --------------------------------------------------------------
;; Testing
(defun int= (a b)
"Poor way to do equality testing on UB8V items. This method fails to
account for vectors with leading null bytes. Okay for comparing
compressed ECC points - public keys, signatures. Not okay for hash
comparisons."
(= (int a) (int b)))
(defun vec= (a b)
"Easy way to do equality testing on UB8V items"
(equalp (bev-vec a) (bev-vec b)))
;; --------------------------------------------------------------
;; Utility functions
(defun sbs (str)
(coerce str 'simple-base-string))
|
82502
|
;; vec-repr.lisp -- Uniform and varied representation of UB8 Vectors
;;
;; DM/Emotiq 02/18
;; ----------------------------------------------------------------
#|
The MIT License
Copyright (c) 2018 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
|#
(in-package :vec-repr)
;; ---------------------------------------------------------
;; This package describes interchangeable representations of vectors
;; of (unsigned-byte 8) values.
;;
;; Class Hierarchy
;; ---------------
;;
;; UB8V
;; |
;; +-----+------+--------+-------+
;; | | | | |
;; LEV BEV BASE58 BASE64 HEX
;;
;; Class UB8V serves as an abstract superclass for all of these
;; parallel sub-classes. Any object of one of the subclasses can be
;; instantly converted into another parallel representation.
;;
;; Additionlly we make provision for conversion from bignum integers
;; to/from these vector representations.
;;
;; Finally, the Class UB8V-REPR is a mixin for future classes to use,
;; to indicate that they have the ability to produce a UB8V
;; representation, e.g., public keys, secret keys, compressed points
;; of Elliptic Curves, etc. This representation may be requested from
;; them with the UB8V-REPR method call.
;;
;; Type UB8 represents '(UNSIGNED-BYTE 8). Type UB8-VECTOR is defined
;; to represent any vector of actual UB8 values. Endian interpretation
;; is in the eye of the beholder.
;;
;; Each of the subclasses also has methods defined with the same name
;; as their class name, to perform conversions to their specific form
;; of representation. For example:
;;
;; (base58 (lev #(1 2 3 4)))
;; ==>
;; #<BASE58 1111156wxj2 >
;;
;; These conversion operators may be applied to objects of any of the
;; parallel subclasses, as well as to INTEGER, LIST, and VECTOR. The
;; latter two must contain only elements of type UB8.
;;
;; The operators can also be applied to any class that inherits from
;; the mixin class UB8V-REPR and which implements a method by that
;; same name to return an instance of one of these parallel
;; subclasses. (c.f., PBC.LISP)
;;
;; NOTE: Items of these types should be considered inviolable atomic
;; values, just like bignums. Modification of their internal contents
;; may have unpredictable consequences.
;;
;; ----------------------------------------------------------
;; Declare Types UB8 and UB8-VECTOR
(deftype ub8 ()
'(unsigned-byte 8))
(deftype ub8-vector (&optional nel)
`(array ub8 (,nel)))
(defun make-ub8-vector (nel &rest args)
(apply 'make-array nel
:element-type 'ub8
args))
;; ----------------------------------------------------------
;; from https://bitcointalk.org/index.php?topic=1026.0
(um:defconstant+ +alphabet-58+
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
(um:defconstant+ +len-58+
(length +alphabet-58+)) ;; should be 58
(defun make-inverse-alphabet (alphabet)
(let ((arr (make-ub8-vector 256
:initial-element 0)))
(loop for c across alphabet
for ix from 1
do
(setf (aref arr (char-code c)) ix))
arr))
(defvar +inv-alphabet-58+
(make-inverse-alphabet +alphabet-58+))
;; ----------------------------------------------------------
(um:defconstant+ +alphabet-64+
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
(defvar +inv-alphabet-64+
(make-inverse-alphabet +alphabet-64+))
;; ---------------------------------------------------------
;; UB8V - the top abstract class of objects which represent
;; UB8-VECTORs. Declare a single slot to hold the data. Object of
;; these classes are intended to be immuatable. All subclasses share
;; this same slot.
(defclass ub8v ()
((val :reader ub8v-vec
:initarg :vec)))
;; ---------------------------------------------------------
;; Declare a useful mixin class to allow future classes to show a UB8V
;; representation
(defclass ub8v-repr ()
())
(defgeneric ub8v-repr (x)
;; subclasses of the mixin should return whatever representation
;; they need
(:method ((x ub8v-repr))
(error "Subclass responsibility")))
;; -----------------------------------------------
(defmethod print-object ((obj ub8v) out-stream)
(if *print-readably*
(with-standard-io-syntax
(princ "#." out-stream)
(prin1 `(,(class-name (class-of obj)) (hex ,(hex-str (hex obj))))
out-stream))
;; else
(print-unreadable-object (obj out-stream :type t)
(princ (short-str (ub8v-vec obj)) out-stream))
))
(defmethod print-object ((obj ub8v-repr) out-stream)
;; subclasses of UB8V-REPR mixin should feel free to override this
(if *print-readably*
(format out-stream "#.(make-instance '~W :value ~A)"
(class-name (class-of obj))
(ub8v-repr obj))
;; else
(print-unreadable-object (obj out-stream :type t)
(princ (short-str (ub8v-repr obj)) out-stream))
))
(defun short-str (str)
(let ((len (length str)))
(if (< len 17)
str
(format nil "~A..~A"
(subseq str 0 7)
(subseq str (- len 7)))
)))
;; ----------------------------------------------------------
;; Base58 encodes integers into character strings of the restricted
;; alphabet.
(defclass base58 (ub8v)
((val :reader base58-str
:initarg :str)
))
(defgeneric base58 (x))
(defmethod base58-str (x)
(base58-str (base58 x)))
;; ----------------------------------------------------------
;; Base64 encodes UB8 vectors and integers into character strings of
;; the restricted alphabet. Encoding has a 6-character prefix that
;; represents the total number of bytes in the vector, up to 2^32
;; elements.
(defclass base64 (ub8v)
((val :reader base64-str
:initarg :str)
))
(defgeneric base64 (x))
(defmethod base64-str (x)
(base64-str (base64 x)))
;; -----------------------------------------------------------
;; Hex-string representation, 1 char per 4-bit nibble
(defclass hex (ub8v)
((val :reader hex-str
:initarg :str)))
(defgeneric hex (x))
(defmethod hex-str (x)
(hex-str (hex x)))
;; -----------------------------------------------------------
;; LEV-UB8 are little-endian vectors of UB8 elements
(defclass lev (ub8v)
((val :reader lev-vec
:initarg :vec)
))
(defgeneric lev (x))
(defmethod lev-vec (x)
(lev-vec (lev x)))
;; -----------------------------------------------------------
;; BEV-UB8 are big-endian vectors of UB8 elements
(defclass bev (ub8v)
((val :reader bev-vec
:initarg :vec)
))
(defgeneric bev (x))
(defmethod bev-vec (x)
(bev-vec (bev x)))
;; ---------------------------------------------------------
;; Integer to/from vector form - conversion starts at LSB and works
;; toward MSB. So FROR-END should be true for big-endian vectors, and
;; false for little-endian vectors.
(defun convert-vec-to-int (vec &key
(start 0)
(end (length vec))
(from-end t))
;; from-end t is suitable for big-endian format
(let ((val 0))
(if from-end
(do ((ix (1- end) (1- ix))
(pos 0 (+ pos 8)))
((< ix start) val)
(setf val (dpb (aref vec ix) (byte 8 pos) val)))
;; else
(do ((ix start (1+ ix))
(pos 0 (+ 8 pos)))
((>= ix end) val)
(setf val (dpb (aref vec ix) (byte 8 pos) val)))
)))
(defun convert-int-to-vec (val &key
(from-end t)
(nb (max 1 (ceiling (integer-length val) 8))))
;; convert val to little-endian vector of UB8
(let ((v (make-ub8-vector nb
:initial-element 0)))
(if from-end
(do ((ix (1- nb) (1- ix))
(pos 0 (+ 8 pos)))
((minusp ix) v)
(setf (aref v ix) (ldb (byte 8 pos) val)))
;; else
(do ((ix 0 (1+ ix))
(pos 0 (+ 8 pos)))
((>= ix nb) v)
(setf (aref v ix) (ldb (byte 8 pos) val)))
)))
;; --------------------------------------------------------------
;; Integer conversions - these produce raw integers without any type
;; context
(defmethod int ((x integer))
x)
(defmethod int ((x lev))
(convert-vec-to-int (lev-vec x)
:from-end nil))
(defmethod int ((x bev))
(convert-vec-to-int (bev-vec x)))
(defmethod int ((x base58))
(let* ((str (base58-str x))
(limit (length str)))
(um:nlet-tail iter ((pos 0)
(val 0))
(if (>= pos limit)
val
(let* ((c (char str pos))
(v (aref +inv-alphabet-58+ (char-code c))))
(when (zerop v)
(error "Invalid Base58 string: ~A" str))
(iter (1+ pos) (+ (1- v) (* 58 val)))
))
)))
(defmethod int ((x base64))
(let* ((str (base64-str x))
(limit (length str)))
(um:nlet-tail iter ((pos 0)
(val 0))
(if (>= pos limit)
val
(let* ((c (char str pos)))
(if (char= c #\=)
val
(let ((v (aref +inv-alphabet-64+ (char-code c))))
(when (zerop v)
(error "Invalid Base64 string: ~A" str))
(iter (1+ pos) (+ (1- v) (ash val 6)))
)))
))))
(defmethod int ((x hex))
(let ((str (hex-str x)))
(if (string= "" str)
0
(let ((*read-eval* nil)
(*read-base* 16))
(read-from-string str)))
))
(defmethod int (x)
(int (bev x)))
;; --------------------------------------------------------------
;; Base58 -- Integer value as Base58 string
;;
;; NOTE: The rules followed in this package try to preserve the byte
;; vector as the fundamental unit of importance. So if a byte vector
;; (BEV or LEV) is converted into a Base58, Base64, or HEX
;; representation, that representation will have at least the same
;; overall bit-length as the underlying byte vector.
;;
;; This means, e.g., suppose we have a byte vector with 32 bytes. That
;; is 256 bits.
;;
;; In Base58, each character accounts for 5.86 bits, so
;; the Base58 representation will have 44 (= (ceiling 256 5.86))
;; chars, for a bit length of 257.84 bits.
;;
;; A Base64 representation of the same 256 bit value will have 43
;; chars, for a bit length of 258 bits.
;;
;; With this understanding, on conversion back to byte vector form,
;; the underlying byte vector will end up with (FLOOR nbits 8) bytes,
;; where nbits is the number of bits represented by the string. In the
;; case of Base58 this will be (floor (* 5.86 (length str)) 8) bits.
;; In the case of Base64 it will be (floor (* 6 (length str)) 8).
;;
;; For Hex encodings, every byte vector will produce an even number of
;; hex digits. But if a Hex value with an odd number of digits is
;; converted back to a byte vector, we round upward. So HEX "012" will
;; produce a BEV vector of #(0 #x12).
;;
;; For now, if this departs from Bitcoin standards, too bad.
;; ------------------------------------------------------------------
(defun validate-base58-string (str)
(every (lambda (c)
(plusp (aref +alphabet-58+ (char-code c))))
str))
(defun convert-int-to-base58-string (val vec)
;; vec is byte vector from which val was computed
(declare (integer val))
(let* ((nbytes (length vec))
(n58 (ceiling (* nbytes #.(log 256 58))))
(cs nil))
(declare (fixnum nbytes n58))
(um:nlet-tail iter ((val val)
(ct n58))
(declare (integer val)
(fixnum ct))
(when (plusp ct)
(multiple-value-bind (vw vf) (floor val 58)
(declare (integer vw)
(fixnum vf))
(let ((c (aref +alphabet-58+ vf)))
(push c cs)
(iter vw (1- ct)))))
(coerce cs 'string))
))
;; ---
(defmethod base58 ((x base58))
x)
(defmethod base58 ((x string))
(assert (every (um:rcurry 'find +alphabet-58+) x))
(make-instance 'base58
:str x))
(defmethod base58 ((x vector))
;; this code assumes x is big-endian...
(make-instance 'base58
:str (convert-int-to-base58-string (convert-vec-to-int x) x)))
(defmethod base58 ((x bev))
(base58 (bev-vec x)))
(defmethod base58 ((x lev))
(make-instance 'base58
:str (convert-int-to-base58-string (int x) (lev-vec x))))
(defmethod base58 (x)
;; preserve leading zeros
(base58 (bev x)))
;; -------------------------------------------------------------
;; Base64 Conversions
(defun convert-int-to-base64-string (val vec)
;; vec is byte vector from which val was computed
(declare (integer val))
(let* ((nbytes (length vec))
(n64 (ceiling (* nbytes #.(log 256 64))))
(ntail (logand n64 3))
(cs nil))
(declare (fixnum nbytes n64 ntail))
(unless (zerop ntail)
(loop repeat (- 4 ntail) do (push #\= cs)))
(um:nlet-tail iter ((val val)
(ct n64))
(declare (integer val)
(fixnum ct))
(when (plusp ct)
(let* ((bits (ldb (byte 6 0) val))
(c (aref +alphabet-64+ bits)))
(declare (fixnum bits))
(push c cs)
(iter (ash val -6) (1- ct)))))
(coerce cs 'string)))
(defmethod base64 ((x bev))
(make-instance 'base64
:str (convert-int-to-base64-string (int x) (bev-vec x))))
(defmethod base64 ((x lev))
(make-instance 'base64
:str (convert-int-to-base64-string (int x) (lev-vec x))))
(defmethod base64 ((x string))
(assert (every (um:rcurry 'find +alphabet-64+) (string-right-trim '(#\=) x)))
(make-instance 'base64
:str x))
(defmethod base64 ((x base64))
x)
(defmethod base64 (x)
(base64 (bev x)))
;; -------------------------------------------------------------
;; HEX Conversions
(defun convert-int-to-hex-string (val vec)
;; convert int val to hex string of length sufficient to cover vec
;; from which val was derived.
(declare (integer val))
(let ((nc (* 2 (length vec))))
(declare (fixnum nc))
(format nil "~@?" (format nil "~~~A,'0x" nc) val)))
(defmethod hex ((x bev))
(make-instance 'hex
:str (convert-int-to-hex-string (int x) (bev-vec x))))
(defmethod hex ((x lev))
(make-instance 'hex
:str (convert-int-to-hex-string (int x) (lev-vec x))))
(defmethod hex ((x hex))
x)
(defmethod hex ((x string))
(assert (every (um:rcurry 'digit-char-p 16) x))
(make-instance 'hex
:str x))
(defmethod hex (x)
(hex (bev x)))
;; ------------------------------------------------------
;; LEV -- encode vector as little-endian (LSB first)
(defmethod lev ((x lev))
x)
(defmethod lev ((x bev))
(make-instance 'lev
:vec (reverse (bev-vec x))))
(defmethod lev ((val integer))
(make-instance 'lev
:vec (convert-int-to-vec val :from-end nil)))
(defmethod lev ((x sequence))
;; LIST and VECTOR when can be coerced to UB8-VECTOR
(make-instance 'lev
:vec (coerce x 'ub8-vector)))
(defmethod lev ((x ub8v-repr))
(lev (ub8v-repr x)))
(defmethod lev ((x base58))
;; convert Base58 to LEV, respecting leading zeros
(let* ((str (base58-str x))
(val (int x))
(nel (floor (* (length str) #.(log 58 256)))))
(levn val nel)))
(defmethod lev ((x base64))
;; convert Base64 to LEV, respecting leading zeros
(let* ((str (string-right-trim "=" (base64-str x)))
(val (int x))
(nel (floor (* (length str) #.(log 64 256)))))
(levn val nel)))
(defmethod lev ((x hex))
;; convert HEX to LEV, respecting leading zeros
(let* ((str (hex-str x))
(val (int x))
(nel (floor (1+ (length str)) 2)))
(levn val nel)))
(defmethod lev (x)
(make-instance 'lev
:vec (nreverse
(bev-vec (bev x)))))
(defun levn (x nb)
;; create a LEV with a specified number of UB8 bytes
(let* ((lev (lev x))
(nel (length (lev-vec lev))))
(cond ((< nel nb)
;; extend with zero filled tail
(let* ((diff (- nb nel))
(tail (make-ub8-vector diff
:initial-element 0)))
(make-instance 'lev
:vec (concatenate 'ub8-vector (lev-vec lev) tail))))
((> nel nb)
;; take from the LSB side
(make-instance 'lev
:vec (subseq (lev-vec lev) 0 nb)))
(t
lev)
)))
;; -----------------------------------------------------------
;; BEV -- encode vector as big-endian (MSB first)
(defmethod bev ((x bev))
x)
(defmethod bev ((x ub8v-repr))
(bev (ub8v-repr x)))
(defmethod bev ((x lev))
;; conversion of LEV to BEV
(make-instance 'bev
:vec (reverse (lev-vec x))))
(defmethod bev ((x sequence))
;; LIST and VECTOR when can be coerced to UB8-VECTOR
(make-instance 'bev
:vec (coerce x 'ub8-vector)))
(defmethod bev ((x string))
(bev (hex x)))
(defmethod bev ((x integer))
;; convert integer to BEV vector
(make-instance 'bev
:vec (convert-int-to-vec x :from-end t)))
(defmethod bev ((x base58))
;; convert Base58 to BEV, respecting leading zeros
(let* ((str (base58-str x))
(val (int x))
(nel (floor (* (length str) #.(log 58 256)))))
(bevn val nel)))
(defmethod bev ((x base64))
;; convert Base64 to BEV respecting leading zeros
(let* ((str (string-right-trim "=" (base64-str x)))
(val (int x))
(nel (floor (* (length str) #.(log 64 256)))))
(bevn val nel)))
(defmethod bev ((x hex))
;; convert HEX to BEV, respecting leading zeros
(let* ((str (hex-str x))
(val (int x))
(nel (ash (1+ (length str)) -1)))
(bevn val nel)))
(defun bevn (x nb)
;; construct a BEV with a specified number of UB8 bytes
(let* ((bev (bev x))
(nel (length (bev-vec bev))))
(cond ((< nel nb)
;; prepend with zero filled prefix
(let* ((diff (- nb nel))
(pref (make-ub8-vector diff
:initial-element 0)))
(make-instance 'bev
:vec (concatenate 'ub8-vector pref (bev-vec bev)))))
((> nel nb)
;; take a portion from the LSB side
(make-instance 'bev
:vec (subseq (bev-vec bev) (- nel nb))))
(t
bev)
)))
;; --------------------------------------------------------------
;; Testing
(defun int= (a b)
"Poor way to do equality testing on UB8V items. This method fails to
account for vectors with leading null bytes. Okay for comparing
compressed ECC points - public keys, signatures. Not okay for hash
comparisons."
(= (int a) (int b)))
(defun vec= (a b)
"Easy way to do equality testing on UB8V items"
(equalp (bev-vec a) (bev-vec b)))
;; --------------------------------------------------------------
;; Utility functions
(defun sbs (str)
(coerce str 'simple-base-string))
| true |
;; vec-repr.lisp -- Uniform and varied representation of UB8 Vectors
;;
;; DM/Emotiq 02/18
;; ----------------------------------------------------------------
#|
The MIT License
Copyright (c) 2018 PI:NAME:<NAME>END_PI
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
|#
(in-package :vec-repr)
;; ---------------------------------------------------------
;; This package describes interchangeable representations of vectors
;; of (unsigned-byte 8) values.
;;
;; Class Hierarchy
;; ---------------
;;
;; UB8V
;; |
;; +-----+------+--------+-------+
;; | | | | |
;; LEV BEV BASE58 BASE64 HEX
;;
;; Class UB8V serves as an abstract superclass for all of these
;; parallel sub-classes. Any object of one of the subclasses can be
;; instantly converted into another parallel representation.
;;
;; Additionlly we make provision for conversion from bignum integers
;; to/from these vector representations.
;;
;; Finally, the Class UB8V-REPR is a mixin for future classes to use,
;; to indicate that they have the ability to produce a UB8V
;; representation, e.g., public keys, secret keys, compressed points
;; of Elliptic Curves, etc. This representation may be requested from
;; them with the UB8V-REPR method call.
;;
;; Type UB8 represents '(UNSIGNED-BYTE 8). Type UB8-VECTOR is defined
;; to represent any vector of actual UB8 values. Endian interpretation
;; is in the eye of the beholder.
;;
;; Each of the subclasses also has methods defined with the same name
;; as their class name, to perform conversions to their specific form
;; of representation. For example:
;;
;; (base58 (lev #(1 2 3 4)))
;; ==>
;; #<BASE58 1111156wxj2 >
;;
;; These conversion operators may be applied to objects of any of the
;; parallel subclasses, as well as to INTEGER, LIST, and VECTOR. The
;; latter two must contain only elements of type UB8.
;;
;; The operators can also be applied to any class that inherits from
;; the mixin class UB8V-REPR and which implements a method by that
;; same name to return an instance of one of these parallel
;; subclasses. (c.f., PBC.LISP)
;;
;; NOTE: Items of these types should be considered inviolable atomic
;; values, just like bignums. Modification of their internal contents
;; may have unpredictable consequences.
;;
;; ----------------------------------------------------------
;; Declare Types UB8 and UB8-VECTOR
(deftype ub8 ()
'(unsigned-byte 8))
(deftype ub8-vector (&optional nel)
`(array ub8 (,nel)))
(defun make-ub8-vector (nel &rest args)
(apply 'make-array nel
:element-type 'ub8
args))
;; ----------------------------------------------------------
;; from https://bitcointalk.org/index.php?topic=1026.0
(um:defconstant+ +alphabet-58+
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
(um:defconstant+ +len-58+
(length +alphabet-58+)) ;; should be 58
(defun make-inverse-alphabet (alphabet)
(let ((arr (make-ub8-vector 256
:initial-element 0)))
(loop for c across alphabet
for ix from 1
do
(setf (aref arr (char-code c)) ix))
arr))
(defvar +inv-alphabet-58+
(make-inverse-alphabet +alphabet-58+))
;; ----------------------------------------------------------
(um:defconstant+ +alphabet-64+
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
(defvar +inv-alphabet-64+
(make-inverse-alphabet +alphabet-64+))
;; ---------------------------------------------------------
;; UB8V - the top abstract class of objects which represent
;; UB8-VECTORs. Declare a single slot to hold the data. Object of
;; these classes are intended to be immuatable. All subclasses share
;; this same slot.
(defclass ub8v ()
((val :reader ub8v-vec
:initarg :vec)))
;; ---------------------------------------------------------
;; Declare a useful mixin class to allow future classes to show a UB8V
;; representation
(defclass ub8v-repr ()
())
(defgeneric ub8v-repr (x)
;; subclasses of the mixin should return whatever representation
;; they need
(:method ((x ub8v-repr))
(error "Subclass responsibility")))
;; -----------------------------------------------
(defmethod print-object ((obj ub8v) out-stream)
(if *print-readably*
(with-standard-io-syntax
(princ "#." out-stream)
(prin1 `(,(class-name (class-of obj)) (hex ,(hex-str (hex obj))))
out-stream))
;; else
(print-unreadable-object (obj out-stream :type t)
(princ (short-str (ub8v-vec obj)) out-stream))
))
(defmethod print-object ((obj ub8v-repr) out-stream)
;; subclasses of UB8V-REPR mixin should feel free to override this
(if *print-readably*
(format out-stream "#.(make-instance '~W :value ~A)"
(class-name (class-of obj))
(ub8v-repr obj))
;; else
(print-unreadable-object (obj out-stream :type t)
(princ (short-str (ub8v-repr obj)) out-stream))
))
(defun short-str (str)
(let ((len (length str)))
(if (< len 17)
str
(format nil "~A..~A"
(subseq str 0 7)
(subseq str (- len 7)))
)))
;; ----------------------------------------------------------
;; Base58 encodes integers into character strings of the restricted
;; alphabet.
(defclass base58 (ub8v)
((val :reader base58-str
:initarg :str)
))
(defgeneric base58 (x))
(defmethod base58-str (x)
(base58-str (base58 x)))
;; ----------------------------------------------------------
;; Base64 encodes UB8 vectors and integers into character strings of
;; the restricted alphabet. Encoding has a 6-character prefix that
;; represents the total number of bytes in the vector, up to 2^32
;; elements.
(defclass base64 (ub8v)
((val :reader base64-str
:initarg :str)
))
(defgeneric base64 (x))
(defmethod base64-str (x)
(base64-str (base64 x)))
;; -----------------------------------------------------------
;; Hex-string representation, 1 char per 4-bit nibble
(defclass hex (ub8v)
((val :reader hex-str
:initarg :str)))
(defgeneric hex (x))
(defmethod hex-str (x)
(hex-str (hex x)))
;; -----------------------------------------------------------
;; LEV-UB8 are little-endian vectors of UB8 elements
(defclass lev (ub8v)
((val :reader lev-vec
:initarg :vec)
))
(defgeneric lev (x))
(defmethod lev-vec (x)
(lev-vec (lev x)))
;; -----------------------------------------------------------
;; BEV-UB8 are big-endian vectors of UB8 elements
(defclass bev (ub8v)
((val :reader bev-vec
:initarg :vec)
))
(defgeneric bev (x))
(defmethod bev-vec (x)
(bev-vec (bev x)))
;; ---------------------------------------------------------
;; Integer to/from vector form - conversion starts at LSB and works
;; toward MSB. So FROR-END should be true for big-endian vectors, and
;; false for little-endian vectors.
(defun convert-vec-to-int (vec &key
(start 0)
(end (length vec))
(from-end t))
;; from-end t is suitable for big-endian format
(let ((val 0))
(if from-end
(do ((ix (1- end) (1- ix))
(pos 0 (+ pos 8)))
((< ix start) val)
(setf val (dpb (aref vec ix) (byte 8 pos) val)))
;; else
(do ((ix start (1+ ix))
(pos 0 (+ 8 pos)))
((>= ix end) val)
(setf val (dpb (aref vec ix) (byte 8 pos) val)))
)))
(defun convert-int-to-vec (val &key
(from-end t)
(nb (max 1 (ceiling (integer-length val) 8))))
;; convert val to little-endian vector of UB8
(let ((v (make-ub8-vector nb
:initial-element 0)))
(if from-end
(do ((ix (1- nb) (1- ix))
(pos 0 (+ 8 pos)))
((minusp ix) v)
(setf (aref v ix) (ldb (byte 8 pos) val)))
;; else
(do ((ix 0 (1+ ix))
(pos 0 (+ 8 pos)))
((>= ix nb) v)
(setf (aref v ix) (ldb (byte 8 pos) val)))
)))
;; --------------------------------------------------------------
;; Integer conversions - these produce raw integers without any type
;; context
(defmethod int ((x integer))
x)
(defmethod int ((x lev))
(convert-vec-to-int (lev-vec x)
:from-end nil))
(defmethod int ((x bev))
(convert-vec-to-int (bev-vec x)))
(defmethod int ((x base58))
(let* ((str (base58-str x))
(limit (length str)))
(um:nlet-tail iter ((pos 0)
(val 0))
(if (>= pos limit)
val
(let* ((c (char str pos))
(v (aref +inv-alphabet-58+ (char-code c))))
(when (zerop v)
(error "Invalid Base58 string: ~A" str))
(iter (1+ pos) (+ (1- v) (* 58 val)))
))
)))
(defmethod int ((x base64))
(let* ((str (base64-str x))
(limit (length str)))
(um:nlet-tail iter ((pos 0)
(val 0))
(if (>= pos limit)
val
(let* ((c (char str pos)))
(if (char= c #\=)
val
(let ((v (aref +inv-alphabet-64+ (char-code c))))
(when (zerop v)
(error "Invalid Base64 string: ~A" str))
(iter (1+ pos) (+ (1- v) (ash val 6)))
)))
))))
(defmethod int ((x hex))
(let ((str (hex-str x)))
(if (string= "" str)
0
(let ((*read-eval* nil)
(*read-base* 16))
(read-from-string str)))
))
(defmethod int (x)
(int (bev x)))
;; --------------------------------------------------------------
;; Base58 -- Integer value as Base58 string
;;
;; NOTE: The rules followed in this package try to preserve the byte
;; vector as the fundamental unit of importance. So if a byte vector
;; (BEV or LEV) is converted into a Base58, Base64, or HEX
;; representation, that representation will have at least the same
;; overall bit-length as the underlying byte vector.
;;
;; This means, e.g., suppose we have a byte vector with 32 bytes. That
;; is 256 bits.
;;
;; In Base58, each character accounts for 5.86 bits, so
;; the Base58 representation will have 44 (= (ceiling 256 5.86))
;; chars, for a bit length of 257.84 bits.
;;
;; A Base64 representation of the same 256 bit value will have 43
;; chars, for a bit length of 258 bits.
;;
;; With this understanding, on conversion back to byte vector form,
;; the underlying byte vector will end up with (FLOOR nbits 8) bytes,
;; where nbits is the number of bits represented by the string. In the
;; case of Base58 this will be (floor (* 5.86 (length str)) 8) bits.
;; In the case of Base64 it will be (floor (* 6 (length str)) 8).
;;
;; For Hex encodings, every byte vector will produce an even number of
;; hex digits. But if a Hex value with an odd number of digits is
;; converted back to a byte vector, we round upward. So HEX "012" will
;; produce a BEV vector of #(0 #x12).
;;
;; For now, if this departs from Bitcoin standards, too bad.
;; ------------------------------------------------------------------
(defun validate-base58-string (str)
(every (lambda (c)
(plusp (aref +alphabet-58+ (char-code c))))
str))
(defun convert-int-to-base58-string (val vec)
;; vec is byte vector from which val was computed
(declare (integer val))
(let* ((nbytes (length vec))
(n58 (ceiling (* nbytes #.(log 256 58))))
(cs nil))
(declare (fixnum nbytes n58))
(um:nlet-tail iter ((val val)
(ct n58))
(declare (integer val)
(fixnum ct))
(when (plusp ct)
(multiple-value-bind (vw vf) (floor val 58)
(declare (integer vw)
(fixnum vf))
(let ((c (aref +alphabet-58+ vf)))
(push c cs)
(iter vw (1- ct)))))
(coerce cs 'string))
))
;; ---
(defmethod base58 ((x base58))
x)
(defmethod base58 ((x string))
(assert (every (um:rcurry 'find +alphabet-58+) x))
(make-instance 'base58
:str x))
(defmethod base58 ((x vector))
;; this code assumes x is big-endian...
(make-instance 'base58
:str (convert-int-to-base58-string (convert-vec-to-int x) x)))
(defmethod base58 ((x bev))
(base58 (bev-vec x)))
(defmethod base58 ((x lev))
(make-instance 'base58
:str (convert-int-to-base58-string (int x) (lev-vec x))))
(defmethod base58 (x)
;; preserve leading zeros
(base58 (bev x)))
;; -------------------------------------------------------------
;; Base64 Conversions
(defun convert-int-to-base64-string (val vec)
;; vec is byte vector from which val was computed
(declare (integer val))
(let* ((nbytes (length vec))
(n64 (ceiling (* nbytes #.(log 256 64))))
(ntail (logand n64 3))
(cs nil))
(declare (fixnum nbytes n64 ntail))
(unless (zerop ntail)
(loop repeat (- 4 ntail) do (push #\= cs)))
(um:nlet-tail iter ((val val)
(ct n64))
(declare (integer val)
(fixnum ct))
(when (plusp ct)
(let* ((bits (ldb (byte 6 0) val))
(c (aref +alphabet-64+ bits)))
(declare (fixnum bits))
(push c cs)
(iter (ash val -6) (1- ct)))))
(coerce cs 'string)))
(defmethod base64 ((x bev))
(make-instance 'base64
:str (convert-int-to-base64-string (int x) (bev-vec x))))
(defmethod base64 ((x lev))
(make-instance 'base64
:str (convert-int-to-base64-string (int x) (lev-vec x))))
(defmethod base64 ((x string))
(assert (every (um:rcurry 'find +alphabet-64+) (string-right-trim '(#\=) x)))
(make-instance 'base64
:str x))
(defmethod base64 ((x base64))
x)
(defmethod base64 (x)
(base64 (bev x)))
;; -------------------------------------------------------------
;; HEX Conversions
(defun convert-int-to-hex-string (val vec)
;; convert int val to hex string of length sufficient to cover vec
;; from which val was derived.
(declare (integer val))
(let ((nc (* 2 (length vec))))
(declare (fixnum nc))
(format nil "~@?" (format nil "~~~A,'0x" nc) val)))
(defmethod hex ((x bev))
(make-instance 'hex
:str (convert-int-to-hex-string (int x) (bev-vec x))))
(defmethod hex ((x lev))
(make-instance 'hex
:str (convert-int-to-hex-string (int x) (lev-vec x))))
(defmethod hex ((x hex))
x)
(defmethod hex ((x string))
(assert (every (um:rcurry 'digit-char-p 16) x))
(make-instance 'hex
:str x))
(defmethod hex (x)
(hex (bev x)))
;; ------------------------------------------------------
;; LEV -- encode vector as little-endian (LSB first)
(defmethod lev ((x lev))
x)
(defmethod lev ((x bev))
(make-instance 'lev
:vec (reverse (bev-vec x))))
(defmethod lev ((val integer))
(make-instance 'lev
:vec (convert-int-to-vec val :from-end nil)))
(defmethod lev ((x sequence))
;; LIST and VECTOR when can be coerced to UB8-VECTOR
(make-instance 'lev
:vec (coerce x 'ub8-vector)))
(defmethod lev ((x ub8v-repr))
(lev (ub8v-repr x)))
(defmethod lev ((x base58))
;; convert Base58 to LEV, respecting leading zeros
(let* ((str (base58-str x))
(val (int x))
(nel (floor (* (length str) #.(log 58 256)))))
(levn val nel)))
(defmethod lev ((x base64))
;; convert Base64 to LEV, respecting leading zeros
(let* ((str (string-right-trim "=" (base64-str x)))
(val (int x))
(nel (floor (* (length str) #.(log 64 256)))))
(levn val nel)))
(defmethod lev ((x hex))
;; convert HEX to LEV, respecting leading zeros
(let* ((str (hex-str x))
(val (int x))
(nel (floor (1+ (length str)) 2)))
(levn val nel)))
(defmethod lev (x)
(make-instance 'lev
:vec (nreverse
(bev-vec (bev x)))))
(defun levn (x nb)
;; create a LEV with a specified number of UB8 bytes
(let* ((lev (lev x))
(nel (length (lev-vec lev))))
(cond ((< nel nb)
;; extend with zero filled tail
(let* ((diff (- nb nel))
(tail (make-ub8-vector diff
:initial-element 0)))
(make-instance 'lev
:vec (concatenate 'ub8-vector (lev-vec lev) tail))))
((> nel nb)
;; take from the LSB side
(make-instance 'lev
:vec (subseq (lev-vec lev) 0 nb)))
(t
lev)
)))
;; -----------------------------------------------------------
;; BEV -- encode vector as big-endian (MSB first)
(defmethod bev ((x bev))
x)
(defmethod bev ((x ub8v-repr))
(bev (ub8v-repr x)))
(defmethod bev ((x lev))
;; conversion of LEV to BEV
(make-instance 'bev
:vec (reverse (lev-vec x))))
(defmethod bev ((x sequence))
;; LIST and VECTOR when can be coerced to UB8-VECTOR
(make-instance 'bev
:vec (coerce x 'ub8-vector)))
(defmethod bev ((x string))
(bev (hex x)))
(defmethod bev ((x integer))
;; convert integer to BEV vector
(make-instance 'bev
:vec (convert-int-to-vec x :from-end t)))
(defmethod bev ((x base58))
;; convert Base58 to BEV, respecting leading zeros
(let* ((str (base58-str x))
(val (int x))
(nel (floor (* (length str) #.(log 58 256)))))
(bevn val nel)))
(defmethod bev ((x base64))
;; convert Base64 to BEV respecting leading zeros
(let* ((str (string-right-trim "=" (base64-str x)))
(val (int x))
(nel (floor (* (length str) #.(log 64 256)))))
(bevn val nel)))
(defmethod bev ((x hex))
;; convert HEX to BEV, respecting leading zeros
(let* ((str (hex-str x))
(val (int x))
(nel (ash (1+ (length str)) -1)))
(bevn val nel)))
(defun bevn (x nb)
;; construct a BEV with a specified number of UB8 bytes
(let* ((bev (bev x))
(nel (length (bev-vec bev))))
(cond ((< nel nb)
;; prepend with zero filled prefix
(let* ((diff (- nb nel))
(pref (make-ub8-vector diff
:initial-element 0)))
(make-instance 'bev
:vec (concatenate 'ub8-vector pref (bev-vec bev)))))
((> nel nb)
;; take a portion from the LSB side
(make-instance 'bev
:vec (subseq (bev-vec bev) (- nel nb))))
(t
bev)
)))
;; --------------------------------------------------------------
;; Testing
(defun int= (a b)
"Poor way to do equality testing on UB8V items. This method fails to
account for vectors with leading null bytes. Okay for comparing
compressed ECC points - public keys, signatures. Not okay for hash
comparisons."
(= (int a) (int b)))
(defun vec= (a b)
"Easy way to do equality testing on UB8V items"
(equalp (bev-vec a) (bev-vec b)))
;; --------------------------------------------------------------
;; Utility functions
(defun sbs (str)
(coerce str 'simple-base-string))
|
[
{
"context": "ts.lisp --- arglist related code ??\n;;\n;; Authors: Matthias Koeppe <[email protected]>\n;; ",
"end": 82,
"score": 0.9998744130134583,
"start": 67,
"tag": "NAME",
"value": "Matthias Koeppe"
},
{
"context": " related code ??\n;;\n;; Authors: Matthias Koeppe <[email protected]>\n;; Tobias C. Rittweiler <[email protected]",
"end": 119,
"score": 0.9999345541000366,
"start": 85,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " <[email protected]>\n;; Tobias C. Rittweiler <[email protected]>\n;; and others\n;;\n;; Li",
"end": 153,
"score": 0.9998772740364075,
"start": 133,
"tag": "NAME",
"value": "Tobias C. Rittweiler"
},
{
"context": "i-magdeburg.de>\n;; Tobias C. Rittweiler <[email protected]>\n;; and others\n;;\n;; License: Public Dom",
"end": 170,
"score": 0.9999317526817322,
"start": 155,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
slime/contrib/swank-arglists.lisp
|
darionyaphet/vim.backup
| 1 |
;;; swank-arglists.lisp --- arglist related code ??
;;
;; Authors: Matthias Koeppe <[email protected]>
;; Tobias C. Rittweiler <[email protected]>
;; and others
;;
;; License: Public Domain
;;
(in-package :swank)
(eval-when (:compile-toplevel :load-toplevel :execute)
(swank-require :swank-c-p-c))
;;;; Utilities
(defun compose (&rest functions)
"Compose FUNCTIONS right-associatively, returning a function"
#'(lambda (x)
(reduce #'funcall functions :initial-value x :from-end t)))
(defun length= (seq n)
"Test for whether SEQ contains N number of elements. I.e. it's equivalent
to (= (LENGTH SEQ) N), but besides being more concise, it may also be more
efficiently implemented."
(etypecase seq
(list (do ((i n (1- i))
(list seq (cdr list)))
((or (<= i 0) (null list))
(and (zerop i) (null list)))))
(sequence (= (length seq) n))))
(declaim (inline memq))
(defun memq (item list)
(member item list :test #'eq))
(defun exactly-one-p (&rest values)
"If exactly one value in VALUES is non-NIL, this value is returned.
Otherwise NIL is returned."
(let ((found nil))
(dolist (v values)
(when v (if found
(return-from exactly-one-p nil)
(setq found v))))
found))
(defun valid-operator-symbol-p (symbol)
"Is SYMBOL the name of a function, a macro, or a special-operator?"
(or (fboundp symbol)
(macro-function symbol)
(special-operator-p symbol)
(member symbol '(declare declaim))))
(defun function-exists-p (form)
(and (valid-function-name-p form)
(fboundp form)
t))
(defmacro multiple-value-or (&rest forms)
(if (null forms)
nil
(let ((first (first forms))
(rest (rest forms)))
`(let* ((values (multiple-value-list ,first))
(primary-value (first values)))
(if primary-value
(values-list values)
(multiple-value-or ,@rest))))))
(defun arglist-available-p (arglist)
(not (eql arglist :not-available)))
(defmacro with-available-arglist ((var &rest more-vars) form &body body)
`(multiple-value-bind (,var ,@more-vars) ,form
(if (eql ,var :not-available)
:not-available
(progn ,@body))))
;;;; Arglist Definition
(defstruct (arglist (:conc-name arglist.) (:predicate arglist-p))
provided-args ; list of the provided actual arguments
required-args ; list of the required arguments
optional-args ; list of the optional arguments
key-p ; whether &key appeared
keyword-args ; list of the keywords
rest ; name of the &rest or &body argument (if any)
body-p ; whether the rest argument is a &body
allow-other-keys-p ; whether &allow-other-keys appeared
aux-args ; list of &aux variables
any-p ; whether &any appeared
any-args ; list of &any arguments [*]
known-junk ; &whole, &environment
unknown-junk) ; unparsed stuff
;;;
;;; [*] The &ANY lambda keyword is an extension to ANSI Common Lisp,
;;; and is only used to describe certain arglists that cannot be
;;; described in another way.
;;;
;;; &ANY is very similiar to &KEY but while &KEY is based upon
;;; the idea of a plist (key1 value1 key2 value2), &ANY is a
;;; cross between &OPTIONAL, &KEY and *FEATURES* lists:
;;;
;;; a) (&ANY :A :B :C) means that you can provide any (non-null)
;;; set consisting of the keywords `:A', `:B', or `:C' in
;;; the arglist. E.g. (:A) or (:C :B :A).
;;;
;;; (This is not restricted to keywords only, but any self-evaluating
;;; expression is allowed.)
;;;
;;; b) (&ANY (key1 v1) (key2 v2) (key3 v3)) means that you can
;;; provide any (non-null) set consisting of lists where
;;; the CAR of the list is one of `key1', `key2', or `key3'.
;;; E.g. ((key1 100) (key3 42)), or ((key3 66) (key2 23))
;;;
;;;
;;; For example, a) let us describe the situations of EVAL-WHEN as
;;;
;;; (EVAL-WHEN (&ANY :compile-toplevel :load-toplevel :execute) &BODY body)
;;;
;;; and b) let us describe the optimization qualifiers that are valid
;;; in the declaration specifier `OPTIMIZE':
;;;
;;; (DECLARE (OPTIMIZE &ANY (compilation-speed 1) (safety 1) ...))
;;;
;; This is a wrapper object around anything that came from Slime and
;; could not reliably be read.
(defstruct (arglist-dummy
(:conc-name #:arglist-dummy.)
(:constructor make-arglist-dummy (string-representation)))
string-representation)
(defun empty-arg-p (dummy)
(and (arglist-dummy-p dummy)
(zerop (length (arglist-dummy.string-representation dummy)))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter +lambda-list-keywords+
'(&provided &required &optional &rest &key &any)))
(defmacro do-decoded-arglist (decoded-arglist &body clauses)
(assert (loop for clause in clauses
thereis (member (car clause) +lambda-list-keywords+)))
(flet ((parse-clauses (clauses)
(let* ((size (length +lambda-list-keywords+))
(initial (make-hash-table :test #'eq :size size))
(main (make-hash-table :test #'eq :size size))
(final (make-hash-table :test #'eq :size size)))
(loop for clause in clauses
for lambda-list-keyword = (first clause)
for clause-parameter = (second clause)
doing (cond ((eq clause-parameter :initially)
(setf (gethash lambda-list-keyword initial) clause))
((eq clause-parameter :finally)
(setf (gethash lambda-list-keyword final) clause))
(t
(setf (gethash lambda-list-keyword main) clause)))
finally
(return (values initial main final)))))
(generate-main-clause (clause arglist)
(destructure-case clause
((&provided (&optional arg) . body)
(let ((gensym (gensym "PROVIDED-ARG+")))
`(dolist (,gensym (arglist.provided-args ,arglist))
(declare (ignorable ,gensym))
(let (,@(when arg `((,arg ,gensym))))
,@body))))
((&required (&optional arg) . body)
(let ((gensym (gensym "REQUIRED-ARG+")))
`(dolist (,gensym (arglist.required-args ,arglist))
(declare (ignorable ,gensym))
(let (,@(when arg `((,arg ,gensym))))
,@body))))
((&optional (&optional arg init) . body)
(let ((optarg (gensym "OPTIONAL-ARG+")))
`(dolist (,optarg (arglist.optional-args ,arglist))
(declare (ignorable ,optarg))
(let (,@(when arg `((,arg (optional-arg.arg-name ,optarg))))
,@(when init `((,init (optional-arg.default-arg ,optarg)))))
,@body))))
((&key (&optional keyword arg init) . body)
(let ((keyarg (gensym "KEY-ARG+")))
`(dolist (,keyarg (arglist.keyword-args ,arglist))
(declare (ignorable ,keyarg))
(let (,@(when keyword `((,keyword (keyword-arg.keyword ,keyarg))))
,@(when arg `((,arg (keyword-arg.arg-name ,keyarg))))
,@(when init `((,init (keyword-arg.default-arg ,keyarg)))))
,@body))))
((&rest (&optional arg body-p) . body)
`(when (arglist.rest ,arglist)
(let (,@(when arg `((,arg (arglist.rest ,arglist))))
,@(when body-p `((,body-p (arglist.body-p ,arglist)))))
,@body)))
((&any (&optional arg) . body)
(let ((gensym (gensym "REQUIRED-ARG+")))
`(dolist (,gensym (arglist.any-args ,arglist))
(declare (ignorable ,gensym))
(let (,@(when arg `((,arg ,gensym))))
,@body)))))))
(let ((arglist (gensym "DECODED-ARGLIST+")))
(multiple-value-bind (initially-clauses main-clauses finally-clauses)
(parse-clauses clauses)
`(let ((,arglist ,decoded-arglist))
(block do-decoded-arglist
,@(loop for keyword in '(&provided &required &optional &rest &key &any)
append (cddr (gethash keyword initially-clauses))
collect (let ((clause (gethash keyword main-clauses)))
(when clause (generate-main-clause clause arglist)))
append (cddr (gethash keyword finally-clauses)))))))))
;;;; Arglist Printing
(defun undummy (x)
(if (typep x 'arglist-dummy)
(arglist-dummy.string-representation x)
(prin1-to-string x)))
(defun print-decoded-arglist (arglist &key operator provided-args highlight)
(macrolet ((space ()
;; Kludge: When OPERATOR is not given, we don't want to
;; print a space for the first argument.
`(if (not operator)
(setq operator t)
(progn (write-char #\space)
(pprint-newline :fill))))
(with-highlighting ((&key index) &body body)
`(if (eql ,index (car highlight))
(progn (princ "===> ") ,@body (princ " <==="))
(progn ,@body)))
(print-arglist-recursively (argl &key index)
`(if (eql ,index (car highlight))
(print-decoded-arglist ,argl :highlight (cdr highlight))
(print-decoded-arglist ,argl))))
(let ((index 0))
(pprint-logical-block (nil nil :prefix "(" :suffix ")")
(when operator
(print-arg operator)
(pprint-indent :current 1)) ; 1 due to possibly added space
(do-decoded-arglist (remove-given-args arglist provided-args)
(&provided (arg)
(space)
(print-arg arg)
(incf index))
(&required (arg)
(space)
(if (arglist-p arg)
(print-arglist-recursively arg :index index)
(with-highlighting (:index index)
(print-arg arg)))
(incf index))
(&optional :initially
(when (arglist.optional-args arglist)
(space)
(princ '&optional)))
(&optional (arg init-value)
(space)
(if (arglist-p arg)
(print-arglist-recursively arg :index index)
(with-highlighting (:index index)
(if (null init-value)
(print-arg arg)
(format t "~:@<~A ~A~@:>"
(undummy arg) (undummy init-value)))))
(incf index))
(&key :initially
(when (arglist.key-p arglist)
(space)
(princ '&key)))
(&key (keyword arg init)
(space)
(if (arglist-p arg)
(pprint-logical-block (nil nil :prefix "(" :suffix ")")
(prin1 keyword) (space)
(print-arglist-recursively arg :index keyword))
(with-highlighting (:index keyword)
(cond ((and init (keywordp keyword))
(format t "~:@<~A ~A~@:>" keyword (undummy init)))
(init
(format t "~:@<(~A ..) ~A~@:>"
(undummy keyword) (undummy init)))
((not (keywordp keyword))
(format t "~:@<(~S ..)~@:>" keyword))
(t
(princ keyword))))))
(&key :finally
(when (arglist.allow-other-keys-p arglist)
(space)
(princ '&allow-other-keys)))
(&any :initially
(when (arglist.any-p arglist)
(space)
(princ '&any)))
(&any (arg)
(space)
(print-arg arg))
(&rest (args bodyp)
(space)
(princ (if bodyp '&body '&rest))
(space)
(if (arglist-p args)
(print-arglist-recursively args :index index)
(with-highlighting (:index index)
(print-arg args))))
;; FIXME: add &UNKNOWN-JUNK?
)))))
(defun print-arg (arg)
(let ((arg (if (arglist-dummy-p arg)
(arglist-dummy.string-representation arg)
arg)))
(if (keywordp arg)
(prin1 arg)
(princ arg))))
(defun print-decoded-arglist-as-template (decoded-arglist &key
(prefix "(") (suffix ")"))
(let ((first-p t))
(flet ((space ()
(unless first-p
(write-char #\space))
(setq first-p nil))
(print-arg-or-pattern (arg)
(etypecase arg
(symbol (if (keywordp arg) (prin1 arg) (princ arg)))
(string (princ arg))
(list (princ arg))
(arglist-dummy (princ (arglist-dummy.string-representation arg)))
(arglist (print-decoded-arglist-as-template arg)))
(pprint-newline :fill)))
(pprint-logical-block (nil nil :prefix prefix :suffix suffix)
(do-decoded-arglist decoded-arglist
(&provided ()) ; do nothing; provided args are in the buffer already.
(&required (arg)
(space) (print-arg-or-pattern arg))
(&optional (arg)
(space) (princ "[") (print-arg-or-pattern arg) (princ "]"))
(&key (keyword arg)
(space)
(prin1 (if (keywordp keyword) keyword `',keyword))
(space)
(print-arg-or-pattern arg)
(pprint-newline :linear))
(&any (arg)
(space) (print-arg-or-pattern arg))
(&rest (args)
(when (or (not (arglist.keyword-args decoded-arglist))
(arglist.allow-other-keys-p decoded-arglist))
(space)
(format t "~A..." args))))))))
(defvar *arglist-pprint-bindings*
'((*print-case* . :downcase)
(*print-pretty* . t)
(*print-circle* . nil)
(*print-readably* . nil)
(*print-level* . 10)
(*print-length* . 20)
(*print-escape* . nil)))
(defvar *arglist-show-packages* t)
(defmacro with-arglist-io-syntax (&body body)
(let ((package (gensym)))
`(let ((,package *package*))
(with-standard-io-syntax
(let ((*package* (if *arglist-show-packages*
*package*
,package)))
(with-bindings *arglist-pprint-bindings*
,@body))))))
(defun decoded-arglist-to-string (decoded-arglist
&key operator highlight
print-right-margin)
(with-output-to-string (*standard-output*)
(with-arglist-io-syntax
(let ((*print-right-margin* print-right-margin))
(print-decoded-arglist decoded-arglist
:operator operator
:highlight highlight)))))
(defun decoded-arglist-to-template-string (decoded-arglist
&key (prefix "(") (suffix ")"))
(with-output-to-string (*standard-output*)
(with-arglist-io-syntax
(print-decoded-arglist-as-template decoded-arglist
:prefix prefix
:suffix suffix))))
;;;; Arglist Decoding / Encoding
(defun decode-required-arg (arg)
"ARG can be a symbol or a destructuring pattern."
(etypecase arg
(symbol arg)
(arglist-dummy arg)
(list (decode-arglist arg))))
(defun encode-required-arg (arg)
(etypecase arg
(symbol arg)
(arglist (encode-arglist arg))))
(defstruct (keyword-arg
(:conc-name keyword-arg.)
(:constructor make-keyword-arg (keyword arg-name default-arg)))
keyword
arg-name
default-arg)
(defun decode-keyword-arg (arg)
"Decode a keyword item of formal argument list.
Return three values: keyword, argument name, default arg."
(flet ((intern-as-keyword (arg)
(intern (etypecase arg
(symbol (symbol-name arg))
(arglist-dummy (arglist-dummy.string-representation arg)))
keyword-package)))
(cond ((or (symbolp arg) (arglist-dummy-p arg))
(make-keyword-arg (intern-as-keyword arg) arg nil))
((and (consp arg)
(consp (car arg)))
(make-keyword-arg (caar arg)
(decode-required-arg (cadar arg))
(cadr arg)))
((consp arg)
(make-keyword-arg (intern-as-keyword (car arg)) (car arg) (cadr arg)))
(t
(error "Bad keyword item of formal argument list")))))
(defun encode-keyword-arg (arg)
(cond
((arglist-p (keyword-arg.arg-name arg))
;; Destructuring pattern
(let ((keyword/name (list (keyword-arg.keyword arg)
(encode-required-arg
(keyword-arg.arg-name arg)))))
(if (keyword-arg.default-arg arg)
(list keyword/name
(keyword-arg.default-arg arg))
(list keyword/name))))
((eql (intern (symbol-name (keyword-arg.arg-name arg))
keyword-package)
(keyword-arg.keyword arg))
(if (keyword-arg.default-arg arg)
(list (keyword-arg.arg-name arg)
(keyword-arg.default-arg arg))
(keyword-arg.arg-name arg)))
(t
(let ((keyword/name (list (keyword-arg.keyword arg)
(keyword-arg.arg-name arg))))
(if (keyword-arg.default-arg arg)
(list keyword/name
(keyword-arg.default-arg arg))
(list keyword/name))))))
(progn
(assert (equalp (decode-keyword-arg 'x)
(make-keyword-arg :x 'x nil)))
(assert (equalp (decode-keyword-arg '(x t))
(make-keyword-arg :x 'x t)))
(assert (equalp (decode-keyword-arg '((:x y)))
(make-keyword-arg :x 'y nil)))
(assert (equalp (decode-keyword-arg '((:x y) t))
(make-keyword-arg :x 'y t))))
;;; FIXME suppliedp?
(defstruct (optional-arg
(:conc-name optional-arg.)
(:constructor make-optional-arg (arg-name default-arg)))
arg-name
default-arg)
(defun decode-optional-arg (arg)
"Decode an optional item of a formal argument list.
Return an OPTIONAL-ARG structure."
(etypecase arg
(symbol (make-optional-arg arg nil))
(arglist-dummy (make-optional-arg arg nil))
(list (make-optional-arg (decode-required-arg (car arg))
(cadr arg)))))
(defun encode-optional-arg (optional-arg)
(if (or (optional-arg.default-arg optional-arg)
(arglist-p (optional-arg.arg-name optional-arg)))
(list (encode-required-arg
(optional-arg.arg-name optional-arg))
(optional-arg.default-arg optional-arg))
(optional-arg.arg-name optional-arg)))
(progn
(assert (equalp (decode-optional-arg 'x)
(make-optional-arg 'x nil)))
(assert (equalp (decode-optional-arg '(x t))
(make-optional-arg 'x t))))
(define-modify-macro nreversef () nreverse "Reverse the list in PLACE.")
(defun decode-arglist (arglist)
"Parse the list ARGLIST and return an ARGLIST structure."
(etypecase arglist
((eql :not-available) (return-from decode-arglist
:not-available))
(list))
(loop
with mode = nil
with result = (make-arglist)
for arg = (if (consp arglist)
(pop arglist)
(progn
(prog1 arglist
(setf mode '&rest
arglist nil))))
do (cond
((eql mode '&unknown-junk)
;; don't leave this mode -- we don't know how the arglist
;; after unknown lambda-list keywords is interpreted
(push arg (arglist.unknown-junk result)))
((eql arg '&allow-other-keys)
(setf (arglist.allow-other-keys-p result) t))
((eql arg '&key)
(setf (arglist.key-p result) t
mode arg))
((memq arg '(&optional &rest &body &aux))
(setq mode arg))
((memq arg '(&whole &environment))
(setq mode arg)
(push arg (arglist.known-junk result)))
((and (symbolp arg)
(string= (symbol-name arg) (string '#:&any))) ; may be interned
(setf (arglist.any-p result) t) ; in any *package*.
(setq mode '&any))
((memq arg lambda-list-keywords)
(setq mode '&unknown-junk)
(push arg (arglist.unknown-junk result)))
(t
(ecase mode
(&key
(push (decode-keyword-arg arg)
(arglist.keyword-args result)))
(&optional
(push (decode-optional-arg arg)
(arglist.optional-args result)))
(&body
(setf (arglist.body-p result) t
(arglist.rest result) arg))
(&rest
(setf (arglist.rest result) arg))
(&aux
(push (decode-optional-arg arg)
(arglist.aux-args result)))
((nil)
(push (decode-required-arg arg)
(arglist.required-args result)))
((&whole &environment)
(setf mode nil)
(push arg (arglist.known-junk result)))
(&any
(push arg (arglist.any-args result))))))
until (null arglist)
finally (nreversef (arglist.required-args result))
finally (nreversef (arglist.optional-args result))
finally (nreversef (arglist.keyword-args result))
finally (nreversef (arglist.aux-args result))
finally (nreversef (arglist.any-args result))
finally (nreversef (arglist.known-junk result))
finally (nreversef (arglist.unknown-junk result))
finally (assert (or (and (not (arglist.key-p result))
(not (arglist.any-p result)))
(exactly-one-p (arglist.key-p result)
(arglist.any-p result))))
finally (return result)))
(defun encode-arglist (decoded-arglist)
(append (mapcar #'encode-required-arg (arglist.required-args decoded-arglist))
(when (arglist.optional-args decoded-arglist)
'(&optional))
(mapcar #'encode-optional-arg (arglist.optional-args decoded-arglist))
(when (arglist.key-p decoded-arglist)
'(&key))
(mapcar #'encode-keyword-arg (arglist.keyword-args decoded-arglist))
(when (arglist.allow-other-keys-p decoded-arglist)
'(&allow-other-keys))
(when (arglist.any-args decoded-arglist)
`(&any ,@(arglist.any-args decoded-arglist)))
(cond ((not (arglist.rest decoded-arglist))
'())
((arglist.body-p decoded-arglist)
`(&body ,(arglist.rest decoded-arglist)))
(t
`(&rest ,(arglist.rest decoded-arglist))))
(when (arglist.aux-args decoded-arglist)
`(&aux ,(arglist.aux-args decoded-arglist)))
(arglist.known-junk decoded-arglist)
(arglist.unknown-junk decoded-arglist)))
;;;; Arglist Enrichment
(defun arglist-keywords (lambda-list)
"Return the list of keywords in ARGLIST.
As a secondary value, return whether &allow-other-keys appears."
(let ((decoded-arglist (decode-arglist lambda-list)))
(values (arglist.keyword-args decoded-arglist)
(arglist.allow-other-keys-p decoded-arglist))))
(defun methods-keywords (methods)
"Collect all keywords in the arglists of METHODS.
As a secondary value, return whether &allow-other-keys appears somewhere."
(let ((keywords '())
(allow-other-keys nil))
(dolist (method methods)
(multiple-value-bind (kw aok)
(arglist-keywords
(swank-mop:method-lambda-list method))
(setq keywords (remove-duplicates (append keywords kw)
:key #'keyword-arg.keyword)
allow-other-keys (or allow-other-keys aok))))
(values keywords allow-other-keys)))
(defun generic-function-keywords (generic-function)
"Collect all keywords in the methods of GENERIC-FUNCTION.
As a secondary value, return whether &allow-other-keys appears somewhere."
(methods-keywords
(swank-mop:generic-function-methods generic-function)))
(defun applicable-methods-keywords (generic-function arguments)
"Collect all keywords in the methods of GENERIC-FUNCTION that are
applicable for argument of CLASSES. As a secondary value, return
whether &allow-other-keys appears somewhere."
(methods-keywords
(multiple-value-bind (amuc okp)
(swank-mop:compute-applicable-methods-using-classes
generic-function (mapcar #'class-of arguments))
(if okp
amuc
(compute-applicable-methods generic-function arguments)))))
(defgeneric extra-keywords (operator &rest args)
(:documentation "Return a list of extra keywords of OPERATOR (a
symbol) when applied to the (unevaluated) ARGS.
As a secondary value, return whether other keys are allowed.
As a tertiary value, return the initial sublist of ARGS that was needed
to determine the extra keywords."))
;;; We make sure that symbol-from-KEYWORD-using keywords come before
;;; symbol-from-arbitrary-package-using keywords. And we sort the
;;; latter according to how their home-packages relate to *PACKAGE*.
;;;
;;; Rationale is to show those key parameters first which make most
;;; sense in the current context. And in particular: to put
;;; implementation-internal stuff last.
;;;
;;; This matters tremendeously on Allegro in combination with
;;; AllegroCache as that does some evil tinkering with initargs,
;;; obfuscating the arglist of MAKE-INSTANCE.
;;;
(defmethod extra-keywords :around (op &rest args)
(declare (ignorable op args))
(multiple-value-bind (keywords aok enrichments) (call-next-method)
(values (sort-extra-keywords keywords) aok enrichments)))
(defun make-package-comparator (reference-packages)
"Returns a two-argument test function which compares packages
according to their used-by relation with REFERENCE-PACKAGES. Packages
will be sorted first which appear first in the PACKAGE-USE-LIST of the
reference packages."
(let ((package-use-table (make-hash-table :test 'eq)))
;; Walk the package dependency graph breadth-fist, and fill
;; PACKAGE-USE-TABLE accordingly.
(loop with queue = (copy-list reference-packages)
with bfn = 0 ; Breadth-First Number
for p = (pop queue)
unless (gethash p package-use-table)
do (setf (gethash p package-use-table) (shiftf bfn (1+ bfn)))
and do (setf queue (nconc queue (copy-list (package-use-list p))))
while queue)
#'(lambda (p1 p2)
(let ((bfn1 (gethash p1 package-use-table))
(bfn2 (gethash p2 package-use-table)))
(cond ((and bfn1 bfn2) (<= bfn1 bfn2))
(bfn1 bfn1)
(bfn2 nil) ; p2 is used, p1 not
(t (string<= (package-name p1) (package-name p2))))))))
(defun sort-extra-keywords (kwds)
(stable-sort kwds (make-package-comparator (list keyword-package *package*))
:key (compose #'symbol-package #'keyword-arg.keyword)))
(defun keywords-of-operator (operator)
"Return a list of KEYWORD-ARGs that OPERATOR accepts.
This function is useful for writing EXTRA-KEYWORDS methods for
user-defined functions which are declared &ALLOW-OTHER-KEYS and which
forward keywords to OPERATOR."
(with-available-arglist (arglist) (arglist-from-form (ensure-list operator))
(values (arglist.keyword-args arglist)
(arglist.allow-other-keys-p arglist))))
(defmethod extra-keywords (operator &rest args)
;; default method
(declare (ignore args))
(let ((symbol-function (symbol-function operator)))
(if (typep symbol-function 'generic-function)
(generic-function-keywords symbol-function)
nil)))
(defun class-from-class-name-form (class-name-form)
(when (and (listp class-name-form)
(= (length class-name-form) 2)
(eq (car class-name-form) 'quote))
(let* ((class-name (cadr class-name-form))
(class (find-class class-name nil)))
(when (and class
(not (swank-mop:class-finalized-p class)))
;; Try to finalize the class, which can fail if
;; superclasses are not defined yet
(handler-case (swank-mop:finalize-inheritance class)
(program-error (c)
(declare (ignore c)))))
class)))
(defun extra-keywords/slots (class)
(multiple-value-bind (slots allow-other-keys-p)
(if (swank-mop:class-finalized-p class)
(values (swank-mop:class-slots class) nil)
(values (swank-mop:class-direct-slots class) t))
(let ((slot-init-keywords
(loop for slot in slots append
(mapcar (lambda (initarg)
(make-keyword-arg
initarg
(swank-mop:slot-definition-name slot)
(swank-mop:slot-definition-initform slot)))
(swank-mop:slot-definition-initargs slot)))))
(values slot-init-keywords allow-other-keys-p))))
(defun extra-keywords/make-instance (operator &rest args)
(declare (ignore operator))
(unless (null args)
(let* ((class-name-form (car args))
(class (class-from-class-name-form class-name-form)))
(when class
(multiple-value-bind (slot-init-keywords class-aokp)
(extra-keywords/slots class)
(multiple-value-bind (allocate-instance-keywords ai-aokp)
(applicable-methods-keywords
#'allocate-instance (list class))
(multiple-value-bind (initialize-instance-keywords ii-aokp)
(ignore-errors
(applicable-methods-keywords
#'initialize-instance (list (swank-mop:class-prototype class))))
(multiple-value-bind (shared-initialize-keywords si-aokp)
(ignore-errors
(applicable-methods-keywords
#'shared-initialize (list (swank-mop:class-prototype class) t)))
(values (append slot-init-keywords
allocate-instance-keywords
initialize-instance-keywords
shared-initialize-keywords)
(or class-aokp ai-aokp ii-aokp si-aokp)
(list class-name-form))))))))))
(defun extra-keywords/change-class (operator &rest args)
(declare (ignore operator))
(unless (null args)
(let* ((class-name-form (car args))
(class (class-from-class-name-form class-name-form)))
(when class
(multiple-value-bind (slot-init-keywords class-aokp)
(extra-keywords/slots class)
(declare (ignore class-aokp))
(multiple-value-bind (shared-initialize-keywords si-aokp)
(ignore-errors
(applicable-methods-keywords
#'shared-initialize (list (swank-mop:class-prototype class) t)))
;; FIXME: much as it would be nice to include the
;; applicable keywords from
;; UPDATE-INSTANCE-FOR-DIFFERENT-CLASS, I don't really see
;; how to do it: so we punt, always declaring
;; &ALLOW-OTHER-KEYS.
(declare (ignore si-aokp))
(values (append slot-init-keywords shared-initialize-keywords)
t
(list class-name-form))))))))
(defmethod extra-keywords ((operator (eql 'make-instance))
&rest args)
(multiple-value-or (apply #'extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'make-condition))
&rest args)
(multiple-value-or (apply #'extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'error))
&rest args)
(multiple-value-or (apply #'extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'signal))
&rest args)
(multiple-value-or (apply #'extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'warn))
&rest args)
(multiple-value-or (apply #'extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'cerror))
&rest args)
(multiple-value-bind (keywords aok determiners)
(apply #'extra-keywords/make-instance operator
(cdr args))
(if keywords
(values keywords aok
(cons (car args) determiners))
(call-next-method))))
(defmethod extra-keywords ((operator (eql 'change-class))
&rest args)
(multiple-value-bind (keywords aok determiners)
(apply #'extra-keywords/change-class operator (cdr args))
(if keywords
(values keywords aok
(cons (car args) determiners))
(call-next-method))))
(defun enrich-decoded-arglist-with-keywords (decoded-arglist keywords allow-other-keys-p)
"Modify DECODED-ARGLIST using KEYWORDS and ALLOW-OTHER-KEYS-P."
(when keywords
(setf (arglist.key-p decoded-arglist) t)
(setf (arglist.keyword-args decoded-arglist)
(remove-duplicates
(append (arglist.keyword-args decoded-arglist)
keywords)
:key #'keyword-arg.keyword)))
(setf (arglist.allow-other-keys-p decoded-arglist)
(or (arglist.allow-other-keys-p decoded-arglist)
allow-other-keys-p)))
(defun enrich-decoded-arglist-with-extra-keywords (decoded-arglist form)
"Determine extra keywords from the function call FORM, and modify
DECODED-ARGLIST to include them. As a secondary return value, return
the initial sublist of ARGS that was needed to determine the extra
keywords. As a tertiary return value, return whether any enrichment
was done."
(multiple-value-bind (extra-keywords extra-aok determining-args)
(apply #'extra-keywords form)
;; enrich the list of keywords with the extra keywords
(enrich-decoded-arglist-with-keywords decoded-arglist
extra-keywords extra-aok)
(values decoded-arglist
determining-args
(or extra-keywords extra-aok))))
(defgeneric compute-enriched-decoded-arglist (operator-form argument-forms)
(:documentation
"Return three values: DECODED-ARGLIST, DETERMINING-ARGS, and
ANY-ENRICHMENT, just like enrich-decoded-arglist-with-extra-keywords.
If the arglist is not available, return :NOT-AVAILABLE."))
(defmethod compute-enriched-decoded-arglist (operator-form argument-forms)
(with-available-arglist (decoded-arglist)
(decode-arglist (arglist operator-form))
(enrich-decoded-arglist-with-extra-keywords decoded-arglist
(cons operator-form
argument-forms))))
(defmethod compute-enriched-decoded-arglist ((operator-form (eql 'with-open-file))
argument-forms)
(declare (ignore argument-forms))
(multiple-value-bind (decoded-arglist determining-args)
(call-next-method)
(let ((first-arg (first (arglist.required-args decoded-arglist)))
(open-arglist (compute-enriched-decoded-arglist 'open nil)))
(when (and (arglist-p first-arg) (arglist-p open-arglist))
(enrich-decoded-arglist-with-keywords
first-arg
(arglist.keyword-args open-arglist)
nil)))
(values decoded-arglist determining-args t)))
(defmethod compute-enriched-decoded-arglist ((operator-form (eql 'apply))
argument-forms)
(let ((function-name-form (car argument-forms)))
(when (and (listp function-name-form)
(length= function-name-form 2)
(memq (car function-name-form) '(quote function)))
(let ((function-name (cadr function-name-form)))
(when (valid-operator-symbol-p function-name)
(let ((function-arglist
(compute-enriched-decoded-arglist function-name
(cdr argument-forms))))
(return-from compute-enriched-decoded-arglist
(values (make-arglist :required-args
(list 'function)
:optional-args
(append
(mapcar #'(lambda (arg)
(make-optional-arg arg nil))
(arglist.required-args function-arglist))
(arglist.optional-args function-arglist))
:key-p
(arglist.key-p function-arglist)
:keyword-args
(arglist.keyword-args function-arglist)
:rest
'args
:allow-other-keys-p
(arglist.allow-other-keys-p function-arglist))
(list function-name-form)
t)))))))
(call-next-method))
(defun delete-given-args (decoded-arglist args)
"Delete given ARGS from DECODED-ARGLIST."
(macrolet ((pop-or-return (list)
`(if (null ,list)
(return-from do-decoded-arglist)
(pop ,list))))
(do-decoded-arglist decoded-arglist
(&provided ()
(assert (eq (pop-or-return args)
(pop (arglist.provided-args decoded-arglist)))))
(&required ()
(pop-or-return args)
(pop (arglist.required-args decoded-arglist)))
(&optional ()
(pop-or-return args)
(pop (arglist.optional-args decoded-arglist)))
(&key (keyword)
;; N.b. we consider a keyword to be given only when the keyword
;; _and_ a value has been given for it.
(loop for (key value) on args by #'cddr
when (and (eq keyword key) value)
do (setf (arglist.keyword-args decoded-arglist)
(remove keyword (arglist.keyword-args decoded-arglist)
:key #'keyword-arg.keyword))))))
decoded-arglist)
(defun remove-given-args (decoded-arglist args)
;; FIXME: We actually needa deep copy here.
(delete-given-args (copy-arglist decoded-arglist) args))
;;;; Arglist Retrieval
(defun arglist-from-form (form)
(if (null form)
:not-available
(arglist-dispatch (car form) (cdr form))))
(export 'arglist-dispatch)
(defgeneric arglist-dispatch (operator arguments)
;; Default method
(:method (operator arguments)
(unless (and (symbolp operator) (valid-operator-symbol-p operator))
(return-from arglist-dispatch :not-available))
(multiple-value-bind (decoded-arglist determining-args)
(compute-enriched-decoded-arglist operator arguments)
(with-available-arglist (arglist) decoded-arglist
;; replace some formal args by determining actual args
(setf arglist (delete-given-args arglist determining-args))
(setf (arglist.provided-args arglist) determining-args)
arglist))))
(defmethod arglist-dispatch ((operator (eql 'defmethod)) arguments)
(match (cons operator arguments)
(('defmethod (#'function-exists-p gf-name) . rest)
(let ((gf (fdefinition gf-name)))
(when (typep gf 'generic-function)
(with-available-arglist (arglist) (decode-arglist (arglist gf))
(let ((qualifiers (loop for x in rest
until (or (listp x) (empty-arg-p x))
collect x)))
(return-from arglist-dispatch
(make-arglist :provided-args (cons gf-name qualifiers)
:required-args (list arglist)
:rest "body" :body-p t)))))))
(_)) ; Fall through
(call-next-method))
(defmethod arglist-dispatch ((operator (eql 'define-compiler-macro)) arguments)
(match (cons operator arguments)
(('define-compiler-macro (#'function-exists-p gf-name) . _)
(let ((gf (fdefinition gf-name)))
(with-available-arglist (arglist) (decode-arglist (arglist gf))
(return-from arglist-dispatch
(make-arglist :provided-args (list gf-name)
:required-args (list arglist)
:rest "body" :body-p t)))))
(_)) ; Fall through
(call-next-method))
(defmethod arglist-dispatch ((operator (eql 'eval-when)) arguments)
(declare (ignore arguments))
(let ((eval-when-args '(:compile-toplevel :load-toplevel :execute)))
(make-arglist
:required-args (list (make-arglist :any-p t :any-args eval-when-args))
:rest '#:body :body-p t)))
(defmethod arglist-dispatch ((operator (eql 'declare)) arguments)
(let* ((declaration (cons operator (last arguments)))
(typedecl-arglist (arglist-for-type-declaration declaration)))
(if (arglist-available-p typedecl-arglist)
typedecl-arglist
(match declaration
(('declare ((#'consp typespec) . decl-args))
(with-available-arglist (typespec-arglist)
(decoded-arglist-for-type-specifier typespec)
(make-arglist
:required-args (list (make-arglist
:required-args (list typespec-arglist)
:rest '#:variables)))))
(('declare (decl-identifier . decl-args))
(decoded-arglist-for-declaration decl-identifier decl-args))
(_ (make-arglist :rest '#:declaration-specifiers))))))
(defmethod arglist-dispatch ((operator (eql 'declaim)) arguments)
(arglist-dispatch 'declare arguments))
(defun arglist-for-type-declaration (declaration)
(flet ((%arglist-for-type-declaration (identifier typespec rest-var-name)
(with-available-arglist (typespec-arglist)
(decoded-arglist-for-type-specifier typespec)
(make-arglist
:required-args (list (make-arglist
:provided-args (list identifier)
:required-args (list typespec-arglist)
:rest rest-var-name))))))
(match declaration
(('declare ('type (#'consp typespec) . decl-args))
(%arglist-for-type-declaration 'type typespec '#:variables))
(('declare ('ftype (#'consp typespec) . decl-args))
(%arglist-for-type-declaration 'ftype typespec '#:function-names))
(('declare ((#'consp typespec) . decl-args))
(with-available-arglist (typespec-arglist)
(decoded-arglist-for-type-specifier typespec)
(make-arglist
:required-args (list (make-arglist
:required-args (list typespec-arglist)
:rest '#:variables)))))
(_ :not-available))))
(defun decoded-arglist-for-declaration (decl-identifier decl-args)
(declare (ignore decl-args))
(with-available-arglist (arglist)
(decode-arglist (declaration-arglist decl-identifier))
(setf (arglist.provided-args arglist) (list decl-identifier))
(make-arglist :required-args (list arglist))))
(defun decoded-arglist-for-type-specifier (type-specifier)
(etypecase type-specifier
(arglist-dummy :not-available)
(cons (decoded-arglist-for-type-specifier (car type-specifier)))
(symbol
(with-available-arglist (arglist)
(decode-arglist (type-specifier-arglist type-specifier))
(setf (arglist.provided-args arglist) (list type-specifier))
arglist))))
;;; Slimefuns
;;; We work on a RAW-FORM, or BUFFER-FORM, which represent the form at
;;; user's point in Emacs. A RAW-FORM looks like
;;;
;;; ("FOO" ("BAR" ...) "QUUX" ("ZURP" SWANK::%CURSOR-MARKER%))
;;;
;;; The expression before the cursor marker is the expression where
;;; user's cursor points at. An explicit marker is necessary to
;;; disambiguate between
;;;
;;; ("IF" ("PRED")
;;; ("F" "X" "Y" %CURSOR-MARKER%))
;;;
;;; and
;;; ("IF" ("PRED")
;;; ("F" "X" "Y") %CURSOR-MARKER%)
;;; Notice that for a form like (FOO (BAR |) QUUX), where | denotes
;;; user's point, the following should be sent ("FOO" ("BAR" ""
;;; %CURSOR-MARKER%)). Only the forms up to point should be
;;; considered.
(defslimefun autodoc (raw-form &key print-right-margin)
"Return a list of two elements.
First, a string representing the arglist for the deepest subform in
RAW-FORM that does have an arglist. The highlighted parameter is
wrapped in ===> X <===.
Second, a boolean value telling whether the returned string can be cached."
(handler-bind ((serious-condition
#'(lambda (c)
(unless (debug-on-swank-error)
(let ((*print-right-margin* print-right-margin))
(return-from autodoc
(format nil "Arglist Error: \"~A\"" c)))))))
(with-buffer-syntax ()
(multiple-value-bind (form arglist obj-at-cursor form-path)
(find-subform-with-arglist (parse-raw-form raw-form))
(cond ((boundp-and-interesting obj-at-cursor)
(list (print-variable-to-string obj-at-cursor) nil))
(t
(list
(with-available-arglist (arglist) arglist
(decoded-arglist-to-string
arglist
:print-right-margin print-right-margin
:operator (car form)
:highlight (form-path-to-arglist-path form-path
form
arglist)))
t)))))))
(defun boundp-and-interesting (symbol)
(and symbol
(symbolp symbol)
(boundp symbol)
(not (memq symbol '(cl:t cl:nil)))
(not (keywordp symbol))))
(defun print-variable-to-string (symbol)
"Return a short description of VARIABLE-NAME, or NIL."
(let ((*print-pretty* t) (*print-level* 4)
(*print-length* 10) (*print-lines* 1)
(*print-readably* nil)
(value (symbol-value symbol)))
(call/truncated-output-to-string
75 (lambda (s)
(without-printing-errors (:object value :stream s)
(format s "~A ~A~S" symbol *echo-area-prefix* value))))))
(defslimefun complete-form (raw-form)
"Read FORM-STRING in the current buffer package, then complete it
by adding a template for the missing arguments."
;; We do not catch errors here because COMPLETE-FORM is an
;; interactive command, not automatically run in the background like
;; ARGLIST-FOR-ECHO-AREA.
(with-buffer-syntax ()
(multiple-value-bind (arglist provided-args)
(find-immediately-containing-arglist (parse-raw-form raw-form))
(with-available-arglist (arglist) arglist
(decoded-arglist-to-template-string
(delete-given-args arglist
(remove-if #'empty-arg-p provided-args
:from-end t :count 1))
:prefix "" :suffix "")))))
(defslimefun completions-for-keyword (keyword-string raw-form)
"Return a list of possible completions for KEYWORD-STRING relative
to the context provided by RAW-FORM."
(with-buffer-syntax ()
(let ((arglist (find-immediately-containing-arglist
(parse-raw-form raw-form))))
(when (arglist-available-p arglist)
;; It would be possible to complete keywords only if we are in
;; a keyword position, but it is not clear if we want that.
(let* ((keywords
(append (mapcar #'keyword-arg.keyword
(arglist.keyword-args arglist))
(remove-if-not #'keywordp (arglist.any-args arglist))))
(keyword-name
(tokenize-symbol keyword-string))
(matching-keywords
(find-matching-symbols-in-list
keyword-name keywords (make-compound-prefix-matcher #\-)))
(converter (completion-output-symbol-converter keyword-string))
(strings
(mapcar converter
(mapcar #'symbol-name matching-keywords)))
(completion-set
(format-completion-set strings nil "")))
(list completion-set
(longest-compound-prefix completion-set)))))))
(defparameter +cursor-marker+ '%cursor-marker%)
(defun find-subform-with-arglist (form)
"Returns four values:
The appropriate subform of `form' which is closest to the
+CURSOR-MARKER+ and whose operator is valid and has an
arglist. The +CURSOR-MARKER+ is removed from that subform.
Second value is the arglist. Local function and macro definitions
appearing in `form' into account.
Third value is the object in front of +CURSOR-MARKER+.
Fourth value is a form path to that object."
(labels
((yield-success (form local-ops)
(multiple-value-bind (form obj-at-cursor form-path)
(extract-cursor-marker form)
(values form
(let ((entry (assoc (car form) local-ops :test #'op=)))
(if entry
(decode-arglist (cdr entry))
(arglist-from-form form)))
obj-at-cursor
form-path)))
(yield-failure ()
(values nil :not-available))
(operator-p (operator local-ops)
(or (and (symbolp operator) (valid-operator-symbol-p operator))
(assoc operator local-ops :test #'op=)))
(op= (op1 op2)
(cond ((and (symbolp op1) (symbolp op2))
(eq op1 op2))
((and (arglist-dummy-p op1) (arglist-dummy-p op2))
(string= (arglist-dummy.string-representation op1)
(arglist-dummy.string-representation op2)))))
(grovel-form (form local-ops)
"Descend FORM top-down, always taking the rightest branch,
until +CURSOR-MARKER+."
(assert (listp form))
(destructuring-bind (operator . args) form
;; N.b. the user's cursor is at the rightmost, deepest
;; subform right before +CURSOR-MARKER+.
(let ((last-subform (car (last form)))
(new-ops))
(cond
((eq last-subform +cursor-marker+)
(if (operator-p operator local-ops)
(yield-success form local-ops)
(yield-failure)))
((not (operator-p operator local-ops))
(grovel-form last-subform local-ops))
;; Make sure to pick up the arglists of local
;; function/macro definitions.
((setq new-ops (extract-local-op-arglists operator args))
(multiple-value-or (grovel-form last-subform
(nconc new-ops local-ops))
(yield-success form local-ops)))
;; Some typespecs clash with function names, so we make
;; sure to bail out early.
((member operator '(cl:declare cl:declaim))
(yield-success form local-ops))
;; Mostly uninteresting, hence skip.
((memq operator '(cl:quote cl:function))
(yield-failure))
(t
(multiple-value-or (grovel-form last-subform local-ops)
(yield-success form local-ops))))))))
(if (null form)
(yield-failure)
(grovel-form form '()))))
(defun extract-cursor-marker (form)
"Returns three values: normalized `form' without +CURSOR-MARKER+,
the object in front of +CURSOR-MARKER+, and a form path to that
object."
(labels ((grovel (form last path)
(let ((result-form))
(loop for (car . cdr) on form do
(cond ((eql car +cursor-marker+)
(decf (first path))
(return-from grovel
(values (nreconc result-form cdr)
last
(nreverse path))))
((consp car)
(multiple-value-bind (new-car new-last new-path)
(grovel car last (cons 0 path))
(when new-path ; CAR contained cursor-marker?
(return-from grovel
(values (nreconc
(cons new-car result-form) cdr)
new-last
new-path))))))
(push car result-form)
(setq last car)
(incf (first path))
finally
(return-from grovel
(values (nreverse result-form) nil nil))))))
(grovel form nil (list 0))))
(defgeneric extract-local-op-arglists (operator args)
(:documentation
"If the form `(OPERATOR ,@ARGS) is a local operator binding form,
return a list of pairs (OP . ARGLIST) for each locally bound op.")
(:method (operator args)
(declare (ignore operator args))
nil)
;; FLET
(:method ((operator (eql 'cl:flet)) args)
(let ((defs (first args))
(body (rest args)))
(cond ((null body) nil) ; `(flet ((foo (x) |'
((atom defs) nil) ; `(flet ,foo (|'
(t (%collect-op/argl-alist defs)))))
;; LABELS
(:method ((operator (eql 'cl:labels)) args)
;; Notice that we only have information to "look backward" and
;; show arglists of previously occuring local functions.
(destructuring-bind (defs . body) args
(unless (or (atom defs) (null body)) ; `(labels ,foo (|'
(let ((current-def (car (last defs))))
(cond ((atom current-def) nil) ; `(labels ((foo (x) ...)|'
((not (null body))
(extract-local-op-arglists 'cl:flet args))
(t
(let ((def.body (cddr current-def)))
(when def.body
(%collect-op/argl-alist defs)))))))))
;; MACROLET
(:method ((operator (eql 'cl:macrolet)) args)
(extract-local-op-arglists 'cl:labels args)))
(defun %collect-op/argl-alist (defs)
(setq defs (remove-if-not #'(lambda (x)
;; Well-formed FLET/LABELS def?
(and (consp x) (second x)))
defs))
(loop for (name arglist . nil) in defs
collect (cons name arglist)))
(defun find-immediately-containing-arglist (form)
"Returns the arglist of the subform _immediately_ containing
+CURSOR-MARKER+ in `form'. Notice, however, that +CURSOR-MARKER+ may
be in a nested arglist \(e.g. `(WITH-OPEN-FILE (<here>'\), and the
arglist of the appropriate parent form \(WITH-OPEN-FILE\) will be
returned in that case."
(flet ((try (form-path form arglist)
(let* ((arglist-path (form-path-to-arglist-path form-path
form
arglist))
(argl (apply #'arglist-ref
arglist
arglist-path))
(args (apply #'provided-arguments-ref
(cdr form)
arglist
arglist-path)))
(when (and (arglist-p argl) (listp args))
(values argl args)))))
(multiple-value-bind (form arglist obj form-path)
(find-subform-with-arglist form)
(declare (ignore obj))
(with-available-arglist (arglist) arglist
;; First try the form the cursor is in (in case of a normal
;; form), then try the surrounding form (in case of a nested
;; macro form).
(multiple-value-or (try form-path form arglist)
(try (butlast form-path) form arglist)
:not-available)))))
(defun form-path-to-arglist-path (form-path form arglist)
"Convert a form path to an arglist path consisting of arglist
indices."
(labels ((convert (path args arglist)
(if (null path)
nil
(let* ((idx (car path))
(idx* (arglist-index idx args arglist))
(arglist* (and idx* (arglist-ref arglist idx*)))
(args* (and idx* (provided-arguments-ref args
arglist
idx*))))
;; The FORM-PATH may be more detailed than ARGLIST;
;; consider (defun foo (x y) ...), a form path may
;; point into the function's lambda-list, but the
;; arglist of DEFUN won't contain as much information.
;; So we only recurse if possible.
(cond ((null idx*)
nil)
((arglist-p arglist*)
(cons idx* (convert (cdr path) args* arglist*)))
(t
(list idx*)))))))
(convert
;; FORM contains irrelevant operator. Adjust FORM-PATH.
(cond ((null form-path) nil)
((equal form-path '(0)) nil)
(t
(destructuring-bind (car . cdr) form-path
(cons (1- car) cdr))))
(cdr form)
arglist)))
(defun arglist-index (provided-argument-index provided-arguments arglist)
"Return the arglist index into `arglist' for the parameter belonging
to the argument (NTH `provided-argument-index' `provided-arguments')."
(let ((positional-args# (positional-args-number arglist))
(arg-index provided-argument-index))
(with-struct (arglist. key-p rest) arglist
(cond
((< arg-index positional-args#) ; required + optional
arg-index)
((and (not key-p) (not rest)) ; more provided than allowed
nil)
((not key-p) ; rest + body
(assert (arglist.rest arglist))
positional-args#)
(t ; key
;; Find last provided &key parameter
(let* ((argument (nth arg-index provided-arguments))
(provided-keys (subseq provided-arguments positional-args#)))
(loop for (key value) on provided-keys by #'cddr
when (eq value argument)
return (match key
(('quote symbol) symbol)
(_ key)))))))))
(defun arglist-ref (arglist &rest indices)
"Returns the parameter in ARGLIST along the INDICIES path. Numbers
represent positional parameters (required, optional), keywords
represent key parameters."
(flet ((ref-positional-arg (arglist index)
(check-type index (integer 0 *))
(with-struct (arglist. provided-args required-args optional-args rest)
arglist
(loop for args in (list provided-args required-args
(mapcar #'optional-arg.arg-name optional-args))
for args# = (length args)
if (< index args#)
return (nth index args)
else
do (decf index args#)
finally (return (or rest nil)))))
(ref-keyword-arg (arglist keyword)
;; keyword argument may be any symbol,
;; not only from the KEYWORD package.
(let ((keyword (match keyword
(('quote symbol) symbol)
(_ keyword))))
(do-decoded-arglist arglist
(&key (kw arg) (when (eq kw keyword)
(return-from ref-keyword-arg arg)))))
nil))
(dolist (index indices)
(assert (arglist-p arglist))
(setq arglist (if (numberp index)
(ref-positional-arg arglist index)
(ref-keyword-arg arglist index))))
arglist))
(defun provided-arguments-ref (provided-args arglist &rest indices)
"Returns the argument in PROVIDED-ARGUMENT along the INDICES path
relative to ARGLIST."
(check-type arglist arglist)
(flet ((ref (provided-args arglist index)
(if (numberp index)
(nth index provided-args)
(let ((provided-keys (subseq provided-args
(positional-args-number arglist))))
(loop for (key value) on provided-keys
when (eq key index)
return value)))))
(dolist (idx indices)
(setq provided-args (ref provided-args arglist idx))
(setq arglist (arglist-ref arglist idx)))
provided-args))
(defun positional-args-number (arglist)
(+ (length (arglist.provided-args arglist))
(length (arglist.required-args arglist))
(length (arglist.optional-args arglist))))
(defun parse-raw-form (raw-form)
"Parse a RAW-FORM into a Lisp form. I.e. substitute strings by
symbols if already interned. For strings not already interned, use
ARGLIST-DUMMY."
(unless (null raw-form)
(loop for element in raw-form
collect (etypecase element
(string (read-conversatively element))
(list (parse-raw-form element))
(symbol (prog1 element
;; Comes after list, so ELEMENT can't be NIL.
(assert (eq element +cursor-marker+))))))))
(defun read-conversatively (string)
"Tries to find the symbol that's represented by STRING.
If it can't, this either means that STRING does not represent a
symbol, or that the symbol behind STRING would have to be freshly
interned. Because this function is supposed to be called from the
automatic arglist display stuff from Slime, interning freshly
symbols is a big no-no.
In such a case (that no symbol could be found), an object of type
ARGLIST-DUMMY is returned instead, which works as a placeholder
datum for subsequent logics to rely on."
(let* ((string (string-left-trim '(#\Space #\Tab #\Newline) string))
(length (length string))
(type (cond ((zerop length) nil)
((eql (aref string 0) #\')
:quoted-symbol)
((search "#'" string :end2 (min length 2))
:sharpquoted-symbol)
((char= (char string 0) (char string (1- length))
#\")
:string)
(t
:symbol))))
(multiple-value-bind (symbol found?)
(case type
(:symbol (parse-symbol string))
(:quoted-symbol (parse-symbol (subseq string 1)))
(:sharpquoted-symbol (parse-symbol (subseq string 2)))
(:string (values string t))
(t (values string nil)))
(if found?
(ecase type
(:symbol symbol)
(:quoted-symbol `(quote ,symbol))
(:sharpquoted-symbol `(function ,symbol))
(:string (if (> length 1)
(subseq string 1 (1- length))
string)))
(make-arglist-dummy string)))))
(defun test-print-arglist ()
(flet ((test (arglist string)
(let* ((*package* (find-package :swank))
(actual (decoded-arglist-to-string (decode-arglist arglist))))
(unless (string= actual string)
(warn "Test failed: ~S => ~S~% Expected: ~S"
arglist actual string)))))
(test '(function cons) "(function cons)")
(test '(quote cons) "(quote cons)")
(test '(&key (function #'+)) "(&key (function #'+))")
(test '(&whole x y z) "(y z)")
(test '(x &aux y z) "(x)")
(test '(x &environment env y) "(x y)")
(test '(&key ((function f))) "(&key ((function ..)))")
(test '(eval-when (&any :compile-toplevel :load-toplevel :execute) &body body)
"(eval-when (&any :compile-toplevel :load-toplevel :execute) &body body)")
(test '(declare (optimize &any (speed 1) (safety 1)))
"(declare (optimize &any (speed 1) (safety 1)))")
))
(defun test-arglist-ref ()
(macrolet ((soft-assert (form)
`(unless ,form
(warn "Assertion failed: ~S~%" ',form))))
(let ((sample (decode-arglist '(x &key ((:k (y z)))))))
(soft-assert (eq (arglist-ref sample 0) 'x))
(soft-assert (eq (arglist-ref sample :k 0) 'y))
(soft-assert (eq (arglist-ref sample :k 1) 'z))
(soft-assert (eq (provided-arguments-ref '(a :k (b c)) sample 0) 'a))
(soft-assert (eq (provided-arguments-ref '(a :k (b c)) sample :k 0) 'b))
(soft-assert (eq (provided-arguments-ref '(a :k (b c)) sample :k 1) 'c)))))
(test-print-arglist)
(test-arglist-ref)
(provide :swank-arglists)
|
21638
|
;;; swank-arglists.lisp --- arglist related code ??
;;
;; Authors: <NAME> <<EMAIL>>
;; <NAME> <<EMAIL>>
;; and others
;;
;; License: Public Domain
;;
(in-package :swank)
(eval-when (:compile-toplevel :load-toplevel :execute)
(swank-require :swank-c-p-c))
;;;; Utilities
(defun compose (&rest functions)
"Compose FUNCTIONS right-associatively, returning a function"
#'(lambda (x)
(reduce #'funcall functions :initial-value x :from-end t)))
(defun length= (seq n)
"Test for whether SEQ contains N number of elements. I.e. it's equivalent
to (= (LENGTH SEQ) N), but besides being more concise, it may also be more
efficiently implemented."
(etypecase seq
(list (do ((i n (1- i))
(list seq (cdr list)))
((or (<= i 0) (null list))
(and (zerop i) (null list)))))
(sequence (= (length seq) n))))
(declaim (inline memq))
(defun memq (item list)
(member item list :test #'eq))
(defun exactly-one-p (&rest values)
"If exactly one value in VALUES is non-NIL, this value is returned.
Otherwise NIL is returned."
(let ((found nil))
(dolist (v values)
(when v (if found
(return-from exactly-one-p nil)
(setq found v))))
found))
(defun valid-operator-symbol-p (symbol)
"Is SYMBOL the name of a function, a macro, or a special-operator?"
(or (fboundp symbol)
(macro-function symbol)
(special-operator-p symbol)
(member symbol '(declare declaim))))
(defun function-exists-p (form)
(and (valid-function-name-p form)
(fboundp form)
t))
(defmacro multiple-value-or (&rest forms)
(if (null forms)
nil
(let ((first (first forms))
(rest (rest forms)))
`(let* ((values (multiple-value-list ,first))
(primary-value (first values)))
(if primary-value
(values-list values)
(multiple-value-or ,@rest))))))
(defun arglist-available-p (arglist)
(not (eql arglist :not-available)))
(defmacro with-available-arglist ((var &rest more-vars) form &body body)
`(multiple-value-bind (,var ,@more-vars) ,form
(if (eql ,var :not-available)
:not-available
(progn ,@body))))
;;;; Arglist Definition
(defstruct (arglist (:conc-name arglist.) (:predicate arglist-p))
provided-args ; list of the provided actual arguments
required-args ; list of the required arguments
optional-args ; list of the optional arguments
key-p ; whether &key appeared
keyword-args ; list of the keywords
rest ; name of the &rest or &body argument (if any)
body-p ; whether the rest argument is a &body
allow-other-keys-p ; whether &allow-other-keys appeared
aux-args ; list of &aux variables
any-p ; whether &any appeared
any-args ; list of &any arguments [*]
known-junk ; &whole, &environment
unknown-junk) ; unparsed stuff
;;;
;;; [*] The &ANY lambda keyword is an extension to ANSI Common Lisp,
;;; and is only used to describe certain arglists that cannot be
;;; described in another way.
;;;
;;; &ANY is very similiar to &KEY but while &KEY is based upon
;;; the idea of a plist (key1 value1 key2 value2), &ANY is a
;;; cross between &OPTIONAL, &KEY and *FEATURES* lists:
;;;
;;; a) (&ANY :A :B :C) means that you can provide any (non-null)
;;; set consisting of the keywords `:A', `:B', or `:C' in
;;; the arglist. E.g. (:A) or (:C :B :A).
;;;
;;; (This is not restricted to keywords only, but any self-evaluating
;;; expression is allowed.)
;;;
;;; b) (&ANY (key1 v1) (key2 v2) (key3 v3)) means that you can
;;; provide any (non-null) set consisting of lists where
;;; the CAR of the list is one of `key1', `key2', or `key3'.
;;; E.g. ((key1 100) (key3 42)), or ((key3 66) (key2 23))
;;;
;;;
;;; For example, a) let us describe the situations of EVAL-WHEN as
;;;
;;; (EVAL-WHEN (&ANY :compile-toplevel :load-toplevel :execute) &BODY body)
;;;
;;; and b) let us describe the optimization qualifiers that are valid
;;; in the declaration specifier `OPTIMIZE':
;;;
;;; (DECLARE (OPTIMIZE &ANY (compilation-speed 1) (safety 1) ...))
;;;
;; This is a wrapper object around anything that came from Slime and
;; could not reliably be read.
(defstruct (arglist-dummy
(:conc-name #:arglist-dummy.)
(:constructor make-arglist-dummy (string-representation)))
string-representation)
(defun empty-arg-p (dummy)
(and (arglist-dummy-p dummy)
(zerop (length (arglist-dummy.string-representation dummy)))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter +lambda-list-keywords+
'(&provided &required &optional &rest &key &any)))
(defmacro do-decoded-arglist (decoded-arglist &body clauses)
(assert (loop for clause in clauses
thereis (member (car clause) +lambda-list-keywords+)))
(flet ((parse-clauses (clauses)
(let* ((size (length +lambda-list-keywords+))
(initial (make-hash-table :test #'eq :size size))
(main (make-hash-table :test #'eq :size size))
(final (make-hash-table :test #'eq :size size)))
(loop for clause in clauses
for lambda-list-keyword = (first clause)
for clause-parameter = (second clause)
doing (cond ((eq clause-parameter :initially)
(setf (gethash lambda-list-keyword initial) clause))
((eq clause-parameter :finally)
(setf (gethash lambda-list-keyword final) clause))
(t
(setf (gethash lambda-list-keyword main) clause)))
finally
(return (values initial main final)))))
(generate-main-clause (clause arglist)
(destructure-case clause
((&provided (&optional arg) . body)
(let ((gensym (gensym "PROVIDED-ARG+")))
`(dolist (,gensym (arglist.provided-args ,arglist))
(declare (ignorable ,gensym))
(let (,@(when arg `((,arg ,gensym))))
,@body))))
((&required (&optional arg) . body)
(let ((gensym (gensym "REQUIRED-ARG+")))
`(dolist (,gensym (arglist.required-args ,arglist))
(declare (ignorable ,gensym))
(let (,@(when arg `((,arg ,gensym))))
,@body))))
((&optional (&optional arg init) . body)
(let ((optarg (gensym "OPTIONAL-ARG+")))
`(dolist (,optarg (arglist.optional-args ,arglist))
(declare (ignorable ,optarg))
(let (,@(when arg `((,arg (optional-arg.arg-name ,optarg))))
,@(when init `((,init (optional-arg.default-arg ,optarg)))))
,@body))))
((&key (&optional keyword arg init) . body)
(let ((keyarg (gensym "KEY-ARG+")))
`(dolist (,keyarg (arglist.keyword-args ,arglist))
(declare (ignorable ,keyarg))
(let (,@(when keyword `((,keyword (keyword-arg.keyword ,keyarg))))
,@(when arg `((,arg (keyword-arg.arg-name ,keyarg))))
,@(when init `((,init (keyword-arg.default-arg ,keyarg)))))
,@body))))
((&rest (&optional arg body-p) . body)
`(when (arglist.rest ,arglist)
(let (,@(when arg `((,arg (arglist.rest ,arglist))))
,@(when body-p `((,body-p (arglist.body-p ,arglist)))))
,@body)))
((&any (&optional arg) . body)
(let ((gensym (gensym "REQUIRED-ARG+")))
`(dolist (,gensym (arglist.any-args ,arglist))
(declare (ignorable ,gensym))
(let (,@(when arg `((,arg ,gensym))))
,@body)))))))
(let ((arglist (gensym "DECODED-ARGLIST+")))
(multiple-value-bind (initially-clauses main-clauses finally-clauses)
(parse-clauses clauses)
`(let ((,arglist ,decoded-arglist))
(block do-decoded-arglist
,@(loop for keyword in '(&provided &required &optional &rest &key &any)
append (cddr (gethash keyword initially-clauses))
collect (let ((clause (gethash keyword main-clauses)))
(when clause (generate-main-clause clause arglist)))
append (cddr (gethash keyword finally-clauses)))))))))
;;;; Arglist Printing
(defun undummy (x)
(if (typep x 'arglist-dummy)
(arglist-dummy.string-representation x)
(prin1-to-string x)))
(defun print-decoded-arglist (arglist &key operator provided-args highlight)
(macrolet ((space ()
;; Kludge: When OPERATOR is not given, we don't want to
;; print a space for the first argument.
`(if (not operator)
(setq operator t)
(progn (write-char #\space)
(pprint-newline :fill))))
(with-highlighting ((&key index) &body body)
`(if (eql ,index (car highlight))
(progn (princ "===> ") ,@body (princ " <==="))
(progn ,@body)))
(print-arglist-recursively (argl &key index)
`(if (eql ,index (car highlight))
(print-decoded-arglist ,argl :highlight (cdr highlight))
(print-decoded-arglist ,argl))))
(let ((index 0))
(pprint-logical-block (nil nil :prefix "(" :suffix ")")
(when operator
(print-arg operator)
(pprint-indent :current 1)) ; 1 due to possibly added space
(do-decoded-arglist (remove-given-args arglist provided-args)
(&provided (arg)
(space)
(print-arg arg)
(incf index))
(&required (arg)
(space)
(if (arglist-p arg)
(print-arglist-recursively arg :index index)
(with-highlighting (:index index)
(print-arg arg)))
(incf index))
(&optional :initially
(when (arglist.optional-args arglist)
(space)
(princ '&optional)))
(&optional (arg init-value)
(space)
(if (arglist-p arg)
(print-arglist-recursively arg :index index)
(with-highlighting (:index index)
(if (null init-value)
(print-arg arg)
(format t "~:@<~A ~A~@:>"
(undummy arg) (undummy init-value)))))
(incf index))
(&key :initially
(when (arglist.key-p arglist)
(space)
(princ '&key)))
(&key (keyword arg init)
(space)
(if (arglist-p arg)
(pprint-logical-block (nil nil :prefix "(" :suffix ")")
(prin1 keyword) (space)
(print-arglist-recursively arg :index keyword))
(with-highlighting (:index keyword)
(cond ((and init (keywordp keyword))
(format t "~:@<~A ~A~@:>" keyword (undummy init)))
(init
(format t "~:@<(~A ..) ~A~@:>"
(undummy keyword) (undummy init)))
((not (keywordp keyword))
(format t "~:@<(~S ..)~@:>" keyword))
(t
(princ keyword))))))
(&key :finally
(when (arglist.allow-other-keys-p arglist)
(space)
(princ '&allow-other-keys)))
(&any :initially
(when (arglist.any-p arglist)
(space)
(princ '&any)))
(&any (arg)
(space)
(print-arg arg))
(&rest (args bodyp)
(space)
(princ (if bodyp '&body '&rest))
(space)
(if (arglist-p args)
(print-arglist-recursively args :index index)
(with-highlighting (:index index)
(print-arg args))))
;; FIXME: add &UNKNOWN-JUNK?
)))))
(defun print-arg (arg)
(let ((arg (if (arglist-dummy-p arg)
(arglist-dummy.string-representation arg)
arg)))
(if (keywordp arg)
(prin1 arg)
(princ arg))))
(defun print-decoded-arglist-as-template (decoded-arglist &key
(prefix "(") (suffix ")"))
(let ((first-p t))
(flet ((space ()
(unless first-p
(write-char #\space))
(setq first-p nil))
(print-arg-or-pattern (arg)
(etypecase arg
(symbol (if (keywordp arg) (prin1 arg) (princ arg)))
(string (princ arg))
(list (princ arg))
(arglist-dummy (princ (arglist-dummy.string-representation arg)))
(arglist (print-decoded-arglist-as-template arg)))
(pprint-newline :fill)))
(pprint-logical-block (nil nil :prefix prefix :suffix suffix)
(do-decoded-arglist decoded-arglist
(&provided ()) ; do nothing; provided args are in the buffer already.
(&required (arg)
(space) (print-arg-or-pattern arg))
(&optional (arg)
(space) (princ "[") (print-arg-or-pattern arg) (princ "]"))
(&key (keyword arg)
(space)
(prin1 (if (keywordp keyword) keyword `',keyword))
(space)
(print-arg-or-pattern arg)
(pprint-newline :linear))
(&any (arg)
(space) (print-arg-or-pattern arg))
(&rest (args)
(when (or (not (arglist.keyword-args decoded-arglist))
(arglist.allow-other-keys-p decoded-arglist))
(space)
(format t "~A..." args))))))))
(defvar *arglist-pprint-bindings*
'((*print-case* . :downcase)
(*print-pretty* . t)
(*print-circle* . nil)
(*print-readably* . nil)
(*print-level* . 10)
(*print-length* . 20)
(*print-escape* . nil)))
(defvar *arglist-show-packages* t)
(defmacro with-arglist-io-syntax (&body body)
(let ((package (gensym)))
`(let ((,package *package*))
(with-standard-io-syntax
(let ((*package* (if *arglist-show-packages*
*package*
,package)))
(with-bindings *arglist-pprint-bindings*
,@body))))))
(defun decoded-arglist-to-string (decoded-arglist
&key operator highlight
print-right-margin)
(with-output-to-string (*standard-output*)
(with-arglist-io-syntax
(let ((*print-right-margin* print-right-margin))
(print-decoded-arglist decoded-arglist
:operator operator
:highlight highlight)))))
(defun decoded-arglist-to-template-string (decoded-arglist
&key (prefix "(") (suffix ")"))
(with-output-to-string (*standard-output*)
(with-arglist-io-syntax
(print-decoded-arglist-as-template decoded-arglist
:prefix prefix
:suffix suffix))))
;;;; Arglist Decoding / Encoding
(defun decode-required-arg (arg)
"ARG can be a symbol or a destructuring pattern."
(etypecase arg
(symbol arg)
(arglist-dummy arg)
(list (decode-arglist arg))))
(defun encode-required-arg (arg)
(etypecase arg
(symbol arg)
(arglist (encode-arglist arg))))
(defstruct (keyword-arg
(:conc-name keyword-arg.)
(:constructor make-keyword-arg (keyword arg-name default-arg)))
keyword
arg-name
default-arg)
(defun decode-keyword-arg (arg)
"Decode a keyword item of formal argument list.
Return three values: keyword, argument name, default arg."
(flet ((intern-as-keyword (arg)
(intern (etypecase arg
(symbol (symbol-name arg))
(arglist-dummy (arglist-dummy.string-representation arg)))
keyword-package)))
(cond ((or (symbolp arg) (arglist-dummy-p arg))
(make-keyword-arg (intern-as-keyword arg) arg nil))
((and (consp arg)
(consp (car arg)))
(make-keyword-arg (caar arg)
(decode-required-arg (cadar arg))
(cadr arg)))
((consp arg)
(make-keyword-arg (intern-as-keyword (car arg)) (car arg) (cadr arg)))
(t
(error "Bad keyword item of formal argument list")))))
(defun encode-keyword-arg (arg)
(cond
((arglist-p (keyword-arg.arg-name arg))
;; Destructuring pattern
(let ((keyword/name (list (keyword-arg.keyword arg)
(encode-required-arg
(keyword-arg.arg-name arg)))))
(if (keyword-arg.default-arg arg)
(list keyword/name
(keyword-arg.default-arg arg))
(list keyword/name))))
((eql (intern (symbol-name (keyword-arg.arg-name arg))
keyword-package)
(keyword-arg.keyword arg))
(if (keyword-arg.default-arg arg)
(list (keyword-arg.arg-name arg)
(keyword-arg.default-arg arg))
(keyword-arg.arg-name arg)))
(t
(let ((keyword/name (list (keyword-arg.keyword arg)
(keyword-arg.arg-name arg))))
(if (keyword-arg.default-arg arg)
(list keyword/name
(keyword-arg.default-arg arg))
(list keyword/name))))))
(progn
(assert (equalp (decode-keyword-arg 'x)
(make-keyword-arg :x 'x nil)))
(assert (equalp (decode-keyword-arg '(x t))
(make-keyword-arg :x 'x t)))
(assert (equalp (decode-keyword-arg '((:x y)))
(make-keyword-arg :x 'y nil)))
(assert (equalp (decode-keyword-arg '((:x y) t))
(make-keyword-arg :x 'y t))))
;;; FIXME suppliedp?
(defstruct (optional-arg
(:conc-name optional-arg.)
(:constructor make-optional-arg (arg-name default-arg)))
arg-name
default-arg)
(defun decode-optional-arg (arg)
"Decode an optional item of a formal argument list.
Return an OPTIONAL-ARG structure."
(etypecase arg
(symbol (make-optional-arg arg nil))
(arglist-dummy (make-optional-arg arg nil))
(list (make-optional-arg (decode-required-arg (car arg))
(cadr arg)))))
(defun encode-optional-arg (optional-arg)
(if (or (optional-arg.default-arg optional-arg)
(arglist-p (optional-arg.arg-name optional-arg)))
(list (encode-required-arg
(optional-arg.arg-name optional-arg))
(optional-arg.default-arg optional-arg))
(optional-arg.arg-name optional-arg)))
(progn
(assert (equalp (decode-optional-arg 'x)
(make-optional-arg 'x nil)))
(assert (equalp (decode-optional-arg '(x t))
(make-optional-arg 'x t))))
(define-modify-macro nreversef () nreverse "Reverse the list in PLACE.")
(defun decode-arglist (arglist)
"Parse the list ARGLIST and return an ARGLIST structure."
(etypecase arglist
((eql :not-available) (return-from decode-arglist
:not-available))
(list))
(loop
with mode = nil
with result = (make-arglist)
for arg = (if (consp arglist)
(pop arglist)
(progn
(prog1 arglist
(setf mode '&rest
arglist nil))))
do (cond
((eql mode '&unknown-junk)
;; don't leave this mode -- we don't know how the arglist
;; after unknown lambda-list keywords is interpreted
(push arg (arglist.unknown-junk result)))
((eql arg '&allow-other-keys)
(setf (arglist.allow-other-keys-p result) t))
((eql arg '&key)
(setf (arglist.key-p result) t
mode arg))
((memq arg '(&optional &rest &body &aux))
(setq mode arg))
((memq arg '(&whole &environment))
(setq mode arg)
(push arg (arglist.known-junk result)))
((and (symbolp arg)
(string= (symbol-name arg) (string '#:&any))) ; may be interned
(setf (arglist.any-p result) t) ; in any *package*.
(setq mode '&any))
((memq arg lambda-list-keywords)
(setq mode '&unknown-junk)
(push arg (arglist.unknown-junk result)))
(t
(ecase mode
(&key
(push (decode-keyword-arg arg)
(arglist.keyword-args result)))
(&optional
(push (decode-optional-arg arg)
(arglist.optional-args result)))
(&body
(setf (arglist.body-p result) t
(arglist.rest result) arg))
(&rest
(setf (arglist.rest result) arg))
(&aux
(push (decode-optional-arg arg)
(arglist.aux-args result)))
((nil)
(push (decode-required-arg arg)
(arglist.required-args result)))
((&whole &environment)
(setf mode nil)
(push arg (arglist.known-junk result)))
(&any
(push arg (arglist.any-args result))))))
until (null arglist)
finally (nreversef (arglist.required-args result))
finally (nreversef (arglist.optional-args result))
finally (nreversef (arglist.keyword-args result))
finally (nreversef (arglist.aux-args result))
finally (nreversef (arglist.any-args result))
finally (nreversef (arglist.known-junk result))
finally (nreversef (arglist.unknown-junk result))
finally (assert (or (and (not (arglist.key-p result))
(not (arglist.any-p result)))
(exactly-one-p (arglist.key-p result)
(arglist.any-p result))))
finally (return result)))
(defun encode-arglist (decoded-arglist)
(append (mapcar #'encode-required-arg (arglist.required-args decoded-arglist))
(when (arglist.optional-args decoded-arglist)
'(&optional))
(mapcar #'encode-optional-arg (arglist.optional-args decoded-arglist))
(when (arglist.key-p decoded-arglist)
'(&key))
(mapcar #'encode-keyword-arg (arglist.keyword-args decoded-arglist))
(when (arglist.allow-other-keys-p decoded-arglist)
'(&allow-other-keys))
(when (arglist.any-args decoded-arglist)
`(&any ,@(arglist.any-args decoded-arglist)))
(cond ((not (arglist.rest decoded-arglist))
'())
((arglist.body-p decoded-arglist)
`(&body ,(arglist.rest decoded-arglist)))
(t
`(&rest ,(arglist.rest decoded-arglist))))
(when (arglist.aux-args decoded-arglist)
`(&aux ,(arglist.aux-args decoded-arglist)))
(arglist.known-junk decoded-arglist)
(arglist.unknown-junk decoded-arglist)))
;;;; Arglist Enrichment
(defun arglist-keywords (lambda-list)
"Return the list of keywords in ARGLIST.
As a secondary value, return whether &allow-other-keys appears."
(let ((decoded-arglist (decode-arglist lambda-list)))
(values (arglist.keyword-args decoded-arglist)
(arglist.allow-other-keys-p decoded-arglist))))
(defun methods-keywords (methods)
"Collect all keywords in the arglists of METHODS.
As a secondary value, return whether &allow-other-keys appears somewhere."
(let ((keywords '())
(allow-other-keys nil))
(dolist (method methods)
(multiple-value-bind (kw aok)
(arglist-keywords
(swank-mop:method-lambda-list method))
(setq keywords (remove-duplicates (append keywords kw)
:key #'keyword-arg.keyword)
allow-other-keys (or allow-other-keys aok))))
(values keywords allow-other-keys)))
(defun generic-function-keywords (generic-function)
"Collect all keywords in the methods of GENERIC-FUNCTION.
As a secondary value, return whether &allow-other-keys appears somewhere."
(methods-keywords
(swank-mop:generic-function-methods generic-function)))
(defun applicable-methods-keywords (generic-function arguments)
"Collect all keywords in the methods of GENERIC-FUNCTION that are
applicable for argument of CLASSES. As a secondary value, return
whether &allow-other-keys appears somewhere."
(methods-keywords
(multiple-value-bind (amuc okp)
(swank-mop:compute-applicable-methods-using-classes
generic-function (mapcar #'class-of arguments))
(if okp
amuc
(compute-applicable-methods generic-function arguments)))))
(defgeneric extra-keywords (operator &rest args)
(:documentation "Return a list of extra keywords of OPERATOR (a
symbol) when applied to the (unevaluated) ARGS.
As a secondary value, return whether other keys are allowed.
As a tertiary value, return the initial sublist of ARGS that was needed
to determine the extra keywords."))
;;; We make sure that symbol-from-KEYWORD-using keywords come before
;;; symbol-from-arbitrary-package-using keywords. And we sort the
;;; latter according to how their home-packages relate to *PACKAGE*.
;;;
;;; Rationale is to show those key parameters first which make most
;;; sense in the current context. And in particular: to put
;;; implementation-internal stuff last.
;;;
;;; This matters tremendeously on Allegro in combination with
;;; AllegroCache as that does some evil tinkering with initargs,
;;; obfuscating the arglist of MAKE-INSTANCE.
;;;
(defmethod extra-keywords :around (op &rest args)
(declare (ignorable op args))
(multiple-value-bind (keywords aok enrichments) (call-next-method)
(values (sort-extra-keywords keywords) aok enrichments)))
(defun make-package-comparator (reference-packages)
"Returns a two-argument test function which compares packages
according to their used-by relation with REFERENCE-PACKAGES. Packages
will be sorted first which appear first in the PACKAGE-USE-LIST of the
reference packages."
(let ((package-use-table (make-hash-table :test 'eq)))
;; Walk the package dependency graph breadth-fist, and fill
;; PACKAGE-USE-TABLE accordingly.
(loop with queue = (copy-list reference-packages)
with bfn = 0 ; Breadth-First Number
for p = (pop queue)
unless (gethash p package-use-table)
do (setf (gethash p package-use-table) (shiftf bfn (1+ bfn)))
and do (setf queue (nconc queue (copy-list (package-use-list p))))
while queue)
#'(lambda (p1 p2)
(let ((bfn1 (gethash p1 package-use-table))
(bfn2 (gethash p2 package-use-table)))
(cond ((and bfn1 bfn2) (<= bfn1 bfn2))
(bfn1 bfn1)
(bfn2 nil) ; p2 is used, p1 not
(t (string<= (package-name p1) (package-name p2))))))))
(defun sort-extra-keywords (kwds)
(stable-sort kwds (make-package-comparator (list keyword-package *package*))
:key (compose #'symbol-package #'keyword-arg.keyword)))
(defun keywords-of-operator (operator)
"Return a list of KEYWORD-ARGs that OPERATOR accepts.
This function is useful for writing EXTRA-KEYWORDS methods for
user-defined functions which are declared &ALLOW-OTHER-KEYS and which
forward keywords to OPERATOR."
(with-available-arglist (arglist) (arglist-from-form (ensure-list operator))
(values (arglist.keyword-args arglist)
(arglist.allow-other-keys-p arglist))))
(defmethod extra-keywords (operator &rest args)
;; default method
(declare (ignore args))
(let ((symbol-function (symbol-function operator)))
(if (typep symbol-function 'generic-function)
(generic-function-keywords symbol-function)
nil)))
(defun class-from-class-name-form (class-name-form)
(when (and (listp class-name-form)
(= (length class-name-form) 2)
(eq (car class-name-form) 'quote))
(let* ((class-name (cadr class-name-form))
(class (find-class class-name nil)))
(when (and class
(not (swank-mop:class-finalized-p class)))
;; Try to finalize the class, which can fail if
;; superclasses are not defined yet
(handler-case (swank-mop:finalize-inheritance class)
(program-error (c)
(declare (ignore c)))))
class)))
(defun extra-keywords/slots (class)
(multiple-value-bind (slots allow-other-keys-p)
(if (swank-mop:class-finalized-p class)
(values (swank-mop:class-slots class) nil)
(values (swank-mop:class-direct-slots class) t))
(let ((slot-init-keywords
(loop for slot in slots append
(mapcar (lambda (initarg)
(make-keyword-arg
initarg
(swank-mop:slot-definition-name slot)
(swank-mop:slot-definition-initform slot)))
(swank-mop:slot-definition-initargs slot)))))
(values slot-init-keywords allow-other-keys-p))))
(defun extra-keywords/make-instance (operator &rest args)
(declare (ignore operator))
(unless (null args)
(let* ((class-name-form (car args))
(class (class-from-class-name-form class-name-form)))
(when class
(multiple-value-bind (slot-init-keywords class-aokp)
(extra-keywords/slots class)
(multiple-value-bind (allocate-instance-keywords ai-aokp)
(applicable-methods-keywords
#'allocate-instance (list class))
(multiple-value-bind (initialize-instance-keywords ii-aokp)
(ignore-errors
(applicable-methods-keywords
#'initialize-instance (list (swank-mop:class-prototype class))))
(multiple-value-bind (shared-initialize-keywords si-aokp)
(ignore-errors
(applicable-methods-keywords
#'shared-initialize (list (swank-mop:class-prototype class) t)))
(values (append slot-init-keywords
allocate-instance-keywords
initialize-instance-keywords
shared-initialize-keywords)
(or class-aokp ai-aokp ii-aokp si-aokp)
(list class-name-form))))))))))
(defun extra-keywords/change-class (operator &rest args)
(declare (ignore operator))
(unless (null args)
(let* ((class-name-form (car args))
(class (class-from-class-name-form class-name-form)))
(when class
(multiple-value-bind (slot-init-keywords class-aokp)
(extra-keywords/slots class)
(declare (ignore class-aokp))
(multiple-value-bind (shared-initialize-keywords si-aokp)
(ignore-errors
(applicable-methods-keywords
#'shared-initialize (list (swank-mop:class-prototype class) t)))
;; FIXME: much as it would be nice to include the
;; applicable keywords from
;; UPDATE-INSTANCE-FOR-DIFFERENT-CLASS, I don't really see
;; how to do it: so we punt, always declaring
;; &ALLOW-OTHER-KEYS.
(declare (ignore si-aokp))
(values (append slot-init-keywords shared-initialize-keywords)
t
(list class-name-form))))))))
(defmethod extra-keywords ((operator (eql 'make-instance))
&rest args)
(multiple-value-or (apply #'extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'make-condition))
&rest args)
(multiple-value-or (apply #'extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'error))
&rest args)
(multiple-value-or (apply #'extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'signal))
&rest args)
(multiple-value-or (apply #'extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'warn))
&rest args)
(multiple-value-or (apply #'extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'cerror))
&rest args)
(multiple-value-bind (keywords aok determiners)
(apply #'extra-keywords/make-instance operator
(cdr args))
(if keywords
(values keywords aok
(cons (car args) determiners))
(call-next-method))))
(defmethod extra-keywords ((operator (eql 'change-class))
&rest args)
(multiple-value-bind (keywords aok determiners)
(apply #'extra-keywords/change-class operator (cdr args))
(if keywords
(values keywords aok
(cons (car args) determiners))
(call-next-method))))
(defun enrich-decoded-arglist-with-keywords (decoded-arglist keywords allow-other-keys-p)
"Modify DECODED-ARGLIST using KEYWORDS and ALLOW-OTHER-KEYS-P."
(when keywords
(setf (arglist.key-p decoded-arglist) t)
(setf (arglist.keyword-args decoded-arglist)
(remove-duplicates
(append (arglist.keyword-args decoded-arglist)
keywords)
:key #'keyword-arg.keyword)))
(setf (arglist.allow-other-keys-p decoded-arglist)
(or (arglist.allow-other-keys-p decoded-arglist)
allow-other-keys-p)))
(defun enrich-decoded-arglist-with-extra-keywords (decoded-arglist form)
"Determine extra keywords from the function call FORM, and modify
DECODED-ARGLIST to include them. As a secondary return value, return
the initial sublist of ARGS that was needed to determine the extra
keywords. As a tertiary return value, return whether any enrichment
was done."
(multiple-value-bind (extra-keywords extra-aok determining-args)
(apply #'extra-keywords form)
;; enrich the list of keywords with the extra keywords
(enrich-decoded-arglist-with-keywords decoded-arglist
extra-keywords extra-aok)
(values decoded-arglist
determining-args
(or extra-keywords extra-aok))))
(defgeneric compute-enriched-decoded-arglist (operator-form argument-forms)
(:documentation
"Return three values: DECODED-ARGLIST, DETERMINING-ARGS, and
ANY-ENRICHMENT, just like enrich-decoded-arglist-with-extra-keywords.
If the arglist is not available, return :NOT-AVAILABLE."))
(defmethod compute-enriched-decoded-arglist (operator-form argument-forms)
(with-available-arglist (decoded-arglist)
(decode-arglist (arglist operator-form))
(enrich-decoded-arglist-with-extra-keywords decoded-arglist
(cons operator-form
argument-forms))))
(defmethod compute-enriched-decoded-arglist ((operator-form (eql 'with-open-file))
argument-forms)
(declare (ignore argument-forms))
(multiple-value-bind (decoded-arglist determining-args)
(call-next-method)
(let ((first-arg (first (arglist.required-args decoded-arglist)))
(open-arglist (compute-enriched-decoded-arglist 'open nil)))
(when (and (arglist-p first-arg) (arglist-p open-arglist))
(enrich-decoded-arglist-with-keywords
first-arg
(arglist.keyword-args open-arglist)
nil)))
(values decoded-arglist determining-args t)))
(defmethod compute-enriched-decoded-arglist ((operator-form (eql 'apply))
argument-forms)
(let ((function-name-form (car argument-forms)))
(when (and (listp function-name-form)
(length= function-name-form 2)
(memq (car function-name-form) '(quote function)))
(let ((function-name (cadr function-name-form)))
(when (valid-operator-symbol-p function-name)
(let ((function-arglist
(compute-enriched-decoded-arglist function-name
(cdr argument-forms))))
(return-from compute-enriched-decoded-arglist
(values (make-arglist :required-args
(list 'function)
:optional-args
(append
(mapcar #'(lambda (arg)
(make-optional-arg arg nil))
(arglist.required-args function-arglist))
(arglist.optional-args function-arglist))
:key-p
(arglist.key-p function-arglist)
:keyword-args
(arglist.keyword-args function-arglist)
:rest
'args
:allow-other-keys-p
(arglist.allow-other-keys-p function-arglist))
(list function-name-form)
t)))))))
(call-next-method))
(defun delete-given-args (decoded-arglist args)
"Delete given ARGS from DECODED-ARGLIST."
(macrolet ((pop-or-return (list)
`(if (null ,list)
(return-from do-decoded-arglist)
(pop ,list))))
(do-decoded-arglist decoded-arglist
(&provided ()
(assert (eq (pop-or-return args)
(pop (arglist.provided-args decoded-arglist)))))
(&required ()
(pop-or-return args)
(pop (arglist.required-args decoded-arglist)))
(&optional ()
(pop-or-return args)
(pop (arglist.optional-args decoded-arglist)))
(&key (keyword)
;; N.b. we consider a keyword to be given only when the keyword
;; _and_ a value has been given for it.
(loop for (key value) on args by #'cddr
when (and (eq keyword key) value)
do (setf (arglist.keyword-args decoded-arglist)
(remove keyword (arglist.keyword-args decoded-arglist)
:key #'keyword-arg.keyword))))))
decoded-arglist)
(defun remove-given-args (decoded-arglist args)
;; FIXME: We actually needa deep copy here.
(delete-given-args (copy-arglist decoded-arglist) args))
;;;; Arglist Retrieval
(defun arglist-from-form (form)
(if (null form)
:not-available
(arglist-dispatch (car form) (cdr form))))
(export 'arglist-dispatch)
(defgeneric arglist-dispatch (operator arguments)
;; Default method
(:method (operator arguments)
(unless (and (symbolp operator) (valid-operator-symbol-p operator))
(return-from arglist-dispatch :not-available))
(multiple-value-bind (decoded-arglist determining-args)
(compute-enriched-decoded-arglist operator arguments)
(with-available-arglist (arglist) decoded-arglist
;; replace some formal args by determining actual args
(setf arglist (delete-given-args arglist determining-args))
(setf (arglist.provided-args arglist) determining-args)
arglist))))
(defmethod arglist-dispatch ((operator (eql 'defmethod)) arguments)
(match (cons operator arguments)
(('defmethod (#'function-exists-p gf-name) . rest)
(let ((gf (fdefinition gf-name)))
(when (typep gf 'generic-function)
(with-available-arglist (arglist) (decode-arglist (arglist gf))
(let ((qualifiers (loop for x in rest
until (or (listp x) (empty-arg-p x))
collect x)))
(return-from arglist-dispatch
(make-arglist :provided-args (cons gf-name qualifiers)
:required-args (list arglist)
:rest "body" :body-p t)))))))
(_)) ; Fall through
(call-next-method))
(defmethod arglist-dispatch ((operator (eql 'define-compiler-macro)) arguments)
(match (cons operator arguments)
(('define-compiler-macro (#'function-exists-p gf-name) . _)
(let ((gf (fdefinition gf-name)))
(with-available-arglist (arglist) (decode-arglist (arglist gf))
(return-from arglist-dispatch
(make-arglist :provided-args (list gf-name)
:required-args (list arglist)
:rest "body" :body-p t)))))
(_)) ; Fall through
(call-next-method))
(defmethod arglist-dispatch ((operator (eql 'eval-when)) arguments)
(declare (ignore arguments))
(let ((eval-when-args '(:compile-toplevel :load-toplevel :execute)))
(make-arglist
:required-args (list (make-arglist :any-p t :any-args eval-when-args))
:rest '#:body :body-p t)))
(defmethod arglist-dispatch ((operator (eql 'declare)) arguments)
(let* ((declaration (cons operator (last arguments)))
(typedecl-arglist (arglist-for-type-declaration declaration)))
(if (arglist-available-p typedecl-arglist)
typedecl-arglist
(match declaration
(('declare ((#'consp typespec) . decl-args))
(with-available-arglist (typespec-arglist)
(decoded-arglist-for-type-specifier typespec)
(make-arglist
:required-args (list (make-arglist
:required-args (list typespec-arglist)
:rest '#:variables)))))
(('declare (decl-identifier . decl-args))
(decoded-arglist-for-declaration decl-identifier decl-args))
(_ (make-arglist :rest '#:declaration-specifiers))))))
(defmethod arglist-dispatch ((operator (eql 'declaim)) arguments)
(arglist-dispatch 'declare arguments))
(defun arglist-for-type-declaration (declaration)
(flet ((%arglist-for-type-declaration (identifier typespec rest-var-name)
(with-available-arglist (typespec-arglist)
(decoded-arglist-for-type-specifier typespec)
(make-arglist
:required-args (list (make-arglist
:provided-args (list identifier)
:required-args (list typespec-arglist)
:rest rest-var-name))))))
(match declaration
(('declare ('type (#'consp typespec) . decl-args))
(%arglist-for-type-declaration 'type typespec '#:variables))
(('declare ('ftype (#'consp typespec) . decl-args))
(%arglist-for-type-declaration 'ftype typespec '#:function-names))
(('declare ((#'consp typespec) . decl-args))
(with-available-arglist (typespec-arglist)
(decoded-arglist-for-type-specifier typespec)
(make-arglist
:required-args (list (make-arglist
:required-args (list typespec-arglist)
:rest '#:variables)))))
(_ :not-available))))
(defun decoded-arglist-for-declaration (decl-identifier decl-args)
(declare (ignore decl-args))
(with-available-arglist (arglist)
(decode-arglist (declaration-arglist decl-identifier))
(setf (arglist.provided-args arglist) (list decl-identifier))
(make-arglist :required-args (list arglist))))
(defun decoded-arglist-for-type-specifier (type-specifier)
(etypecase type-specifier
(arglist-dummy :not-available)
(cons (decoded-arglist-for-type-specifier (car type-specifier)))
(symbol
(with-available-arglist (arglist)
(decode-arglist (type-specifier-arglist type-specifier))
(setf (arglist.provided-args arglist) (list type-specifier))
arglist))))
;;; Slimefuns
;;; We work on a RAW-FORM, or BUFFER-FORM, which represent the form at
;;; user's point in Emacs. A RAW-FORM looks like
;;;
;;; ("FOO" ("BAR" ...) "QUUX" ("ZURP" SWANK::%CURSOR-MARKER%))
;;;
;;; The expression before the cursor marker is the expression where
;;; user's cursor points at. An explicit marker is necessary to
;;; disambiguate between
;;;
;;; ("IF" ("PRED")
;;; ("F" "X" "Y" %CURSOR-MARKER%))
;;;
;;; and
;;; ("IF" ("PRED")
;;; ("F" "X" "Y") %CURSOR-MARKER%)
;;; Notice that for a form like (FOO (BAR |) QUUX), where | denotes
;;; user's point, the following should be sent ("FOO" ("BAR" ""
;;; %CURSOR-MARKER%)). Only the forms up to point should be
;;; considered.
(defslimefun autodoc (raw-form &key print-right-margin)
"Return a list of two elements.
First, a string representing the arglist for the deepest subform in
RAW-FORM that does have an arglist. The highlighted parameter is
wrapped in ===> X <===.
Second, a boolean value telling whether the returned string can be cached."
(handler-bind ((serious-condition
#'(lambda (c)
(unless (debug-on-swank-error)
(let ((*print-right-margin* print-right-margin))
(return-from autodoc
(format nil "Arglist Error: \"~A\"" c)))))))
(with-buffer-syntax ()
(multiple-value-bind (form arglist obj-at-cursor form-path)
(find-subform-with-arglist (parse-raw-form raw-form))
(cond ((boundp-and-interesting obj-at-cursor)
(list (print-variable-to-string obj-at-cursor) nil))
(t
(list
(with-available-arglist (arglist) arglist
(decoded-arglist-to-string
arglist
:print-right-margin print-right-margin
:operator (car form)
:highlight (form-path-to-arglist-path form-path
form
arglist)))
t)))))))
(defun boundp-and-interesting (symbol)
(and symbol
(symbolp symbol)
(boundp symbol)
(not (memq symbol '(cl:t cl:nil)))
(not (keywordp symbol))))
(defun print-variable-to-string (symbol)
"Return a short description of VARIABLE-NAME, or NIL."
(let ((*print-pretty* t) (*print-level* 4)
(*print-length* 10) (*print-lines* 1)
(*print-readably* nil)
(value (symbol-value symbol)))
(call/truncated-output-to-string
75 (lambda (s)
(without-printing-errors (:object value :stream s)
(format s "~A ~A~S" symbol *echo-area-prefix* value))))))
(defslimefun complete-form (raw-form)
"Read FORM-STRING in the current buffer package, then complete it
by adding a template for the missing arguments."
;; We do not catch errors here because COMPLETE-FORM is an
;; interactive command, not automatically run in the background like
;; ARGLIST-FOR-ECHO-AREA.
(with-buffer-syntax ()
(multiple-value-bind (arglist provided-args)
(find-immediately-containing-arglist (parse-raw-form raw-form))
(with-available-arglist (arglist) arglist
(decoded-arglist-to-template-string
(delete-given-args arglist
(remove-if #'empty-arg-p provided-args
:from-end t :count 1))
:prefix "" :suffix "")))))
(defslimefun completions-for-keyword (keyword-string raw-form)
"Return a list of possible completions for KEYWORD-STRING relative
to the context provided by RAW-FORM."
(with-buffer-syntax ()
(let ((arglist (find-immediately-containing-arglist
(parse-raw-form raw-form))))
(when (arglist-available-p arglist)
;; It would be possible to complete keywords only if we are in
;; a keyword position, but it is not clear if we want that.
(let* ((keywords
(append (mapcar #'keyword-arg.keyword
(arglist.keyword-args arglist))
(remove-if-not #'keywordp (arglist.any-args arglist))))
(keyword-name
(tokenize-symbol keyword-string))
(matching-keywords
(find-matching-symbols-in-list
keyword-name keywords (make-compound-prefix-matcher #\-)))
(converter (completion-output-symbol-converter keyword-string))
(strings
(mapcar converter
(mapcar #'symbol-name matching-keywords)))
(completion-set
(format-completion-set strings nil "")))
(list completion-set
(longest-compound-prefix completion-set)))))))
(defparameter +cursor-marker+ '%cursor-marker%)
(defun find-subform-with-arglist (form)
"Returns four values:
The appropriate subform of `form' which is closest to the
+CURSOR-MARKER+ and whose operator is valid and has an
arglist. The +CURSOR-MARKER+ is removed from that subform.
Second value is the arglist. Local function and macro definitions
appearing in `form' into account.
Third value is the object in front of +CURSOR-MARKER+.
Fourth value is a form path to that object."
(labels
((yield-success (form local-ops)
(multiple-value-bind (form obj-at-cursor form-path)
(extract-cursor-marker form)
(values form
(let ((entry (assoc (car form) local-ops :test #'op=)))
(if entry
(decode-arglist (cdr entry))
(arglist-from-form form)))
obj-at-cursor
form-path)))
(yield-failure ()
(values nil :not-available))
(operator-p (operator local-ops)
(or (and (symbolp operator) (valid-operator-symbol-p operator))
(assoc operator local-ops :test #'op=)))
(op= (op1 op2)
(cond ((and (symbolp op1) (symbolp op2))
(eq op1 op2))
((and (arglist-dummy-p op1) (arglist-dummy-p op2))
(string= (arglist-dummy.string-representation op1)
(arglist-dummy.string-representation op2)))))
(grovel-form (form local-ops)
"Descend FORM top-down, always taking the rightest branch,
until +CURSOR-MARKER+."
(assert (listp form))
(destructuring-bind (operator . args) form
;; N.b. the user's cursor is at the rightmost, deepest
;; subform right before +CURSOR-MARKER+.
(let ((last-subform (car (last form)))
(new-ops))
(cond
((eq last-subform +cursor-marker+)
(if (operator-p operator local-ops)
(yield-success form local-ops)
(yield-failure)))
((not (operator-p operator local-ops))
(grovel-form last-subform local-ops))
;; Make sure to pick up the arglists of local
;; function/macro definitions.
((setq new-ops (extract-local-op-arglists operator args))
(multiple-value-or (grovel-form last-subform
(nconc new-ops local-ops))
(yield-success form local-ops)))
;; Some typespecs clash with function names, so we make
;; sure to bail out early.
((member operator '(cl:declare cl:declaim))
(yield-success form local-ops))
;; Mostly uninteresting, hence skip.
((memq operator '(cl:quote cl:function))
(yield-failure))
(t
(multiple-value-or (grovel-form last-subform local-ops)
(yield-success form local-ops))))))))
(if (null form)
(yield-failure)
(grovel-form form '()))))
(defun extract-cursor-marker (form)
"Returns three values: normalized `form' without +CURSOR-MARKER+,
the object in front of +CURSOR-MARKER+, and a form path to that
object."
(labels ((grovel (form last path)
(let ((result-form))
(loop for (car . cdr) on form do
(cond ((eql car +cursor-marker+)
(decf (first path))
(return-from grovel
(values (nreconc result-form cdr)
last
(nreverse path))))
((consp car)
(multiple-value-bind (new-car new-last new-path)
(grovel car last (cons 0 path))
(when new-path ; CAR contained cursor-marker?
(return-from grovel
(values (nreconc
(cons new-car result-form) cdr)
new-last
new-path))))))
(push car result-form)
(setq last car)
(incf (first path))
finally
(return-from grovel
(values (nreverse result-form) nil nil))))))
(grovel form nil (list 0))))
(defgeneric extract-local-op-arglists (operator args)
(:documentation
"If the form `(OPERATOR ,@ARGS) is a local operator binding form,
return a list of pairs (OP . ARGLIST) for each locally bound op.")
(:method (operator args)
(declare (ignore operator args))
nil)
;; FLET
(:method ((operator (eql 'cl:flet)) args)
(let ((defs (first args))
(body (rest args)))
(cond ((null body) nil) ; `(flet ((foo (x) |'
((atom defs) nil) ; `(flet ,foo (|'
(t (%collect-op/argl-alist defs)))))
;; LABELS
(:method ((operator (eql 'cl:labels)) args)
;; Notice that we only have information to "look backward" and
;; show arglists of previously occuring local functions.
(destructuring-bind (defs . body) args
(unless (or (atom defs) (null body)) ; `(labels ,foo (|'
(let ((current-def (car (last defs))))
(cond ((atom current-def) nil) ; `(labels ((foo (x) ...)|'
((not (null body))
(extract-local-op-arglists 'cl:flet args))
(t
(let ((def.body (cddr current-def)))
(when def.body
(%collect-op/argl-alist defs)))))))))
;; MACROLET
(:method ((operator (eql 'cl:macrolet)) args)
(extract-local-op-arglists 'cl:labels args)))
(defun %collect-op/argl-alist (defs)
(setq defs (remove-if-not #'(lambda (x)
;; Well-formed FLET/LABELS def?
(and (consp x) (second x)))
defs))
(loop for (name arglist . nil) in defs
collect (cons name arglist)))
(defun find-immediately-containing-arglist (form)
"Returns the arglist of the subform _immediately_ containing
+CURSOR-MARKER+ in `form'. Notice, however, that +CURSOR-MARKER+ may
be in a nested arglist \(e.g. `(WITH-OPEN-FILE (<here>'\), and the
arglist of the appropriate parent form \(WITH-OPEN-FILE\) will be
returned in that case."
(flet ((try (form-path form arglist)
(let* ((arglist-path (form-path-to-arglist-path form-path
form
arglist))
(argl (apply #'arglist-ref
arglist
arglist-path))
(args (apply #'provided-arguments-ref
(cdr form)
arglist
arglist-path)))
(when (and (arglist-p argl) (listp args))
(values argl args)))))
(multiple-value-bind (form arglist obj form-path)
(find-subform-with-arglist form)
(declare (ignore obj))
(with-available-arglist (arglist) arglist
;; First try the form the cursor is in (in case of a normal
;; form), then try the surrounding form (in case of a nested
;; macro form).
(multiple-value-or (try form-path form arglist)
(try (butlast form-path) form arglist)
:not-available)))))
(defun form-path-to-arglist-path (form-path form arglist)
"Convert a form path to an arglist path consisting of arglist
indices."
(labels ((convert (path args arglist)
(if (null path)
nil
(let* ((idx (car path))
(idx* (arglist-index idx args arglist))
(arglist* (and idx* (arglist-ref arglist idx*)))
(args* (and idx* (provided-arguments-ref args
arglist
idx*))))
;; The FORM-PATH may be more detailed than ARGLIST;
;; consider (defun foo (x y) ...), a form path may
;; point into the function's lambda-list, but the
;; arglist of DEFUN won't contain as much information.
;; So we only recurse if possible.
(cond ((null idx*)
nil)
((arglist-p arglist*)
(cons idx* (convert (cdr path) args* arglist*)))
(t
(list idx*)))))))
(convert
;; FORM contains irrelevant operator. Adjust FORM-PATH.
(cond ((null form-path) nil)
((equal form-path '(0)) nil)
(t
(destructuring-bind (car . cdr) form-path
(cons (1- car) cdr))))
(cdr form)
arglist)))
(defun arglist-index (provided-argument-index provided-arguments arglist)
"Return the arglist index into `arglist' for the parameter belonging
to the argument (NTH `provided-argument-index' `provided-arguments')."
(let ((positional-args# (positional-args-number arglist))
(arg-index provided-argument-index))
(with-struct (arglist. key-p rest) arglist
(cond
((< arg-index positional-args#) ; required + optional
arg-index)
((and (not key-p) (not rest)) ; more provided than allowed
nil)
((not key-p) ; rest + body
(assert (arglist.rest arglist))
positional-args#)
(t ; key
;; Find last provided &key parameter
(let* ((argument (nth arg-index provided-arguments))
(provided-keys (subseq provided-arguments positional-args#)))
(loop for (key value) on provided-keys by #'cddr
when (eq value argument)
return (match key
(('quote symbol) symbol)
(_ key)))))))))
(defun arglist-ref (arglist &rest indices)
"Returns the parameter in ARGLIST along the INDICIES path. Numbers
represent positional parameters (required, optional), keywords
represent key parameters."
(flet ((ref-positional-arg (arglist index)
(check-type index (integer 0 *))
(with-struct (arglist. provided-args required-args optional-args rest)
arglist
(loop for args in (list provided-args required-args
(mapcar #'optional-arg.arg-name optional-args))
for args# = (length args)
if (< index args#)
return (nth index args)
else
do (decf index args#)
finally (return (or rest nil)))))
(ref-keyword-arg (arglist keyword)
;; keyword argument may be any symbol,
;; not only from the KEYWORD package.
(let ((keyword (match keyword
(('quote symbol) symbol)
(_ keyword))))
(do-decoded-arglist arglist
(&key (kw arg) (when (eq kw keyword)
(return-from ref-keyword-arg arg)))))
nil))
(dolist (index indices)
(assert (arglist-p arglist))
(setq arglist (if (numberp index)
(ref-positional-arg arglist index)
(ref-keyword-arg arglist index))))
arglist))
(defun provided-arguments-ref (provided-args arglist &rest indices)
"Returns the argument in PROVIDED-ARGUMENT along the INDICES path
relative to ARGLIST."
(check-type arglist arglist)
(flet ((ref (provided-args arglist index)
(if (numberp index)
(nth index provided-args)
(let ((provided-keys (subseq provided-args
(positional-args-number arglist))))
(loop for (key value) on provided-keys
when (eq key index)
return value)))))
(dolist (idx indices)
(setq provided-args (ref provided-args arglist idx))
(setq arglist (arglist-ref arglist idx)))
provided-args))
(defun positional-args-number (arglist)
(+ (length (arglist.provided-args arglist))
(length (arglist.required-args arglist))
(length (arglist.optional-args arglist))))
(defun parse-raw-form (raw-form)
"Parse a RAW-FORM into a Lisp form. I.e. substitute strings by
symbols if already interned. For strings not already interned, use
ARGLIST-DUMMY."
(unless (null raw-form)
(loop for element in raw-form
collect (etypecase element
(string (read-conversatively element))
(list (parse-raw-form element))
(symbol (prog1 element
;; Comes after list, so ELEMENT can't be NIL.
(assert (eq element +cursor-marker+))))))))
(defun read-conversatively (string)
"Tries to find the symbol that's represented by STRING.
If it can't, this either means that STRING does not represent a
symbol, or that the symbol behind STRING would have to be freshly
interned. Because this function is supposed to be called from the
automatic arglist display stuff from Slime, interning freshly
symbols is a big no-no.
In such a case (that no symbol could be found), an object of type
ARGLIST-DUMMY is returned instead, which works as a placeholder
datum for subsequent logics to rely on."
(let* ((string (string-left-trim '(#\Space #\Tab #\Newline) string))
(length (length string))
(type (cond ((zerop length) nil)
((eql (aref string 0) #\')
:quoted-symbol)
((search "#'" string :end2 (min length 2))
:sharpquoted-symbol)
((char= (char string 0) (char string (1- length))
#\")
:string)
(t
:symbol))))
(multiple-value-bind (symbol found?)
(case type
(:symbol (parse-symbol string))
(:quoted-symbol (parse-symbol (subseq string 1)))
(:sharpquoted-symbol (parse-symbol (subseq string 2)))
(:string (values string t))
(t (values string nil)))
(if found?
(ecase type
(:symbol symbol)
(:quoted-symbol `(quote ,symbol))
(:sharpquoted-symbol `(function ,symbol))
(:string (if (> length 1)
(subseq string 1 (1- length))
string)))
(make-arglist-dummy string)))))
(defun test-print-arglist ()
(flet ((test (arglist string)
(let* ((*package* (find-package :swank))
(actual (decoded-arglist-to-string (decode-arglist arglist))))
(unless (string= actual string)
(warn "Test failed: ~S => ~S~% Expected: ~S"
arglist actual string)))))
(test '(function cons) "(function cons)")
(test '(quote cons) "(quote cons)")
(test '(&key (function #'+)) "(&key (function #'+))")
(test '(&whole x y z) "(y z)")
(test '(x &aux y z) "(x)")
(test '(x &environment env y) "(x y)")
(test '(&key ((function f))) "(&key ((function ..)))")
(test '(eval-when (&any :compile-toplevel :load-toplevel :execute) &body body)
"(eval-when (&any :compile-toplevel :load-toplevel :execute) &body body)")
(test '(declare (optimize &any (speed 1) (safety 1)))
"(declare (optimize &any (speed 1) (safety 1)))")
))
(defun test-arglist-ref ()
(macrolet ((soft-assert (form)
`(unless ,form
(warn "Assertion failed: ~S~%" ',form))))
(let ((sample (decode-arglist '(x &key ((:k (y z)))))))
(soft-assert (eq (arglist-ref sample 0) 'x))
(soft-assert (eq (arglist-ref sample :k 0) 'y))
(soft-assert (eq (arglist-ref sample :k 1) 'z))
(soft-assert (eq (provided-arguments-ref '(a :k (b c)) sample 0) 'a))
(soft-assert (eq (provided-arguments-ref '(a :k (b c)) sample :k 0) 'b))
(soft-assert (eq (provided-arguments-ref '(a :k (b c)) sample :k 1) 'c)))))
(test-print-arglist)
(test-arglist-ref)
(provide :swank-arglists)
| true |
;;; swank-arglists.lisp --- arglist related code ??
;;
;; Authors: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; and others
;;
;; License: Public Domain
;;
(in-package :swank)
(eval-when (:compile-toplevel :load-toplevel :execute)
(swank-require :swank-c-p-c))
;;;; Utilities
(defun compose (&rest functions)
"Compose FUNCTIONS right-associatively, returning a function"
#'(lambda (x)
(reduce #'funcall functions :initial-value x :from-end t)))
(defun length= (seq n)
"Test for whether SEQ contains N number of elements. I.e. it's equivalent
to (= (LENGTH SEQ) N), but besides being more concise, it may also be more
efficiently implemented."
(etypecase seq
(list (do ((i n (1- i))
(list seq (cdr list)))
((or (<= i 0) (null list))
(and (zerop i) (null list)))))
(sequence (= (length seq) n))))
(declaim (inline memq))
(defun memq (item list)
(member item list :test #'eq))
(defun exactly-one-p (&rest values)
"If exactly one value in VALUES is non-NIL, this value is returned.
Otherwise NIL is returned."
(let ((found nil))
(dolist (v values)
(when v (if found
(return-from exactly-one-p nil)
(setq found v))))
found))
(defun valid-operator-symbol-p (symbol)
"Is SYMBOL the name of a function, a macro, or a special-operator?"
(or (fboundp symbol)
(macro-function symbol)
(special-operator-p symbol)
(member symbol '(declare declaim))))
(defun function-exists-p (form)
(and (valid-function-name-p form)
(fboundp form)
t))
(defmacro multiple-value-or (&rest forms)
(if (null forms)
nil
(let ((first (first forms))
(rest (rest forms)))
`(let* ((values (multiple-value-list ,first))
(primary-value (first values)))
(if primary-value
(values-list values)
(multiple-value-or ,@rest))))))
(defun arglist-available-p (arglist)
(not (eql arglist :not-available)))
(defmacro with-available-arglist ((var &rest more-vars) form &body body)
`(multiple-value-bind (,var ,@more-vars) ,form
(if (eql ,var :not-available)
:not-available
(progn ,@body))))
;;;; Arglist Definition
(defstruct (arglist (:conc-name arglist.) (:predicate arglist-p))
provided-args ; list of the provided actual arguments
required-args ; list of the required arguments
optional-args ; list of the optional arguments
key-p ; whether &key appeared
keyword-args ; list of the keywords
rest ; name of the &rest or &body argument (if any)
body-p ; whether the rest argument is a &body
allow-other-keys-p ; whether &allow-other-keys appeared
aux-args ; list of &aux variables
any-p ; whether &any appeared
any-args ; list of &any arguments [*]
known-junk ; &whole, &environment
unknown-junk) ; unparsed stuff
;;;
;;; [*] The &ANY lambda keyword is an extension to ANSI Common Lisp,
;;; and is only used to describe certain arglists that cannot be
;;; described in another way.
;;;
;;; &ANY is very similiar to &KEY but while &KEY is based upon
;;; the idea of a plist (key1 value1 key2 value2), &ANY is a
;;; cross between &OPTIONAL, &KEY and *FEATURES* lists:
;;;
;;; a) (&ANY :A :B :C) means that you can provide any (non-null)
;;; set consisting of the keywords `:A', `:B', or `:C' in
;;; the arglist. E.g. (:A) or (:C :B :A).
;;;
;;; (This is not restricted to keywords only, but any self-evaluating
;;; expression is allowed.)
;;;
;;; b) (&ANY (key1 v1) (key2 v2) (key3 v3)) means that you can
;;; provide any (non-null) set consisting of lists where
;;; the CAR of the list is one of `key1', `key2', or `key3'.
;;; E.g. ((key1 100) (key3 42)), or ((key3 66) (key2 23))
;;;
;;;
;;; For example, a) let us describe the situations of EVAL-WHEN as
;;;
;;; (EVAL-WHEN (&ANY :compile-toplevel :load-toplevel :execute) &BODY body)
;;;
;;; and b) let us describe the optimization qualifiers that are valid
;;; in the declaration specifier `OPTIMIZE':
;;;
;;; (DECLARE (OPTIMIZE &ANY (compilation-speed 1) (safety 1) ...))
;;;
;; This is a wrapper object around anything that came from Slime and
;; could not reliably be read.
(defstruct (arglist-dummy
(:conc-name #:arglist-dummy.)
(:constructor make-arglist-dummy (string-representation)))
string-representation)
(defun empty-arg-p (dummy)
(and (arglist-dummy-p dummy)
(zerop (length (arglist-dummy.string-representation dummy)))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter +lambda-list-keywords+
'(&provided &required &optional &rest &key &any)))
(defmacro do-decoded-arglist (decoded-arglist &body clauses)
(assert (loop for clause in clauses
thereis (member (car clause) +lambda-list-keywords+)))
(flet ((parse-clauses (clauses)
(let* ((size (length +lambda-list-keywords+))
(initial (make-hash-table :test #'eq :size size))
(main (make-hash-table :test #'eq :size size))
(final (make-hash-table :test #'eq :size size)))
(loop for clause in clauses
for lambda-list-keyword = (first clause)
for clause-parameter = (second clause)
doing (cond ((eq clause-parameter :initially)
(setf (gethash lambda-list-keyword initial) clause))
((eq clause-parameter :finally)
(setf (gethash lambda-list-keyword final) clause))
(t
(setf (gethash lambda-list-keyword main) clause)))
finally
(return (values initial main final)))))
(generate-main-clause (clause arglist)
(destructure-case clause
((&provided (&optional arg) . body)
(let ((gensym (gensym "PROVIDED-ARG+")))
`(dolist (,gensym (arglist.provided-args ,arglist))
(declare (ignorable ,gensym))
(let (,@(when arg `((,arg ,gensym))))
,@body))))
((&required (&optional arg) . body)
(let ((gensym (gensym "REQUIRED-ARG+")))
`(dolist (,gensym (arglist.required-args ,arglist))
(declare (ignorable ,gensym))
(let (,@(when arg `((,arg ,gensym))))
,@body))))
((&optional (&optional arg init) . body)
(let ((optarg (gensym "OPTIONAL-ARG+")))
`(dolist (,optarg (arglist.optional-args ,arglist))
(declare (ignorable ,optarg))
(let (,@(when arg `((,arg (optional-arg.arg-name ,optarg))))
,@(when init `((,init (optional-arg.default-arg ,optarg)))))
,@body))))
((&key (&optional keyword arg init) . body)
(let ((keyarg (gensym "KEY-ARG+")))
`(dolist (,keyarg (arglist.keyword-args ,arglist))
(declare (ignorable ,keyarg))
(let (,@(when keyword `((,keyword (keyword-arg.keyword ,keyarg))))
,@(when arg `((,arg (keyword-arg.arg-name ,keyarg))))
,@(when init `((,init (keyword-arg.default-arg ,keyarg)))))
,@body))))
((&rest (&optional arg body-p) . body)
`(when (arglist.rest ,arglist)
(let (,@(when arg `((,arg (arglist.rest ,arglist))))
,@(when body-p `((,body-p (arglist.body-p ,arglist)))))
,@body)))
((&any (&optional arg) . body)
(let ((gensym (gensym "REQUIRED-ARG+")))
`(dolist (,gensym (arglist.any-args ,arglist))
(declare (ignorable ,gensym))
(let (,@(when arg `((,arg ,gensym))))
,@body)))))))
(let ((arglist (gensym "DECODED-ARGLIST+")))
(multiple-value-bind (initially-clauses main-clauses finally-clauses)
(parse-clauses clauses)
`(let ((,arglist ,decoded-arglist))
(block do-decoded-arglist
,@(loop for keyword in '(&provided &required &optional &rest &key &any)
append (cddr (gethash keyword initially-clauses))
collect (let ((clause (gethash keyword main-clauses)))
(when clause (generate-main-clause clause arglist)))
append (cddr (gethash keyword finally-clauses)))))))))
;;;; Arglist Printing
(defun undummy (x)
(if (typep x 'arglist-dummy)
(arglist-dummy.string-representation x)
(prin1-to-string x)))
(defun print-decoded-arglist (arglist &key operator provided-args highlight)
(macrolet ((space ()
;; Kludge: When OPERATOR is not given, we don't want to
;; print a space for the first argument.
`(if (not operator)
(setq operator t)
(progn (write-char #\space)
(pprint-newline :fill))))
(with-highlighting ((&key index) &body body)
`(if (eql ,index (car highlight))
(progn (princ "===> ") ,@body (princ " <==="))
(progn ,@body)))
(print-arglist-recursively (argl &key index)
`(if (eql ,index (car highlight))
(print-decoded-arglist ,argl :highlight (cdr highlight))
(print-decoded-arglist ,argl))))
(let ((index 0))
(pprint-logical-block (nil nil :prefix "(" :suffix ")")
(when operator
(print-arg operator)
(pprint-indent :current 1)) ; 1 due to possibly added space
(do-decoded-arglist (remove-given-args arglist provided-args)
(&provided (arg)
(space)
(print-arg arg)
(incf index))
(&required (arg)
(space)
(if (arglist-p arg)
(print-arglist-recursively arg :index index)
(with-highlighting (:index index)
(print-arg arg)))
(incf index))
(&optional :initially
(when (arglist.optional-args arglist)
(space)
(princ '&optional)))
(&optional (arg init-value)
(space)
(if (arglist-p arg)
(print-arglist-recursively arg :index index)
(with-highlighting (:index index)
(if (null init-value)
(print-arg arg)
(format t "~:@<~A ~A~@:>"
(undummy arg) (undummy init-value)))))
(incf index))
(&key :initially
(when (arglist.key-p arglist)
(space)
(princ '&key)))
(&key (keyword arg init)
(space)
(if (arglist-p arg)
(pprint-logical-block (nil nil :prefix "(" :suffix ")")
(prin1 keyword) (space)
(print-arglist-recursively arg :index keyword))
(with-highlighting (:index keyword)
(cond ((and init (keywordp keyword))
(format t "~:@<~A ~A~@:>" keyword (undummy init)))
(init
(format t "~:@<(~A ..) ~A~@:>"
(undummy keyword) (undummy init)))
((not (keywordp keyword))
(format t "~:@<(~S ..)~@:>" keyword))
(t
(princ keyword))))))
(&key :finally
(when (arglist.allow-other-keys-p arglist)
(space)
(princ '&allow-other-keys)))
(&any :initially
(when (arglist.any-p arglist)
(space)
(princ '&any)))
(&any (arg)
(space)
(print-arg arg))
(&rest (args bodyp)
(space)
(princ (if bodyp '&body '&rest))
(space)
(if (arglist-p args)
(print-arglist-recursively args :index index)
(with-highlighting (:index index)
(print-arg args))))
;; FIXME: add &UNKNOWN-JUNK?
)))))
(defun print-arg (arg)
(let ((arg (if (arglist-dummy-p arg)
(arglist-dummy.string-representation arg)
arg)))
(if (keywordp arg)
(prin1 arg)
(princ arg))))
(defun print-decoded-arglist-as-template (decoded-arglist &key
(prefix "(") (suffix ")"))
(let ((first-p t))
(flet ((space ()
(unless first-p
(write-char #\space))
(setq first-p nil))
(print-arg-or-pattern (arg)
(etypecase arg
(symbol (if (keywordp arg) (prin1 arg) (princ arg)))
(string (princ arg))
(list (princ arg))
(arglist-dummy (princ (arglist-dummy.string-representation arg)))
(arglist (print-decoded-arglist-as-template arg)))
(pprint-newline :fill)))
(pprint-logical-block (nil nil :prefix prefix :suffix suffix)
(do-decoded-arglist decoded-arglist
(&provided ()) ; do nothing; provided args are in the buffer already.
(&required (arg)
(space) (print-arg-or-pattern arg))
(&optional (arg)
(space) (princ "[") (print-arg-or-pattern arg) (princ "]"))
(&key (keyword arg)
(space)
(prin1 (if (keywordp keyword) keyword `',keyword))
(space)
(print-arg-or-pattern arg)
(pprint-newline :linear))
(&any (arg)
(space) (print-arg-or-pattern arg))
(&rest (args)
(when (or (not (arglist.keyword-args decoded-arglist))
(arglist.allow-other-keys-p decoded-arglist))
(space)
(format t "~A..." args))))))))
(defvar *arglist-pprint-bindings*
'((*print-case* . :downcase)
(*print-pretty* . t)
(*print-circle* . nil)
(*print-readably* . nil)
(*print-level* . 10)
(*print-length* . 20)
(*print-escape* . nil)))
(defvar *arglist-show-packages* t)
(defmacro with-arglist-io-syntax (&body body)
(let ((package (gensym)))
`(let ((,package *package*))
(with-standard-io-syntax
(let ((*package* (if *arglist-show-packages*
*package*
,package)))
(with-bindings *arglist-pprint-bindings*
,@body))))))
(defun decoded-arglist-to-string (decoded-arglist
&key operator highlight
print-right-margin)
(with-output-to-string (*standard-output*)
(with-arglist-io-syntax
(let ((*print-right-margin* print-right-margin))
(print-decoded-arglist decoded-arglist
:operator operator
:highlight highlight)))))
(defun decoded-arglist-to-template-string (decoded-arglist
&key (prefix "(") (suffix ")"))
(with-output-to-string (*standard-output*)
(with-arglist-io-syntax
(print-decoded-arglist-as-template decoded-arglist
:prefix prefix
:suffix suffix))))
;;;; Arglist Decoding / Encoding
(defun decode-required-arg (arg)
"ARG can be a symbol or a destructuring pattern."
(etypecase arg
(symbol arg)
(arglist-dummy arg)
(list (decode-arglist arg))))
(defun encode-required-arg (arg)
(etypecase arg
(symbol arg)
(arglist (encode-arglist arg))))
(defstruct (keyword-arg
(:conc-name keyword-arg.)
(:constructor make-keyword-arg (keyword arg-name default-arg)))
keyword
arg-name
default-arg)
(defun decode-keyword-arg (arg)
"Decode a keyword item of formal argument list.
Return three values: keyword, argument name, default arg."
(flet ((intern-as-keyword (arg)
(intern (etypecase arg
(symbol (symbol-name arg))
(arglist-dummy (arglist-dummy.string-representation arg)))
keyword-package)))
(cond ((or (symbolp arg) (arglist-dummy-p arg))
(make-keyword-arg (intern-as-keyword arg) arg nil))
((and (consp arg)
(consp (car arg)))
(make-keyword-arg (caar arg)
(decode-required-arg (cadar arg))
(cadr arg)))
((consp arg)
(make-keyword-arg (intern-as-keyword (car arg)) (car arg) (cadr arg)))
(t
(error "Bad keyword item of formal argument list")))))
(defun encode-keyword-arg (arg)
(cond
((arglist-p (keyword-arg.arg-name arg))
;; Destructuring pattern
(let ((keyword/name (list (keyword-arg.keyword arg)
(encode-required-arg
(keyword-arg.arg-name arg)))))
(if (keyword-arg.default-arg arg)
(list keyword/name
(keyword-arg.default-arg arg))
(list keyword/name))))
((eql (intern (symbol-name (keyword-arg.arg-name arg))
keyword-package)
(keyword-arg.keyword arg))
(if (keyword-arg.default-arg arg)
(list (keyword-arg.arg-name arg)
(keyword-arg.default-arg arg))
(keyword-arg.arg-name arg)))
(t
(let ((keyword/name (list (keyword-arg.keyword arg)
(keyword-arg.arg-name arg))))
(if (keyword-arg.default-arg arg)
(list keyword/name
(keyword-arg.default-arg arg))
(list keyword/name))))))
(progn
(assert (equalp (decode-keyword-arg 'x)
(make-keyword-arg :x 'x nil)))
(assert (equalp (decode-keyword-arg '(x t))
(make-keyword-arg :x 'x t)))
(assert (equalp (decode-keyword-arg '((:x y)))
(make-keyword-arg :x 'y nil)))
(assert (equalp (decode-keyword-arg '((:x y) t))
(make-keyword-arg :x 'y t))))
;;; FIXME suppliedp?
(defstruct (optional-arg
(:conc-name optional-arg.)
(:constructor make-optional-arg (arg-name default-arg)))
arg-name
default-arg)
(defun decode-optional-arg (arg)
"Decode an optional item of a formal argument list.
Return an OPTIONAL-ARG structure."
(etypecase arg
(symbol (make-optional-arg arg nil))
(arglist-dummy (make-optional-arg arg nil))
(list (make-optional-arg (decode-required-arg (car arg))
(cadr arg)))))
(defun encode-optional-arg (optional-arg)
(if (or (optional-arg.default-arg optional-arg)
(arglist-p (optional-arg.arg-name optional-arg)))
(list (encode-required-arg
(optional-arg.arg-name optional-arg))
(optional-arg.default-arg optional-arg))
(optional-arg.arg-name optional-arg)))
(progn
(assert (equalp (decode-optional-arg 'x)
(make-optional-arg 'x nil)))
(assert (equalp (decode-optional-arg '(x t))
(make-optional-arg 'x t))))
(define-modify-macro nreversef () nreverse "Reverse the list in PLACE.")
(defun decode-arglist (arglist)
"Parse the list ARGLIST and return an ARGLIST structure."
(etypecase arglist
((eql :not-available) (return-from decode-arglist
:not-available))
(list))
(loop
with mode = nil
with result = (make-arglist)
for arg = (if (consp arglist)
(pop arglist)
(progn
(prog1 arglist
(setf mode '&rest
arglist nil))))
do (cond
((eql mode '&unknown-junk)
;; don't leave this mode -- we don't know how the arglist
;; after unknown lambda-list keywords is interpreted
(push arg (arglist.unknown-junk result)))
((eql arg '&allow-other-keys)
(setf (arglist.allow-other-keys-p result) t))
((eql arg '&key)
(setf (arglist.key-p result) t
mode arg))
((memq arg '(&optional &rest &body &aux))
(setq mode arg))
((memq arg '(&whole &environment))
(setq mode arg)
(push arg (arglist.known-junk result)))
((and (symbolp arg)
(string= (symbol-name arg) (string '#:&any))) ; may be interned
(setf (arglist.any-p result) t) ; in any *package*.
(setq mode '&any))
((memq arg lambda-list-keywords)
(setq mode '&unknown-junk)
(push arg (arglist.unknown-junk result)))
(t
(ecase mode
(&key
(push (decode-keyword-arg arg)
(arglist.keyword-args result)))
(&optional
(push (decode-optional-arg arg)
(arglist.optional-args result)))
(&body
(setf (arglist.body-p result) t
(arglist.rest result) arg))
(&rest
(setf (arglist.rest result) arg))
(&aux
(push (decode-optional-arg arg)
(arglist.aux-args result)))
((nil)
(push (decode-required-arg arg)
(arglist.required-args result)))
((&whole &environment)
(setf mode nil)
(push arg (arglist.known-junk result)))
(&any
(push arg (arglist.any-args result))))))
until (null arglist)
finally (nreversef (arglist.required-args result))
finally (nreversef (arglist.optional-args result))
finally (nreversef (arglist.keyword-args result))
finally (nreversef (arglist.aux-args result))
finally (nreversef (arglist.any-args result))
finally (nreversef (arglist.known-junk result))
finally (nreversef (arglist.unknown-junk result))
finally (assert (or (and (not (arglist.key-p result))
(not (arglist.any-p result)))
(exactly-one-p (arglist.key-p result)
(arglist.any-p result))))
finally (return result)))
(defun encode-arglist (decoded-arglist)
(append (mapcar #'encode-required-arg (arglist.required-args decoded-arglist))
(when (arglist.optional-args decoded-arglist)
'(&optional))
(mapcar #'encode-optional-arg (arglist.optional-args decoded-arglist))
(when (arglist.key-p decoded-arglist)
'(&key))
(mapcar #'encode-keyword-arg (arglist.keyword-args decoded-arglist))
(when (arglist.allow-other-keys-p decoded-arglist)
'(&allow-other-keys))
(when (arglist.any-args decoded-arglist)
`(&any ,@(arglist.any-args decoded-arglist)))
(cond ((not (arglist.rest decoded-arglist))
'())
((arglist.body-p decoded-arglist)
`(&body ,(arglist.rest decoded-arglist)))
(t
`(&rest ,(arglist.rest decoded-arglist))))
(when (arglist.aux-args decoded-arglist)
`(&aux ,(arglist.aux-args decoded-arglist)))
(arglist.known-junk decoded-arglist)
(arglist.unknown-junk decoded-arglist)))
;;;; Arglist Enrichment
(defun arglist-keywords (lambda-list)
"Return the list of keywords in ARGLIST.
As a secondary value, return whether &allow-other-keys appears."
(let ((decoded-arglist (decode-arglist lambda-list)))
(values (arglist.keyword-args decoded-arglist)
(arglist.allow-other-keys-p decoded-arglist))))
(defun methods-keywords (methods)
"Collect all keywords in the arglists of METHODS.
As a secondary value, return whether &allow-other-keys appears somewhere."
(let ((keywords '())
(allow-other-keys nil))
(dolist (method methods)
(multiple-value-bind (kw aok)
(arglist-keywords
(swank-mop:method-lambda-list method))
(setq keywords (remove-duplicates (append keywords kw)
:key #'keyword-arg.keyword)
allow-other-keys (or allow-other-keys aok))))
(values keywords allow-other-keys)))
(defun generic-function-keywords (generic-function)
"Collect all keywords in the methods of GENERIC-FUNCTION.
As a secondary value, return whether &allow-other-keys appears somewhere."
(methods-keywords
(swank-mop:generic-function-methods generic-function)))
(defun applicable-methods-keywords (generic-function arguments)
"Collect all keywords in the methods of GENERIC-FUNCTION that are
applicable for argument of CLASSES. As a secondary value, return
whether &allow-other-keys appears somewhere."
(methods-keywords
(multiple-value-bind (amuc okp)
(swank-mop:compute-applicable-methods-using-classes
generic-function (mapcar #'class-of arguments))
(if okp
amuc
(compute-applicable-methods generic-function arguments)))))
(defgeneric extra-keywords (operator &rest args)
(:documentation "Return a list of extra keywords of OPERATOR (a
symbol) when applied to the (unevaluated) ARGS.
As a secondary value, return whether other keys are allowed.
As a tertiary value, return the initial sublist of ARGS that was needed
to determine the extra keywords."))
;;; We make sure that symbol-from-KEYWORD-using keywords come before
;;; symbol-from-arbitrary-package-using keywords. And we sort the
;;; latter according to how their home-packages relate to *PACKAGE*.
;;;
;;; Rationale is to show those key parameters first which make most
;;; sense in the current context. And in particular: to put
;;; implementation-internal stuff last.
;;;
;;; This matters tremendeously on Allegro in combination with
;;; AllegroCache as that does some evil tinkering with initargs,
;;; obfuscating the arglist of MAKE-INSTANCE.
;;;
(defmethod extra-keywords :around (op &rest args)
(declare (ignorable op args))
(multiple-value-bind (keywords aok enrichments) (call-next-method)
(values (sort-extra-keywords keywords) aok enrichments)))
(defun make-package-comparator (reference-packages)
"Returns a two-argument test function which compares packages
according to their used-by relation with REFERENCE-PACKAGES. Packages
will be sorted first which appear first in the PACKAGE-USE-LIST of the
reference packages."
(let ((package-use-table (make-hash-table :test 'eq)))
;; Walk the package dependency graph breadth-fist, and fill
;; PACKAGE-USE-TABLE accordingly.
(loop with queue = (copy-list reference-packages)
with bfn = 0 ; Breadth-First Number
for p = (pop queue)
unless (gethash p package-use-table)
do (setf (gethash p package-use-table) (shiftf bfn (1+ bfn)))
and do (setf queue (nconc queue (copy-list (package-use-list p))))
while queue)
#'(lambda (p1 p2)
(let ((bfn1 (gethash p1 package-use-table))
(bfn2 (gethash p2 package-use-table)))
(cond ((and bfn1 bfn2) (<= bfn1 bfn2))
(bfn1 bfn1)
(bfn2 nil) ; p2 is used, p1 not
(t (string<= (package-name p1) (package-name p2))))))))
(defun sort-extra-keywords (kwds)
(stable-sort kwds (make-package-comparator (list keyword-package *package*))
:key (compose #'symbol-package #'keyword-arg.keyword)))
(defun keywords-of-operator (operator)
"Return a list of KEYWORD-ARGs that OPERATOR accepts.
This function is useful for writing EXTRA-KEYWORDS methods for
user-defined functions which are declared &ALLOW-OTHER-KEYS and which
forward keywords to OPERATOR."
(with-available-arglist (arglist) (arglist-from-form (ensure-list operator))
(values (arglist.keyword-args arglist)
(arglist.allow-other-keys-p arglist))))
(defmethod extra-keywords (operator &rest args)
;; default method
(declare (ignore args))
(let ((symbol-function (symbol-function operator)))
(if (typep symbol-function 'generic-function)
(generic-function-keywords symbol-function)
nil)))
(defun class-from-class-name-form (class-name-form)
(when (and (listp class-name-form)
(= (length class-name-form) 2)
(eq (car class-name-form) 'quote))
(let* ((class-name (cadr class-name-form))
(class (find-class class-name nil)))
(when (and class
(not (swank-mop:class-finalized-p class)))
;; Try to finalize the class, which can fail if
;; superclasses are not defined yet
(handler-case (swank-mop:finalize-inheritance class)
(program-error (c)
(declare (ignore c)))))
class)))
(defun extra-keywords/slots (class)
(multiple-value-bind (slots allow-other-keys-p)
(if (swank-mop:class-finalized-p class)
(values (swank-mop:class-slots class) nil)
(values (swank-mop:class-direct-slots class) t))
(let ((slot-init-keywords
(loop for slot in slots append
(mapcar (lambda (initarg)
(make-keyword-arg
initarg
(swank-mop:slot-definition-name slot)
(swank-mop:slot-definition-initform slot)))
(swank-mop:slot-definition-initargs slot)))))
(values slot-init-keywords allow-other-keys-p))))
(defun extra-keywords/make-instance (operator &rest args)
(declare (ignore operator))
(unless (null args)
(let* ((class-name-form (car args))
(class (class-from-class-name-form class-name-form)))
(when class
(multiple-value-bind (slot-init-keywords class-aokp)
(extra-keywords/slots class)
(multiple-value-bind (allocate-instance-keywords ai-aokp)
(applicable-methods-keywords
#'allocate-instance (list class))
(multiple-value-bind (initialize-instance-keywords ii-aokp)
(ignore-errors
(applicable-methods-keywords
#'initialize-instance (list (swank-mop:class-prototype class))))
(multiple-value-bind (shared-initialize-keywords si-aokp)
(ignore-errors
(applicable-methods-keywords
#'shared-initialize (list (swank-mop:class-prototype class) t)))
(values (append slot-init-keywords
allocate-instance-keywords
initialize-instance-keywords
shared-initialize-keywords)
(or class-aokp ai-aokp ii-aokp si-aokp)
(list class-name-form))))))))))
(defun extra-keywords/change-class (operator &rest args)
(declare (ignore operator))
(unless (null args)
(let* ((class-name-form (car args))
(class (class-from-class-name-form class-name-form)))
(when class
(multiple-value-bind (slot-init-keywords class-aokp)
(extra-keywords/slots class)
(declare (ignore class-aokp))
(multiple-value-bind (shared-initialize-keywords si-aokp)
(ignore-errors
(applicable-methods-keywords
#'shared-initialize (list (swank-mop:class-prototype class) t)))
;; FIXME: much as it would be nice to include the
;; applicable keywords from
;; UPDATE-INSTANCE-FOR-DIFFERENT-CLASS, I don't really see
;; how to do it: so we punt, always declaring
;; &ALLOW-OTHER-KEYS.
(declare (ignore si-aokp))
(values (append slot-init-keywords shared-initialize-keywords)
t
(list class-name-form))))))))
(defmethod extra-keywords ((operator (eql 'make-instance))
&rest args)
(multiple-value-or (apply #'extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'make-condition))
&rest args)
(multiple-value-or (apply #'extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'error))
&rest args)
(multiple-value-or (apply #'extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'signal))
&rest args)
(multiple-value-or (apply #'extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'warn))
&rest args)
(multiple-value-or (apply #'extra-keywords/make-instance operator args)
(call-next-method)))
(defmethod extra-keywords ((operator (eql 'cerror))
&rest args)
(multiple-value-bind (keywords aok determiners)
(apply #'extra-keywords/make-instance operator
(cdr args))
(if keywords
(values keywords aok
(cons (car args) determiners))
(call-next-method))))
(defmethod extra-keywords ((operator (eql 'change-class))
&rest args)
(multiple-value-bind (keywords aok determiners)
(apply #'extra-keywords/change-class operator (cdr args))
(if keywords
(values keywords aok
(cons (car args) determiners))
(call-next-method))))
(defun enrich-decoded-arglist-with-keywords (decoded-arglist keywords allow-other-keys-p)
"Modify DECODED-ARGLIST using KEYWORDS and ALLOW-OTHER-KEYS-P."
(when keywords
(setf (arglist.key-p decoded-arglist) t)
(setf (arglist.keyword-args decoded-arglist)
(remove-duplicates
(append (arglist.keyword-args decoded-arglist)
keywords)
:key #'keyword-arg.keyword)))
(setf (arglist.allow-other-keys-p decoded-arglist)
(or (arglist.allow-other-keys-p decoded-arglist)
allow-other-keys-p)))
(defun enrich-decoded-arglist-with-extra-keywords (decoded-arglist form)
"Determine extra keywords from the function call FORM, and modify
DECODED-ARGLIST to include them. As a secondary return value, return
the initial sublist of ARGS that was needed to determine the extra
keywords. As a tertiary return value, return whether any enrichment
was done."
(multiple-value-bind (extra-keywords extra-aok determining-args)
(apply #'extra-keywords form)
;; enrich the list of keywords with the extra keywords
(enrich-decoded-arglist-with-keywords decoded-arglist
extra-keywords extra-aok)
(values decoded-arglist
determining-args
(or extra-keywords extra-aok))))
(defgeneric compute-enriched-decoded-arglist (operator-form argument-forms)
(:documentation
"Return three values: DECODED-ARGLIST, DETERMINING-ARGS, and
ANY-ENRICHMENT, just like enrich-decoded-arglist-with-extra-keywords.
If the arglist is not available, return :NOT-AVAILABLE."))
(defmethod compute-enriched-decoded-arglist (operator-form argument-forms)
(with-available-arglist (decoded-arglist)
(decode-arglist (arglist operator-form))
(enrich-decoded-arglist-with-extra-keywords decoded-arglist
(cons operator-form
argument-forms))))
(defmethod compute-enriched-decoded-arglist ((operator-form (eql 'with-open-file))
argument-forms)
(declare (ignore argument-forms))
(multiple-value-bind (decoded-arglist determining-args)
(call-next-method)
(let ((first-arg (first (arglist.required-args decoded-arglist)))
(open-arglist (compute-enriched-decoded-arglist 'open nil)))
(when (and (arglist-p first-arg) (arglist-p open-arglist))
(enrich-decoded-arglist-with-keywords
first-arg
(arglist.keyword-args open-arglist)
nil)))
(values decoded-arglist determining-args t)))
(defmethod compute-enriched-decoded-arglist ((operator-form (eql 'apply))
argument-forms)
(let ((function-name-form (car argument-forms)))
(when (and (listp function-name-form)
(length= function-name-form 2)
(memq (car function-name-form) '(quote function)))
(let ((function-name (cadr function-name-form)))
(when (valid-operator-symbol-p function-name)
(let ((function-arglist
(compute-enriched-decoded-arglist function-name
(cdr argument-forms))))
(return-from compute-enriched-decoded-arglist
(values (make-arglist :required-args
(list 'function)
:optional-args
(append
(mapcar #'(lambda (arg)
(make-optional-arg arg nil))
(arglist.required-args function-arglist))
(arglist.optional-args function-arglist))
:key-p
(arglist.key-p function-arglist)
:keyword-args
(arglist.keyword-args function-arglist)
:rest
'args
:allow-other-keys-p
(arglist.allow-other-keys-p function-arglist))
(list function-name-form)
t)))))))
(call-next-method))
(defun delete-given-args (decoded-arglist args)
"Delete given ARGS from DECODED-ARGLIST."
(macrolet ((pop-or-return (list)
`(if (null ,list)
(return-from do-decoded-arglist)
(pop ,list))))
(do-decoded-arglist decoded-arglist
(&provided ()
(assert (eq (pop-or-return args)
(pop (arglist.provided-args decoded-arglist)))))
(&required ()
(pop-or-return args)
(pop (arglist.required-args decoded-arglist)))
(&optional ()
(pop-or-return args)
(pop (arglist.optional-args decoded-arglist)))
(&key (keyword)
;; N.b. we consider a keyword to be given only when the keyword
;; _and_ a value has been given for it.
(loop for (key value) on args by #'cddr
when (and (eq keyword key) value)
do (setf (arglist.keyword-args decoded-arglist)
(remove keyword (arglist.keyword-args decoded-arglist)
:key #'keyword-arg.keyword))))))
decoded-arglist)
(defun remove-given-args (decoded-arglist args)
;; FIXME: We actually needa deep copy here.
(delete-given-args (copy-arglist decoded-arglist) args))
;;;; Arglist Retrieval
(defun arglist-from-form (form)
(if (null form)
:not-available
(arglist-dispatch (car form) (cdr form))))
(export 'arglist-dispatch)
(defgeneric arglist-dispatch (operator arguments)
;; Default method
(:method (operator arguments)
(unless (and (symbolp operator) (valid-operator-symbol-p operator))
(return-from arglist-dispatch :not-available))
(multiple-value-bind (decoded-arglist determining-args)
(compute-enriched-decoded-arglist operator arguments)
(with-available-arglist (arglist) decoded-arglist
;; replace some formal args by determining actual args
(setf arglist (delete-given-args arglist determining-args))
(setf (arglist.provided-args arglist) determining-args)
arglist))))
(defmethod arglist-dispatch ((operator (eql 'defmethod)) arguments)
(match (cons operator arguments)
(('defmethod (#'function-exists-p gf-name) . rest)
(let ((gf (fdefinition gf-name)))
(when (typep gf 'generic-function)
(with-available-arglist (arglist) (decode-arglist (arglist gf))
(let ((qualifiers (loop for x in rest
until (or (listp x) (empty-arg-p x))
collect x)))
(return-from arglist-dispatch
(make-arglist :provided-args (cons gf-name qualifiers)
:required-args (list arglist)
:rest "body" :body-p t)))))))
(_)) ; Fall through
(call-next-method))
(defmethod arglist-dispatch ((operator (eql 'define-compiler-macro)) arguments)
(match (cons operator arguments)
(('define-compiler-macro (#'function-exists-p gf-name) . _)
(let ((gf (fdefinition gf-name)))
(with-available-arglist (arglist) (decode-arglist (arglist gf))
(return-from arglist-dispatch
(make-arglist :provided-args (list gf-name)
:required-args (list arglist)
:rest "body" :body-p t)))))
(_)) ; Fall through
(call-next-method))
(defmethod arglist-dispatch ((operator (eql 'eval-when)) arguments)
(declare (ignore arguments))
(let ((eval-when-args '(:compile-toplevel :load-toplevel :execute)))
(make-arglist
:required-args (list (make-arglist :any-p t :any-args eval-when-args))
:rest '#:body :body-p t)))
(defmethod arglist-dispatch ((operator (eql 'declare)) arguments)
(let* ((declaration (cons operator (last arguments)))
(typedecl-arglist (arglist-for-type-declaration declaration)))
(if (arglist-available-p typedecl-arglist)
typedecl-arglist
(match declaration
(('declare ((#'consp typespec) . decl-args))
(with-available-arglist (typespec-arglist)
(decoded-arglist-for-type-specifier typespec)
(make-arglist
:required-args (list (make-arglist
:required-args (list typespec-arglist)
:rest '#:variables)))))
(('declare (decl-identifier . decl-args))
(decoded-arglist-for-declaration decl-identifier decl-args))
(_ (make-arglist :rest '#:declaration-specifiers))))))
(defmethod arglist-dispatch ((operator (eql 'declaim)) arguments)
(arglist-dispatch 'declare arguments))
(defun arglist-for-type-declaration (declaration)
(flet ((%arglist-for-type-declaration (identifier typespec rest-var-name)
(with-available-arglist (typespec-arglist)
(decoded-arglist-for-type-specifier typespec)
(make-arglist
:required-args (list (make-arglist
:provided-args (list identifier)
:required-args (list typespec-arglist)
:rest rest-var-name))))))
(match declaration
(('declare ('type (#'consp typespec) . decl-args))
(%arglist-for-type-declaration 'type typespec '#:variables))
(('declare ('ftype (#'consp typespec) . decl-args))
(%arglist-for-type-declaration 'ftype typespec '#:function-names))
(('declare ((#'consp typespec) . decl-args))
(with-available-arglist (typespec-arglist)
(decoded-arglist-for-type-specifier typespec)
(make-arglist
:required-args (list (make-arglist
:required-args (list typespec-arglist)
:rest '#:variables)))))
(_ :not-available))))
(defun decoded-arglist-for-declaration (decl-identifier decl-args)
(declare (ignore decl-args))
(with-available-arglist (arglist)
(decode-arglist (declaration-arglist decl-identifier))
(setf (arglist.provided-args arglist) (list decl-identifier))
(make-arglist :required-args (list arglist))))
(defun decoded-arglist-for-type-specifier (type-specifier)
(etypecase type-specifier
(arglist-dummy :not-available)
(cons (decoded-arglist-for-type-specifier (car type-specifier)))
(symbol
(with-available-arglist (arglist)
(decode-arglist (type-specifier-arglist type-specifier))
(setf (arglist.provided-args arglist) (list type-specifier))
arglist))))
;;; Slimefuns
;;; We work on a RAW-FORM, or BUFFER-FORM, which represent the form at
;;; user's point in Emacs. A RAW-FORM looks like
;;;
;;; ("FOO" ("BAR" ...) "QUUX" ("ZURP" SWANK::%CURSOR-MARKER%))
;;;
;;; The expression before the cursor marker is the expression where
;;; user's cursor points at. An explicit marker is necessary to
;;; disambiguate between
;;;
;;; ("IF" ("PRED")
;;; ("F" "X" "Y" %CURSOR-MARKER%))
;;;
;;; and
;;; ("IF" ("PRED")
;;; ("F" "X" "Y") %CURSOR-MARKER%)
;;; Notice that for a form like (FOO (BAR |) QUUX), where | denotes
;;; user's point, the following should be sent ("FOO" ("BAR" ""
;;; %CURSOR-MARKER%)). Only the forms up to point should be
;;; considered.
(defslimefun autodoc (raw-form &key print-right-margin)
"Return a list of two elements.
First, a string representing the arglist for the deepest subform in
RAW-FORM that does have an arglist. The highlighted parameter is
wrapped in ===> X <===.
Second, a boolean value telling whether the returned string can be cached."
(handler-bind ((serious-condition
#'(lambda (c)
(unless (debug-on-swank-error)
(let ((*print-right-margin* print-right-margin))
(return-from autodoc
(format nil "Arglist Error: \"~A\"" c)))))))
(with-buffer-syntax ()
(multiple-value-bind (form arglist obj-at-cursor form-path)
(find-subform-with-arglist (parse-raw-form raw-form))
(cond ((boundp-and-interesting obj-at-cursor)
(list (print-variable-to-string obj-at-cursor) nil))
(t
(list
(with-available-arglist (arglist) arglist
(decoded-arglist-to-string
arglist
:print-right-margin print-right-margin
:operator (car form)
:highlight (form-path-to-arglist-path form-path
form
arglist)))
t)))))))
(defun boundp-and-interesting (symbol)
(and symbol
(symbolp symbol)
(boundp symbol)
(not (memq symbol '(cl:t cl:nil)))
(not (keywordp symbol))))
(defun print-variable-to-string (symbol)
"Return a short description of VARIABLE-NAME, or NIL."
(let ((*print-pretty* t) (*print-level* 4)
(*print-length* 10) (*print-lines* 1)
(*print-readably* nil)
(value (symbol-value symbol)))
(call/truncated-output-to-string
75 (lambda (s)
(without-printing-errors (:object value :stream s)
(format s "~A ~A~S" symbol *echo-area-prefix* value))))))
(defslimefun complete-form (raw-form)
"Read FORM-STRING in the current buffer package, then complete it
by adding a template for the missing arguments."
;; We do not catch errors here because COMPLETE-FORM is an
;; interactive command, not automatically run in the background like
;; ARGLIST-FOR-ECHO-AREA.
(with-buffer-syntax ()
(multiple-value-bind (arglist provided-args)
(find-immediately-containing-arglist (parse-raw-form raw-form))
(with-available-arglist (arglist) arglist
(decoded-arglist-to-template-string
(delete-given-args arglist
(remove-if #'empty-arg-p provided-args
:from-end t :count 1))
:prefix "" :suffix "")))))
(defslimefun completions-for-keyword (keyword-string raw-form)
"Return a list of possible completions for KEYWORD-STRING relative
to the context provided by RAW-FORM."
(with-buffer-syntax ()
(let ((arglist (find-immediately-containing-arglist
(parse-raw-form raw-form))))
(when (arglist-available-p arglist)
;; It would be possible to complete keywords only if we are in
;; a keyword position, but it is not clear if we want that.
(let* ((keywords
(append (mapcar #'keyword-arg.keyword
(arglist.keyword-args arglist))
(remove-if-not #'keywordp (arglist.any-args arglist))))
(keyword-name
(tokenize-symbol keyword-string))
(matching-keywords
(find-matching-symbols-in-list
keyword-name keywords (make-compound-prefix-matcher #\-)))
(converter (completion-output-symbol-converter keyword-string))
(strings
(mapcar converter
(mapcar #'symbol-name matching-keywords)))
(completion-set
(format-completion-set strings nil "")))
(list completion-set
(longest-compound-prefix completion-set)))))))
(defparameter +cursor-marker+ '%cursor-marker%)
(defun find-subform-with-arglist (form)
"Returns four values:
The appropriate subform of `form' which is closest to the
+CURSOR-MARKER+ and whose operator is valid and has an
arglist. The +CURSOR-MARKER+ is removed from that subform.
Second value is the arglist. Local function and macro definitions
appearing in `form' into account.
Third value is the object in front of +CURSOR-MARKER+.
Fourth value is a form path to that object."
(labels
((yield-success (form local-ops)
(multiple-value-bind (form obj-at-cursor form-path)
(extract-cursor-marker form)
(values form
(let ((entry (assoc (car form) local-ops :test #'op=)))
(if entry
(decode-arglist (cdr entry))
(arglist-from-form form)))
obj-at-cursor
form-path)))
(yield-failure ()
(values nil :not-available))
(operator-p (operator local-ops)
(or (and (symbolp operator) (valid-operator-symbol-p operator))
(assoc operator local-ops :test #'op=)))
(op= (op1 op2)
(cond ((and (symbolp op1) (symbolp op2))
(eq op1 op2))
((and (arglist-dummy-p op1) (arglist-dummy-p op2))
(string= (arglist-dummy.string-representation op1)
(arglist-dummy.string-representation op2)))))
(grovel-form (form local-ops)
"Descend FORM top-down, always taking the rightest branch,
until +CURSOR-MARKER+."
(assert (listp form))
(destructuring-bind (operator . args) form
;; N.b. the user's cursor is at the rightmost, deepest
;; subform right before +CURSOR-MARKER+.
(let ((last-subform (car (last form)))
(new-ops))
(cond
((eq last-subform +cursor-marker+)
(if (operator-p operator local-ops)
(yield-success form local-ops)
(yield-failure)))
((not (operator-p operator local-ops))
(grovel-form last-subform local-ops))
;; Make sure to pick up the arglists of local
;; function/macro definitions.
((setq new-ops (extract-local-op-arglists operator args))
(multiple-value-or (grovel-form last-subform
(nconc new-ops local-ops))
(yield-success form local-ops)))
;; Some typespecs clash with function names, so we make
;; sure to bail out early.
((member operator '(cl:declare cl:declaim))
(yield-success form local-ops))
;; Mostly uninteresting, hence skip.
((memq operator '(cl:quote cl:function))
(yield-failure))
(t
(multiple-value-or (grovel-form last-subform local-ops)
(yield-success form local-ops))))))))
(if (null form)
(yield-failure)
(grovel-form form '()))))
(defun extract-cursor-marker (form)
"Returns three values: normalized `form' without +CURSOR-MARKER+,
the object in front of +CURSOR-MARKER+, and a form path to that
object."
(labels ((grovel (form last path)
(let ((result-form))
(loop for (car . cdr) on form do
(cond ((eql car +cursor-marker+)
(decf (first path))
(return-from grovel
(values (nreconc result-form cdr)
last
(nreverse path))))
((consp car)
(multiple-value-bind (new-car new-last new-path)
(grovel car last (cons 0 path))
(when new-path ; CAR contained cursor-marker?
(return-from grovel
(values (nreconc
(cons new-car result-form) cdr)
new-last
new-path))))))
(push car result-form)
(setq last car)
(incf (first path))
finally
(return-from grovel
(values (nreverse result-form) nil nil))))))
(grovel form nil (list 0))))
(defgeneric extract-local-op-arglists (operator args)
(:documentation
"If the form `(OPERATOR ,@ARGS) is a local operator binding form,
return a list of pairs (OP . ARGLIST) for each locally bound op.")
(:method (operator args)
(declare (ignore operator args))
nil)
;; FLET
(:method ((operator (eql 'cl:flet)) args)
(let ((defs (first args))
(body (rest args)))
(cond ((null body) nil) ; `(flet ((foo (x) |'
((atom defs) nil) ; `(flet ,foo (|'
(t (%collect-op/argl-alist defs)))))
;; LABELS
(:method ((operator (eql 'cl:labels)) args)
;; Notice that we only have information to "look backward" and
;; show arglists of previously occuring local functions.
(destructuring-bind (defs . body) args
(unless (or (atom defs) (null body)) ; `(labels ,foo (|'
(let ((current-def (car (last defs))))
(cond ((atom current-def) nil) ; `(labels ((foo (x) ...)|'
((not (null body))
(extract-local-op-arglists 'cl:flet args))
(t
(let ((def.body (cddr current-def)))
(when def.body
(%collect-op/argl-alist defs)))))))))
;; MACROLET
(:method ((operator (eql 'cl:macrolet)) args)
(extract-local-op-arglists 'cl:labels args)))
(defun %collect-op/argl-alist (defs)
(setq defs (remove-if-not #'(lambda (x)
;; Well-formed FLET/LABELS def?
(and (consp x) (second x)))
defs))
(loop for (name arglist . nil) in defs
collect (cons name arglist)))
(defun find-immediately-containing-arglist (form)
"Returns the arglist of the subform _immediately_ containing
+CURSOR-MARKER+ in `form'. Notice, however, that +CURSOR-MARKER+ may
be in a nested arglist \(e.g. `(WITH-OPEN-FILE (<here>'\), and the
arglist of the appropriate parent form \(WITH-OPEN-FILE\) will be
returned in that case."
(flet ((try (form-path form arglist)
(let* ((arglist-path (form-path-to-arglist-path form-path
form
arglist))
(argl (apply #'arglist-ref
arglist
arglist-path))
(args (apply #'provided-arguments-ref
(cdr form)
arglist
arglist-path)))
(when (and (arglist-p argl) (listp args))
(values argl args)))))
(multiple-value-bind (form arglist obj form-path)
(find-subform-with-arglist form)
(declare (ignore obj))
(with-available-arglist (arglist) arglist
;; First try the form the cursor is in (in case of a normal
;; form), then try the surrounding form (in case of a nested
;; macro form).
(multiple-value-or (try form-path form arglist)
(try (butlast form-path) form arglist)
:not-available)))))
(defun form-path-to-arglist-path (form-path form arglist)
"Convert a form path to an arglist path consisting of arglist
indices."
(labels ((convert (path args arglist)
(if (null path)
nil
(let* ((idx (car path))
(idx* (arglist-index idx args arglist))
(arglist* (and idx* (arglist-ref arglist idx*)))
(args* (and idx* (provided-arguments-ref args
arglist
idx*))))
;; The FORM-PATH may be more detailed than ARGLIST;
;; consider (defun foo (x y) ...), a form path may
;; point into the function's lambda-list, but the
;; arglist of DEFUN won't contain as much information.
;; So we only recurse if possible.
(cond ((null idx*)
nil)
((arglist-p arglist*)
(cons idx* (convert (cdr path) args* arglist*)))
(t
(list idx*)))))))
(convert
;; FORM contains irrelevant operator. Adjust FORM-PATH.
(cond ((null form-path) nil)
((equal form-path '(0)) nil)
(t
(destructuring-bind (car . cdr) form-path
(cons (1- car) cdr))))
(cdr form)
arglist)))
(defun arglist-index (provided-argument-index provided-arguments arglist)
"Return the arglist index into `arglist' for the parameter belonging
to the argument (NTH `provided-argument-index' `provided-arguments')."
(let ((positional-args# (positional-args-number arglist))
(arg-index provided-argument-index))
(with-struct (arglist. key-p rest) arglist
(cond
((< arg-index positional-args#) ; required + optional
arg-index)
((and (not key-p) (not rest)) ; more provided than allowed
nil)
((not key-p) ; rest + body
(assert (arglist.rest arglist))
positional-args#)
(t ; key
;; Find last provided &key parameter
(let* ((argument (nth arg-index provided-arguments))
(provided-keys (subseq provided-arguments positional-args#)))
(loop for (key value) on provided-keys by #'cddr
when (eq value argument)
return (match key
(('quote symbol) symbol)
(_ key)))))))))
(defun arglist-ref (arglist &rest indices)
"Returns the parameter in ARGLIST along the INDICIES path. Numbers
represent positional parameters (required, optional), keywords
represent key parameters."
(flet ((ref-positional-arg (arglist index)
(check-type index (integer 0 *))
(with-struct (arglist. provided-args required-args optional-args rest)
arglist
(loop for args in (list provided-args required-args
(mapcar #'optional-arg.arg-name optional-args))
for args# = (length args)
if (< index args#)
return (nth index args)
else
do (decf index args#)
finally (return (or rest nil)))))
(ref-keyword-arg (arglist keyword)
;; keyword argument may be any symbol,
;; not only from the KEYWORD package.
(let ((keyword (match keyword
(('quote symbol) symbol)
(_ keyword))))
(do-decoded-arglist arglist
(&key (kw arg) (when (eq kw keyword)
(return-from ref-keyword-arg arg)))))
nil))
(dolist (index indices)
(assert (arglist-p arglist))
(setq arglist (if (numberp index)
(ref-positional-arg arglist index)
(ref-keyword-arg arglist index))))
arglist))
(defun provided-arguments-ref (provided-args arglist &rest indices)
"Returns the argument in PROVIDED-ARGUMENT along the INDICES path
relative to ARGLIST."
(check-type arglist arglist)
(flet ((ref (provided-args arglist index)
(if (numberp index)
(nth index provided-args)
(let ((provided-keys (subseq provided-args
(positional-args-number arglist))))
(loop for (key value) on provided-keys
when (eq key index)
return value)))))
(dolist (idx indices)
(setq provided-args (ref provided-args arglist idx))
(setq arglist (arglist-ref arglist idx)))
provided-args))
(defun positional-args-number (arglist)
(+ (length (arglist.provided-args arglist))
(length (arglist.required-args arglist))
(length (arglist.optional-args arglist))))
(defun parse-raw-form (raw-form)
"Parse a RAW-FORM into a Lisp form. I.e. substitute strings by
symbols if already interned. For strings not already interned, use
ARGLIST-DUMMY."
(unless (null raw-form)
(loop for element in raw-form
collect (etypecase element
(string (read-conversatively element))
(list (parse-raw-form element))
(symbol (prog1 element
;; Comes after list, so ELEMENT can't be NIL.
(assert (eq element +cursor-marker+))))))))
(defun read-conversatively (string)
"Tries to find the symbol that's represented by STRING.
If it can't, this either means that STRING does not represent a
symbol, or that the symbol behind STRING would have to be freshly
interned. Because this function is supposed to be called from the
automatic arglist display stuff from Slime, interning freshly
symbols is a big no-no.
In such a case (that no symbol could be found), an object of type
ARGLIST-DUMMY is returned instead, which works as a placeholder
datum for subsequent logics to rely on."
(let* ((string (string-left-trim '(#\Space #\Tab #\Newline) string))
(length (length string))
(type (cond ((zerop length) nil)
((eql (aref string 0) #\')
:quoted-symbol)
((search "#'" string :end2 (min length 2))
:sharpquoted-symbol)
((char= (char string 0) (char string (1- length))
#\")
:string)
(t
:symbol))))
(multiple-value-bind (symbol found?)
(case type
(:symbol (parse-symbol string))
(:quoted-symbol (parse-symbol (subseq string 1)))
(:sharpquoted-symbol (parse-symbol (subseq string 2)))
(:string (values string t))
(t (values string nil)))
(if found?
(ecase type
(:symbol symbol)
(:quoted-symbol `(quote ,symbol))
(:sharpquoted-symbol `(function ,symbol))
(:string (if (> length 1)
(subseq string 1 (1- length))
string)))
(make-arglist-dummy string)))))
(defun test-print-arglist ()
(flet ((test (arglist string)
(let* ((*package* (find-package :swank))
(actual (decoded-arglist-to-string (decode-arglist arglist))))
(unless (string= actual string)
(warn "Test failed: ~S => ~S~% Expected: ~S"
arglist actual string)))))
(test '(function cons) "(function cons)")
(test '(quote cons) "(quote cons)")
(test '(&key (function #'+)) "(&key (function #'+))")
(test '(&whole x y z) "(y z)")
(test '(x &aux y z) "(x)")
(test '(x &environment env y) "(x y)")
(test '(&key ((function f))) "(&key ((function ..)))")
(test '(eval-when (&any :compile-toplevel :load-toplevel :execute) &body body)
"(eval-when (&any :compile-toplevel :load-toplevel :execute) &body body)")
(test '(declare (optimize &any (speed 1) (safety 1)))
"(declare (optimize &any (speed 1) (safety 1)))")
))
(defun test-arglist-ref ()
(macrolet ((soft-assert (form)
`(unless ,form
(warn "Assertion failed: ~S~%" ',form))))
(let ((sample (decode-arglist '(x &key ((:k (y z)))))))
(soft-assert (eq (arglist-ref sample 0) 'x))
(soft-assert (eq (arglist-ref sample :k 0) 'y))
(soft-assert (eq (arglist-ref sample :k 1) 'z))
(soft-assert (eq (provided-arguments-ref '(a :k (b c)) sample 0) 'a))
(soft-assert (eq (provided-arguments-ref '(a :k (b c)) sample :k 0) 'b))
(soft-assert (eq (provided-arguments-ref '(a :k (b c)) sample :k 1) 'c)))))
(test-print-arglist)
(test-arglist-ref)
(provide :swank-arglists)
|
[
{
"context": ";-*- Mode: Lisp -*-\n;;;; Author: Paul Dietz\n;;;; Created: Sun Apr 20 15:43:44 2003\n;;;; Cont",
"end": 49,
"score": 0.9998450875282288,
"start": 39,
"tag": "NAME",
"value": "Paul Dietz"
}
] |
ansi-tests/shiftf.lsp
|
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD
| 10 |
;-*- Mode: Lisp -*-
;;;; Author: Paul Dietz
;;;; Created: Sun Apr 20 15:43:44 2003
;;;; Contains: Tests of SHIFTF
(in-package :cl-test)
(deftest shiftf-order.1
(let ((x (vector 'a 'b 'c 'd 'e))
(i 2))
(values (shiftf (aref x (incf i)) (incf i)) x i))
d #(a b c 4 e) 4)
(deftest shiftf-order.2
(let ((x (vector 'a 'b 'c 'd 'e 'f 'g 'h))
(i 2))
(values (shiftf (aref x (incf i)) (aref x (incf i)) (incf i)) x i))
d #(a b c e 5 f g h) 5)
(deftest shiftf.1
(let ((x 0))
(values
x
(shiftf x 1)
x))
0 0 1)
(deftest shiftf.2
(let ((x 'a) (y 'b) (z 'c))
(values
x y z
(shiftf x y z 'd)
x y z))
a b c
a
b c d)
(deftest shiftf.3
(let ((x (vector 0 1 2 3)))
(values
(copy-seq x)
(shiftf (aref x (aref x 0))
(aref x (aref x 1))
(aref x (aref x 2))
(aref x (aref x 3))
'foo)
(copy-seq x)))
#(0 1 2 3)
0
#(1 2 3 foo))
;;; Test that explicit calls to macroexpand in subforms
;;; are done in the correct environment
(deftest shiftf.4
(macrolet
((%m (z) z))
(let ((x 1) (y 2))
(values
(shiftf (expand-in-current-env (%m x)) y 'foo)
x y)))
1 2 foo)
(deftest shiftf.5
(macrolet
((%m (z) z))
(let ((x 1) (y 2))
(values
(shiftf x (expand-in-current-env (%m y)) 'foo)
x y)))
1 2 foo)
(deftest shiftf.6
(macrolet
((%m (z) z))
(let ((x 1) (y 2))
(values
(shiftf x y (expand-in-current-env (%m 'foo)))
x y)))
1 2 foo)
;;; Need to add more shiftf tests here
|
9654
|
;-*- Mode: Lisp -*-
;;;; Author: <NAME>
;;;; Created: Sun Apr 20 15:43:44 2003
;;;; Contains: Tests of SHIFTF
(in-package :cl-test)
(deftest shiftf-order.1
(let ((x (vector 'a 'b 'c 'd 'e))
(i 2))
(values (shiftf (aref x (incf i)) (incf i)) x i))
d #(a b c 4 e) 4)
(deftest shiftf-order.2
(let ((x (vector 'a 'b 'c 'd 'e 'f 'g 'h))
(i 2))
(values (shiftf (aref x (incf i)) (aref x (incf i)) (incf i)) x i))
d #(a b c e 5 f g h) 5)
(deftest shiftf.1
(let ((x 0))
(values
x
(shiftf x 1)
x))
0 0 1)
(deftest shiftf.2
(let ((x 'a) (y 'b) (z 'c))
(values
x y z
(shiftf x y z 'd)
x y z))
a b c
a
b c d)
(deftest shiftf.3
(let ((x (vector 0 1 2 3)))
(values
(copy-seq x)
(shiftf (aref x (aref x 0))
(aref x (aref x 1))
(aref x (aref x 2))
(aref x (aref x 3))
'foo)
(copy-seq x)))
#(0 1 2 3)
0
#(1 2 3 foo))
;;; Test that explicit calls to macroexpand in subforms
;;; are done in the correct environment
(deftest shiftf.4
(macrolet
((%m (z) z))
(let ((x 1) (y 2))
(values
(shiftf (expand-in-current-env (%m x)) y 'foo)
x y)))
1 2 foo)
(deftest shiftf.5
(macrolet
((%m (z) z))
(let ((x 1) (y 2))
(values
(shiftf x (expand-in-current-env (%m y)) 'foo)
x y)))
1 2 foo)
(deftest shiftf.6
(macrolet
((%m (z) z))
(let ((x 1) (y 2))
(values
(shiftf x y (expand-in-current-env (%m 'foo)))
x y)))
1 2 foo)
;;; Need to add more shiftf tests here
| true |
;-*- Mode: Lisp -*-
;;;; Author: PI:NAME:<NAME>END_PI
;;;; Created: Sun Apr 20 15:43:44 2003
;;;; Contains: Tests of SHIFTF
(in-package :cl-test)
(deftest shiftf-order.1
(let ((x (vector 'a 'b 'c 'd 'e))
(i 2))
(values (shiftf (aref x (incf i)) (incf i)) x i))
d #(a b c 4 e) 4)
(deftest shiftf-order.2
(let ((x (vector 'a 'b 'c 'd 'e 'f 'g 'h))
(i 2))
(values (shiftf (aref x (incf i)) (aref x (incf i)) (incf i)) x i))
d #(a b c e 5 f g h) 5)
(deftest shiftf.1
(let ((x 0))
(values
x
(shiftf x 1)
x))
0 0 1)
(deftest shiftf.2
(let ((x 'a) (y 'b) (z 'c))
(values
x y z
(shiftf x y z 'd)
x y z))
a b c
a
b c d)
(deftest shiftf.3
(let ((x (vector 0 1 2 3)))
(values
(copy-seq x)
(shiftf (aref x (aref x 0))
(aref x (aref x 1))
(aref x (aref x 2))
(aref x (aref x 3))
'foo)
(copy-seq x)))
#(0 1 2 3)
0
#(1 2 3 foo))
;;; Test that explicit calls to macroexpand in subforms
;;; are done in the correct environment
(deftest shiftf.4
(macrolet
((%m (z) z))
(let ((x 1) (y 2))
(values
(shiftf (expand-in-current-env (%m x)) y 'foo)
x y)))
1 2 foo)
(deftest shiftf.5
(macrolet
((%m (z) z))
(let ((x 1) (y 2))
(values
(shiftf x (expand-in-current-env (%m y)) 'foo)
x y)))
1 2 foo)
(deftest shiftf.6
(macrolet
((%m (z) z))
(let ((x 1) (y 2))
(values
(shiftf x y (expand-in-current-env (%m 'foo)))
x y)))
1 2 foo)
;;; Need to add more shiftf tests here
|
[
{
"context": ";; copyright (c) 2020 by Andrei Borac\n\n(require \"packer.rb\")\n",
"end": 37,
"score": 0.999872624874115,
"start": 25,
"tag": "NAME",
"value": "Andrei Borac"
}
] |
stdlib/packer.lisp
|
AndreiBorac/nocaml
| 2 |
;; copyright (c) 2020 by Andrei Borac
(require "packer.rb")
|
98118
|
;; copyright (c) 2020 by <NAME>
(require "packer.rb")
| true |
;; copyright (c) 2020 by PI:NAME:<NAME>END_PI
(require "packer.rb")
|
[
{
"context": " DEALINGS IN THE SOFTWARE.\n;\n; Original authors: Sol Swords <[email protected]>\n\n(in-package \"IPASIR\")\n\n(i",
"end": 1424,
"score": 0.9998652338981628,
"start": 1414,
"tag": "NAME",
"value": "Sol Swords"
},
{
"context": "N THE SOFTWARE.\n;\n; Original authors: Sol Swords <[email protected]>\n\n(in-package \"IPASIR\")\n\n(include-book \"ipasir-lo",
"end": 1446,
"score": 0.99992835521698,
"start": 1426,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/centaur/ipasir/ipasir-tools.lisp
|
solswords/acl2
| 0 |
; IPASIR - Link from ACL2 to IPASIR incremental sat solvers
; Copyright (C) 2017 Centaur Technology
;
; Contact:
; Centaur Technology Formal Verification Group
; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA.
; http://www.centtech.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original authors: Sol Swords <[email protected]>
(in-package "IPASIR")
(include-book "ipasir-logic")
(local (include-book "centaur/satlink/cnf-basics" :dir :system))
(local (include-book "std/basic/arith-equivs" :dir :system))
(local (in-theory (disable ifix)))
(defmacro l- (x)
`(lit-negate ,x))
(defmacro l+ (x)
`(lit-fix ,x))
(local (defthm eval-lit-of-negate-strong
(implies (equal (lit-fix z) (lit-negate x))
(equal (eval-lit z assign)
(b-not (eval-lit x assign))))
:hints(("Goal" :in-theory (enable eval-lit)))))
(define ipasir-cancel-new-clause (ipasir)
:parents (ipasir-formula)
:short "Identity function in execution; in the logic, ensures that the new-clause
field of the ipasir is empty, which it must be by the guard."
:long "<p>See @(see ipasir-add-binary), particularly
@('ipasir-add-binary-formula'), for an example: if we didn't use this function
at the beginning of @('ipasir-add-binary'), then we'd need a hypothesis of
@('(not (ipasir$a->new-clause ipasir))') in
@('ipasir-add-binary-formula').</p>"
:guard (non-exec (not (ipasir$a->new-clause ipasir)))
:inline t
:returns (new-ipasir)
(mbe :logic (non-exec (change-ipasir$a ipasir :new-clause nil))
:exec ipasir)
///
(defret ipasir-cancel-new-clause-status
(equal (ipasir$a->status new-ipasir)
(ipasir$a->status ipasir)))
(defret ipasir-cancel-new-clause-formula
(equal (ipasir$a->formula new-ipasir)
(ipasir$a->formula ipasir)))
(defret ipasir-cancel-new-clause-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-cancel-new-clause-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir)))
(in-theory (disable (ipasir-cancel-new-clause))))
(define ipasir-cancel-assumption (ipasir)
:parents (ipasir-formula)
:short "Identity function in execution; in the logic, ensures that the assumption
field of the ipasir is empty, which it must be by the guard."
:long "<p>See @(see ipasir-add-binary), particularly
@('ipasir-add-binary-formula'), for an example: if we didn't use this function
at the beginning of @('ipasir-add-binary'), then we'd need a hypothesis of
@('(not (ipasir$a->assumption ipasir))') in
@('ipasir-add-binary-formula').</p>"
:guard (non-exec (not (ipasir$a->assumption ipasir)))
:inline t
:returns (new-ipasir)
(mbe :logic (non-exec (change-ipasir$a ipasir :assumption nil))
:exec ipasir)
///
(defret ipasir-cancel-assumption-status
(equal (ipasir$a->status new-ipasir)
(ipasir$a->status ipasir)))
(defret ipasir-cancel-assumption-formula
(equal (ipasir$a->formula new-ipasir)
(ipasir$a->formula ipasir)))
(defret ipasir-cancel-assumption-assumption
(not (ipasir$a->assumption new-ipasir)))
(defret ipasir-cancel-assumption-new-clause
(equal (ipasir$a->new-clause new-ipasir)
(ipasir$a->new-clause ipasir)))
(in-theory (disable (ipasir-cancel-assumption))))
(define ipasir-add-empty (ipasir)
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add an empty clause. Likely useless because the solver is then unsat forever."
(b* ((ipasir (ipasir-cancel-new-clause ipasir)))
(ipasir-finalize-clause ipasir))
///
(defret ipasir-add-empty-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-empty-formula
(equal (ipasir$a->formula new-ipasir)
(cons nil (ipasir$a->formula ipasir))))
(defretd ipasir-add-empty-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env) 0)
:hints(("Goal" :in-theory (enable eval-formula eval-clause))))
(defret ipasir-add-empty-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-empty-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-add-unary (ipasir (a litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add a unary clause to the formula, permanently restricting the given literal to be true."
(b* ((ipasir (ipasir-cancel-new-clause ipasir))
(ipasir (ipasir-add-lit ipasir a)))
(ipasir-finalize-clause ipasir))
///
(defret ipasir-add-unary-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-unary-formula
(equal (ipasir$a->formula new-ipasir)
(cons (lit-list-fix (list a)) (ipasir$a->formula ipasir))))
(defret ipasir-add-unary-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (eval-lit a env)
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-add-unary-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-unary-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-add-binary (ipasir (a litp) (b litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add a binary clause to the formula"
(b* ((ipasir (ipasir-cancel-new-clause ipasir))
(ipasir (ipasir-add-lit ipasir a))
(ipasir (ipasir-add-lit ipasir b)))
(ipasir-finalize-clause ipasir))
///
(defret ipasir-add-binary-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-binary-formula
(equal (ipasir$a->formula new-ipasir)
(cons (lit-list-fix (list b a))
(ipasir$a->formula ipasir))))
(defret ipasir-add-binary-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) assum)
(eval-formula (cons (list a b)
(ipasir$a->formula ipasir))
assum)))
(defret ipasir-add-binary-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-binary-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-add-ternary (ipasir (a litp) (b litp) (c litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add a ternary clause to the formula"
(b* ((ipasir (ipasir-cancel-new-clause ipasir))
(ipasir (ipasir-add-lit ipasir a))
(ipasir (ipasir-add-lit ipasir b))
(ipasir (ipasir-add-lit ipasir c)))
(ipasir-finalize-clause ipasir))
///
(defret ipasir-add-ternary-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-ternary-formula
(equal (ipasir$a->formula new-ipasir)
(cons (lit-list-fix (list c b a))
(ipasir$a->formula ipasir))))
(defret ipasir-add-ternary-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) assum)
(eval-formula (cons (list c b a)
(ipasir$a->formula ipasir))
assum)))
(defret ipasir-add-ternary-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-ternary-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
;; Note: at one point we defined this form of add-clause which checked for
;; duplicate/contradictory literals. But we think all reasonable solvers
;; already do this for us so we'll just use the non-checking versions for now.
;; (define ipasir-add-4ary (ipasir (a litp) (b litp) (c litp) (d litp))
;; :guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
;; (not (ipasir$a->new-clause ipasir))))
;; :returns (new-ipasir)
;; :parents (ipasir-formula)
;; (b* ((a (lit-fix a))
;; (b (lit-fix b))
;; (c (lit-fix c))
;; (d (lit-fix d))
;; (ipasir (ipasir-cancel-new-clause ipasir))
;; ((when (or (int= (- a) b) (int= (- a) c) (int= (- a) d)
;; (int= (- b) c) (int= (- b) d)
;; (int= (- c) d)))
;; (ipasir-input ipasir))
;; (ipasir (ipasir-add-lit ipasir a))
;; (ipasir (if (int= a b)
;; (if (int= a c)
;; (if (int= a d)
;; ipasir
;; (ipasir-add-lit ipasir d))
;; (b* ((ipasir (ipasir-add-lit ipasir c)))
;; (if (or (int= a d) (int= c d))
;; ipasir
;; (ipasir-add-lit ipasir d))))
;; (b* ((ipasir (ipasir-add-lit ipasir b)))
;; (if (or (int= a c) (int= b c))
;; (if (or (int= a d) (int= b d))
;; ipasir
;; (ipasir-add-lit ipasir d))
;; (b* ((ipasir (ipasir-add-lit ipasir c)))
;; (if (or (int= a d) (int= b d) (int= c d))
;; ipasir
;; (ipasir-add-lit ipasir d))))))))
;; (ipasir-finalize-clause ipasir))
;; ///
;; (defret ipasir-add-4ary-status
;; (equal (ipasir$a->status new-ipasir) :input))
;; (defret ipasir-add-4ary-formula
;; (equal (eval-formula (ipasir$a->formula new-ipasir) env)
;; (eval-formula (cons (list d c b a)
;; (ipasir$a->formula ipasir))
;; env)))
;; (defret ipasir-add-4ary-new-clause
;; (not (ipasir$a->new-clause new-ipasir)))
;; (defret ipasir-add-4ary-assumption
;; (equal (ipasir$a->assumption new-ipasir)
;; (ipasir$a->assumption ipasir))))
(define ipasir-add-4ary (ipasir (a litp) (b litp) (c litp) (d litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add a 4-literal clause to the formula"
(b* ((ipasir (ipasir-cancel-new-clause ipasir))
(ipasir (ipasir-add-lit ipasir a))
(ipasir (ipasir-add-lit ipasir b))
(ipasir (ipasir-add-lit ipasir c))
(ipasir (ipasir-add-lit ipasir d)))
(ipasir-finalize-clause ipasir))
///
(defret ipasir-add-4ary-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-4ary-formula
(equal (ipasir$a->formula new-ipasir)
(cons (lit-list-fix (list d c b a))
(ipasir$a->formula ipasir))))
(defret ipasir-add-4ary-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(eval-formula (cons (list d c b a)
(ipasir$a->formula ipasir))
env)))
(defret ipasir-add-4ary-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-4ary-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-add-list-aux (ipasir (clause lit-listp))
:guard (non-exec (not (eq (ipasir$a->status ipasir) :undef)))
:returns (new-ipasir)
(if (atom clause)
(ipasir-finalize-clause ipasir)
(b* ((ipasir (ipasir-add-lit ipasir (car clause))))
(ipasir-add-list-aux ipasir (cdr clause))))
///
(defret ipasir-add-list-aux-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-list-aux-formula
(equal (ipasir$a->formula new-ipasir)
(cons (revappend (lit-list-fix clause) (ipasir$a->new-clause ipasir))
(ipasir$a->formula ipasir))))
(defret ipasir-add-list-aux-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(eval-formula (cons (append clause (ipasir$a->new-clause ipasir))
(ipasir$a->formula ipasir))
env)))
(defret ipasir-add-list-aux-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-list-aux-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-add-list (ipasir (clause lit-listp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add a clause (given as a list of literals) to the formula"
(b* ((ipasir (ipasir-cancel-new-clause ipasir)))
(ipasir-add-list-aux ipasir clause))
///
(defret ipasir-add-list-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-list-formula
(equal (ipasir$a->formula new-ipasir)
(cons (rev (lit-list-fix clause))
(ipasir$a->formula ipasir)))
:hints(("Goal" :in-theory (enable ipasir-add-list-aux-formula))))
(defret ipasir-add-list-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(eval-formula (cons clause (ipasir$a->formula ipasir))
env)))
(defret ipasir-add-list-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-list-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define rev-each (x)
(if (atom x)
nil
(cons (rev (car x))
(rev-each (cdr x)))))
(define ipasir-add-clauses (ipasir (clauses lit-list-listp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add a list of clauses to the formula"
(if (atom clauses)
(b* ((ipasir (ipasir-cancel-new-clause ipasir)))
(ipasir-input ipasir))
(b* ((ipasir (ipasir-add-list ipasir (car clauses))))
(ipasir-add-clauses ipasir (cdr clauses))))
///
(defret ipasir-add-clauses-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-clauses-formula
(equal (ipasir$a->formula new-ipasir)
(append (rev (rev-each (lit-list-list-fix clauses)))
(ipasir$a->formula ipasir)))
:hints(("Goal" :in-theory (enable lit-list-list-fix
rev-each
ipasir-add-list-formula))))
(defret ipasir-add-clauses-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(eval-formula (append clauses (ipasir$a->formula ipasir))
env)))
(defret ipasir-add-clauses-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-clauses-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-set-buf (ipasir (out litp) (in litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add clauses restricting @('out') to have the same value as @('in')."
(b* ((ipasir (ipasir-cancel-new-clause ipasir))
(ipasir (ipasir-add-binary ipasir (l- out) in)))
(ipasir-add-binary ipasir out (l- in)))
///
(defret ipasir-set-buf-status
(equal (ipasir$a->status new-ipasir) :input))
(defret ipasir-set-buf-formula
(implies (syntaxp (not (equal ipasir ''nil)))
(equal (ipasir$a->formula new-ipasir)
(append (ipasir$a->formula (ipasir-set-buf nil out in))
(ipasir$a->formula ipasir))))
:hints(("Goal" :in-theory (e/d (ipasir-add-binary-formula)
((ipasir-cancel-new-clause))))))
(defret ipasir-set-buf-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (b-eqv (eval-lit out env)
(eval-lit in env))
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-set-buf-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-set-buf-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-set-and (ipasir (out litp) (in1 litp) (in2 litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add clauses restricting @('out') to be the AND of @('in1') and @('in2')."
(b* ((ipasir (ipasir-cancel-new-clause ipasir))
;; ~in1 -> ~out
(ipasir (ipasir-add-binary ipasir (l- out) in1))
;; ~in2 -> ~out
(ipasir (ipasir-add-binary ipasir (l- out) in2)))
;; in1 & in2 -> out
(ipasir-add-ternary ipasir out (l- in1) (l- in2)))
///
(defret ipasir-set-and-status
(equal (ipasir$a->status new-ipasir) :input))
(defret ipasir-set-and-formula
(implies (syntaxp (not (equal ipasir ''nil)))
(equal (ipasir$a->formula new-ipasir)
(append (ipasir$a->formula (ipasir-set-and nil out in1 in2))
(ipasir$a->formula ipasir))))
:hints(("Goal" :in-theory (e/d (ipasir-add-binary-formula
ipasir-add-ternary-formula)
((ipasir-cancel-new-clause))))))
(defret ipasir-set-and-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (b-eqv (eval-lit out env)
(b-and (eval-lit in1 env)
(eval-lit in2 env)))
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-set-and-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-set-and-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-set-or (ipasir (out litp) (in1 litp) (in2 litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:inline t
:short "Add clauses restricting @('out') to be the OR of @('in1') and @('in2')."
(ipasir-set-and ipasir (l- out) (l- in1) (l- in2))
///
(defret ipasir-set-or-status
(equal (ipasir$a->status new-ipasir) :input))
(defret ipasir-set-or-formula
(implies (syntaxp (not (equal ipasir ''nil)))
(equal (ipasir$a->formula new-ipasir)
(append (ipasir$a->formula (ipasir-set-or nil out in1 in2))
(ipasir$a->formula ipasir)))))
(defret ipasir-set-or-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (b-eqv (eval-lit out env)
(b-ior (eval-lit in1 env)
(eval-lit in2 env)))
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-set-or-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-set-or-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-set-mux (ipasir (out litp) (test litp) (then litp) (else litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add clauses restricting @('out') to be @('(if test then else)')."
(b* (;; test & then -> out
(ipasir (ipasir-add-ternary ipasir out (l- test) (l- then)))
;; test & ~then -> ~out
(ipasir (ipasir-add-ternary ipasir (l- out) (l- test) then))
;; ~test & else -> out
(ipasir (ipasir-add-ternary ipasir out test (l- else)))
;; ~test & ~else -> ~out
(ipasir (ipasir-add-ternary ipasir (l- out) test else))
;; the above clauses are sufficient but the two below are helpful,
;; then & else -> out
(ipasir (ipasir-add-ternary ipasir out (l- then) (l- else)))
;; ~then & ~else -> ~out
(ipasir (ipasir-add-ternary ipasir (l- out) then else)))
ipasir)
///
(defret ipasir-set-mux-status
(equal (ipasir$a->status new-ipasir) :input))
(defret ipasir-set-mux-formula
(implies (syntaxp (not (equal ipasir ''nil)))
(equal (ipasir$a->formula new-ipasir)
(append (ipasir$a->formula (ipasir-set-mux nil out test then else))
(ipasir$a->formula ipasir))))
:hints(("Goal" :in-theory (e/d (ipasir-add-ternary-formula)))))
(defret ipasir-set-mux-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (b-eqv (eval-lit out env)
(b-ite (eval-lit test env)
(eval-lit then env)
(eval-lit else env)))
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-set-mux-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-set-mux-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-set-xor (ipasir (out litp) (in1 litp) (in2 litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add clauses restricting @('out') to be the XOR of @('in1') and @('in2')."
(b* (;; in1 & in2 -> ~out
(ipasir (ipasir-add-ternary ipasir out (l- in1) in2))
;; in1 & ~in2 -> out
(ipasir (ipasir-add-ternary ipasir (l- out) (l- in1) (l- in2)))
;; ~in1 & in2 -> out
(ipasir (ipasir-add-ternary ipasir out in1 (l- in2)))
;; ~in1 & ~in2 -> ~out
(ipasir (ipasir-add-ternary ipasir (l- out) in1 in2)))
ipasir)
///
(defret ipasir-set-xor-status
(equal (ipasir$a->status new-ipasir) :input))
(defret ipasir-set-xor-formula
(implies (syntaxp (not (equal ipasir ''nil)))
(equal (ipasir$a->formula new-ipasir)
(append (ipasir$a->formula (ipasir-set-xor nil out in1 in2))
(ipasir$a->formula ipasir))))
:hints(("Goal" :in-theory (e/d (ipasir-add-ternary-formula)))))
(defret ipasir-set-xor-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (b-eqv (eval-lit out env)
(b-xor (eval-lit in1 env)
(eval-lit in2 env)))
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-set-xor-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-set-xor-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-set-iff (ipasir (out litp) (in1 litp) (in2 litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:inline t
:short "Add clauses restricting @('out') to be the IFF of @('in1') and @('in2')."
(ipasir-set-xor ipasir out (l- in1) in2)
///
(defret ipasir-set-iff-status
(equal (ipasir$a->status new-ipasir) :input))
(defret ipasir-set-iff-formula
(implies (syntaxp (not (equal ipasir ''nil)))
(equal (ipasir$a->formula new-ipasir)
(append (ipasir$a->formula (ipasir-set-iff nil out in1 in2))
(ipasir$a->formula ipasir)))))
(defret ipasir-set-iff-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (b-eqv (eval-lit out env)
(b-eqv (eval-lit in1 env)
(eval-lit in2 env)))
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-set-iff-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-set-iff-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(defxdoc ipasir-formula
:parents (ipasir)
:short "Tools for constructing the ipasir formula."
:long "<p>We provide several helper functions for constructing formulas:</p>
<ul>
<li>@('ipasir-add-*ary') add a fixed-length clause to the formula</li>
<li>@('ipasir-add-list') adds a clause from a list to the formula</li>
<li>@('ipasir-set-*') add clauses restricting the literal @('out') to be
assigned the given logical function of the other input literals</li>
</ul>
<p>These all have a guard saying that the current new-clause of the ipasir
stobj must be empty, and they preserve this property unconditionally.</p>")
(defthm ipasir-solve$a-unsat-implies-unsat
(b* (((ipasir$a solver))
((mv status (ipasir$a new-solver)) (ipasir-solve$a solver)))
(implies (and (equal formula solver.formula)
(equal 1 (eval-formula formula env$))
(case-split (equal 1 (eval-cube solver.assumption env$))))
(not (equal status :unsat))))
:hints (("goal" :use ipasir-solve$a-unsat
:in-theory (e/d (satlink::eval-cube-when-subset)
(ipasir-solve$a-unsat)))))
(defthm ipasir-solve$a-unsat-when-not-sat-or-failed
(b* (((mv status &) (ipasir-solve$a solver)))
(implies (not (equal status :sat))
(equal (equal status :failed)
(not (equal status :unsat))))))
(define ipasir-check-equivalence (ipasir (lit1 litp) (lit2 litp))
:returns (mv (status (or (equal status :failed)
(equal status :unsat)
(equal status :sat))
:rule-classes ((:forward-chaining :trigger-terms (status))))
new-ipasir)
:guard (non-exec (and (not (eq (ipasir::ipasir$a->status ipasir) :undef))
(not (ipasir::ipasir$a->assumption ipasir))
(not (ipasir::ipasir$a->new-clause ipasir))))
(b* ((ipasir (ipasir-cancel-assumption ipasir))
(ipasir (ipasir-assume ipasir lit1))
(ipasir (ipasir-assume ipasir (lit-negate lit2)))
((mv status1 ipasir) (ipasir-solve ipasir))
((when (or (eq status1 :sat)
(eq status1 :failed)))
(mv status1 ipasir))
(ipasir (ipasir-assume ipasir (lit-negate lit1)))
(ipasir (ipasir-assume ipasir lit2)))
(ipasir-solve ipasir))
///
(defret ipasir-check-equivalence-ipasir-status
(equal (ipasir$a->status new-ipasir)
(case status
(:sat :sat)
(:unsat :unsat)
(otherwise :input))))
(defret ipasir-check-equivalence-formula
(equal (ipasir$a->formula new-ipasir)
(ipasir$a->formula ipasir)))
(defret ipasir-check-equivalence-new-clause
(equal (ipasir$a->new-clause new-ipasir) nil))
(defret ipasir-check-equivalence-assumption
(equal (ipasir$a->assumption new-ipasir) nil))
(defret ipasir-check-equivalence-unsat
(implies (and (equal 1 (eval-formula (ipasir$a->formula ipasir) env))
(case-split (not (equal (eval-lit lit1 env)
(eval-lit lit2 env)))))
(not (equal status :unsat)))))
|
67094
|
; IPASIR - Link from ACL2 to IPASIR incremental sat solvers
; Copyright (C) 2017 Centaur Technology
;
; Contact:
; Centaur Technology Formal Verification Group
; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA.
; http://www.centtech.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original authors: <NAME> <<EMAIL>>
(in-package "IPASIR")
(include-book "ipasir-logic")
(local (include-book "centaur/satlink/cnf-basics" :dir :system))
(local (include-book "std/basic/arith-equivs" :dir :system))
(local (in-theory (disable ifix)))
(defmacro l- (x)
`(lit-negate ,x))
(defmacro l+ (x)
`(lit-fix ,x))
(local (defthm eval-lit-of-negate-strong
(implies (equal (lit-fix z) (lit-negate x))
(equal (eval-lit z assign)
(b-not (eval-lit x assign))))
:hints(("Goal" :in-theory (enable eval-lit)))))
(define ipasir-cancel-new-clause (ipasir)
:parents (ipasir-formula)
:short "Identity function in execution; in the logic, ensures that the new-clause
field of the ipasir is empty, which it must be by the guard."
:long "<p>See @(see ipasir-add-binary), particularly
@('ipasir-add-binary-formula'), for an example: if we didn't use this function
at the beginning of @('ipasir-add-binary'), then we'd need a hypothesis of
@('(not (ipasir$a->new-clause ipasir))') in
@('ipasir-add-binary-formula').</p>"
:guard (non-exec (not (ipasir$a->new-clause ipasir)))
:inline t
:returns (new-ipasir)
(mbe :logic (non-exec (change-ipasir$a ipasir :new-clause nil))
:exec ipasir)
///
(defret ipasir-cancel-new-clause-status
(equal (ipasir$a->status new-ipasir)
(ipasir$a->status ipasir)))
(defret ipasir-cancel-new-clause-formula
(equal (ipasir$a->formula new-ipasir)
(ipasir$a->formula ipasir)))
(defret ipasir-cancel-new-clause-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-cancel-new-clause-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir)))
(in-theory (disable (ipasir-cancel-new-clause))))
(define ipasir-cancel-assumption (ipasir)
:parents (ipasir-formula)
:short "Identity function in execution; in the logic, ensures that the assumption
field of the ipasir is empty, which it must be by the guard."
:long "<p>See @(see ipasir-add-binary), particularly
@('ipasir-add-binary-formula'), for an example: if we didn't use this function
at the beginning of @('ipasir-add-binary'), then we'd need a hypothesis of
@('(not (ipasir$a->assumption ipasir))') in
@('ipasir-add-binary-formula').</p>"
:guard (non-exec (not (ipasir$a->assumption ipasir)))
:inline t
:returns (new-ipasir)
(mbe :logic (non-exec (change-ipasir$a ipasir :assumption nil))
:exec ipasir)
///
(defret ipasir-cancel-assumption-status
(equal (ipasir$a->status new-ipasir)
(ipasir$a->status ipasir)))
(defret ipasir-cancel-assumption-formula
(equal (ipasir$a->formula new-ipasir)
(ipasir$a->formula ipasir)))
(defret ipasir-cancel-assumption-assumption
(not (ipasir$a->assumption new-ipasir)))
(defret ipasir-cancel-assumption-new-clause
(equal (ipasir$a->new-clause new-ipasir)
(ipasir$a->new-clause ipasir)))
(in-theory (disable (ipasir-cancel-assumption))))
(define ipasir-add-empty (ipasir)
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add an empty clause. Likely useless because the solver is then unsat forever."
(b* ((ipasir (ipasir-cancel-new-clause ipasir)))
(ipasir-finalize-clause ipasir))
///
(defret ipasir-add-empty-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-empty-formula
(equal (ipasir$a->formula new-ipasir)
(cons nil (ipasir$a->formula ipasir))))
(defretd ipasir-add-empty-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env) 0)
:hints(("Goal" :in-theory (enable eval-formula eval-clause))))
(defret ipasir-add-empty-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-empty-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-add-unary (ipasir (a litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add a unary clause to the formula, permanently restricting the given literal to be true."
(b* ((ipasir (ipasir-cancel-new-clause ipasir))
(ipasir (ipasir-add-lit ipasir a)))
(ipasir-finalize-clause ipasir))
///
(defret ipasir-add-unary-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-unary-formula
(equal (ipasir$a->formula new-ipasir)
(cons (lit-list-fix (list a)) (ipasir$a->formula ipasir))))
(defret ipasir-add-unary-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (eval-lit a env)
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-add-unary-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-unary-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-add-binary (ipasir (a litp) (b litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add a binary clause to the formula"
(b* ((ipasir (ipasir-cancel-new-clause ipasir))
(ipasir (ipasir-add-lit ipasir a))
(ipasir (ipasir-add-lit ipasir b)))
(ipasir-finalize-clause ipasir))
///
(defret ipasir-add-binary-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-binary-formula
(equal (ipasir$a->formula new-ipasir)
(cons (lit-list-fix (list b a))
(ipasir$a->formula ipasir))))
(defret ipasir-add-binary-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) assum)
(eval-formula (cons (list a b)
(ipasir$a->formula ipasir))
assum)))
(defret ipasir-add-binary-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-binary-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-add-ternary (ipasir (a litp) (b litp) (c litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add a ternary clause to the formula"
(b* ((ipasir (ipasir-cancel-new-clause ipasir))
(ipasir (ipasir-add-lit ipasir a))
(ipasir (ipasir-add-lit ipasir b))
(ipasir (ipasir-add-lit ipasir c)))
(ipasir-finalize-clause ipasir))
///
(defret ipasir-add-ternary-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-ternary-formula
(equal (ipasir$a->formula new-ipasir)
(cons (lit-list-fix (list c b a))
(ipasir$a->formula ipasir))))
(defret ipasir-add-ternary-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) assum)
(eval-formula (cons (list c b a)
(ipasir$a->formula ipasir))
assum)))
(defret ipasir-add-ternary-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-ternary-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
;; Note: at one point we defined this form of add-clause which checked for
;; duplicate/contradictory literals. But we think all reasonable solvers
;; already do this for us so we'll just use the non-checking versions for now.
;; (define ipasir-add-4ary (ipasir (a litp) (b litp) (c litp) (d litp))
;; :guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
;; (not (ipasir$a->new-clause ipasir))))
;; :returns (new-ipasir)
;; :parents (ipasir-formula)
;; (b* ((a (lit-fix a))
;; (b (lit-fix b))
;; (c (lit-fix c))
;; (d (lit-fix d))
;; (ipasir (ipasir-cancel-new-clause ipasir))
;; ((when (or (int= (- a) b) (int= (- a) c) (int= (- a) d)
;; (int= (- b) c) (int= (- b) d)
;; (int= (- c) d)))
;; (ipasir-input ipasir))
;; (ipasir (ipasir-add-lit ipasir a))
;; (ipasir (if (int= a b)
;; (if (int= a c)
;; (if (int= a d)
;; ipasir
;; (ipasir-add-lit ipasir d))
;; (b* ((ipasir (ipasir-add-lit ipasir c)))
;; (if (or (int= a d) (int= c d))
;; ipasir
;; (ipasir-add-lit ipasir d))))
;; (b* ((ipasir (ipasir-add-lit ipasir b)))
;; (if (or (int= a c) (int= b c))
;; (if (or (int= a d) (int= b d))
;; ipasir
;; (ipasir-add-lit ipasir d))
;; (b* ((ipasir (ipasir-add-lit ipasir c)))
;; (if (or (int= a d) (int= b d) (int= c d))
;; ipasir
;; (ipasir-add-lit ipasir d))))))))
;; (ipasir-finalize-clause ipasir))
;; ///
;; (defret ipasir-add-4ary-status
;; (equal (ipasir$a->status new-ipasir) :input))
;; (defret ipasir-add-4ary-formula
;; (equal (eval-formula (ipasir$a->formula new-ipasir) env)
;; (eval-formula (cons (list d c b a)
;; (ipasir$a->formula ipasir))
;; env)))
;; (defret ipasir-add-4ary-new-clause
;; (not (ipasir$a->new-clause new-ipasir)))
;; (defret ipasir-add-4ary-assumption
;; (equal (ipasir$a->assumption new-ipasir)
;; (ipasir$a->assumption ipasir))))
(define ipasir-add-4ary (ipasir (a litp) (b litp) (c litp) (d litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add a 4-literal clause to the formula"
(b* ((ipasir (ipasir-cancel-new-clause ipasir))
(ipasir (ipasir-add-lit ipasir a))
(ipasir (ipasir-add-lit ipasir b))
(ipasir (ipasir-add-lit ipasir c))
(ipasir (ipasir-add-lit ipasir d)))
(ipasir-finalize-clause ipasir))
///
(defret ipasir-add-4ary-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-4ary-formula
(equal (ipasir$a->formula new-ipasir)
(cons (lit-list-fix (list d c b a))
(ipasir$a->formula ipasir))))
(defret ipasir-add-4ary-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(eval-formula (cons (list d c b a)
(ipasir$a->formula ipasir))
env)))
(defret ipasir-add-4ary-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-4ary-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-add-list-aux (ipasir (clause lit-listp))
:guard (non-exec (not (eq (ipasir$a->status ipasir) :undef)))
:returns (new-ipasir)
(if (atom clause)
(ipasir-finalize-clause ipasir)
(b* ((ipasir (ipasir-add-lit ipasir (car clause))))
(ipasir-add-list-aux ipasir (cdr clause))))
///
(defret ipasir-add-list-aux-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-list-aux-formula
(equal (ipasir$a->formula new-ipasir)
(cons (revappend (lit-list-fix clause) (ipasir$a->new-clause ipasir))
(ipasir$a->formula ipasir))))
(defret ipasir-add-list-aux-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(eval-formula (cons (append clause (ipasir$a->new-clause ipasir))
(ipasir$a->formula ipasir))
env)))
(defret ipasir-add-list-aux-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-list-aux-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-add-list (ipasir (clause lit-listp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add a clause (given as a list of literals) to the formula"
(b* ((ipasir (ipasir-cancel-new-clause ipasir)))
(ipasir-add-list-aux ipasir clause))
///
(defret ipasir-add-list-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-list-formula
(equal (ipasir$a->formula new-ipasir)
(cons (rev (lit-list-fix clause))
(ipasir$a->formula ipasir)))
:hints(("Goal" :in-theory (enable ipasir-add-list-aux-formula))))
(defret ipasir-add-list-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(eval-formula (cons clause (ipasir$a->formula ipasir))
env)))
(defret ipasir-add-list-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-list-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define rev-each (x)
(if (atom x)
nil
(cons (rev (car x))
(rev-each (cdr x)))))
(define ipasir-add-clauses (ipasir (clauses lit-list-listp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add a list of clauses to the formula"
(if (atom clauses)
(b* ((ipasir (ipasir-cancel-new-clause ipasir)))
(ipasir-input ipasir))
(b* ((ipasir (ipasir-add-list ipasir (car clauses))))
(ipasir-add-clauses ipasir (cdr clauses))))
///
(defret ipasir-add-clauses-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-clauses-formula
(equal (ipasir$a->formula new-ipasir)
(append (rev (rev-each (lit-list-list-fix clauses)))
(ipasir$a->formula ipasir)))
:hints(("Goal" :in-theory (enable lit-list-list-fix
rev-each
ipasir-add-list-formula))))
(defret ipasir-add-clauses-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(eval-formula (append clauses (ipasir$a->formula ipasir))
env)))
(defret ipasir-add-clauses-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-clauses-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-set-buf (ipasir (out litp) (in litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add clauses restricting @('out') to have the same value as @('in')."
(b* ((ipasir (ipasir-cancel-new-clause ipasir))
(ipasir (ipasir-add-binary ipasir (l- out) in)))
(ipasir-add-binary ipasir out (l- in)))
///
(defret ipasir-set-buf-status
(equal (ipasir$a->status new-ipasir) :input))
(defret ipasir-set-buf-formula
(implies (syntaxp (not (equal ipasir ''nil)))
(equal (ipasir$a->formula new-ipasir)
(append (ipasir$a->formula (ipasir-set-buf nil out in))
(ipasir$a->formula ipasir))))
:hints(("Goal" :in-theory (e/d (ipasir-add-binary-formula)
((ipasir-cancel-new-clause))))))
(defret ipasir-set-buf-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (b-eqv (eval-lit out env)
(eval-lit in env))
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-set-buf-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-set-buf-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-set-and (ipasir (out litp) (in1 litp) (in2 litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add clauses restricting @('out') to be the AND of @('in1') and @('in2')."
(b* ((ipasir (ipasir-cancel-new-clause ipasir))
;; ~in1 -> ~out
(ipasir (ipasir-add-binary ipasir (l- out) in1))
;; ~in2 -> ~out
(ipasir (ipasir-add-binary ipasir (l- out) in2)))
;; in1 & in2 -> out
(ipasir-add-ternary ipasir out (l- in1) (l- in2)))
///
(defret ipasir-set-and-status
(equal (ipasir$a->status new-ipasir) :input))
(defret ipasir-set-and-formula
(implies (syntaxp (not (equal ipasir ''nil)))
(equal (ipasir$a->formula new-ipasir)
(append (ipasir$a->formula (ipasir-set-and nil out in1 in2))
(ipasir$a->formula ipasir))))
:hints(("Goal" :in-theory (e/d (ipasir-add-binary-formula
ipasir-add-ternary-formula)
((ipasir-cancel-new-clause))))))
(defret ipasir-set-and-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (b-eqv (eval-lit out env)
(b-and (eval-lit in1 env)
(eval-lit in2 env)))
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-set-and-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-set-and-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-set-or (ipasir (out litp) (in1 litp) (in2 litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:inline t
:short "Add clauses restricting @('out') to be the OR of @('in1') and @('in2')."
(ipasir-set-and ipasir (l- out) (l- in1) (l- in2))
///
(defret ipasir-set-or-status
(equal (ipasir$a->status new-ipasir) :input))
(defret ipasir-set-or-formula
(implies (syntaxp (not (equal ipasir ''nil)))
(equal (ipasir$a->formula new-ipasir)
(append (ipasir$a->formula (ipasir-set-or nil out in1 in2))
(ipasir$a->formula ipasir)))))
(defret ipasir-set-or-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (b-eqv (eval-lit out env)
(b-ior (eval-lit in1 env)
(eval-lit in2 env)))
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-set-or-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-set-or-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-set-mux (ipasir (out litp) (test litp) (then litp) (else litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add clauses restricting @('out') to be @('(if test then else)')."
(b* (;; test & then -> out
(ipasir (ipasir-add-ternary ipasir out (l- test) (l- then)))
;; test & ~then -> ~out
(ipasir (ipasir-add-ternary ipasir (l- out) (l- test) then))
;; ~test & else -> out
(ipasir (ipasir-add-ternary ipasir out test (l- else)))
;; ~test & ~else -> ~out
(ipasir (ipasir-add-ternary ipasir (l- out) test else))
;; the above clauses are sufficient but the two below are helpful,
;; then & else -> out
(ipasir (ipasir-add-ternary ipasir out (l- then) (l- else)))
;; ~then & ~else -> ~out
(ipasir (ipasir-add-ternary ipasir (l- out) then else)))
ipasir)
///
(defret ipasir-set-mux-status
(equal (ipasir$a->status new-ipasir) :input))
(defret ipasir-set-mux-formula
(implies (syntaxp (not (equal ipasir ''nil)))
(equal (ipasir$a->formula new-ipasir)
(append (ipasir$a->formula (ipasir-set-mux nil out test then else))
(ipasir$a->formula ipasir))))
:hints(("Goal" :in-theory (e/d (ipasir-add-ternary-formula)))))
(defret ipasir-set-mux-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (b-eqv (eval-lit out env)
(b-ite (eval-lit test env)
(eval-lit then env)
(eval-lit else env)))
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-set-mux-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-set-mux-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-set-xor (ipasir (out litp) (in1 litp) (in2 litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add clauses restricting @('out') to be the XOR of @('in1') and @('in2')."
(b* (;; in1 & in2 -> ~out
(ipasir (ipasir-add-ternary ipasir out (l- in1) in2))
;; in1 & ~in2 -> out
(ipasir (ipasir-add-ternary ipasir (l- out) (l- in1) (l- in2)))
;; ~in1 & in2 -> out
(ipasir (ipasir-add-ternary ipasir out in1 (l- in2)))
;; ~in1 & ~in2 -> ~out
(ipasir (ipasir-add-ternary ipasir (l- out) in1 in2)))
ipasir)
///
(defret ipasir-set-xor-status
(equal (ipasir$a->status new-ipasir) :input))
(defret ipasir-set-xor-formula
(implies (syntaxp (not (equal ipasir ''nil)))
(equal (ipasir$a->formula new-ipasir)
(append (ipasir$a->formula (ipasir-set-xor nil out in1 in2))
(ipasir$a->formula ipasir))))
:hints(("Goal" :in-theory (e/d (ipasir-add-ternary-formula)))))
(defret ipasir-set-xor-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (b-eqv (eval-lit out env)
(b-xor (eval-lit in1 env)
(eval-lit in2 env)))
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-set-xor-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-set-xor-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-set-iff (ipasir (out litp) (in1 litp) (in2 litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:inline t
:short "Add clauses restricting @('out') to be the IFF of @('in1') and @('in2')."
(ipasir-set-xor ipasir out (l- in1) in2)
///
(defret ipasir-set-iff-status
(equal (ipasir$a->status new-ipasir) :input))
(defret ipasir-set-iff-formula
(implies (syntaxp (not (equal ipasir ''nil)))
(equal (ipasir$a->formula new-ipasir)
(append (ipasir$a->formula (ipasir-set-iff nil out in1 in2))
(ipasir$a->formula ipasir)))))
(defret ipasir-set-iff-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (b-eqv (eval-lit out env)
(b-eqv (eval-lit in1 env)
(eval-lit in2 env)))
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-set-iff-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-set-iff-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(defxdoc ipasir-formula
:parents (ipasir)
:short "Tools for constructing the ipasir formula."
:long "<p>We provide several helper functions for constructing formulas:</p>
<ul>
<li>@('ipasir-add-*ary') add a fixed-length clause to the formula</li>
<li>@('ipasir-add-list') adds a clause from a list to the formula</li>
<li>@('ipasir-set-*') add clauses restricting the literal @('out') to be
assigned the given logical function of the other input literals</li>
</ul>
<p>These all have a guard saying that the current new-clause of the ipasir
stobj must be empty, and they preserve this property unconditionally.</p>")
(defthm ipasir-solve$a-unsat-implies-unsat
(b* (((ipasir$a solver))
((mv status (ipasir$a new-solver)) (ipasir-solve$a solver)))
(implies (and (equal formula solver.formula)
(equal 1 (eval-formula formula env$))
(case-split (equal 1 (eval-cube solver.assumption env$))))
(not (equal status :unsat))))
:hints (("goal" :use ipasir-solve$a-unsat
:in-theory (e/d (satlink::eval-cube-when-subset)
(ipasir-solve$a-unsat)))))
(defthm ipasir-solve$a-unsat-when-not-sat-or-failed
(b* (((mv status &) (ipasir-solve$a solver)))
(implies (not (equal status :sat))
(equal (equal status :failed)
(not (equal status :unsat))))))
(define ipasir-check-equivalence (ipasir (lit1 litp) (lit2 litp))
:returns (mv (status (or (equal status :failed)
(equal status :unsat)
(equal status :sat))
:rule-classes ((:forward-chaining :trigger-terms (status))))
new-ipasir)
:guard (non-exec (and (not (eq (ipasir::ipasir$a->status ipasir) :undef))
(not (ipasir::ipasir$a->assumption ipasir))
(not (ipasir::ipasir$a->new-clause ipasir))))
(b* ((ipasir (ipasir-cancel-assumption ipasir))
(ipasir (ipasir-assume ipasir lit1))
(ipasir (ipasir-assume ipasir (lit-negate lit2)))
((mv status1 ipasir) (ipasir-solve ipasir))
((when (or (eq status1 :sat)
(eq status1 :failed)))
(mv status1 ipasir))
(ipasir (ipasir-assume ipasir (lit-negate lit1)))
(ipasir (ipasir-assume ipasir lit2)))
(ipasir-solve ipasir))
///
(defret ipasir-check-equivalence-ipasir-status
(equal (ipasir$a->status new-ipasir)
(case status
(:sat :sat)
(:unsat :unsat)
(otherwise :input))))
(defret ipasir-check-equivalence-formula
(equal (ipasir$a->formula new-ipasir)
(ipasir$a->formula ipasir)))
(defret ipasir-check-equivalence-new-clause
(equal (ipasir$a->new-clause new-ipasir) nil))
(defret ipasir-check-equivalence-assumption
(equal (ipasir$a->assumption new-ipasir) nil))
(defret ipasir-check-equivalence-unsat
(implies (and (equal 1 (eval-formula (ipasir$a->formula ipasir) env))
(case-split (not (equal (eval-lit lit1 env)
(eval-lit lit2 env)))))
(not (equal status :unsat)))))
| true |
; IPASIR - Link from ACL2 to IPASIR incremental sat solvers
; Copyright (C) 2017 Centaur Technology
;
; Contact:
; Centaur Technology Formal Verification Group
; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA.
; http://www.centtech.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original authors: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
(in-package "IPASIR")
(include-book "ipasir-logic")
(local (include-book "centaur/satlink/cnf-basics" :dir :system))
(local (include-book "std/basic/arith-equivs" :dir :system))
(local (in-theory (disable ifix)))
(defmacro l- (x)
`(lit-negate ,x))
(defmacro l+ (x)
`(lit-fix ,x))
(local (defthm eval-lit-of-negate-strong
(implies (equal (lit-fix z) (lit-negate x))
(equal (eval-lit z assign)
(b-not (eval-lit x assign))))
:hints(("Goal" :in-theory (enable eval-lit)))))
(define ipasir-cancel-new-clause (ipasir)
:parents (ipasir-formula)
:short "Identity function in execution; in the logic, ensures that the new-clause
field of the ipasir is empty, which it must be by the guard."
:long "<p>See @(see ipasir-add-binary), particularly
@('ipasir-add-binary-formula'), for an example: if we didn't use this function
at the beginning of @('ipasir-add-binary'), then we'd need a hypothesis of
@('(not (ipasir$a->new-clause ipasir))') in
@('ipasir-add-binary-formula').</p>"
:guard (non-exec (not (ipasir$a->new-clause ipasir)))
:inline t
:returns (new-ipasir)
(mbe :logic (non-exec (change-ipasir$a ipasir :new-clause nil))
:exec ipasir)
///
(defret ipasir-cancel-new-clause-status
(equal (ipasir$a->status new-ipasir)
(ipasir$a->status ipasir)))
(defret ipasir-cancel-new-clause-formula
(equal (ipasir$a->formula new-ipasir)
(ipasir$a->formula ipasir)))
(defret ipasir-cancel-new-clause-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-cancel-new-clause-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir)))
(in-theory (disable (ipasir-cancel-new-clause))))
(define ipasir-cancel-assumption (ipasir)
:parents (ipasir-formula)
:short "Identity function in execution; in the logic, ensures that the assumption
field of the ipasir is empty, which it must be by the guard."
:long "<p>See @(see ipasir-add-binary), particularly
@('ipasir-add-binary-formula'), for an example: if we didn't use this function
at the beginning of @('ipasir-add-binary'), then we'd need a hypothesis of
@('(not (ipasir$a->assumption ipasir))') in
@('ipasir-add-binary-formula').</p>"
:guard (non-exec (not (ipasir$a->assumption ipasir)))
:inline t
:returns (new-ipasir)
(mbe :logic (non-exec (change-ipasir$a ipasir :assumption nil))
:exec ipasir)
///
(defret ipasir-cancel-assumption-status
(equal (ipasir$a->status new-ipasir)
(ipasir$a->status ipasir)))
(defret ipasir-cancel-assumption-formula
(equal (ipasir$a->formula new-ipasir)
(ipasir$a->formula ipasir)))
(defret ipasir-cancel-assumption-assumption
(not (ipasir$a->assumption new-ipasir)))
(defret ipasir-cancel-assumption-new-clause
(equal (ipasir$a->new-clause new-ipasir)
(ipasir$a->new-clause ipasir)))
(in-theory (disable (ipasir-cancel-assumption))))
(define ipasir-add-empty (ipasir)
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add an empty clause. Likely useless because the solver is then unsat forever."
(b* ((ipasir (ipasir-cancel-new-clause ipasir)))
(ipasir-finalize-clause ipasir))
///
(defret ipasir-add-empty-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-empty-formula
(equal (ipasir$a->formula new-ipasir)
(cons nil (ipasir$a->formula ipasir))))
(defretd ipasir-add-empty-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env) 0)
:hints(("Goal" :in-theory (enable eval-formula eval-clause))))
(defret ipasir-add-empty-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-empty-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-add-unary (ipasir (a litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add a unary clause to the formula, permanently restricting the given literal to be true."
(b* ((ipasir (ipasir-cancel-new-clause ipasir))
(ipasir (ipasir-add-lit ipasir a)))
(ipasir-finalize-clause ipasir))
///
(defret ipasir-add-unary-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-unary-formula
(equal (ipasir$a->formula new-ipasir)
(cons (lit-list-fix (list a)) (ipasir$a->formula ipasir))))
(defret ipasir-add-unary-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (eval-lit a env)
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-add-unary-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-unary-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-add-binary (ipasir (a litp) (b litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add a binary clause to the formula"
(b* ((ipasir (ipasir-cancel-new-clause ipasir))
(ipasir (ipasir-add-lit ipasir a))
(ipasir (ipasir-add-lit ipasir b)))
(ipasir-finalize-clause ipasir))
///
(defret ipasir-add-binary-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-binary-formula
(equal (ipasir$a->formula new-ipasir)
(cons (lit-list-fix (list b a))
(ipasir$a->formula ipasir))))
(defret ipasir-add-binary-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) assum)
(eval-formula (cons (list a b)
(ipasir$a->formula ipasir))
assum)))
(defret ipasir-add-binary-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-binary-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-add-ternary (ipasir (a litp) (b litp) (c litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add a ternary clause to the formula"
(b* ((ipasir (ipasir-cancel-new-clause ipasir))
(ipasir (ipasir-add-lit ipasir a))
(ipasir (ipasir-add-lit ipasir b))
(ipasir (ipasir-add-lit ipasir c)))
(ipasir-finalize-clause ipasir))
///
(defret ipasir-add-ternary-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-ternary-formula
(equal (ipasir$a->formula new-ipasir)
(cons (lit-list-fix (list c b a))
(ipasir$a->formula ipasir))))
(defret ipasir-add-ternary-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) assum)
(eval-formula (cons (list c b a)
(ipasir$a->formula ipasir))
assum)))
(defret ipasir-add-ternary-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-ternary-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
;; Note: at one point we defined this form of add-clause which checked for
;; duplicate/contradictory literals. But we think all reasonable solvers
;; already do this for us so we'll just use the non-checking versions for now.
;; (define ipasir-add-4ary (ipasir (a litp) (b litp) (c litp) (d litp))
;; :guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
;; (not (ipasir$a->new-clause ipasir))))
;; :returns (new-ipasir)
;; :parents (ipasir-formula)
;; (b* ((a (lit-fix a))
;; (b (lit-fix b))
;; (c (lit-fix c))
;; (d (lit-fix d))
;; (ipasir (ipasir-cancel-new-clause ipasir))
;; ((when (or (int= (- a) b) (int= (- a) c) (int= (- a) d)
;; (int= (- b) c) (int= (- b) d)
;; (int= (- c) d)))
;; (ipasir-input ipasir))
;; (ipasir (ipasir-add-lit ipasir a))
;; (ipasir (if (int= a b)
;; (if (int= a c)
;; (if (int= a d)
;; ipasir
;; (ipasir-add-lit ipasir d))
;; (b* ((ipasir (ipasir-add-lit ipasir c)))
;; (if (or (int= a d) (int= c d))
;; ipasir
;; (ipasir-add-lit ipasir d))))
;; (b* ((ipasir (ipasir-add-lit ipasir b)))
;; (if (or (int= a c) (int= b c))
;; (if (or (int= a d) (int= b d))
;; ipasir
;; (ipasir-add-lit ipasir d))
;; (b* ((ipasir (ipasir-add-lit ipasir c)))
;; (if (or (int= a d) (int= b d) (int= c d))
;; ipasir
;; (ipasir-add-lit ipasir d))))))))
;; (ipasir-finalize-clause ipasir))
;; ///
;; (defret ipasir-add-4ary-status
;; (equal (ipasir$a->status new-ipasir) :input))
;; (defret ipasir-add-4ary-formula
;; (equal (eval-formula (ipasir$a->formula new-ipasir) env)
;; (eval-formula (cons (list d c b a)
;; (ipasir$a->formula ipasir))
;; env)))
;; (defret ipasir-add-4ary-new-clause
;; (not (ipasir$a->new-clause new-ipasir)))
;; (defret ipasir-add-4ary-assumption
;; (equal (ipasir$a->assumption new-ipasir)
;; (ipasir$a->assumption ipasir))))
(define ipasir-add-4ary (ipasir (a litp) (b litp) (c litp) (d litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add a 4-literal clause to the formula"
(b* ((ipasir (ipasir-cancel-new-clause ipasir))
(ipasir (ipasir-add-lit ipasir a))
(ipasir (ipasir-add-lit ipasir b))
(ipasir (ipasir-add-lit ipasir c))
(ipasir (ipasir-add-lit ipasir d)))
(ipasir-finalize-clause ipasir))
///
(defret ipasir-add-4ary-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-4ary-formula
(equal (ipasir$a->formula new-ipasir)
(cons (lit-list-fix (list d c b a))
(ipasir$a->formula ipasir))))
(defret ipasir-add-4ary-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(eval-formula (cons (list d c b a)
(ipasir$a->formula ipasir))
env)))
(defret ipasir-add-4ary-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-4ary-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-add-list-aux (ipasir (clause lit-listp))
:guard (non-exec (not (eq (ipasir$a->status ipasir) :undef)))
:returns (new-ipasir)
(if (atom clause)
(ipasir-finalize-clause ipasir)
(b* ((ipasir (ipasir-add-lit ipasir (car clause))))
(ipasir-add-list-aux ipasir (cdr clause))))
///
(defret ipasir-add-list-aux-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-list-aux-formula
(equal (ipasir$a->formula new-ipasir)
(cons (revappend (lit-list-fix clause) (ipasir$a->new-clause ipasir))
(ipasir$a->formula ipasir))))
(defret ipasir-add-list-aux-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(eval-formula (cons (append clause (ipasir$a->new-clause ipasir))
(ipasir$a->formula ipasir))
env)))
(defret ipasir-add-list-aux-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-list-aux-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-add-list (ipasir (clause lit-listp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add a clause (given as a list of literals) to the formula"
(b* ((ipasir (ipasir-cancel-new-clause ipasir)))
(ipasir-add-list-aux ipasir clause))
///
(defret ipasir-add-list-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-list-formula
(equal (ipasir$a->formula new-ipasir)
(cons (rev (lit-list-fix clause))
(ipasir$a->formula ipasir)))
:hints(("Goal" :in-theory (enable ipasir-add-list-aux-formula))))
(defret ipasir-add-list-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(eval-formula (cons clause (ipasir$a->formula ipasir))
env)))
(defret ipasir-add-list-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-list-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define rev-each (x)
(if (atom x)
nil
(cons (rev (car x))
(rev-each (cdr x)))))
(define ipasir-add-clauses (ipasir (clauses lit-list-listp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add a list of clauses to the formula"
(if (atom clauses)
(b* ((ipasir (ipasir-cancel-new-clause ipasir)))
(ipasir-input ipasir))
(b* ((ipasir (ipasir-add-list ipasir (car clauses))))
(ipasir-add-clauses ipasir (cdr clauses))))
///
(defret ipasir-add-clauses-status
(equal (ipasir$a->status new-ipasir) :input))
(defretd ipasir-add-clauses-formula
(equal (ipasir$a->formula new-ipasir)
(append (rev (rev-each (lit-list-list-fix clauses)))
(ipasir$a->formula ipasir)))
:hints(("Goal" :in-theory (enable lit-list-list-fix
rev-each
ipasir-add-list-formula))))
(defret ipasir-add-clauses-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(eval-formula (append clauses (ipasir$a->formula ipasir))
env)))
(defret ipasir-add-clauses-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-add-clauses-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-set-buf (ipasir (out litp) (in litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add clauses restricting @('out') to have the same value as @('in')."
(b* ((ipasir (ipasir-cancel-new-clause ipasir))
(ipasir (ipasir-add-binary ipasir (l- out) in)))
(ipasir-add-binary ipasir out (l- in)))
///
(defret ipasir-set-buf-status
(equal (ipasir$a->status new-ipasir) :input))
(defret ipasir-set-buf-formula
(implies (syntaxp (not (equal ipasir ''nil)))
(equal (ipasir$a->formula new-ipasir)
(append (ipasir$a->formula (ipasir-set-buf nil out in))
(ipasir$a->formula ipasir))))
:hints(("Goal" :in-theory (e/d (ipasir-add-binary-formula)
((ipasir-cancel-new-clause))))))
(defret ipasir-set-buf-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (b-eqv (eval-lit out env)
(eval-lit in env))
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-set-buf-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-set-buf-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-set-and (ipasir (out litp) (in1 litp) (in2 litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add clauses restricting @('out') to be the AND of @('in1') and @('in2')."
(b* ((ipasir (ipasir-cancel-new-clause ipasir))
;; ~in1 -> ~out
(ipasir (ipasir-add-binary ipasir (l- out) in1))
;; ~in2 -> ~out
(ipasir (ipasir-add-binary ipasir (l- out) in2)))
;; in1 & in2 -> out
(ipasir-add-ternary ipasir out (l- in1) (l- in2)))
///
(defret ipasir-set-and-status
(equal (ipasir$a->status new-ipasir) :input))
(defret ipasir-set-and-formula
(implies (syntaxp (not (equal ipasir ''nil)))
(equal (ipasir$a->formula new-ipasir)
(append (ipasir$a->formula (ipasir-set-and nil out in1 in2))
(ipasir$a->formula ipasir))))
:hints(("Goal" :in-theory (e/d (ipasir-add-binary-formula
ipasir-add-ternary-formula)
((ipasir-cancel-new-clause))))))
(defret ipasir-set-and-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (b-eqv (eval-lit out env)
(b-and (eval-lit in1 env)
(eval-lit in2 env)))
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-set-and-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-set-and-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-set-or (ipasir (out litp) (in1 litp) (in2 litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:inline t
:short "Add clauses restricting @('out') to be the OR of @('in1') and @('in2')."
(ipasir-set-and ipasir (l- out) (l- in1) (l- in2))
///
(defret ipasir-set-or-status
(equal (ipasir$a->status new-ipasir) :input))
(defret ipasir-set-or-formula
(implies (syntaxp (not (equal ipasir ''nil)))
(equal (ipasir$a->formula new-ipasir)
(append (ipasir$a->formula (ipasir-set-or nil out in1 in2))
(ipasir$a->formula ipasir)))))
(defret ipasir-set-or-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (b-eqv (eval-lit out env)
(b-ior (eval-lit in1 env)
(eval-lit in2 env)))
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-set-or-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-set-or-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-set-mux (ipasir (out litp) (test litp) (then litp) (else litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add clauses restricting @('out') to be @('(if test then else)')."
(b* (;; test & then -> out
(ipasir (ipasir-add-ternary ipasir out (l- test) (l- then)))
;; test & ~then -> ~out
(ipasir (ipasir-add-ternary ipasir (l- out) (l- test) then))
;; ~test & else -> out
(ipasir (ipasir-add-ternary ipasir out test (l- else)))
;; ~test & ~else -> ~out
(ipasir (ipasir-add-ternary ipasir (l- out) test else))
;; the above clauses are sufficient but the two below are helpful,
;; then & else -> out
(ipasir (ipasir-add-ternary ipasir out (l- then) (l- else)))
;; ~then & ~else -> ~out
(ipasir (ipasir-add-ternary ipasir (l- out) then else)))
ipasir)
///
(defret ipasir-set-mux-status
(equal (ipasir$a->status new-ipasir) :input))
(defret ipasir-set-mux-formula
(implies (syntaxp (not (equal ipasir ''nil)))
(equal (ipasir$a->formula new-ipasir)
(append (ipasir$a->formula (ipasir-set-mux nil out test then else))
(ipasir$a->formula ipasir))))
:hints(("Goal" :in-theory (e/d (ipasir-add-ternary-formula)))))
(defret ipasir-set-mux-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (b-eqv (eval-lit out env)
(b-ite (eval-lit test env)
(eval-lit then env)
(eval-lit else env)))
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-set-mux-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-set-mux-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-set-xor (ipasir (out litp) (in1 litp) (in2 litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:short "Add clauses restricting @('out') to be the XOR of @('in1') and @('in2')."
(b* (;; in1 & in2 -> ~out
(ipasir (ipasir-add-ternary ipasir out (l- in1) in2))
;; in1 & ~in2 -> out
(ipasir (ipasir-add-ternary ipasir (l- out) (l- in1) (l- in2)))
;; ~in1 & in2 -> out
(ipasir (ipasir-add-ternary ipasir out in1 (l- in2)))
;; ~in1 & ~in2 -> ~out
(ipasir (ipasir-add-ternary ipasir (l- out) in1 in2)))
ipasir)
///
(defret ipasir-set-xor-status
(equal (ipasir$a->status new-ipasir) :input))
(defret ipasir-set-xor-formula
(implies (syntaxp (not (equal ipasir ''nil)))
(equal (ipasir$a->formula new-ipasir)
(append (ipasir$a->formula (ipasir-set-xor nil out in1 in2))
(ipasir$a->formula ipasir))))
:hints(("Goal" :in-theory (e/d (ipasir-add-ternary-formula)))))
(defret ipasir-set-xor-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (b-eqv (eval-lit out env)
(b-xor (eval-lit in1 env)
(eval-lit in2 env)))
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-set-xor-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-set-xor-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(define ipasir-set-iff (ipasir (out litp) (in1 litp) (in2 litp))
:guard (non-exec (and (not (eq (ipasir$a->status ipasir) :undef))
(not (ipasir$a->new-clause ipasir))))
:returns (new-ipasir)
:parents (ipasir-formula)
:inline t
:short "Add clauses restricting @('out') to be the IFF of @('in1') and @('in2')."
(ipasir-set-xor ipasir out (l- in1) in2)
///
(defret ipasir-set-iff-status
(equal (ipasir$a->status new-ipasir) :input))
(defret ipasir-set-iff-formula
(implies (syntaxp (not (equal ipasir ''nil)))
(equal (ipasir$a->formula new-ipasir)
(append (ipasir$a->formula (ipasir-set-iff nil out in1 in2))
(ipasir$a->formula ipasir)))))
(defret ipasir-set-iff-eval-formula
(equal (eval-formula (ipasir$a->formula new-ipasir) env)
(b-and (b-eqv (eval-lit out env)
(b-eqv (eval-lit in1 env)
(eval-lit in2 env)))
(eval-formula (ipasir$a->formula ipasir) env))))
(defret ipasir-set-iff-new-clause
(not (ipasir$a->new-clause new-ipasir)))
(defret ipasir-set-iff-assumption
(equal (ipasir$a->assumption new-ipasir)
(ipasir$a->assumption ipasir))))
(defxdoc ipasir-formula
:parents (ipasir)
:short "Tools for constructing the ipasir formula."
:long "<p>We provide several helper functions for constructing formulas:</p>
<ul>
<li>@('ipasir-add-*ary') add a fixed-length clause to the formula</li>
<li>@('ipasir-add-list') adds a clause from a list to the formula</li>
<li>@('ipasir-set-*') add clauses restricting the literal @('out') to be
assigned the given logical function of the other input literals</li>
</ul>
<p>These all have a guard saying that the current new-clause of the ipasir
stobj must be empty, and they preserve this property unconditionally.</p>")
(defthm ipasir-solve$a-unsat-implies-unsat
(b* (((ipasir$a solver))
((mv status (ipasir$a new-solver)) (ipasir-solve$a solver)))
(implies (and (equal formula solver.formula)
(equal 1 (eval-formula formula env$))
(case-split (equal 1 (eval-cube solver.assumption env$))))
(not (equal status :unsat))))
:hints (("goal" :use ipasir-solve$a-unsat
:in-theory (e/d (satlink::eval-cube-when-subset)
(ipasir-solve$a-unsat)))))
(defthm ipasir-solve$a-unsat-when-not-sat-or-failed
(b* (((mv status &) (ipasir-solve$a solver)))
(implies (not (equal status :sat))
(equal (equal status :failed)
(not (equal status :unsat))))))
(define ipasir-check-equivalence (ipasir (lit1 litp) (lit2 litp))
:returns (mv (status (or (equal status :failed)
(equal status :unsat)
(equal status :sat))
:rule-classes ((:forward-chaining :trigger-terms (status))))
new-ipasir)
:guard (non-exec (and (not (eq (ipasir::ipasir$a->status ipasir) :undef))
(not (ipasir::ipasir$a->assumption ipasir))
(not (ipasir::ipasir$a->new-clause ipasir))))
(b* ((ipasir (ipasir-cancel-assumption ipasir))
(ipasir (ipasir-assume ipasir lit1))
(ipasir (ipasir-assume ipasir (lit-negate lit2)))
((mv status1 ipasir) (ipasir-solve ipasir))
((when (or (eq status1 :sat)
(eq status1 :failed)))
(mv status1 ipasir))
(ipasir (ipasir-assume ipasir (lit-negate lit1)))
(ipasir (ipasir-assume ipasir lit2)))
(ipasir-solve ipasir))
///
(defret ipasir-check-equivalence-ipasir-status
(equal (ipasir$a->status new-ipasir)
(case status
(:sat :sat)
(:unsat :unsat)
(otherwise :input))))
(defret ipasir-check-equivalence-formula
(equal (ipasir$a->formula new-ipasir)
(ipasir$a->formula ipasir)))
(defret ipasir-check-equivalence-new-clause
(equal (ipasir$a->new-clause new-ipasir) nil))
(defret ipasir-check-equivalence-assumption
(equal (ipasir$a->assumption new-ipasir) nil))
(defret ipasir-check-equivalence-unsat
(implies (and (equal 1 (eval-formula (ipasir$a->formula ipasir) env))
(case-split (not (equal (eval-lit lit1 env)
(eval-lit lit2 env)))))
(not (equal status :unsat)))))
|
[
{
"context": ";;;; form-types.lisp\n;;;;\n;;;; Copyright 2021 Alexander Gutev <[email protected]>\n;;;;\n;;;; Permission is here",
"end": 61,
"score": 0.999874472618103,
"start": 46,
"tag": "NAME",
"value": "Alexander Gutev"
},
{
"context": "es.lisp\n;;;;\n;;;; Copyright 2021 Alexander Gutev <[email protected]>\n;;;;\n;;;; Permission is hereby granted, free of ",
"end": 81,
"score": 0.9999348521232605,
"start": 63,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
src/form-types.lisp
|
alex-gutev/cl-form-types
| 11 |
;;;; form-types.lisp
;;;;
;;;; Copyright 2021 Alexander Gutev <[email protected]>
;;;;
;;;; Permission is hereby granted, free of charge, to any person
;;;; obtaining a copy of this software and associated documentation
;;;; files (the "Software"), to deal in the Software without
;;;; restriction, including without limitation the rights to use,
;;;; copy, modify, merge, publish, distribute, sublicense, and/or sell
;;;; copies of the Software, and to permit persons to whom the
;;;; Software is furnished to do so, subject to the following
;;;; conditions:
;;;;
;;;; The above copyright notice and this permission notice shall be
;;;; included in all copies or substantial portions of the Software.
;;;;
;;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
;;;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
;;;; OTHER DEALINGS IN THE SOFTWARE.
;;;; Functions for obtaining the types of forms based on the type
;;;; information stored in the environment.
(in-package :cl-form-types)
;;; Types
(deftype function-name ()
`(or symbol (cons (eql cl:setf) (cons symbol null))))
;;; Conditions
(define-condition malformed-form-error (program-error)
((form :initarg :form
:reader form))
(:report
(lambda (e s)
(with-slots (form) e
(format s "Encountered a malformed form while code-walking:~%~2T~s" form))))
(:documentation
"Condition signalling that a form passed to FORM-TYPE is malformed."))
(define-condition unknown-special-operator (program-error)
((operator :initarg :operator
:reader operator)
(operands :initarg :operands
:reader operands))
(:report
(lambda (e s)
(with-slots (operator operands) e
(format s "Encountered an unknown special operator ~s, with operands:~%~2T~s"
operator operands))))
(:documentation
"Condition representing that an special operator was encountered
which this library does not know how to process."))
(defun return-default-type (&optional (type t))
"Invoke the RETURN-DEFAULT-TYPE restart for `MALFORMED-FORM-ERROR' conditions.
This restart returns the type TYPE for the type of the malformed
form."
(invoke-restart 'return-default-type type))
;;; Utilities
(defmacro with-default-type-restart (&body forms)
"Evaluate forms in a RESTART-CASE with the RETURN-DEFAULT-TYPE
restart established."
(with-gensyms (type)
`(restart-case (progn ,@forms)
(return-default-type (,type) ,type))))
(defmacro match-form (form &body clauses)
"Like MATCH but with a default clause which signals a
`MALFORMED-FORM-ERROR' condition."
(with-gensyms (whole)
`(match ,form
,@clauses
(,whole
(error 'malformed-form-error :form ,whole)))))
;;; Global Flags
(defvar *constant-eql-types* nil
"Flag for whether EQL type specifiers should be returned for all constant forms.
If NIL EQL types are only returned if a form evaluates to a
constant which is comparable with EQL, such as NUMBERS, CHARACTERS
and SYMBOLS. If T, an EQL type is returned for every form which
evaluates to a constant value.")
(defvar *expand-compiler-macros* nil
"Flag for whether compiler-macros should be expanded prior to
determining form types.")
(defvar *handle-sb-lvars* nil
"Flag for whether SBCL `SB-C::LVAR' structures should be recognized.
If true the type of an LVAR is returned if encountered as a
constant.
If NIL LVARS as treated as literal constant and an EQL type or LVAR
is returned, depending on the value of*CONSTANT-EQL-TYPES*.")
;;; FORM-TYPE functions
(defun form-types (forms env &key ((:constant-eql-types *constant-eql-types*)) ((:expand-compiler-macros *expand-compiler-macros*)))
"Determines the type of each form in FORMS.
FORMS is a list of forms.
ENV is the environment in which the forms occur.
:CONSTANT-EQL-TYPES if a flag for whether EQL type specifiers
should be returned for all constant forms. If NIL EQL types
specifiers are only returned for constants which are comparable
with EQL, that is NUMBERS, CHARACTERS and SYMBOLS.
:EXPAND-COMPILER-MACROS is a flag, which if true, compiler-macros
are expanded prior to determining the type of FORM or a subform of
it.
Returns a list where each element is the type to which the
corresponding form in FORMS evaluates to"
(mapcar (rcurry #'form-type% env) forms))
(defun nth-form-type (form env &optional (n 0) *constant-eql-types* *expand-compiler-macros*)
"Determines the type of the N'th value of a form.
The difference between this and FORM-TYPE is that, FORM-TYPE
returns a VALUES type if the form evaluates to multiple values,
whereas this function returns only the type of the N'th value.
FORM is the form of which to determine the type.
ENV is the environment in which the form occurs.
N is the index of the return value of which to return the type.
CONSTANT-EQL-TYPES if a flag for whether EQL type specifiers
should be returned for all constant forms. If NIL EQL types
specifiers are only returned for constants which are comparable
with EQL, that is NUMBERS, CHARACTERS and SYMBOLS.
EXPAND-COMPILER-MACROS is a flag, which if true, compiler-macros
are expanded prior to determining the type of FORM or a subform of
it.
Returns the type of the N'th return value of FORM. If there is no
type information for the N'th value, that is FORM does not evaluate
to multiple values or evaluates to less values than N, NIL is
returned."
(nth-value-type (form-type% form env) n))
(defun nth-value-type (type &optional (n 0))
"Extract the type of the N'th return value.
If TYPE is a VALUES type specifier, returns the type of the N'th
value, otherwise TYPE is treated as a VALUES type specifier with a
single value type.
TYPE is the type specifier.
N is the index of the return value of which to return the type.
Returns the N'th value type or NIL if there is no information about
the N'th return value."
(labels ((nth-type (types n)
(match types
((list* (or '&optional '&rest '&allow-other-keys)
(or '(&optional)
'(&rest)
'(&allow-other-keys)
nil))
nil)
((list* '&rest type _)
type)
((list* '&optional type rest)
(if (zerop n)
type
(nth-type rest (1- n))))
((list* type rest)
(if (zerop n)
type
(nth-type rest (1- n)))))))
(match type
((list* 'values types)
(nth-type types n))
(_
(when (zerop n)
type)))))
(defun form-type (form env &key ((:expand-compiler-macros *expand-compiler-macros*)) ((:constant-eql-types *constant-eql-types*)))
"Determines the type of a form in an environment.
FORM is the form of which to determine the type.
ENV is the environment in which the form occurs.
:CONSTANT-EQL-TYPES is a flag for whether EQL type specifiers
should be returned for all constant forms. If NIL EQL types
specifiers are only returned for constants which are comparable
with EQL, that is NUMBERS, CHARACTERS and SYMBOLS.
:EXPAND-COMPILER-MACROS is a flag, which if true, compiler-macros
are expanded prior to determining the type of FORM or a subform of
it.
Returns the type of the value to which FORM evaluates to. Returns a
VALUES type if FORM evaluates to multiple values. Returns T if the
type could not be determined."
(form-type% form env))
(defun form-type% (form env)
(if (constantp form env)
(handler-case
(constant-type
(constant-form-value form env))
(error () (expand-form-type form env)))
(expand-form-type form env)))
(defun expand-form-type (form env)
"Determines the type of a form, in an environment, after macroexpand.
FORM is the form of which to determine the type.
ENV is the environment in which the form occurs."
(multiple-value-bind (form expanded?) (macroexpand-1 form env)
(cond
(expanded?
(form-type% form env))
(t
(match form
((type symbol)
(variable-type form env))
((list* op args)
(list-form-type op args env))
(_ t))))))
(defun constant-form-value (form env)
"Determine the value of a constant form.
FORM is the form of which to determine the value. Must be a form
for which CONSTANTP returns true.
ENV is the environment in which FORM is found."
#+(or ccl sbcl cmucl)
(introspect-environment:constant-form-value form env)
;; Use the following as it has more chance of being successful, than
;; a fallback to EVAL, due to evaluating FORM in the correct
;; environment.
#-(or ccl sbcl cmucl)
(funcall (enclose `(lambda () ,form) env)))
;;; VALUES Types
(defstruct values-type-spec
"Parse VALUES type specifier.
TYPES is the list of all type specifiers in the order in which they
appear. Lambda list keywords are removed from this list.
OPTIONAL-START is the index at which the &OPTIONAL keyword is found
in the type specifier list. NIL if there is no &OPTIONAL keyword.
REST-P is true if the type specifier list contains an &REST keyword.
REST-TYPE is the &REST type specifier
ALLOW-OTHER-KEYS is true if the type specifier list contains the
keyword &ALLOW-OTHER-KEYS.
OTHER is a list of the elements following the last applicable valid
component of the VALUES type specifier list. If non-NIL, this
indicates a malformed VALUES type specifier."
types
optional-start
rest-p
rest-type
allow-other-keys
other)
(defun parse-values-type (spec)
"Parse a VALUES type specifier into its components.
SPEC is the VALUES type specifier list following the VALUES
keyword.
Returns a `VALUES-TYPE-SPEC' object."
(let (optional-pos
rest-p
rest-type
allow-other-keys
rest-list)
(labels ((consume-types (types index)
(match types
((list* '&optional types)
(unless optional-pos
(setf optional-pos index))
(consume-types types (1+ index)))
((list* '&rest type rest)
(setf rest-p t)
(setf rest-type type)
(setf rest-list (consume-lambda-keywords rest (+ 2 index)))
nil)
((list '&rest)
(setf rest-p t)
(setf rest-type t)
nil)
((list* '&allow-other-keys rest)
(setf allow-other-keys index)
(setf rest-list rest)
nil)
((list* type rest)
(cons type (consume-types rest (1+ index))))))
(consume-lambda-keywords (list index)
(match list
((list* '&allow-other-keys rest)
(setf allow-other-keys index)
rest)
(_ list))))
(let ((types (consume-types spec 0)))
(make-values-type-spec
:types types
:optional-start optional-pos
:rest-p rest-p
:rest-type rest-type
:allow-other-keys allow-other-keys
:other rest-list)))))
(defun combine-values-types (combinator type1 type2 &optional default-type)
"Combine two type specifier using a combinator keyword.
If both types are a VALUES types, each corresponding value type is
combined into a list with the first element being COMBINATOR and
the next two elements being the type specifiers. If only one of the
types is a VALUES type, the other is treated as a VALUES type with
one value type.
If neither types are values types the result `(,COMBINATOR ,TYPE1
,TYPE2) is returned.
COMBINATOR is the symbol naming the combinator.
TYPES1 and TYPES2 are the types to combine.
DEFAULT-TYPE is the type used when combining the values type
specifier with more value types. When the all the value types in
the specifier with less values, are combined with value types from
the specifier with more values, the remaining extra values are
combined with DEFAULT-TYPE, unless the shorter values type
specifier also specifies a &REST type.
Returns the combined type specifier."
(labels ((combine (types1 types2)
(let* ((spec1 (parse-values-type types1))
(spec2 (parse-values-type types2)))
(if (< (length (values-type-spec-types spec1))
(length (values-type-spec-types spec2)))
(combine-specs spec1 spec2)
(combine-specs spec2 spec1))))
(combine-specs (spec1 spec2)
;; SPEC1 has fewer types than SPEC2
(with-accessors ((types1 values-type-spec-types)
(rest-type values-type-spec-rest-type)
(rest-p values-type-spec-rest-p))
spec1
(with-accessors ((types2 values-type-spec-types))
spec2
(->
(append
(mapcar (curry #'list combinator) types1 types2)
(mapcar (curry #'list combinator (if rest-p rest-type default-type))
(subseq types2 (length types1))))
(add-optional-keyword spec1 spec2)
(add-rest-keyword spec1 spec2)
(add-allow-other-keys spec1 spec2)))))
(add-optional-keyword (combined spec1 spec2)
(with-accessors ((start1 values-type-spec-optional-start))
spec1
(with-accessors ((start2 values-type-spec-optional-start))
spec2
(cond
((and start1 start2)
(add-&optional combined (min start1 start2)))
((or start1 start2)
(add-&optional combined (or start1 start2)))
(t
combined)))))
(add-&optional (types index)
(append
(subseq types 0 index)
'(&optional)
(subseq types index)))
(add-rest-keyword (combined spec1 spec2)
(with-accessors ((rest-p-1 values-type-spec-rest-p)
(rest1 values-type-spec-rest-type))
spec1
(with-accessors ((rest-p-2 values-type-spec-rest-p)
(rest2 values-type-spec-rest-type))
spec2
(if (or rest-p-1 rest-p-2)
(append combined `(&rest (,combinator ,rest1 ,rest2)))
combined))))
(add-allow-other-keys (combined spec1 spec2)
(if (or (values-type-spec-allow-other-keys spec1)
(values-type-spec-allow-other-keys spec2))
(append combined '(&allow-other-keys))
combined)))
(multiple-value-match (values type1 type2)
(((list* 'values types1)
(list* 'values types2))
(list* 'values (combine types1 types2)))
(((list* 'values types1) _)
(list* 'values (combine types1 (list type2))))
((_ (list* 'values types2))
(list* 'values (combine (list type1) types2)))
((_ _)
(list combinator type1 type2)))))
;;; Basic Form Types
(defvar *use-local-declared-types* t
"Flag for whether the declared types, in the local environment, should be used.
If NIL the declared types in the global NIL environment are used.
The purpose of this is to support LOAD-TIME-VALUE, in which the
form is macroexpanded in the local environment but is actually
evaluated in the global environment, therefore it does not have
access to local variables.")
(defgeneric custom-form-type (operator arguments env)
(:documentation
"Method for determining form types of custom forms.
This is useful for adding special type deduction logic for your
own functions, or for non-standard special forms.
OPERATOR is the form operator.
ARGUMENTS is the list of argument forms.
ENV is the environment in which the form is found. This might not
be a native environment but an augmented environment from
cl-environments.")
(:method (operator arguments env)
(declare (ignore operator arguments env))
t))
(defun list-form-type (operator arguments env)
"Determine the type of a list form.
OPERATOR is the list form operator.
ARGUMENTS is the list of arguments following the operator.
ENV is the environment in which the form occurs."
(match operator
((type symbol)
(special-form-type operator arguments env))
((list* 'cl:lambda lambda-list body)
(match (lambda-expression-type lambda-list body env)
((list 'function _ (and (not '*) result))
result)
(_ t)))
(_ t)))
(defun expand-compiler-macros (operator arguments env)
"Expand compiler-macros in a function call expression.
Only expands compiler macros if *EXPAND-COMPILER-MACROS is set.
OPERATOR is the form operator.
ARGUMENTS is the argument list of the form.
ENV is the environment in which the form is found.
Returns the compiler-macro-expanded form or NIL if there is no
compiler-macro for OPERATOR."
(when-let* ((fn (and *expand-compiler-macros*
(compiler-macro-function operator env)))
(form (funcall fn (cons operator arguments) env)))
(unless (equal form (cons operator arguments))
form)))
(defun variable-type (variable env)
"Determine the type of a variable.
VARIABLE is the symbol naming the variable. This may name a
constant as well.
ENV is the environment in which the variable is found."
(flet ((get-vtype (decl)
(aif (assoc 'type decl)
(cdr it)
t)))
(multiple-value-bind (type local decl)
(variable-information variable (when *use-local-declared-types* env))
(declare (ignore local))
(case type
(:constant
`(eql ,(eval variable)))
((:lexical :special)
(get-vtype decl))
(otherwise t)))))
(defun constant-type (value)
"Return the type specifier of a constant value.
If the value is a CHARACTER, NUMBER or SYMBOL an EQL type specifier
is returned. Otherwise the type specifier returned by TYPE-OF is
returned.
VALUE is the constant value."
(cond
#+sbcl
((and *handle-sb-lvars* (sb-c::lvar-p value))
(let ((type
(-> value
sb-c::lvar-%derived-type
sb-kernel::type-specifier)))
(if (eq type '*) t type)))
(*constant-eql-types*
`(eql ,value))
(t
(typecase value
((or number character symbol) `(eql ,value))
(otherwise
(type-of value))))))
;;; Special Form Types
(defgeneric special-form-type (operator operands env)
(:documentation
"Determine the type of a special form.
OPERATOR is the form operator, which must name a special operator.
OPERANDS is the for argument list.
ENV is the environment in which the form is found."))
(defmethod special-form-type :around (operator operands env)
(declare (ignore operator operands env))
(with-default-type-restart
(call-next-method)))
(defmethod special-form-type (operator arguments env)
"Determine the type of a function call expression.
OPERATOR is the expression operator, which may be a special
operator.
ARGUMENTS is the list of arguments following the operator.
ENV is the environment in which the expression is found."
(flet ((get-ftype (decl)
(match (cdr (assoc 'ftype decl))
((list 'function _ (and (not (eq '*)) return-type))
return-type)
(_ t))))
(multiple-value-bind (type local decl)
(function-information operator (when *use-local-declared-types* env))
(declare (ignore local))
(match (custom-form-type operator arguments env)
(t
(case type
(:function
(aif (expand-compiler-macros operator arguments env)
(form-type% it env)
(get-ftype decl)))
(otherwise t)))
(type type)))))
;;;; QUOTE and FUNCTION
(defmethod special-form-type ((operator (eql 'cl:quote)) operands env)
(declare (ignore env))
(match-form operands
((list thing)
(constant-type thing))))
(defmethod special-form-type ((operator (eql 'cl:function)) operands env)
(match operands
((list (and
(or (type symbol)
(list 'cl:setf (type symbol)))
name))
(multiple-value-bind (type local decl)
(function-information name env)
(declare (ignore local))
(case type
((or nil :function)
(or (cdr (assoc 'ftype decl))
'cl:function))
(otherwise t))))
((list (list* 'cl:lambda lambda-list body))
(lambda-expression-type lambda-list body env))
(_ 'cl:function)))
(defun lambda-expression-type (lambda-list body env)
"Determine the function type of a lambda expression.
LAMBDA-LIST is the lambda-list of the lambda expression.
BODY is the body of the lambda expression (the remainder of the
expression following the lambda-list).
ENV is the environment in which the form containing the lambda
expression is found.
Returns a (FUNCTION ...) specifier."
(with-default-type-restart
(labels ((optional-vars (optional)
(ematch optional
((list var _ nil)
(list var))
((list var1 _ var2)
(list var1 var2))))
(key-vars (key)
(ematch key
((list (list _ var) _ nil)
(list var))
((list (list _ var1) _ var2)
(list var1 var2))))
(required-var-types (required env)
(mapcar (rcurry #'var-type env) required))
(optional-var-types (optional env)
(when optional
(list* '&optional
(mapcar (rcurry #'optional-var-type env) optional))))
(key-var-types (key env)
(mapcar (rcurry #'key-var-type env) key))
(var-type (var env)
(multiple-value-bind (var-type local declarations)
(variable-information var env)
(declare (ignore local))
(or
(when (member var-type '(:lexical :special))
(cdr (assoc 'type declarations)))
'*)))
(optional-var-type (optional env)
(var-type (first optional) env))
(key-var-type (key env)
(ematch key
((list (list keyword var) _ _)
(list keyword
(var-type var env)))))
(rest-var-type (var env)
(match (var-type var env)
((list 'cons type _)
type)
(_ '*))))
(multiple-value-bind (required optional rest key allow-other-keys aux has-key-p)
(parse-ordinary-lambda-list lambda-list)
(multiple-value-bind (body declarations)
(parse-body body :documentation nil)
(let ((env (augment-environment
env
:variable
(append required
(mappend #'optional-vars optional)
(ensure-list rest)
(mappend #'key-vars key)
(mapcar #'cdr aux))
:declare
(mappend #'cdr declarations))))
`(function
,(append
(required-var-types required env)
(optional-var-types optional env)
(when rest (list '&rest (rest-var-type rest env)))
(when has-key-p '(&key))
(key-var-types key env)
(when allow-other-keys '(&allow-other-keys)))
,(form-type% (lastcar body) env))))))))
;;;; THE
(defmethod special-form-type ((operator (eql 'cl:the)) operands env)
(match-form operands
((list type value-form)
(combine-values-types 'and type (form-type% value-form env) t))))
;;;; LOAD-TIME-VALUE
(defmethod special-form-type ((operator (eql 'cl:load-time-value)) operands env)
(match-form operands
((list* value _)
(let ((*use-local-declared-types* nil))
(form-type% value env)))))
;;;; SETQ
(defmethod special-form-type ((operator (eql 'cl:setq)) operands env)
(match-form operands
((guard operands
(and (proper-list-p operands)
(evenp (length operands))))
(form-type% (lastcar operands) env))))
;;;; Conditionals
(defmethod special-form-type ((operator (eql 'cl:if)) operands env)
(match-form operands
((list _ if-true if-false)
(combine-values-types
'or
(form-type% if-true env)
(form-type% if-false env)))
((list _ if-true)
(combine-values-types
'or
(form-type% if-true env)
'null))))
;;;; Multiple value call and PROG1
(defmethod special-form-type ((operator (eql 'cl:multiple-value-call)) operands env)
(match-form operands
((list* function _)
(match (nth-value-type (form-type% function env) 0)
((list 'function _ (and (not (eq '*)) return-type))
return-type)
(_ t)))))
(defmethod special-form-type ((operator (eql 'cl:multiple-value-prog1)) operands env)
(match-form operands
((list* first-form _)
(form-type% first-form env))))
;;; Grouping Forms
(defmethod special-form-type ((operator (eql 'cl:progn)) operands env)
(match-form operands
((type proper-list)
(form-type% (lastcar operands) env))))
(defmethod special-form-type ((operator (eql 'cl:progv)) operands env)
(match-form operands
((list* _ _ (and (type proper-list) forms))
(form-type% (lastcar forms) env))))
(defmethod special-form-type ((operator (eql 'cl:eval-when)) operands env)
(match-form operands
((list* (and (type proper-list) situation)
(and (type proper-list) forms))
(if (or (member :execute situation)
(member 'eval situation))
(form-type% (lastcar forms) env)
'null))))
(defmethod special-form-type ((operator (eql 'cl:unwind-protect)) operands env)
(match-form operands
((list* form _)
(form-type% form env))))
(defmethod special-form-type ((operator (eql 'cl:locally)) operands env)
(match-form operands
((type proper-list)
(multiple-value-bind (body declarations)
(parse-body operands :documentation nil)
(form-type%
(lastcar body)
(augment-environment
env
:declare (mappend #'cdr declarations)))))))
;;; Control Flow Context
(defmethod special-form-type ((operator (eql 'cl:tagbody)) operands env)
(declare (ignore operands env))
nil)
;;;; Control Transfer Forms
;; These all return NIL since they do not return any value, but rather
;; execute a jump.
(defmethod special-form-type ((operator (eql 'cl:go)) operands env)
(declare (ignore operands env))
nil)
(defmethod special-form-type ((operator (eql 'cl:throw)) operands env)
(declare (ignore operands env))
nil)
(defmethod special-form-type ((operator (eql 'cl:return-from)) operands env)
(declare (ignore operands env))
nil)
;;; Local Macro Definitions
(defmethod special-form-type ((operator (eql 'cl:macrolet)) operands env)
(flet ((make-macro (def)
(match-form def
((list* (and (type symbol) name)
(and (type proper-list) lambda-list)
(and (type proper-list) body))
(list name (enclose-macro name lambda-list body env))))))
(match-form operands
((list* (and (type proper-list) macros)
(and (type proper-list) body))
(multiple-value-bind (body declarations)
(parse-body body :documentation nil)
(form-type%
(lastcar body)
(augment-environment
env
:macro (mapcar #'make-macro macros)
:declare (mappend #'cdr declarations))))))))
(defmethod special-form-type ((operator (eql 'cl:symbol-macrolet)) operands env)
(match-form operands
((list* (and (type proper-list) symbol-macros)
(and (type proper-list) body))
(multiple-value-bind (body declarations)
(parse-body body :documentation nil)
(form-type%
(lastcar body)
(augment-environment
env
:symbol-macro symbol-macros
:declare (mappend #'cdr declarations)))))))
;;; Local Variable Binding Forms
(defmethod special-form-type ((operator (eql 'cl:let)) operands env)
(let-form-type operands env))
(defmethod special-form-type ((operator (eql 'cl:let*)) operands env)
(let-form-type operands env))
(defun let-form-type (operands env)
"Determine the type of a LET/LET* form.
OPERANDS is the list of operands to the form.
ENV is the environment in which the form is found."
(flet ((extract-var (binding)
"Extract the variable name from a binding."
(match-form binding
((or (and (type symbol) variable)
(list* (and (type symbol) variable) _))
(list variable)))))
(match-form operands
((list* (and (type proper-list) bindings)
(and (type proper-list) body))
(multiple-value-bind (body declarations)
(parse-body body :documentation nil)
(form-type%
(lastcar body)
(augment-environment
env
:variable (mappend #'extract-var bindings)
:declare (mappend #'cdr declarations))))))))
;;; Local Function Binding Forms
(defmethod special-form-type ((operator (eql 'cl:flet)) operands env)
(flet-form-type operands env))
(defmethod special-form-type ((operator (eql 'cl:labels)) operands env)
(flet-form-type operands env))
(defun flet-form-type (operands env)
"Determine the type of a FLET/LABELS form.
OPERANDS is the list of operands to the form.
ENV is the environment in which the form is found."
(flet ((extract-function (binding)
"Extract the function name from a definition."
(match-form binding
((list* (and (type function-name) name) _)
(list name)))))
(match-form operands
((list* (and (type proper-list) functions)
(and (type proper-list) body))
(multiple-value-bind (body declarations)
(parse-body body :documentation nil)
(form-type%
(lastcar body)
(augment-environment
env
:function (mappend #'extract-function functions)
:declare (mappend #'cdr declarations))))))))
|
82168
|
;;;; form-types.lisp
;;;;
;;;; Copyright 2021 <NAME> <<EMAIL>>
;;;;
;;;; Permission is hereby granted, free of charge, to any person
;;;; obtaining a copy of this software and associated documentation
;;;; files (the "Software"), to deal in the Software without
;;;; restriction, including without limitation the rights to use,
;;;; copy, modify, merge, publish, distribute, sublicense, and/or sell
;;;; copies of the Software, and to permit persons to whom the
;;;; Software is furnished to do so, subject to the following
;;;; conditions:
;;;;
;;;; The above copyright notice and this permission notice shall be
;;;; included in all copies or substantial portions of the Software.
;;;;
;;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
;;;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
;;;; OTHER DEALINGS IN THE SOFTWARE.
;;;; Functions for obtaining the types of forms based on the type
;;;; information stored in the environment.
(in-package :cl-form-types)
;;; Types
(deftype function-name ()
`(or symbol (cons (eql cl:setf) (cons symbol null))))
;;; Conditions
(define-condition malformed-form-error (program-error)
((form :initarg :form
:reader form))
(:report
(lambda (e s)
(with-slots (form) e
(format s "Encountered a malformed form while code-walking:~%~2T~s" form))))
(:documentation
"Condition signalling that a form passed to FORM-TYPE is malformed."))
(define-condition unknown-special-operator (program-error)
((operator :initarg :operator
:reader operator)
(operands :initarg :operands
:reader operands))
(:report
(lambda (e s)
(with-slots (operator operands) e
(format s "Encountered an unknown special operator ~s, with operands:~%~2T~s"
operator operands))))
(:documentation
"Condition representing that an special operator was encountered
which this library does not know how to process."))
(defun return-default-type (&optional (type t))
"Invoke the RETURN-DEFAULT-TYPE restart for `MALFORMED-FORM-ERROR' conditions.
This restart returns the type TYPE for the type of the malformed
form."
(invoke-restart 'return-default-type type))
;;; Utilities
(defmacro with-default-type-restart (&body forms)
"Evaluate forms in a RESTART-CASE with the RETURN-DEFAULT-TYPE
restart established."
(with-gensyms (type)
`(restart-case (progn ,@forms)
(return-default-type (,type) ,type))))
(defmacro match-form (form &body clauses)
"Like MATCH but with a default clause which signals a
`MALFORMED-FORM-ERROR' condition."
(with-gensyms (whole)
`(match ,form
,@clauses
(,whole
(error 'malformed-form-error :form ,whole)))))
;;; Global Flags
(defvar *constant-eql-types* nil
"Flag for whether EQL type specifiers should be returned for all constant forms.
If NIL EQL types are only returned if a form evaluates to a
constant which is comparable with EQL, such as NUMBERS, CHARACTERS
and SYMBOLS. If T, an EQL type is returned for every form which
evaluates to a constant value.")
(defvar *expand-compiler-macros* nil
"Flag for whether compiler-macros should be expanded prior to
determining form types.")
(defvar *handle-sb-lvars* nil
"Flag for whether SBCL `SB-C::LVAR' structures should be recognized.
If true the type of an LVAR is returned if encountered as a
constant.
If NIL LVARS as treated as literal constant and an EQL type or LVAR
is returned, depending on the value of*CONSTANT-EQL-TYPES*.")
;;; FORM-TYPE functions
(defun form-types (forms env &key ((:constant-eql-types *constant-eql-types*)) ((:expand-compiler-macros *expand-compiler-macros*)))
"Determines the type of each form in FORMS.
FORMS is a list of forms.
ENV is the environment in which the forms occur.
:CONSTANT-EQL-TYPES if a flag for whether EQL type specifiers
should be returned for all constant forms. If NIL EQL types
specifiers are only returned for constants which are comparable
with EQL, that is NUMBERS, CHARACTERS and SYMBOLS.
:EXPAND-COMPILER-MACROS is a flag, which if true, compiler-macros
are expanded prior to determining the type of FORM or a subform of
it.
Returns a list where each element is the type to which the
corresponding form in FORMS evaluates to"
(mapcar (rcurry #'form-type% env) forms))
(defun nth-form-type (form env &optional (n 0) *constant-eql-types* *expand-compiler-macros*)
"Determines the type of the N'th value of a form.
The difference between this and FORM-TYPE is that, FORM-TYPE
returns a VALUES type if the form evaluates to multiple values,
whereas this function returns only the type of the N'th value.
FORM is the form of which to determine the type.
ENV is the environment in which the form occurs.
N is the index of the return value of which to return the type.
CONSTANT-EQL-TYPES if a flag for whether EQL type specifiers
should be returned for all constant forms. If NIL EQL types
specifiers are only returned for constants which are comparable
with EQL, that is NUMBERS, CHARACTERS and SYMBOLS.
EXPAND-COMPILER-MACROS is a flag, which if true, compiler-macros
are expanded prior to determining the type of FORM or a subform of
it.
Returns the type of the N'th return value of FORM. If there is no
type information for the N'th value, that is FORM does not evaluate
to multiple values or evaluates to less values than N, NIL is
returned."
(nth-value-type (form-type% form env) n))
(defun nth-value-type (type &optional (n 0))
"Extract the type of the N'th return value.
If TYPE is a VALUES type specifier, returns the type of the N'th
value, otherwise TYPE is treated as a VALUES type specifier with a
single value type.
TYPE is the type specifier.
N is the index of the return value of which to return the type.
Returns the N'th value type or NIL if there is no information about
the N'th return value."
(labels ((nth-type (types n)
(match types
((list* (or '&optional '&rest '&allow-other-keys)
(or '(&optional)
'(&rest)
'(&allow-other-keys)
nil))
nil)
((list* '&rest type _)
type)
((list* '&optional type rest)
(if (zerop n)
type
(nth-type rest (1- n))))
((list* type rest)
(if (zerop n)
type
(nth-type rest (1- n)))))))
(match type
((list* 'values types)
(nth-type types n))
(_
(when (zerop n)
type)))))
(defun form-type (form env &key ((:expand-compiler-macros *expand-compiler-macros*)) ((:constant-eql-types *constant-eql-types*)))
"Determines the type of a form in an environment.
FORM is the form of which to determine the type.
ENV is the environment in which the form occurs.
:CONSTANT-EQL-TYPES is a flag for whether EQL type specifiers
should be returned for all constant forms. If NIL EQL types
specifiers are only returned for constants which are comparable
with EQL, that is NUMBERS, CHARACTERS and SYMBOLS.
:EXPAND-COMPILER-MACROS is a flag, which if true, compiler-macros
are expanded prior to determining the type of FORM or a subform of
it.
Returns the type of the value to which FORM evaluates to. Returns a
VALUES type if FORM evaluates to multiple values. Returns T if the
type could not be determined."
(form-type% form env))
(defun form-type% (form env)
(if (constantp form env)
(handler-case
(constant-type
(constant-form-value form env))
(error () (expand-form-type form env)))
(expand-form-type form env)))
(defun expand-form-type (form env)
"Determines the type of a form, in an environment, after macroexpand.
FORM is the form of which to determine the type.
ENV is the environment in which the form occurs."
(multiple-value-bind (form expanded?) (macroexpand-1 form env)
(cond
(expanded?
(form-type% form env))
(t
(match form
((type symbol)
(variable-type form env))
((list* op args)
(list-form-type op args env))
(_ t))))))
(defun constant-form-value (form env)
"Determine the value of a constant form.
FORM is the form of which to determine the value. Must be a form
for which CONSTANTP returns true.
ENV is the environment in which FORM is found."
#+(or ccl sbcl cmucl)
(introspect-environment:constant-form-value form env)
;; Use the following as it has more chance of being successful, than
;; a fallback to EVAL, due to evaluating FORM in the correct
;; environment.
#-(or ccl sbcl cmucl)
(funcall (enclose `(lambda () ,form) env)))
;;; VALUES Types
(defstruct values-type-spec
"Parse VALUES type specifier.
TYPES is the list of all type specifiers in the order in which they
appear. Lambda list keywords are removed from this list.
OPTIONAL-START is the index at which the &OPTIONAL keyword is found
in the type specifier list. NIL if there is no &OPTIONAL keyword.
REST-P is true if the type specifier list contains an &REST keyword.
REST-TYPE is the &REST type specifier
ALLOW-OTHER-KEYS is true if the type specifier list contains the
keyword &ALLOW-OTHER-KEYS.
OTHER is a list of the elements following the last applicable valid
component of the VALUES type specifier list. If non-NIL, this
indicates a malformed VALUES type specifier."
types
optional-start
rest-p
rest-type
allow-other-keys
other)
(defun parse-values-type (spec)
"Parse a VALUES type specifier into its components.
SPEC is the VALUES type specifier list following the VALUES
keyword.
Returns a `VALUES-TYPE-SPEC' object."
(let (optional-pos
rest-p
rest-type
allow-other-keys
rest-list)
(labels ((consume-types (types index)
(match types
((list* '&optional types)
(unless optional-pos
(setf optional-pos index))
(consume-types types (1+ index)))
((list* '&rest type rest)
(setf rest-p t)
(setf rest-type type)
(setf rest-list (consume-lambda-keywords rest (+ 2 index)))
nil)
((list '&rest)
(setf rest-p t)
(setf rest-type t)
nil)
((list* '&allow-other-keys rest)
(setf allow-other-keys index)
(setf rest-list rest)
nil)
((list* type rest)
(cons type (consume-types rest (1+ index))))))
(consume-lambda-keywords (list index)
(match list
((list* '&allow-other-keys rest)
(setf allow-other-keys index)
rest)
(_ list))))
(let ((types (consume-types spec 0)))
(make-values-type-spec
:types types
:optional-start optional-pos
:rest-p rest-p
:rest-type rest-type
:allow-other-keys allow-other-keys
:other rest-list)))))
(defun combine-values-types (combinator type1 type2 &optional default-type)
"Combine two type specifier using a combinator keyword.
If both types are a VALUES types, each corresponding value type is
combined into a list with the first element being COMBINATOR and
the next two elements being the type specifiers. If only one of the
types is a VALUES type, the other is treated as a VALUES type with
one value type.
If neither types are values types the result `(,COMBINATOR ,TYPE1
,TYPE2) is returned.
COMBINATOR is the symbol naming the combinator.
TYPES1 and TYPES2 are the types to combine.
DEFAULT-TYPE is the type used when combining the values type
specifier with more value types. When the all the value types in
the specifier with less values, are combined with value types from
the specifier with more values, the remaining extra values are
combined with DEFAULT-TYPE, unless the shorter values type
specifier also specifies a &REST type.
Returns the combined type specifier."
(labels ((combine (types1 types2)
(let* ((spec1 (parse-values-type types1))
(spec2 (parse-values-type types2)))
(if (< (length (values-type-spec-types spec1))
(length (values-type-spec-types spec2)))
(combine-specs spec1 spec2)
(combine-specs spec2 spec1))))
(combine-specs (spec1 spec2)
;; SPEC1 has fewer types than SPEC2
(with-accessors ((types1 values-type-spec-types)
(rest-type values-type-spec-rest-type)
(rest-p values-type-spec-rest-p))
spec1
(with-accessors ((types2 values-type-spec-types))
spec2
(->
(append
(mapcar (curry #'list combinator) types1 types2)
(mapcar (curry #'list combinator (if rest-p rest-type default-type))
(subseq types2 (length types1))))
(add-optional-keyword spec1 spec2)
(add-rest-keyword spec1 spec2)
(add-allow-other-keys spec1 spec2)))))
(add-optional-keyword (combined spec1 spec2)
(with-accessors ((start1 values-type-spec-optional-start))
spec1
(with-accessors ((start2 values-type-spec-optional-start))
spec2
(cond
((and start1 start2)
(add-&optional combined (min start1 start2)))
((or start1 start2)
(add-&optional combined (or start1 start2)))
(t
combined)))))
(add-&optional (types index)
(append
(subseq types 0 index)
'(&optional)
(subseq types index)))
(add-rest-keyword (combined spec1 spec2)
(with-accessors ((rest-p-1 values-type-spec-rest-p)
(rest1 values-type-spec-rest-type))
spec1
(with-accessors ((rest-p-2 values-type-spec-rest-p)
(rest2 values-type-spec-rest-type))
spec2
(if (or rest-p-1 rest-p-2)
(append combined `(&rest (,combinator ,rest1 ,rest2)))
combined))))
(add-allow-other-keys (combined spec1 spec2)
(if (or (values-type-spec-allow-other-keys spec1)
(values-type-spec-allow-other-keys spec2))
(append combined '(&allow-other-keys))
combined)))
(multiple-value-match (values type1 type2)
(((list* 'values types1)
(list* 'values types2))
(list* 'values (combine types1 types2)))
(((list* 'values types1) _)
(list* 'values (combine types1 (list type2))))
((_ (list* 'values types2))
(list* 'values (combine (list type1) types2)))
((_ _)
(list combinator type1 type2)))))
;;; Basic Form Types
(defvar *use-local-declared-types* t
"Flag for whether the declared types, in the local environment, should be used.
If NIL the declared types in the global NIL environment are used.
The purpose of this is to support LOAD-TIME-VALUE, in which the
form is macroexpanded in the local environment but is actually
evaluated in the global environment, therefore it does not have
access to local variables.")
(defgeneric custom-form-type (operator arguments env)
(:documentation
"Method for determining form types of custom forms.
This is useful for adding special type deduction logic for your
own functions, or for non-standard special forms.
OPERATOR is the form operator.
ARGUMENTS is the list of argument forms.
ENV is the environment in which the form is found. This might not
be a native environment but an augmented environment from
cl-environments.")
(:method (operator arguments env)
(declare (ignore operator arguments env))
t))
(defun list-form-type (operator arguments env)
"Determine the type of a list form.
OPERATOR is the list form operator.
ARGUMENTS is the list of arguments following the operator.
ENV is the environment in which the form occurs."
(match operator
((type symbol)
(special-form-type operator arguments env))
((list* 'cl:lambda lambda-list body)
(match (lambda-expression-type lambda-list body env)
((list 'function _ (and (not '*) result))
result)
(_ t)))
(_ t)))
(defun expand-compiler-macros (operator arguments env)
"Expand compiler-macros in a function call expression.
Only expands compiler macros if *EXPAND-COMPILER-MACROS is set.
OPERATOR is the form operator.
ARGUMENTS is the argument list of the form.
ENV is the environment in which the form is found.
Returns the compiler-macro-expanded form or NIL if there is no
compiler-macro for OPERATOR."
(when-let* ((fn (and *expand-compiler-macros*
(compiler-macro-function operator env)))
(form (funcall fn (cons operator arguments) env)))
(unless (equal form (cons operator arguments))
form)))
(defun variable-type (variable env)
"Determine the type of a variable.
VARIABLE is the symbol naming the variable. This may name a
constant as well.
ENV is the environment in which the variable is found."
(flet ((get-vtype (decl)
(aif (assoc 'type decl)
(cdr it)
t)))
(multiple-value-bind (type local decl)
(variable-information variable (when *use-local-declared-types* env))
(declare (ignore local))
(case type
(:constant
`(eql ,(eval variable)))
((:lexical :special)
(get-vtype decl))
(otherwise t)))))
(defun constant-type (value)
"Return the type specifier of a constant value.
If the value is a CHARACTER, NUMBER or SYMBOL an EQL type specifier
is returned. Otherwise the type specifier returned by TYPE-OF is
returned.
VALUE is the constant value."
(cond
#+sbcl
((and *handle-sb-lvars* (sb-c::lvar-p value))
(let ((type
(-> value
sb-c::lvar-%derived-type
sb-kernel::type-specifier)))
(if (eq type '*) t type)))
(*constant-eql-types*
`(eql ,value))
(t
(typecase value
((or number character symbol) `(eql ,value))
(otherwise
(type-of value))))))
;;; Special Form Types
(defgeneric special-form-type (operator operands env)
(:documentation
"Determine the type of a special form.
OPERATOR is the form operator, which must name a special operator.
OPERANDS is the for argument list.
ENV is the environment in which the form is found."))
(defmethod special-form-type :around (operator operands env)
(declare (ignore operator operands env))
(with-default-type-restart
(call-next-method)))
(defmethod special-form-type (operator arguments env)
"Determine the type of a function call expression.
OPERATOR is the expression operator, which may be a special
operator.
ARGUMENTS is the list of arguments following the operator.
ENV is the environment in which the expression is found."
(flet ((get-ftype (decl)
(match (cdr (assoc 'ftype decl))
((list 'function _ (and (not (eq '*)) return-type))
return-type)
(_ t))))
(multiple-value-bind (type local decl)
(function-information operator (when *use-local-declared-types* env))
(declare (ignore local))
(match (custom-form-type operator arguments env)
(t
(case type
(:function
(aif (expand-compiler-macros operator arguments env)
(form-type% it env)
(get-ftype decl)))
(otherwise t)))
(type type)))))
;;;; QUOTE and FUNCTION
(defmethod special-form-type ((operator (eql 'cl:quote)) operands env)
(declare (ignore env))
(match-form operands
((list thing)
(constant-type thing))))
(defmethod special-form-type ((operator (eql 'cl:function)) operands env)
(match operands
((list (and
(or (type symbol)
(list 'cl:setf (type symbol)))
name))
(multiple-value-bind (type local decl)
(function-information name env)
(declare (ignore local))
(case type
((or nil :function)
(or (cdr (assoc 'ftype decl))
'cl:function))
(otherwise t))))
((list (list* 'cl:lambda lambda-list body))
(lambda-expression-type lambda-list body env))
(_ 'cl:function)))
(defun lambda-expression-type (lambda-list body env)
"Determine the function type of a lambda expression.
LAMBDA-LIST is the lambda-list of the lambda expression.
BODY is the body of the lambda expression (the remainder of the
expression following the lambda-list).
ENV is the environment in which the form containing the lambda
expression is found.
Returns a (FUNCTION ...) specifier."
(with-default-type-restart
(labels ((optional-vars (optional)
(ematch optional
((list var _ nil)
(list var))
((list var1 _ var2)
(list var1 var2))))
(key-vars (key)
(ematch key
((list (list _ var) _ nil)
(list var))
((list (list _ var1) _ var2)
(list var1 var2))))
(required-var-types (required env)
(mapcar (rcurry #'var-type env) required))
(optional-var-types (optional env)
(when optional
(list* '&optional
(mapcar (rcurry #'optional-var-type env) optional))))
(key-var-types (key env)
(mapcar (rcurry #'key-var-type env) key))
(var-type (var env)
(multiple-value-bind (var-type local declarations)
(variable-information var env)
(declare (ignore local))
(or
(when (member var-type '(:lexical :special))
(cdr (assoc 'type declarations)))
'*)))
(optional-var-type (optional env)
(var-type (first optional) env))
(key-var-type (key env)
(ematch key
((list (list keyword var) _ _)
(list keyword
(var-type var env)))))
(rest-var-type (var env)
(match (var-type var env)
((list 'cons type _)
type)
(_ '*))))
(multiple-value-bind (required optional rest key allow-other-keys aux has-key-p)
(parse-ordinary-lambda-list lambda-list)
(multiple-value-bind (body declarations)
(parse-body body :documentation nil)
(let ((env (augment-environment
env
:variable
(append required
(mappend #'optional-vars optional)
(ensure-list rest)
(mappend #'key-vars key)
(mapcar #'cdr aux))
:declare
(mappend #'cdr declarations))))
`(function
,(append
(required-var-types required env)
(optional-var-types optional env)
(when rest (list '&rest (rest-var-type rest env)))
(when has-key-p '(&key))
(key-var-types key env)
(when allow-other-keys '(&allow-other-keys)))
,(form-type% (lastcar body) env))))))))
;;;; THE
(defmethod special-form-type ((operator (eql 'cl:the)) operands env)
(match-form operands
((list type value-form)
(combine-values-types 'and type (form-type% value-form env) t))))
;;;; LOAD-TIME-VALUE
(defmethod special-form-type ((operator (eql 'cl:load-time-value)) operands env)
(match-form operands
((list* value _)
(let ((*use-local-declared-types* nil))
(form-type% value env)))))
;;;; SETQ
(defmethod special-form-type ((operator (eql 'cl:setq)) operands env)
(match-form operands
((guard operands
(and (proper-list-p operands)
(evenp (length operands))))
(form-type% (lastcar operands) env))))
;;;; Conditionals
(defmethod special-form-type ((operator (eql 'cl:if)) operands env)
(match-form operands
((list _ if-true if-false)
(combine-values-types
'or
(form-type% if-true env)
(form-type% if-false env)))
((list _ if-true)
(combine-values-types
'or
(form-type% if-true env)
'null))))
;;;; Multiple value call and PROG1
(defmethod special-form-type ((operator (eql 'cl:multiple-value-call)) operands env)
(match-form operands
((list* function _)
(match (nth-value-type (form-type% function env) 0)
((list 'function _ (and (not (eq '*)) return-type))
return-type)
(_ t)))))
(defmethod special-form-type ((operator (eql 'cl:multiple-value-prog1)) operands env)
(match-form operands
((list* first-form _)
(form-type% first-form env))))
;;; Grouping Forms
(defmethod special-form-type ((operator (eql 'cl:progn)) operands env)
(match-form operands
((type proper-list)
(form-type% (lastcar operands) env))))
(defmethod special-form-type ((operator (eql 'cl:progv)) operands env)
(match-form operands
((list* _ _ (and (type proper-list) forms))
(form-type% (lastcar forms) env))))
(defmethod special-form-type ((operator (eql 'cl:eval-when)) operands env)
(match-form operands
((list* (and (type proper-list) situation)
(and (type proper-list) forms))
(if (or (member :execute situation)
(member 'eval situation))
(form-type% (lastcar forms) env)
'null))))
(defmethod special-form-type ((operator (eql 'cl:unwind-protect)) operands env)
(match-form operands
((list* form _)
(form-type% form env))))
(defmethod special-form-type ((operator (eql 'cl:locally)) operands env)
(match-form operands
((type proper-list)
(multiple-value-bind (body declarations)
(parse-body operands :documentation nil)
(form-type%
(lastcar body)
(augment-environment
env
:declare (mappend #'cdr declarations)))))))
;;; Control Flow Context
(defmethod special-form-type ((operator (eql 'cl:tagbody)) operands env)
(declare (ignore operands env))
nil)
;;;; Control Transfer Forms
;; These all return NIL since they do not return any value, but rather
;; execute a jump.
(defmethod special-form-type ((operator (eql 'cl:go)) operands env)
(declare (ignore operands env))
nil)
(defmethod special-form-type ((operator (eql 'cl:throw)) operands env)
(declare (ignore operands env))
nil)
(defmethod special-form-type ((operator (eql 'cl:return-from)) operands env)
(declare (ignore operands env))
nil)
;;; Local Macro Definitions
(defmethod special-form-type ((operator (eql 'cl:macrolet)) operands env)
(flet ((make-macro (def)
(match-form def
((list* (and (type symbol) name)
(and (type proper-list) lambda-list)
(and (type proper-list) body))
(list name (enclose-macro name lambda-list body env))))))
(match-form operands
((list* (and (type proper-list) macros)
(and (type proper-list) body))
(multiple-value-bind (body declarations)
(parse-body body :documentation nil)
(form-type%
(lastcar body)
(augment-environment
env
:macro (mapcar #'make-macro macros)
:declare (mappend #'cdr declarations))))))))
(defmethod special-form-type ((operator (eql 'cl:symbol-macrolet)) operands env)
(match-form operands
((list* (and (type proper-list) symbol-macros)
(and (type proper-list) body))
(multiple-value-bind (body declarations)
(parse-body body :documentation nil)
(form-type%
(lastcar body)
(augment-environment
env
:symbol-macro symbol-macros
:declare (mappend #'cdr declarations)))))))
;;; Local Variable Binding Forms
(defmethod special-form-type ((operator (eql 'cl:let)) operands env)
(let-form-type operands env))
(defmethod special-form-type ((operator (eql 'cl:let*)) operands env)
(let-form-type operands env))
(defun let-form-type (operands env)
"Determine the type of a LET/LET* form.
OPERANDS is the list of operands to the form.
ENV is the environment in which the form is found."
(flet ((extract-var (binding)
"Extract the variable name from a binding."
(match-form binding
((or (and (type symbol) variable)
(list* (and (type symbol) variable) _))
(list variable)))))
(match-form operands
((list* (and (type proper-list) bindings)
(and (type proper-list) body))
(multiple-value-bind (body declarations)
(parse-body body :documentation nil)
(form-type%
(lastcar body)
(augment-environment
env
:variable (mappend #'extract-var bindings)
:declare (mappend #'cdr declarations))))))))
;;; Local Function Binding Forms
(defmethod special-form-type ((operator (eql 'cl:flet)) operands env)
(flet-form-type operands env))
(defmethod special-form-type ((operator (eql 'cl:labels)) operands env)
(flet-form-type operands env))
(defun flet-form-type (operands env)
"Determine the type of a FLET/LABELS form.
OPERANDS is the list of operands to the form.
ENV is the environment in which the form is found."
(flet ((extract-function (binding)
"Extract the function name from a definition."
(match-form binding
((list* (and (type function-name) name) _)
(list name)))))
(match-form operands
((list* (and (type proper-list) functions)
(and (type proper-list) body))
(multiple-value-bind (body declarations)
(parse-body body :documentation nil)
(form-type%
(lastcar body)
(augment-environment
env
:function (mappend #'extract-function functions)
:declare (mappend #'cdr declarations))))))))
| true |
;;;; form-types.lisp
;;;;
;;;; Copyright 2021 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;;;
;;;; Permission is hereby granted, free of charge, to any person
;;;; obtaining a copy of this software and associated documentation
;;;; files (the "Software"), to deal in the Software without
;;;; restriction, including without limitation the rights to use,
;;;; copy, modify, merge, publish, distribute, sublicense, and/or sell
;;;; copies of the Software, and to permit persons to whom the
;;;; Software is furnished to do so, subject to the following
;;;; conditions:
;;;;
;;;; The above copyright notice and this permission notice shall be
;;;; included in all copies or substantial portions of the Software.
;;;;
;;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
;;;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
;;;; OTHER DEALINGS IN THE SOFTWARE.
;;;; Functions for obtaining the types of forms based on the type
;;;; information stored in the environment.
(in-package :cl-form-types)
;;; Types
(deftype function-name ()
`(or symbol (cons (eql cl:setf) (cons symbol null))))
;;; Conditions
(define-condition malformed-form-error (program-error)
((form :initarg :form
:reader form))
(:report
(lambda (e s)
(with-slots (form) e
(format s "Encountered a malformed form while code-walking:~%~2T~s" form))))
(:documentation
"Condition signalling that a form passed to FORM-TYPE is malformed."))
(define-condition unknown-special-operator (program-error)
((operator :initarg :operator
:reader operator)
(operands :initarg :operands
:reader operands))
(:report
(lambda (e s)
(with-slots (operator operands) e
(format s "Encountered an unknown special operator ~s, with operands:~%~2T~s"
operator operands))))
(:documentation
"Condition representing that an special operator was encountered
which this library does not know how to process."))
(defun return-default-type (&optional (type t))
"Invoke the RETURN-DEFAULT-TYPE restart for `MALFORMED-FORM-ERROR' conditions.
This restart returns the type TYPE for the type of the malformed
form."
(invoke-restart 'return-default-type type))
;;; Utilities
(defmacro with-default-type-restart (&body forms)
"Evaluate forms in a RESTART-CASE with the RETURN-DEFAULT-TYPE
restart established."
(with-gensyms (type)
`(restart-case (progn ,@forms)
(return-default-type (,type) ,type))))
(defmacro match-form (form &body clauses)
"Like MATCH but with a default clause which signals a
`MALFORMED-FORM-ERROR' condition."
(with-gensyms (whole)
`(match ,form
,@clauses
(,whole
(error 'malformed-form-error :form ,whole)))))
;;; Global Flags
(defvar *constant-eql-types* nil
"Flag for whether EQL type specifiers should be returned for all constant forms.
If NIL EQL types are only returned if a form evaluates to a
constant which is comparable with EQL, such as NUMBERS, CHARACTERS
and SYMBOLS. If T, an EQL type is returned for every form which
evaluates to a constant value.")
(defvar *expand-compiler-macros* nil
"Flag for whether compiler-macros should be expanded prior to
determining form types.")
(defvar *handle-sb-lvars* nil
"Flag for whether SBCL `SB-C::LVAR' structures should be recognized.
If true the type of an LVAR is returned if encountered as a
constant.
If NIL LVARS as treated as literal constant and an EQL type or LVAR
is returned, depending on the value of*CONSTANT-EQL-TYPES*.")
;;; FORM-TYPE functions
(defun form-types (forms env &key ((:constant-eql-types *constant-eql-types*)) ((:expand-compiler-macros *expand-compiler-macros*)))
"Determines the type of each form in FORMS.
FORMS is a list of forms.
ENV is the environment in which the forms occur.
:CONSTANT-EQL-TYPES if a flag for whether EQL type specifiers
should be returned for all constant forms. If NIL EQL types
specifiers are only returned for constants which are comparable
with EQL, that is NUMBERS, CHARACTERS and SYMBOLS.
:EXPAND-COMPILER-MACROS is a flag, which if true, compiler-macros
are expanded prior to determining the type of FORM or a subform of
it.
Returns a list where each element is the type to which the
corresponding form in FORMS evaluates to"
(mapcar (rcurry #'form-type% env) forms))
(defun nth-form-type (form env &optional (n 0) *constant-eql-types* *expand-compiler-macros*)
"Determines the type of the N'th value of a form.
The difference between this and FORM-TYPE is that, FORM-TYPE
returns a VALUES type if the form evaluates to multiple values,
whereas this function returns only the type of the N'th value.
FORM is the form of which to determine the type.
ENV is the environment in which the form occurs.
N is the index of the return value of which to return the type.
CONSTANT-EQL-TYPES if a flag for whether EQL type specifiers
should be returned for all constant forms. If NIL EQL types
specifiers are only returned for constants which are comparable
with EQL, that is NUMBERS, CHARACTERS and SYMBOLS.
EXPAND-COMPILER-MACROS is a flag, which if true, compiler-macros
are expanded prior to determining the type of FORM or a subform of
it.
Returns the type of the N'th return value of FORM. If there is no
type information for the N'th value, that is FORM does not evaluate
to multiple values or evaluates to less values than N, NIL is
returned."
(nth-value-type (form-type% form env) n))
(defun nth-value-type (type &optional (n 0))
"Extract the type of the N'th return value.
If TYPE is a VALUES type specifier, returns the type of the N'th
value, otherwise TYPE is treated as a VALUES type specifier with a
single value type.
TYPE is the type specifier.
N is the index of the return value of which to return the type.
Returns the N'th value type or NIL if there is no information about
the N'th return value."
(labels ((nth-type (types n)
(match types
((list* (or '&optional '&rest '&allow-other-keys)
(or '(&optional)
'(&rest)
'(&allow-other-keys)
nil))
nil)
((list* '&rest type _)
type)
((list* '&optional type rest)
(if (zerop n)
type
(nth-type rest (1- n))))
((list* type rest)
(if (zerop n)
type
(nth-type rest (1- n)))))))
(match type
((list* 'values types)
(nth-type types n))
(_
(when (zerop n)
type)))))
(defun form-type (form env &key ((:expand-compiler-macros *expand-compiler-macros*)) ((:constant-eql-types *constant-eql-types*)))
"Determines the type of a form in an environment.
FORM is the form of which to determine the type.
ENV is the environment in which the form occurs.
:CONSTANT-EQL-TYPES is a flag for whether EQL type specifiers
should be returned for all constant forms. If NIL EQL types
specifiers are only returned for constants which are comparable
with EQL, that is NUMBERS, CHARACTERS and SYMBOLS.
:EXPAND-COMPILER-MACROS is a flag, which if true, compiler-macros
are expanded prior to determining the type of FORM or a subform of
it.
Returns the type of the value to which FORM evaluates to. Returns a
VALUES type if FORM evaluates to multiple values. Returns T if the
type could not be determined."
(form-type% form env))
(defun form-type% (form env)
(if (constantp form env)
(handler-case
(constant-type
(constant-form-value form env))
(error () (expand-form-type form env)))
(expand-form-type form env)))
(defun expand-form-type (form env)
"Determines the type of a form, in an environment, after macroexpand.
FORM is the form of which to determine the type.
ENV is the environment in which the form occurs."
(multiple-value-bind (form expanded?) (macroexpand-1 form env)
(cond
(expanded?
(form-type% form env))
(t
(match form
((type symbol)
(variable-type form env))
((list* op args)
(list-form-type op args env))
(_ t))))))
(defun constant-form-value (form env)
"Determine the value of a constant form.
FORM is the form of which to determine the value. Must be a form
for which CONSTANTP returns true.
ENV is the environment in which FORM is found."
#+(or ccl sbcl cmucl)
(introspect-environment:constant-form-value form env)
;; Use the following as it has more chance of being successful, than
;; a fallback to EVAL, due to evaluating FORM in the correct
;; environment.
#-(or ccl sbcl cmucl)
(funcall (enclose `(lambda () ,form) env)))
;;; VALUES Types
(defstruct values-type-spec
"Parse VALUES type specifier.
TYPES is the list of all type specifiers in the order in which they
appear. Lambda list keywords are removed from this list.
OPTIONAL-START is the index at which the &OPTIONAL keyword is found
in the type specifier list. NIL if there is no &OPTIONAL keyword.
REST-P is true if the type specifier list contains an &REST keyword.
REST-TYPE is the &REST type specifier
ALLOW-OTHER-KEYS is true if the type specifier list contains the
keyword &ALLOW-OTHER-KEYS.
OTHER is a list of the elements following the last applicable valid
component of the VALUES type specifier list. If non-NIL, this
indicates a malformed VALUES type specifier."
types
optional-start
rest-p
rest-type
allow-other-keys
other)
(defun parse-values-type (spec)
"Parse a VALUES type specifier into its components.
SPEC is the VALUES type specifier list following the VALUES
keyword.
Returns a `VALUES-TYPE-SPEC' object."
(let (optional-pos
rest-p
rest-type
allow-other-keys
rest-list)
(labels ((consume-types (types index)
(match types
((list* '&optional types)
(unless optional-pos
(setf optional-pos index))
(consume-types types (1+ index)))
((list* '&rest type rest)
(setf rest-p t)
(setf rest-type type)
(setf rest-list (consume-lambda-keywords rest (+ 2 index)))
nil)
((list '&rest)
(setf rest-p t)
(setf rest-type t)
nil)
((list* '&allow-other-keys rest)
(setf allow-other-keys index)
(setf rest-list rest)
nil)
((list* type rest)
(cons type (consume-types rest (1+ index))))))
(consume-lambda-keywords (list index)
(match list
((list* '&allow-other-keys rest)
(setf allow-other-keys index)
rest)
(_ list))))
(let ((types (consume-types spec 0)))
(make-values-type-spec
:types types
:optional-start optional-pos
:rest-p rest-p
:rest-type rest-type
:allow-other-keys allow-other-keys
:other rest-list)))))
(defun combine-values-types (combinator type1 type2 &optional default-type)
"Combine two type specifier using a combinator keyword.
If both types are a VALUES types, each corresponding value type is
combined into a list with the first element being COMBINATOR and
the next two elements being the type specifiers. If only one of the
types is a VALUES type, the other is treated as a VALUES type with
one value type.
If neither types are values types the result `(,COMBINATOR ,TYPE1
,TYPE2) is returned.
COMBINATOR is the symbol naming the combinator.
TYPES1 and TYPES2 are the types to combine.
DEFAULT-TYPE is the type used when combining the values type
specifier with more value types. When the all the value types in
the specifier with less values, are combined with value types from
the specifier with more values, the remaining extra values are
combined with DEFAULT-TYPE, unless the shorter values type
specifier also specifies a &REST type.
Returns the combined type specifier."
(labels ((combine (types1 types2)
(let* ((spec1 (parse-values-type types1))
(spec2 (parse-values-type types2)))
(if (< (length (values-type-spec-types spec1))
(length (values-type-spec-types spec2)))
(combine-specs spec1 spec2)
(combine-specs spec2 spec1))))
(combine-specs (spec1 spec2)
;; SPEC1 has fewer types than SPEC2
(with-accessors ((types1 values-type-spec-types)
(rest-type values-type-spec-rest-type)
(rest-p values-type-spec-rest-p))
spec1
(with-accessors ((types2 values-type-spec-types))
spec2
(->
(append
(mapcar (curry #'list combinator) types1 types2)
(mapcar (curry #'list combinator (if rest-p rest-type default-type))
(subseq types2 (length types1))))
(add-optional-keyword spec1 spec2)
(add-rest-keyword spec1 spec2)
(add-allow-other-keys spec1 spec2)))))
(add-optional-keyword (combined spec1 spec2)
(with-accessors ((start1 values-type-spec-optional-start))
spec1
(with-accessors ((start2 values-type-spec-optional-start))
spec2
(cond
((and start1 start2)
(add-&optional combined (min start1 start2)))
((or start1 start2)
(add-&optional combined (or start1 start2)))
(t
combined)))))
(add-&optional (types index)
(append
(subseq types 0 index)
'(&optional)
(subseq types index)))
(add-rest-keyword (combined spec1 spec2)
(with-accessors ((rest-p-1 values-type-spec-rest-p)
(rest1 values-type-spec-rest-type))
spec1
(with-accessors ((rest-p-2 values-type-spec-rest-p)
(rest2 values-type-spec-rest-type))
spec2
(if (or rest-p-1 rest-p-2)
(append combined `(&rest (,combinator ,rest1 ,rest2)))
combined))))
(add-allow-other-keys (combined spec1 spec2)
(if (or (values-type-spec-allow-other-keys spec1)
(values-type-spec-allow-other-keys spec2))
(append combined '(&allow-other-keys))
combined)))
(multiple-value-match (values type1 type2)
(((list* 'values types1)
(list* 'values types2))
(list* 'values (combine types1 types2)))
(((list* 'values types1) _)
(list* 'values (combine types1 (list type2))))
((_ (list* 'values types2))
(list* 'values (combine (list type1) types2)))
((_ _)
(list combinator type1 type2)))))
;;; Basic Form Types
(defvar *use-local-declared-types* t
"Flag for whether the declared types, in the local environment, should be used.
If NIL the declared types in the global NIL environment are used.
The purpose of this is to support LOAD-TIME-VALUE, in which the
form is macroexpanded in the local environment but is actually
evaluated in the global environment, therefore it does not have
access to local variables.")
(defgeneric custom-form-type (operator arguments env)
(:documentation
"Method for determining form types of custom forms.
This is useful for adding special type deduction logic for your
own functions, or for non-standard special forms.
OPERATOR is the form operator.
ARGUMENTS is the list of argument forms.
ENV is the environment in which the form is found. This might not
be a native environment but an augmented environment from
cl-environments.")
(:method (operator arguments env)
(declare (ignore operator arguments env))
t))
(defun list-form-type (operator arguments env)
"Determine the type of a list form.
OPERATOR is the list form operator.
ARGUMENTS is the list of arguments following the operator.
ENV is the environment in which the form occurs."
(match operator
((type symbol)
(special-form-type operator arguments env))
((list* 'cl:lambda lambda-list body)
(match (lambda-expression-type lambda-list body env)
((list 'function _ (and (not '*) result))
result)
(_ t)))
(_ t)))
(defun expand-compiler-macros (operator arguments env)
"Expand compiler-macros in a function call expression.
Only expands compiler macros if *EXPAND-COMPILER-MACROS is set.
OPERATOR is the form operator.
ARGUMENTS is the argument list of the form.
ENV is the environment in which the form is found.
Returns the compiler-macro-expanded form or NIL if there is no
compiler-macro for OPERATOR."
(when-let* ((fn (and *expand-compiler-macros*
(compiler-macro-function operator env)))
(form (funcall fn (cons operator arguments) env)))
(unless (equal form (cons operator arguments))
form)))
(defun variable-type (variable env)
"Determine the type of a variable.
VARIABLE is the symbol naming the variable. This may name a
constant as well.
ENV is the environment in which the variable is found."
(flet ((get-vtype (decl)
(aif (assoc 'type decl)
(cdr it)
t)))
(multiple-value-bind (type local decl)
(variable-information variable (when *use-local-declared-types* env))
(declare (ignore local))
(case type
(:constant
`(eql ,(eval variable)))
((:lexical :special)
(get-vtype decl))
(otherwise t)))))
(defun constant-type (value)
"Return the type specifier of a constant value.
If the value is a CHARACTER, NUMBER or SYMBOL an EQL type specifier
is returned. Otherwise the type specifier returned by TYPE-OF is
returned.
VALUE is the constant value."
(cond
#+sbcl
((and *handle-sb-lvars* (sb-c::lvar-p value))
(let ((type
(-> value
sb-c::lvar-%derived-type
sb-kernel::type-specifier)))
(if (eq type '*) t type)))
(*constant-eql-types*
`(eql ,value))
(t
(typecase value
((or number character symbol) `(eql ,value))
(otherwise
(type-of value))))))
;;; Special Form Types
(defgeneric special-form-type (operator operands env)
(:documentation
"Determine the type of a special form.
OPERATOR is the form operator, which must name a special operator.
OPERANDS is the for argument list.
ENV is the environment in which the form is found."))
(defmethod special-form-type :around (operator operands env)
(declare (ignore operator operands env))
(with-default-type-restart
(call-next-method)))
(defmethod special-form-type (operator arguments env)
"Determine the type of a function call expression.
OPERATOR is the expression operator, which may be a special
operator.
ARGUMENTS is the list of arguments following the operator.
ENV is the environment in which the expression is found."
(flet ((get-ftype (decl)
(match (cdr (assoc 'ftype decl))
((list 'function _ (and (not (eq '*)) return-type))
return-type)
(_ t))))
(multiple-value-bind (type local decl)
(function-information operator (when *use-local-declared-types* env))
(declare (ignore local))
(match (custom-form-type operator arguments env)
(t
(case type
(:function
(aif (expand-compiler-macros operator arguments env)
(form-type% it env)
(get-ftype decl)))
(otherwise t)))
(type type)))))
;;;; QUOTE and FUNCTION
(defmethod special-form-type ((operator (eql 'cl:quote)) operands env)
(declare (ignore env))
(match-form operands
((list thing)
(constant-type thing))))
(defmethod special-form-type ((operator (eql 'cl:function)) operands env)
(match operands
((list (and
(or (type symbol)
(list 'cl:setf (type symbol)))
name))
(multiple-value-bind (type local decl)
(function-information name env)
(declare (ignore local))
(case type
((or nil :function)
(or (cdr (assoc 'ftype decl))
'cl:function))
(otherwise t))))
((list (list* 'cl:lambda lambda-list body))
(lambda-expression-type lambda-list body env))
(_ 'cl:function)))
(defun lambda-expression-type (lambda-list body env)
"Determine the function type of a lambda expression.
LAMBDA-LIST is the lambda-list of the lambda expression.
BODY is the body of the lambda expression (the remainder of the
expression following the lambda-list).
ENV is the environment in which the form containing the lambda
expression is found.
Returns a (FUNCTION ...) specifier."
(with-default-type-restart
(labels ((optional-vars (optional)
(ematch optional
((list var _ nil)
(list var))
((list var1 _ var2)
(list var1 var2))))
(key-vars (key)
(ematch key
((list (list _ var) _ nil)
(list var))
((list (list _ var1) _ var2)
(list var1 var2))))
(required-var-types (required env)
(mapcar (rcurry #'var-type env) required))
(optional-var-types (optional env)
(when optional
(list* '&optional
(mapcar (rcurry #'optional-var-type env) optional))))
(key-var-types (key env)
(mapcar (rcurry #'key-var-type env) key))
(var-type (var env)
(multiple-value-bind (var-type local declarations)
(variable-information var env)
(declare (ignore local))
(or
(when (member var-type '(:lexical :special))
(cdr (assoc 'type declarations)))
'*)))
(optional-var-type (optional env)
(var-type (first optional) env))
(key-var-type (key env)
(ematch key
((list (list keyword var) _ _)
(list keyword
(var-type var env)))))
(rest-var-type (var env)
(match (var-type var env)
((list 'cons type _)
type)
(_ '*))))
(multiple-value-bind (required optional rest key allow-other-keys aux has-key-p)
(parse-ordinary-lambda-list lambda-list)
(multiple-value-bind (body declarations)
(parse-body body :documentation nil)
(let ((env (augment-environment
env
:variable
(append required
(mappend #'optional-vars optional)
(ensure-list rest)
(mappend #'key-vars key)
(mapcar #'cdr aux))
:declare
(mappend #'cdr declarations))))
`(function
,(append
(required-var-types required env)
(optional-var-types optional env)
(when rest (list '&rest (rest-var-type rest env)))
(when has-key-p '(&key))
(key-var-types key env)
(when allow-other-keys '(&allow-other-keys)))
,(form-type% (lastcar body) env))))))))
;;;; THE
(defmethod special-form-type ((operator (eql 'cl:the)) operands env)
(match-form operands
((list type value-form)
(combine-values-types 'and type (form-type% value-form env) t))))
;;;; LOAD-TIME-VALUE
(defmethod special-form-type ((operator (eql 'cl:load-time-value)) operands env)
(match-form operands
((list* value _)
(let ((*use-local-declared-types* nil))
(form-type% value env)))))
;;;; SETQ
(defmethod special-form-type ((operator (eql 'cl:setq)) operands env)
(match-form operands
((guard operands
(and (proper-list-p operands)
(evenp (length operands))))
(form-type% (lastcar operands) env))))
;;;; Conditionals
(defmethod special-form-type ((operator (eql 'cl:if)) operands env)
(match-form operands
((list _ if-true if-false)
(combine-values-types
'or
(form-type% if-true env)
(form-type% if-false env)))
((list _ if-true)
(combine-values-types
'or
(form-type% if-true env)
'null))))
;;;; Multiple value call and PROG1
(defmethod special-form-type ((operator (eql 'cl:multiple-value-call)) operands env)
(match-form operands
((list* function _)
(match (nth-value-type (form-type% function env) 0)
((list 'function _ (and (not (eq '*)) return-type))
return-type)
(_ t)))))
(defmethod special-form-type ((operator (eql 'cl:multiple-value-prog1)) operands env)
(match-form operands
((list* first-form _)
(form-type% first-form env))))
;;; Grouping Forms
(defmethod special-form-type ((operator (eql 'cl:progn)) operands env)
(match-form operands
((type proper-list)
(form-type% (lastcar operands) env))))
(defmethod special-form-type ((operator (eql 'cl:progv)) operands env)
(match-form operands
((list* _ _ (and (type proper-list) forms))
(form-type% (lastcar forms) env))))
(defmethod special-form-type ((operator (eql 'cl:eval-when)) operands env)
(match-form operands
((list* (and (type proper-list) situation)
(and (type proper-list) forms))
(if (or (member :execute situation)
(member 'eval situation))
(form-type% (lastcar forms) env)
'null))))
(defmethod special-form-type ((operator (eql 'cl:unwind-protect)) operands env)
(match-form operands
((list* form _)
(form-type% form env))))
(defmethod special-form-type ((operator (eql 'cl:locally)) operands env)
(match-form operands
((type proper-list)
(multiple-value-bind (body declarations)
(parse-body operands :documentation nil)
(form-type%
(lastcar body)
(augment-environment
env
:declare (mappend #'cdr declarations)))))))
;;; Control Flow Context
(defmethod special-form-type ((operator (eql 'cl:tagbody)) operands env)
(declare (ignore operands env))
nil)
;;;; Control Transfer Forms
;; These all return NIL since they do not return any value, but rather
;; execute a jump.
(defmethod special-form-type ((operator (eql 'cl:go)) operands env)
(declare (ignore operands env))
nil)
(defmethod special-form-type ((operator (eql 'cl:throw)) operands env)
(declare (ignore operands env))
nil)
(defmethod special-form-type ((operator (eql 'cl:return-from)) operands env)
(declare (ignore operands env))
nil)
;;; Local Macro Definitions
(defmethod special-form-type ((operator (eql 'cl:macrolet)) operands env)
(flet ((make-macro (def)
(match-form def
((list* (and (type symbol) name)
(and (type proper-list) lambda-list)
(and (type proper-list) body))
(list name (enclose-macro name lambda-list body env))))))
(match-form operands
((list* (and (type proper-list) macros)
(and (type proper-list) body))
(multiple-value-bind (body declarations)
(parse-body body :documentation nil)
(form-type%
(lastcar body)
(augment-environment
env
:macro (mapcar #'make-macro macros)
:declare (mappend #'cdr declarations))))))))
(defmethod special-form-type ((operator (eql 'cl:symbol-macrolet)) operands env)
(match-form operands
((list* (and (type proper-list) symbol-macros)
(and (type proper-list) body))
(multiple-value-bind (body declarations)
(parse-body body :documentation nil)
(form-type%
(lastcar body)
(augment-environment
env
:symbol-macro symbol-macros
:declare (mappend #'cdr declarations)))))))
;;; Local Variable Binding Forms
(defmethod special-form-type ((operator (eql 'cl:let)) operands env)
(let-form-type operands env))
(defmethod special-form-type ((operator (eql 'cl:let*)) operands env)
(let-form-type operands env))
(defun let-form-type (operands env)
"Determine the type of a LET/LET* form.
OPERANDS is the list of operands to the form.
ENV is the environment in which the form is found."
(flet ((extract-var (binding)
"Extract the variable name from a binding."
(match-form binding
((or (and (type symbol) variable)
(list* (and (type symbol) variable) _))
(list variable)))))
(match-form operands
((list* (and (type proper-list) bindings)
(and (type proper-list) body))
(multiple-value-bind (body declarations)
(parse-body body :documentation nil)
(form-type%
(lastcar body)
(augment-environment
env
:variable (mappend #'extract-var bindings)
:declare (mappend #'cdr declarations))))))))
;;; Local Function Binding Forms
(defmethod special-form-type ((operator (eql 'cl:flet)) operands env)
(flet-form-type operands env))
(defmethod special-form-type ((operator (eql 'cl:labels)) operands env)
(flet-form-type operands env))
(defun flet-form-type (operands env)
"Determine the type of a FLET/LABELS form.
OPERANDS is the list of operands to the form.
ENV is the environment in which the form is found."
(flet ((extract-function (binding)
"Extract the function name from a definition."
(match-form binding
((list* (and (type function-name) name) _)
(list name)))))
(match-form operands
((list* (and (type proper-list) functions)
(and (type proper-list) body))
(multiple-value-bind (body declarations)
(parse-body body :documentation nil)
(form-type%
(lastcar body)
(augment-environment
env
:function (mappend #'extract-function functions)
:declare (mappend #'cdr declarations))))))))
|
[
{
"context": "e for Project Euler Problem 52.\n;;\n;; Code author: Russell A. Edson\n;; Date last modified: 09/07/2021\n\n;; We can simp",
"end": 73,
"score": 0.9997653961181641,
"start": 57,
"tag": "NAME",
"value": "Russell A. Edson"
}
] |
problem_052.lisp
|
RussellAndrewEdson/project_euler_solutions
| 0 |
;; Code for Project Euler Problem 52.
;;
;; Code author: Russell A. Edson
;; Date last modified: 09/07/2021
;; We can simply hit this problem with modern computation in a brute
;; force solution. Define functions to do the digit-wise comparison,
;; and then loop over some sufficiently large set of numbers.
(defun digits (number)
"Return the set of digits in the given NUMBER."
(coerce (write-to-string number) 'list))
(defun contain-same-digits? (number1 number2)
"True if NUMBER1 and NUMBER2 contain the same digits, False if not."
(null (set-exclusive-or (digits number1) (digits number2))))
(loop for i from 1 to 9999999 do
(if (and (contain-same-digits? i (* 2 i))
(contain-same-digits? i (* 3 i))
(contain-same-digits? i (* 4 i))
(contain-same-digits? i (* 5 i))
(contain-same-digits? i (* 6 i)))
(format t "~a~%" i)))
;;=> 142857
;;=> 1428570
;;=> 1429857
|
3851
|
;; Code for Project Euler Problem 52.
;;
;; Code author: <NAME>
;; Date last modified: 09/07/2021
;; We can simply hit this problem with modern computation in a brute
;; force solution. Define functions to do the digit-wise comparison,
;; and then loop over some sufficiently large set of numbers.
(defun digits (number)
"Return the set of digits in the given NUMBER."
(coerce (write-to-string number) 'list))
(defun contain-same-digits? (number1 number2)
"True if NUMBER1 and NUMBER2 contain the same digits, False if not."
(null (set-exclusive-or (digits number1) (digits number2))))
(loop for i from 1 to 9999999 do
(if (and (contain-same-digits? i (* 2 i))
(contain-same-digits? i (* 3 i))
(contain-same-digits? i (* 4 i))
(contain-same-digits? i (* 5 i))
(contain-same-digits? i (* 6 i)))
(format t "~a~%" i)))
;;=> 142857
;;=> 1428570
;;=> 1429857
| true |
;; Code for Project Euler Problem 52.
;;
;; Code author: PI:NAME:<NAME>END_PI
;; Date last modified: 09/07/2021
;; We can simply hit this problem with modern computation in a brute
;; force solution. Define functions to do the digit-wise comparison,
;; and then loop over some sufficiently large set of numbers.
(defun digits (number)
"Return the set of digits in the given NUMBER."
(coerce (write-to-string number) 'list))
(defun contain-same-digits? (number1 number2)
"True if NUMBER1 and NUMBER2 contain the same digits, False if not."
(null (set-exclusive-or (digits number1) (digits number2))))
(loop for i from 1 to 9999999 do
(if (and (contain-same-digits? i (* 2 i))
(contain-same-digits? i (* 3 i))
(contain-same-digits? i (* 4 i))
(contain-same-digits? i (* 5 i))
(contain-same-digits? i (* 6 i)))
(format t "~a~%" i)))
;;=> 142857
;;=> 1428570
;;=> 1429857
|
[
{
"context": "h wave audio files\"\n :version \"0.1.2\"\n :author \"Ryan King <[email protected]>\"\n :license \"MIT License\"\n :seri",
"end": 182,
"score": 0.9998543858528137,
"start": 173,
"tag": "NAME",
"value": "Ryan King"
},
{
"context": "o files\"\n :version \"0.1.2\"\n :author \"Ryan King <[email protected]>\"\n :license \"MIT License\"\n :serial t\n :depends",
"end": 197,
"score": 0.9999266266822815,
"start": 184,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
cl-wave.asd
|
RyanTKing/cl-wave
| 1 |
;;;; cl-wave.asd
;;;;
;;;; ASDF Configuration file
(asdf:defsystem #:cl-wave
:description "A library for interfacing with wave audio files"
:version "0.1.2"
:author "Ryan King <[email protected]>"
:license "MIT License"
:serial t
:depends-on (#:alexandria)
:components ((:file "package")
(:file "riff")
(:file "wave")
(:file "cl-wave")))
|
43348
|
;;;; cl-wave.asd
;;;;
;;;; ASDF Configuration file
(asdf:defsystem #:cl-wave
:description "A library for interfacing with wave audio files"
:version "0.1.2"
:author "<NAME> <<EMAIL>>"
:license "MIT License"
:serial t
:depends-on (#:alexandria)
:components ((:file "package")
(:file "riff")
(:file "wave")
(:file "cl-wave")))
| true |
;;;; cl-wave.asd
;;;;
;;;; ASDF Configuration file
(asdf:defsystem #:cl-wave
:description "A library for interfacing with wave audio files"
:version "0.1.2"
:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:license "MIT License"
:serial t
:depends-on (#:alexandria)
:components ((:file "package")
(:file "riff")
(:file "wave")
(:file "cl-wave")))
|
[
{
"context": "#|\nCopyright (c) 2016 Thomas W. Lynch and Reasoning Technology Inc.\nReleased under the ",
"end": 37,
"score": 0.9998533129692078,
"start": 22,
"tag": "NAME",
"value": "Thomas W. Lynch"
}
] |
src-0/synonyms.lisp
|
Antigonus/tm
| 6 |
#|
Copyright (c) 2016 Thomas W. Lynch and Reasoning Technology Inc.
Released under the MIT License (MIT)
See LICENSE.txt
|#
(in-package #:tm)
;;defsynonym from "Successful Lisp"
(defmacro defsynonym (old-name new-name)
"Define OLD-NAME to be equivalent to NEW-NAME when used in the first position of a Lisp form."
`(defmacro ,new-name (&rest args) `(,',old-name ,@args))
)
;; unicode support
;;
(defconstant ∅ nil)
(defsynonym /= ≠)
(defsynonym <= ≤)
(defsynonym >= ≥)
(defsynonym not ¬)
(defsynonym and ∧)
(defsynonym or ∨)
(defsynonym string/= string≠)
(defsynonym string<= string≤)
(defsynonym string>= string≥)
(defsynonym lambda λ)
(defsynonym defclass def-type)
(defsynonym defgeneric def-function-class)
(defsynonym defmethod defun-typed)
;; prints a new line
;;
(defun nl (&optional (stream t))
"prints a new line"
(format stream "~%")
)
|
2262
|
#|
Copyright (c) 2016 <NAME> and Reasoning Technology Inc.
Released under the MIT License (MIT)
See LICENSE.txt
|#
(in-package #:tm)
;;defsynonym from "Successful Lisp"
(defmacro defsynonym (old-name new-name)
"Define OLD-NAME to be equivalent to NEW-NAME when used in the first position of a Lisp form."
`(defmacro ,new-name (&rest args) `(,',old-name ,@args))
)
;; unicode support
;;
(defconstant ∅ nil)
(defsynonym /= ≠)
(defsynonym <= ≤)
(defsynonym >= ≥)
(defsynonym not ¬)
(defsynonym and ∧)
(defsynonym or ∨)
(defsynonym string/= string≠)
(defsynonym string<= string≤)
(defsynonym string>= string≥)
(defsynonym lambda λ)
(defsynonym defclass def-type)
(defsynonym defgeneric def-function-class)
(defsynonym defmethod defun-typed)
;; prints a new line
;;
(defun nl (&optional (stream t))
"prints a new line"
(format stream "~%")
)
| true |
#|
Copyright (c) 2016 PI:NAME:<NAME>END_PI and Reasoning Technology Inc.
Released under the MIT License (MIT)
See LICENSE.txt
|#
(in-package #:tm)
;;defsynonym from "Successful Lisp"
(defmacro defsynonym (old-name new-name)
"Define OLD-NAME to be equivalent to NEW-NAME when used in the first position of a Lisp form."
`(defmacro ,new-name (&rest args) `(,',old-name ,@args))
)
;; unicode support
;;
(defconstant ∅ nil)
(defsynonym /= ≠)
(defsynonym <= ≤)
(defsynonym >= ≥)
(defsynonym not ¬)
(defsynonym and ∧)
(defsynonym or ∨)
(defsynonym string/= string≠)
(defsynonym string<= string≤)
(defsynonym string>= string≥)
(defsynonym lambda λ)
(defsynonym defclass def-type)
(defsynonym defgeneric def-function-class)
(defsynonym defmethod defun-typed)
;; prints a new line
;;
(defun nl (&optional (stream t))
"prints a new line"
(format stream "~%")
)
|
[
{
"context": "\n;;; given function.\n;;;\n;;; Copyright © 2014–2018 Mark Karpov\n;;;\n;;; Permission is hereby granted, free of cha",
"end": 191,
"score": 0.999866783618927,
"start": 180,
"tag": "NAME",
"value": "Mark Karpov"
}
] |
trivial-update.lisp
|
cbaggers/trivial-update
| 2 |
;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp -*-
;;;
;;; The library that provides tools for easy modification of places with any
;;; given function.
;;;
;;; Copyright © 2014–2018 Mark Karpov
;;;
;;; Permission is hereby granted, free of charge, to any person obtaining a
;;; copy of this software and associated documentation files (the
;;; "Software"), to deal in the Software without restriction, including
;;; without limitation the rights to use, copy, modify, merge, publish,
;;; distribute, sublicense, and/or sell copies of the Software, and to
;;; permit persons to whom the Software is furnished to do so, subject to
;;; the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be included
;;; in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
;;; OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
;;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
;;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
;;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(defpackage :trivial-update
(:use #:common-lisp)
(:export #:update))
(in-package #:trivial-update)
(defmacro update (place fn &rest args &environment env)
"Replace value at PLACE by applying function FN to it. Value at PLACE is
used as the first argument for given function FN, other optional arguments
ARGS will be used to fill the rest of the argument list. Parameter ENV is
set by Common Lisp implementation during macro expansion.
If value at PLACE should not be put as first argument of given function, use
partial application to pad some arguments. Combination of currying and &REST
arguments will give you opportunity to pass old value at PLACE on any
position in the argument list.
Remember that keyword parameters are just pairs of normal arguments."
(multiple-value-bind (vars forms result writer-form reader-form)
(get-setf-expansion place env)
(let ((g (gensym)))
`(let* ((,g ,fn)
,@(mapcar #'list vars forms)
(,(car result) (funcall ,g ,reader-form ,@args)))
,writer-form))))
|
10223
|
;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp -*-
;;;
;;; The library that provides tools for easy modification of places with any
;;; given function.
;;;
;;; Copyright © 2014–2018 <NAME>
;;;
;;; Permission is hereby granted, free of charge, to any person obtaining a
;;; copy of this software and associated documentation files (the
;;; "Software"), to deal in the Software without restriction, including
;;; without limitation the rights to use, copy, modify, merge, publish,
;;; distribute, sublicense, and/or sell copies of the Software, and to
;;; permit persons to whom the Software is furnished to do so, subject to
;;; the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be included
;;; in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
;;; OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
;;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
;;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
;;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(defpackage :trivial-update
(:use #:common-lisp)
(:export #:update))
(in-package #:trivial-update)
(defmacro update (place fn &rest args &environment env)
"Replace value at PLACE by applying function FN to it. Value at PLACE is
used as the first argument for given function FN, other optional arguments
ARGS will be used to fill the rest of the argument list. Parameter ENV is
set by Common Lisp implementation during macro expansion.
If value at PLACE should not be put as first argument of given function, use
partial application to pad some arguments. Combination of currying and &REST
arguments will give you opportunity to pass old value at PLACE on any
position in the argument list.
Remember that keyword parameters are just pairs of normal arguments."
(multiple-value-bind (vars forms result writer-form reader-form)
(get-setf-expansion place env)
(let ((g (gensym)))
`(let* ((,g ,fn)
,@(mapcar #'list vars forms)
(,(car result) (funcall ,g ,reader-form ,@args)))
,writer-form))))
| true |
;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp -*-
;;;
;;; The library that provides tools for easy modification of places with any
;;; given function.
;;;
;;; Copyright © 2014–2018 PI:NAME:<NAME>END_PI
;;;
;;; Permission is hereby granted, free of charge, to any person obtaining a
;;; copy of this software and associated documentation files (the
;;; "Software"), to deal in the Software without restriction, including
;;; without limitation the rights to use, copy, modify, merge, publish,
;;; distribute, sublicense, and/or sell copies of the Software, and to
;;; permit persons to whom the Software is furnished to do so, subject to
;;; the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be included
;;; in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
;;; OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
;;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
;;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
;;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(defpackage :trivial-update
(:use #:common-lisp)
(:export #:update))
(in-package #:trivial-update)
(defmacro update (place fn &rest args &environment env)
"Replace value at PLACE by applying function FN to it. Value at PLACE is
used as the first argument for given function FN, other optional arguments
ARGS will be used to fill the rest of the argument list. Parameter ENV is
set by Common Lisp implementation during macro expansion.
If value at PLACE should not be put as first argument of given function, use
partial application to pad some arguments. Combination of currying and &REST
arguments will give you opportunity to pass old value at PLACE on any
position in the argument list.
Remember that keyword parameters are just pairs of normal arguments."
(multiple-value-bind (vars forms result writer-form reader-form)
(get-setf-expansion place env)
(let ((g (gensym)))
`(let* ((,g ,fn)
,@(mapcar #'list vars forms)
(,(car result) (funcall ,g ,reader-form ,@args)))
,writer-form))))
|
[
{
"context": ";; copyright (c) 2020 by Andrei Borac\n\n(require \"abort.lisp\")\n(require \"stdlib.lisp\")\n(",
"end": 37,
"score": 0.9998701214790344,
"start": 25,
"tag": "NAME",
"value": "Andrei Borac"
}
] |
programs/udriver/002-progname/main.lisp
|
AndreiBorac/nocaml
| 2 |
;; copyright (c) 2020 by Andrei Borac
(require "abort.lisp")
(require "stdlib.lisp")
(require "stdopt.lisp")
(require "pitab.lisp")
(require "stdio.lisp")
(defun main (argv envp)
(case argv
((ListFini) one)
((ListCons head tail)
(progn
(stdio-write-fully (stdio-new) one head zero (blob-length head (Integer)))
zero))))
|
89182
|
;; copyright (c) 2020 by <NAME>
(require "abort.lisp")
(require "stdlib.lisp")
(require "stdopt.lisp")
(require "pitab.lisp")
(require "stdio.lisp")
(defun main (argv envp)
(case argv
((ListFini) one)
((ListCons head tail)
(progn
(stdio-write-fully (stdio-new) one head zero (blob-length head (Integer)))
zero))))
| true |
;; copyright (c) 2020 by PI:NAME:<NAME>END_PI
(require "abort.lisp")
(require "stdlib.lisp")
(require "stdopt.lisp")
(require "pitab.lisp")
(require "stdio.lisp")
(defun main (argv envp)
(case argv
((ListFini) one)
((ListCons head tail)
(progn
(stdio-write-fully (stdio-new) one head zero (blob-length head (Integer)))
zero))))
|
[
{
"context": "; DEALINGS IN THE SOFTWARE.\n;\n; Original author: Sol Swords <[email protected]>\n\n(in-package \"ACL2\")\n\n(def",
"end": 1416,
"score": 0.9998733401298523,
"start": 1406,
"tag": "NAME",
"value": "Sol Swords"
},
{
"context": "IN THE SOFTWARE.\n;\n; Original author: Sol Swords <[email protected]>\n\n(in-package \"ACL2\")\n\n(defpkg \"GL\"\n (set-differe",
"end": 1438,
"score": 0.9999302625656128,
"start": 1418,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "gl\n\n\n ))\n '(nat-listp ; included 12/4/2012 by Matt K., for addition to *acl2-exports*\n )))\n\n(defpkg",
"end": 5806,
"score": 0.9600112438201904,
"start": 5800,
"tag": "NAME",
"value": "Matt K"
}
] |
books/centaur/gl/package.lsp
|
ragerdl/acl2-defthm-rc2
| 1 |
; GL - A Symbolic Simulation Framework for ACL2
; Copyright (C) 2008-2013 Centaur Technology
;
; Contact:
; Centaur Technology Formal Verification Group
; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA.
; http://www.centtech.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: Sol Swords <[email protected]>
(in-package "ACL2")
(defpkg "GL"
(set-difference-eq
(union-eq
*acl2-exports*
*common-lisp-symbols-from-main-lisp-package*
'(pkg-witness bad-atom<= b* quit exit
hons-acons hons-get hut het hqual hons-equal
hons-assoc-equal make-fal
definline definlined
defxdoc defsection define
__function__
alist-keys alist-vals
qv bfr-and bfr-not bfr-and
bfr-p bfr-or bfr-xor bfr-iff bfr-ite bfr-eval bfr-eval-list
q-implies add-bfr-fn add-bfr-pat add-bfr-fn-pat max-depth
equal-by-bfr-evals-hint-heavy
equal-of-booleans-rewrite bfr-ite-fn q-implies-fn bfr-or
bfr-eval-when-non-consp-values
|(bfr-ite non-nil y z)|
bfr-eval-when-not-consp
bfr-eval-of-non-consp-cheap
bfr-eval-cp-default-hint
bfr-eval-list-when-not-consp
bfr-p-of-bfr-and
bfr-p-of-bfr-not
bfr-p-of-bfr-ite
bfr-p-of-bfr-xor
bfr-p-of-bfr-iff
bfr-p-of-bfr-or
bfr-p-of-q-implies
lnfix lifix lbfix
mv-nth-cons-meta
def-ruleset def-ruleset! add-to-ruleset add-to-ruleset! e/d* enable*
disable* e/d** ruleset-theory
allow-arith5-help
with-arith5-help
arith5-enable-ruleset
arith5-disable-ruleset
prove-guard-invariants
add-untranslate-pattern
def-pattern-match-constructor
defn getprop body
formals stobjs-out theorem recursivep current-acl2-world
unnormalized-body def-bodies
make-n-vars
binary-logand binary-logior name wrld
minimal-arithmetic-theory
minimal-theory
pattern-match
alphorder lexorder
mfc-clause
natp-compound-recognizer
zp-open
add-def-complex
inverse-of-+
translate1
value
default-+-2
default-<-1
default-+-1
default-<-2
default-*-1 default-*-2
default-unary-/
parse-clause-id
is-prefix subgoal-of
bfr-eval-of-bfr-and
bfr-eval-of-bfr-or
bfr-eval-of-bfr-not
a b c d e f g h i j k l m n o p q r s t u v w x y z
fold-constants-in-plus
simplify-products-gather-exponents-equal
simplify-products-gather-exponents-<
lhs rhs
rational-implies1
rational-implies2
default-plus-1
default-plus-2
acl2-numberp-x
INTEGERP-MINUS-X NUMERATOR-ZERO NUMERATOR-POSITIVE
NUMERATOR-NEGATIVE DEFAULT-LESS-THAN-1
DEFAULT-LESS-THAN-2 SIMPLIFY-SUMS-EQUAL
PREFER-POSITIVE-ADDENDS-EQUAL
DEFAULT-TIMES-1 NOT-INTEGERP-1A
PREFER-POSITIVE-ADDENDS-<
SIMPLIFY-SUMS-< META-INTEGERP-CORRECT
REDUCE-INTEGERP-+ ASH-TO-FLOOR
RATIONALP-X REDUCE-ADDITIVE-CONSTANT-<
REDUCE-MULTIPLICATIVE-CONSTANT-<
|(logand y x)|
|(< (logand x y) 0)| NOT-INTEGERP-4A
NOT-INTEGERP-4B FLOOR-ZERO
CANCEL-FLOOR-+ INTEGERP-/-EXPT-2
FLOOR-NEGATIVE FLOOR-POSITIVE
NOT-INTEGERP-3B INTEGERP-/-EXPT-1
NOT-INTEGERP-3A FLOOR-NONPOSITIVE
NOT-INTEGERP-2A FLOOR-NONNEGATIVE
NOT-INTEGERP-2B NOT-INTEGERP-1B
FLOOR-X-Y-=-1 NOT-INTEGERP-4B
DEFAULT-TIMES-2 FLOOR-=-X/Y
EXPT-TYPE-PRESCRIPTION-NONPOSITIVE-BASE-ODD-EXPONENT
EXPT-TYPE-PRESCRIPTION-NONPOSITIVE-BASE-EVEN-EXPONENT
EXPT-TYPE-PRESCRIPTION-NEGATIVE-BASE-ODD-EXPONENT
EXPT-TYPE-PRESCRIPTION-NEGATIVE-BASE-EVEN-EXPONENT
BOOLEAN-LISTP MOD-ZERO MOD-NEGATIVE
conjoin-clauses conjoin disjoin disjoin-lst
pseudo-term-list-listp
two-nats-measure
flag-present flag-fn-name flag-alist flag-defthm-macro flag-equivs-name
use-by-hint use-by-computed-hint
def-gl-clause-processor gl-hint
def-gl-thm def-gl-param-thm
def-g-thm def-g-param-thm make-g-world
mk-g-number mk-g-boolean mk-g-ite mk-g-concrete
gobjectp glc glr gl-fnsym gl-interp
gl-interp-raw gl-interp
gl-aside gl-ignore nonnil-symbol-listp
def-gl-rule
def-gl-ruled
def-gl-rulel
def-gl-ruledl
xor
gl-bdd-mode gl-aig-mode gl-mbe
logcons logcar logcdr loghead logtail logapp
b-ior b-and b-xor b-not bfix bitp boolfix
numlist
defsection
;; some imports for better xdoc integration
hardware-verification
proof-automation
boolean-reasoning
satlink
ubdds
aig
acl2::hons-and-memoization
xdoc
set-max-mem
the-method
aignet
gl
))
'(nat-listp ; included 12/4/2012 by Matt K., for addition to *acl2-exports*
)))
(defpkg "GL-SYM" nil)
(defpkg "GL-THM" nil)
(defpkg "GL-FACT" nil)
(defpkg "GL-FLAG" nil)
;; (defmacro gl::include-book (&rest args)
;; `(acl2::include-book ,@args :ttags :all))
|
55074
|
; GL - A Symbolic Simulation Framework for ACL2
; Copyright (C) 2008-2013 Centaur Technology
;
; Contact:
; Centaur Technology Formal Verification Group
; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA.
; http://www.centtech.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: <NAME> <<EMAIL>>
(in-package "ACL2")
(defpkg "GL"
(set-difference-eq
(union-eq
*acl2-exports*
*common-lisp-symbols-from-main-lisp-package*
'(pkg-witness bad-atom<= b* quit exit
hons-acons hons-get hut het hqual hons-equal
hons-assoc-equal make-fal
definline definlined
defxdoc defsection define
__function__
alist-keys alist-vals
qv bfr-and bfr-not bfr-and
bfr-p bfr-or bfr-xor bfr-iff bfr-ite bfr-eval bfr-eval-list
q-implies add-bfr-fn add-bfr-pat add-bfr-fn-pat max-depth
equal-by-bfr-evals-hint-heavy
equal-of-booleans-rewrite bfr-ite-fn q-implies-fn bfr-or
bfr-eval-when-non-consp-values
|(bfr-ite non-nil y z)|
bfr-eval-when-not-consp
bfr-eval-of-non-consp-cheap
bfr-eval-cp-default-hint
bfr-eval-list-when-not-consp
bfr-p-of-bfr-and
bfr-p-of-bfr-not
bfr-p-of-bfr-ite
bfr-p-of-bfr-xor
bfr-p-of-bfr-iff
bfr-p-of-bfr-or
bfr-p-of-q-implies
lnfix lifix lbfix
mv-nth-cons-meta
def-ruleset def-ruleset! add-to-ruleset add-to-ruleset! e/d* enable*
disable* e/d** ruleset-theory
allow-arith5-help
with-arith5-help
arith5-enable-ruleset
arith5-disable-ruleset
prove-guard-invariants
add-untranslate-pattern
def-pattern-match-constructor
defn getprop body
formals stobjs-out theorem recursivep current-acl2-world
unnormalized-body def-bodies
make-n-vars
binary-logand binary-logior name wrld
minimal-arithmetic-theory
minimal-theory
pattern-match
alphorder lexorder
mfc-clause
natp-compound-recognizer
zp-open
add-def-complex
inverse-of-+
translate1
value
default-+-2
default-<-1
default-+-1
default-<-2
default-*-1 default-*-2
default-unary-/
parse-clause-id
is-prefix subgoal-of
bfr-eval-of-bfr-and
bfr-eval-of-bfr-or
bfr-eval-of-bfr-not
a b c d e f g h i j k l m n o p q r s t u v w x y z
fold-constants-in-plus
simplify-products-gather-exponents-equal
simplify-products-gather-exponents-<
lhs rhs
rational-implies1
rational-implies2
default-plus-1
default-plus-2
acl2-numberp-x
INTEGERP-MINUS-X NUMERATOR-ZERO NUMERATOR-POSITIVE
NUMERATOR-NEGATIVE DEFAULT-LESS-THAN-1
DEFAULT-LESS-THAN-2 SIMPLIFY-SUMS-EQUAL
PREFER-POSITIVE-ADDENDS-EQUAL
DEFAULT-TIMES-1 NOT-INTEGERP-1A
PREFER-POSITIVE-ADDENDS-<
SIMPLIFY-SUMS-< META-INTEGERP-CORRECT
REDUCE-INTEGERP-+ ASH-TO-FLOOR
RATIONALP-X REDUCE-ADDITIVE-CONSTANT-<
REDUCE-MULTIPLICATIVE-CONSTANT-<
|(logand y x)|
|(< (logand x y) 0)| NOT-INTEGERP-4A
NOT-INTEGERP-4B FLOOR-ZERO
CANCEL-FLOOR-+ INTEGERP-/-EXPT-2
FLOOR-NEGATIVE FLOOR-POSITIVE
NOT-INTEGERP-3B INTEGERP-/-EXPT-1
NOT-INTEGERP-3A FLOOR-NONPOSITIVE
NOT-INTEGERP-2A FLOOR-NONNEGATIVE
NOT-INTEGERP-2B NOT-INTEGERP-1B
FLOOR-X-Y-=-1 NOT-INTEGERP-4B
DEFAULT-TIMES-2 FLOOR-=-X/Y
EXPT-TYPE-PRESCRIPTION-NONPOSITIVE-BASE-ODD-EXPONENT
EXPT-TYPE-PRESCRIPTION-NONPOSITIVE-BASE-EVEN-EXPONENT
EXPT-TYPE-PRESCRIPTION-NEGATIVE-BASE-ODD-EXPONENT
EXPT-TYPE-PRESCRIPTION-NEGATIVE-BASE-EVEN-EXPONENT
BOOLEAN-LISTP MOD-ZERO MOD-NEGATIVE
conjoin-clauses conjoin disjoin disjoin-lst
pseudo-term-list-listp
two-nats-measure
flag-present flag-fn-name flag-alist flag-defthm-macro flag-equivs-name
use-by-hint use-by-computed-hint
def-gl-clause-processor gl-hint
def-gl-thm def-gl-param-thm
def-g-thm def-g-param-thm make-g-world
mk-g-number mk-g-boolean mk-g-ite mk-g-concrete
gobjectp glc glr gl-fnsym gl-interp
gl-interp-raw gl-interp
gl-aside gl-ignore nonnil-symbol-listp
def-gl-rule
def-gl-ruled
def-gl-rulel
def-gl-ruledl
xor
gl-bdd-mode gl-aig-mode gl-mbe
logcons logcar logcdr loghead logtail logapp
b-ior b-and b-xor b-not bfix bitp boolfix
numlist
defsection
;; some imports for better xdoc integration
hardware-verification
proof-automation
boolean-reasoning
satlink
ubdds
aig
acl2::hons-and-memoization
xdoc
set-max-mem
the-method
aignet
gl
))
'(nat-listp ; included 12/4/2012 by <NAME>., for addition to *acl2-exports*
)))
(defpkg "GL-SYM" nil)
(defpkg "GL-THM" nil)
(defpkg "GL-FACT" nil)
(defpkg "GL-FLAG" nil)
;; (defmacro gl::include-book (&rest args)
;; `(acl2::include-book ,@args :ttags :all))
| true |
; GL - A Symbolic Simulation Framework for ACL2
; Copyright (C) 2008-2013 Centaur Technology
;
; Contact:
; Centaur Technology Formal Verification Group
; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA.
; http://www.centtech.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
(in-package "ACL2")
(defpkg "GL"
(set-difference-eq
(union-eq
*acl2-exports*
*common-lisp-symbols-from-main-lisp-package*
'(pkg-witness bad-atom<= b* quit exit
hons-acons hons-get hut het hqual hons-equal
hons-assoc-equal make-fal
definline definlined
defxdoc defsection define
__function__
alist-keys alist-vals
qv bfr-and bfr-not bfr-and
bfr-p bfr-or bfr-xor bfr-iff bfr-ite bfr-eval bfr-eval-list
q-implies add-bfr-fn add-bfr-pat add-bfr-fn-pat max-depth
equal-by-bfr-evals-hint-heavy
equal-of-booleans-rewrite bfr-ite-fn q-implies-fn bfr-or
bfr-eval-when-non-consp-values
|(bfr-ite non-nil y z)|
bfr-eval-when-not-consp
bfr-eval-of-non-consp-cheap
bfr-eval-cp-default-hint
bfr-eval-list-when-not-consp
bfr-p-of-bfr-and
bfr-p-of-bfr-not
bfr-p-of-bfr-ite
bfr-p-of-bfr-xor
bfr-p-of-bfr-iff
bfr-p-of-bfr-or
bfr-p-of-q-implies
lnfix lifix lbfix
mv-nth-cons-meta
def-ruleset def-ruleset! add-to-ruleset add-to-ruleset! e/d* enable*
disable* e/d** ruleset-theory
allow-arith5-help
with-arith5-help
arith5-enable-ruleset
arith5-disable-ruleset
prove-guard-invariants
add-untranslate-pattern
def-pattern-match-constructor
defn getprop body
formals stobjs-out theorem recursivep current-acl2-world
unnormalized-body def-bodies
make-n-vars
binary-logand binary-logior name wrld
minimal-arithmetic-theory
minimal-theory
pattern-match
alphorder lexorder
mfc-clause
natp-compound-recognizer
zp-open
add-def-complex
inverse-of-+
translate1
value
default-+-2
default-<-1
default-+-1
default-<-2
default-*-1 default-*-2
default-unary-/
parse-clause-id
is-prefix subgoal-of
bfr-eval-of-bfr-and
bfr-eval-of-bfr-or
bfr-eval-of-bfr-not
a b c d e f g h i j k l m n o p q r s t u v w x y z
fold-constants-in-plus
simplify-products-gather-exponents-equal
simplify-products-gather-exponents-<
lhs rhs
rational-implies1
rational-implies2
default-plus-1
default-plus-2
acl2-numberp-x
INTEGERP-MINUS-X NUMERATOR-ZERO NUMERATOR-POSITIVE
NUMERATOR-NEGATIVE DEFAULT-LESS-THAN-1
DEFAULT-LESS-THAN-2 SIMPLIFY-SUMS-EQUAL
PREFER-POSITIVE-ADDENDS-EQUAL
DEFAULT-TIMES-1 NOT-INTEGERP-1A
PREFER-POSITIVE-ADDENDS-<
SIMPLIFY-SUMS-< META-INTEGERP-CORRECT
REDUCE-INTEGERP-+ ASH-TO-FLOOR
RATIONALP-X REDUCE-ADDITIVE-CONSTANT-<
REDUCE-MULTIPLICATIVE-CONSTANT-<
|(logand y x)|
|(< (logand x y) 0)| NOT-INTEGERP-4A
NOT-INTEGERP-4B FLOOR-ZERO
CANCEL-FLOOR-+ INTEGERP-/-EXPT-2
FLOOR-NEGATIVE FLOOR-POSITIVE
NOT-INTEGERP-3B INTEGERP-/-EXPT-1
NOT-INTEGERP-3A FLOOR-NONPOSITIVE
NOT-INTEGERP-2A FLOOR-NONNEGATIVE
NOT-INTEGERP-2B NOT-INTEGERP-1B
FLOOR-X-Y-=-1 NOT-INTEGERP-4B
DEFAULT-TIMES-2 FLOOR-=-X/Y
EXPT-TYPE-PRESCRIPTION-NONPOSITIVE-BASE-ODD-EXPONENT
EXPT-TYPE-PRESCRIPTION-NONPOSITIVE-BASE-EVEN-EXPONENT
EXPT-TYPE-PRESCRIPTION-NEGATIVE-BASE-ODD-EXPONENT
EXPT-TYPE-PRESCRIPTION-NEGATIVE-BASE-EVEN-EXPONENT
BOOLEAN-LISTP MOD-ZERO MOD-NEGATIVE
conjoin-clauses conjoin disjoin disjoin-lst
pseudo-term-list-listp
two-nats-measure
flag-present flag-fn-name flag-alist flag-defthm-macro flag-equivs-name
use-by-hint use-by-computed-hint
def-gl-clause-processor gl-hint
def-gl-thm def-gl-param-thm
def-g-thm def-g-param-thm make-g-world
mk-g-number mk-g-boolean mk-g-ite mk-g-concrete
gobjectp glc glr gl-fnsym gl-interp
gl-interp-raw gl-interp
gl-aside gl-ignore nonnil-symbol-listp
def-gl-rule
def-gl-ruled
def-gl-rulel
def-gl-ruledl
xor
gl-bdd-mode gl-aig-mode gl-mbe
logcons logcar logcdr loghead logtail logapp
b-ior b-and b-xor b-not bfix bitp boolfix
numlist
defsection
;; some imports for better xdoc integration
hardware-verification
proof-automation
boolean-reasoning
satlink
ubdds
aig
acl2::hons-and-memoization
xdoc
set-max-mem
the-method
aignet
gl
))
'(nat-listp ; included 12/4/2012 by PI:NAME:<NAME>END_PI., for addition to *acl2-exports*
)))
(defpkg "GL-SYM" nil)
(defpkg "GL-THM" nil)
(defpkg "GL-FACT" nil)
(defpkg "GL-FLAG" nil)
;; (defmacro gl::include-book (&rest args)
;; `(acl2::include-book ,@args :ttags :all))
|
[
{
"context": "is a part of dexador project.\n Copyright (c) 2015 Eitaro Fukamachi ([email protected])\n|#\n\n(defsystem \"dexador-test",
"end": 82,
"score": 0.9998825788497925,
"start": 66,
"tag": "NAME",
"value": "Eitaro Fukamachi"
},
{
"context": "r project.\n Copyright (c) 2015 Eitaro Fukamachi ([email protected])\n|#\n\n(defsystem \"dexador-test\"\n :author \"Eitaro ",
"end": 102,
"score": 0.9999212622642517,
"start": 84,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "ail.com)\n|#\n\n(defsystem \"dexador-test\"\n :author \"Eitaro Fukamachi\"\n :license \"MIT\"\n :depends-on (\"dexador\"\n ",
"end": 161,
"score": 0.9998798370361328,
"start": 145,
"tag": "NAME",
"value": "Eitaro Fukamachi"
}
] |
vendor/quicklisp/dists/quicklisp/software/dexador-20210807-git/dexador-test.asd
|
corpix/clx
| 0 |
#|
This file is a part of dexador project.
Copyright (c) 2015 Eitaro Fukamachi ([email protected])
|#
(defsystem "dexador-test"
:author "Eitaro Fukamachi"
:license "MIT"
:depends-on ("dexador"
"rove"
"lack-request"
"clack-test"
"babel"
"cl-cookie")
:components ((:module "t"
:components
((:file "dexador"))))
:perform (test-op (op c) (symbol-call '#:rove '#:run c)))
|
82894
|
#|
This file is a part of dexador project.
Copyright (c) 2015 <NAME> (<EMAIL>)
|#
(defsystem "dexador-test"
:author "<NAME>"
:license "MIT"
:depends-on ("dexador"
"rove"
"lack-request"
"clack-test"
"babel"
"cl-cookie")
:components ((:module "t"
:components
((:file "dexador"))))
:perform (test-op (op c) (symbol-call '#:rove '#:run c)))
| true |
#|
This file is a part of dexador project.
Copyright (c) 2015 PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
|#
(defsystem "dexador-test"
:author "PI:NAME:<NAME>END_PI"
:license "MIT"
:depends-on ("dexador"
"rove"
"lack-request"
"clack-test"
"babel"
"cl-cookie")
:components ((:module "t"
:components
((:file "dexador"))))
:perform (test-op (op c) (symbol-call '#:rove '#:run c)))
|
[
{
"context": ";;; (C) Copyright 1990 - 2014 by Wade L. Hennessey. All rights reserved.\n\n(defmacro defprimitive (na",
"end": 50,
"score": 0.9998784065246582,
"start": 33,
"tag": "NAME",
"value": "Wade L. Hennessey"
}
] |
src/compiler/macros.lisp
|
wadehennessey/wcl
| 73 |
;;; (C) Copyright 1990 - 2014 by Wade L. Hennessey. All rights reserved.
(defmacro defprimitive (name in/out &body body)
(multiple-value-bind (ins outs in-types out-types)
(parse-in/out in/out)
`(eval-when (compile load eval)
(define-primitive
',name ',ins ',outs
(mapcar #'c-type-name->c-type-object ',in-types)
(mapcar #'c-type-name->c-type-object ',out-types)
#'(lambda ,ins ,@body)))))
(defmacro emit-c (string &rest args)
`(format *c-stream* ,string ,@args))
(defmacro emit-lc (tree string &rest args)
`(progn (emit-source-line ,tree)
(format *c-stream* ,string ,@args)))
(defmacro emit-k (string &rest args)
`(format *k-stream* ,string ,@args))
(defmacro emit-win (string &rest args)
`(format *win-stream* ,string ,@args))
;;; other macros are already in the library or in com/cross/macros.lisp
|
30548
|
;;; (C) Copyright 1990 - 2014 by <NAME>. All rights reserved.
(defmacro defprimitive (name in/out &body body)
(multiple-value-bind (ins outs in-types out-types)
(parse-in/out in/out)
`(eval-when (compile load eval)
(define-primitive
',name ',ins ',outs
(mapcar #'c-type-name->c-type-object ',in-types)
(mapcar #'c-type-name->c-type-object ',out-types)
#'(lambda ,ins ,@body)))))
(defmacro emit-c (string &rest args)
`(format *c-stream* ,string ,@args))
(defmacro emit-lc (tree string &rest args)
`(progn (emit-source-line ,tree)
(format *c-stream* ,string ,@args)))
(defmacro emit-k (string &rest args)
`(format *k-stream* ,string ,@args))
(defmacro emit-win (string &rest args)
`(format *win-stream* ,string ,@args))
;;; other macros are already in the library or in com/cross/macros.lisp
| true |
;;; (C) Copyright 1990 - 2014 by PI:NAME:<NAME>END_PI. All rights reserved.
(defmacro defprimitive (name in/out &body body)
(multiple-value-bind (ins outs in-types out-types)
(parse-in/out in/out)
`(eval-when (compile load eval)
(define-primitive
',name ',ins ',outs
(mapcar #'c-type-name->c-type-object ',in-types)
(mapcar #'c-type-name->c-type-object ',out-types)
#'(lambda ,ins ,@body)))))
(defmacro emit-c (string &rest args)
`(format *c-stream* ,string ,@args))
(defmacro emit-lc (tree string &rest args)
`(progn (emit-source-line ,tree)
(format *c-stream* ,string ,@args)))
(defmacro emit-k (string &rest args)
`(format *k-stream* ,string ,@args))
(defmacro emit-win (string &rest args)
`(format *win-stream* ,string ,@args))
;;; other macros are already in the library or in com/cross/macros.lisp
|
[
{
"context": ";;;; Copyright (c) Frank James 2015 <[email protected]>\r\n;;;; This code is",
"end": 30,
"score": 0.9998288750648499,
"start": 19,
"tag": "NAME",
"value": "Frank James"
},
{
"context": ";;;; Copyright (c) Frank James 2015 <[email protected]>\r\n;;;; This code is licensed under the MIT licens",
"end": 60,
"score": 0.9999277591705322,
"start": 37,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
src/nexus.lisp
|
fjames86/cliocp
| 0 |
;;;; Copyright (c) Frank James 2015 <[email protected]>
;;;; This code is licensed under the MIT license.
(in-package #:cliocp)
;; global (toplevel) state
;; includes iocp handle, freelist of foreign data etc
(defclass nexus ()
((iocp :initarg :iocp :accessor nexus-iocp)
(key :initform 0 :accessor nexus-key)
(devices :initform nil :accessor nexus-devices)
(id :initarg :id :initform 0 :accessor nexus-id)
(buffer-size :initarg :buffer-size :initform +buffer-size+ :reader nexus-buffer-size)
(freelist :initform nil :initarg :freelist :accessor nexus-freelist)
(all-foreign :initform nil :accessor nexus-all-foreign)
(requests :initform nil :accessor nexus-requests)))
(defmethod initialize-instance :after ((nexus nexus) &rest initargs &key nthreads buffer-count &allow-other-keys)
(declare (ignore initargs))
(let* ((bcount (or buffer-count 32))
(f (loop :for i :below bcount
:collect (allocate-foreign i (nexus-buffer-size nexus)))))
(setf (nexus-iocp nexus) (open-iocp (or nthreads 0))
(nexus-freelist nexus) f
(nexus-all-foreign nexus) f
(nexus-id nexus) bcount)))
(defun open-nexus ()
(make-instance 'nexus))
(defun close-nexus (nexus)
(declare (type nexus nexus))
;; close all devices
(dolist (d (nexus-devices nexus))
(unregister-device nexus d))
;; close iocp handle
(close-iocp (nexus-iocp nexus))
;; free all foreign
(dolist (f (nexus-all-foreign nexus))
(free-foreign f)))
(defun acquire-foreign (nexus)
(declare (type nexus nexus))
(cond
((nexus-freelist nexus)
(pop (nexus-freelist nexus)))
(t
(incf (nexus-id nexus))
(let ((f (allocate-foreign (nexus-id nexus) (nexus-buffer-size nexus))))
(push f (nexus-all-foreign nexus))
f))))
(defun release-foreign (nexus f)
(declare (type nexus nexus)
(type foreign f))
(push f (nexus-freelist nexus)))
;; --------------------------------------
(defclass device ()
((key :initform nil :accessor device-key)
(handle :initarg :handle :reader device-handle)))
(defgeneric close-device (device))
(defun register-device (nexus device &key (associate t))
(declare (type nexus nexus)
(type device device))
;; allocate this device a key
(incf (nexus-key nexus))
(let ((key (nexus-key nexus)))
;; associate with IOCP
(when associate
(iocp-associate (nexus-iocp nexus) (device-handle device) key))
(setf (device-key device) key)
;; store in assoc list
(push device (nexus-devices nexus)))
device)
(defun unregister-device (nexus device-or-key)
(declare (type nexus nexus)
(type (or integer device) device-or-key))
(etypecase device-or-key
(integer
(let ((d (find-device nexus device-or-key)))
(close-device d)
(setf (nexus-devices nexus)
(remove d (nexus-devices nexus) :test #'eq))))
(device
(close-device device-or-key)
(setf (nexus-devices nexus)
(remove device-or-key (nexus-devices nexus)
:test #'eq)))))
(defun find-device (nexus key-or-type)
(declare (type nexus nexus)
(type (or integer symbol) key-or-type))
(etypecase key-or-type
(integer (find key-or-type (nexus-devices nexus)
:test #'= :key #'device-key))
(symbol (find-if (lambda (dev)
(typep dev key-or-type))
(nexus-devices nexus)))))
;; ---------------------------------------
(defclass request ()
((foreign :initform nil :accessor request-foreign)))
(defun request-id (request)
(declare (type request request))
(foreign-id (request-foreign request)))
(defgeneric nexus-schedule-request (nexus device request))
(defun schedule-request (nexus device request &rest initargs)
(declare (type nexus nexus)
(type device device)
(type (or request symbol class) request))
(let ((r (etypecase request
(request request)
(symbol (apply #'make-instance request initargs))
(class (apply #'make-instance request initargs)))))
;; acquire a foreign and provide it to the request
(let ((f (acquire-foreign nexus)))
(setf (request-foreign r) f)
;; run the custom code to call the relevant underlying API (WriteFile, WSASend etc.)
(nexus-schedule-request nexus device r)
;; push onto the request list so we can get it later
(push r (nexus-requests nexus)))
r))
(defun get-completion-result (nexus &optional timeout alertable)
(declare (type nexus nexus)
(type (or null number) timeout))
;; call GetQueuedCompletionStatus, find the assocaited device and request,
;; then pass those to completion-result, finally return (values device request result)
(multiple-value-bind (key nbytes error-code req-id) (if alertable
(iocp-get-status-ex (nexus-iocp nexus) timeout alertable)
(iocp-get-status (nexus-iocp nexus) timeout))
(let ((dev (find-device nexus key))
(req (find req-id (nexus-requests nexus)
:test #'= :key #'request-id)))
(unless dev (error "Device not found"))
(unless req (error "Request not found"))
;; remove the request from the pending list
(setf (nexus-requests nexus)
(remove req (nexus-requests nexus)))
;; if non-zero error code then release foreign and signal error
(unless (zerop error-code)
(release-foreign nexus (request-foreign req))
(setf (request-foreign req) nil)
(error 'io-error
:code error-code
:dev dev
:req req))
(values dev req nbytes))))
(defun release-request (nexus request)
(declare (type nexus nexus)
(type request request))
(release-foreign nexus (request-foreign request)))
(defmacro with-nexus ((var &optional form) &body body)
`(let ((,var ,(or form '(open-nexus))))
(declare (type nexus ,var))
(unwind-protect (progn ,@body)
(close-nexus ,var))))
(defmacro etypecase* (keyforms &rest clauses)
(if (cdr keyforms)
;; there are more forms to evaluate yet, we need to collect all those clauses of the same initial type
(let ((first-types (remove-duplicates (mapcar #'caar clauses)))
(gvars (mapcar (lambda (form) (declare (ignore form)) (gensym)) keyforms)))
`(let (,@(mapcar (lambda (gvar form)
`(,gvar ,form))
gvars keyforms))
(etypecase ,(car gvars)
,@(mapcar (lambda (type1)
`(,type1 (etypecase* ,(cdr gvars)
,@(mapcan (lambda (clause)
(destructuring-bind (types &body body) clause
(when (eq (car types) type1)
`((,(cdr types) ,@body)))))
clauses))))
first-types))))
`(etypecase ,(car keyforms)
,@(mapcar (lambda (clause)
(destructuring-bind (types &body body) clause
`(,(car types) ,@body)))
clauses))))
|
11690
|
;;;; Copyright (c) <NAME> 2015 <<EMAIL>>
;;;; This code is licensed under the MIT license.
(in-package #:cliocp)
;; global (toplevel) state
;; includes iocp handle, freelist of foreign data etc
(defclass nexus ()
((iocp :initarg :iocp :accessor nexus-iocp)
(key :initform 0 :accessor nexus-key)
(devices :initform nil :accessor nexus-devices)
(id :initarg :id :initform 0 :accessor nexus-id)
(buffer-size :initarg :buffer-size :initform +buffer-size+ :reader nexus-buffer-size)
(freelist :initform nil :initarg :freelist :accessor nexus-freelist)
(all-foreign :initform nil :accessor nexus-all-foreign)
(requests :initform nil :accessor nexus-requests)))
(defmethod initialize-instance :after ((nexus nexus) &rest initargs &key nthreads buffer-count &allow-other-keys)
(declare (ignore initargs))
(let* ((bcount (or buffer-count 32))
(f (loop :for i :below bcount
:collect (allocate-foreign i (nexus-buffer-size nexus)))))
(setf (nexus-iocp nexus) (open-iocp (or nthreads 0))
(nexus-freelist nexus) f
(nexus-all-foreign nexus) f
(nexus-id nexus) bcount)))
(defun open-nexus ()
(make-instance 'nexus))
(defun close-nexus (nexus)
(declare (type nexus nexus))
;; close all devices
(dolist (d (nexus-devices nexus))
(unregister-device nexus d))
;; close iocp handle
(close-iocp (nexus-iocp nexus))
;; free all foreign
(dolist (f (nexus-all-foreign nexus))
(free-foreign f)))
(defun acquire-foreign (nexus)
(declare (type nexus nexus))
(cond
((nexus-freelist nexus)
(pop (nexus-freelist nexus)))
(t
(incf (nexus-id nexus))
(let ((f (allocate-foreign (nexus-id nexus) (nexus-buffer-size nexus))))
(push f (nexus-all-foreign nexus))
f))))
(defun release-foreign (nexus f)
(declare (type nexus nexus)
(type foreign f))
(push f (nexus-freelist nexus)))
;; --------------------------------------
(defclass device ()
((key :initform nil :accessor device-key)
(handle :initarg :handle :reader device-handle)))
(defgeneric close-device (device))
(defun register-device (nexus device &key (associate t))
(declare (type nexus nexus)
(type device device))
;; allocate this device a key
(incf (nexus-key nexus))
(let ((key (nexus-key nexus)))
;; associate with IOCP
(when associate
(iocp-associate (nexus-iocp nexus) (device-handle device) key))
(setf (device-key device) key)
;; store in assoc list
(push device (nexus-devices nexus)))
device)
(defun unregister-device (nexus device-or-key)
(declare (type nexus nexus)
(type (or integer device) device-or-key))
(etypecase device-or-key
(integer
(let ((d (find-device nexus device-or-key)))
(close-device d)
(setf (nexus-devices nexus)
(remove d (nexus-devices nexus) :test #'eq))))
(device
(close-device device-or-key)
(setf (nexus-devices nexus)
(remove device-or-key (nexus-devices nexus)
:test #'eq)))))
(defun find-device (nexus key-or-type)
(declare (type nexus nexus)
(type (or integer symbol) key-or-type))
(etypecase key-or-type
(integer (find key-or-type (nexus-devices nexus)
:test #'= :key #'device-key))
(symbol (find-if (lambda (dev)
(typep dev key-or-type))
(nexus-devices nexus)))))
;; ---------------------------------------
(defclass request ()
((foreign :initform nil :accessor request-foreign)))
(defun request-id (request)
(declare (type request request))
(foreign-id (request-foreign request)))
(defgeneric nexus-schedule-request (nexus device request))
(defun schedule-request (nexus device request &rest initargs)
(declare (type nexus nexus)
(type device device)
(type (or request symbol class) request))
(let ((r (etypecase request
(request request)
(symbol (apply #'make-instance request initargs))
(class (apply #'make-instance request initargs)))))
;; acquire a foreign and provide it to the request
(let ((f (acquire-foreign nexus)))
(setf (request-foreign r) f)
;; run the custom code to call the relevant underlying API (WriteFile, WSASend etc.)
(nexus-schedule-request nexus device r)
;; push onto the request list so we can get it later
(push r (nexus-requests nexus)))
r))
(defun get-completion-result (nexus &optional timeout alertable)
(declare (type nexus nexus)
(type (or null number) timeout))
;; call GetQueuedCompletionStatus, find the assocaited device and request,
;; then pass those to completion-result, finally return (values device request result)
(multiple-value-bind (key nbytes error-code req-id) (if alertable
(iocp-get-status-ex (nexus-iocp nexus) timeout alertable)
(iocp-get-status (nexus-iocp nexus) timeout))
(let ((dev (find-device nexus key))
(req (find req-id (nexus-requests nexus)
:test #'= :key #'request-id)))
(unless dev (error "Device not found"))
(unless req (error "Request not found"))
;; remove the request from the pending list
(setf (nexus-requests nexus)
(remove req (nexus-requests nexus)))
;; if non-zero error code then release foreign and signal error
(unless (zerop error-code)
(release-foreign nexus (request-foreign req))
(setf (request-foreign req) nil)
(error 'io-error
:code error-code
:dev dev
:req req))
(values dev req nbytes))))
(defun release-request (nexus request)
(declare (type nexus nexus)
(type request request))
(release-foreign nexus (request-foreign request)))
(defmacro with-nexus ((var &optional form) &body body)
`(let ((,var ,(or form '(open-nexus))))
(declare (type nexus ,var))
(unwind-protect (progn ,@body)
(close-nexus ,var))))
(defmacro etypecase* (keyforms &rest clauses)
(if (cdr keyforms)
;; there are more forms to evaluate yet, we need to collect all those clauses of the same initial type
(let ((first-types (remove-duplicates (mapcar #'caar clauses)))
(gvars (mapcar (lambda (form) (declare (ignore form)) (gensym)) keyforms)))
`(let (,@(mapcar (lambda (gvar form)
`(,gvar ,form))
gvars keyforms))
(etypecase ,(car gvars)
,@(mapcar (lambda (type1)
`(,type1 (etypecase* ,(cdr gvars)
,@(mapcan (lambda (clause)
(destructuring-bind (types &body body) clause
(when (eq (car types) type1)
`((,(cdr types) ,@body)))))
clauses))))
first-types))))
`(etypecase ,(car keyforms)
,@(mapcar (lambda (clause)
(destructuring-bind (types &body body) clause
`(,(car types) ,@body)))
clauses))))
| true |
;;;; Copyright (c) PI:NAME:<NAME>END_PI 2015 <PI:EMAIL:<EMAIL>END_PI>
;;;; This code is licensed under the MIT license.
(in-package #:cliocp)
;; global (toplevel) state
;; includes iocp handle, freelist of foreign data etc
(defclass nexus ()
((iocp :initarg :iocp :accessor nexus-iocp)
(key :initform 0 :accessor nexus-key)
(devices :initform nil :accessor nexus-devices)
(id :initarg :id :initform 0 :accessor nexus-id)
(buffer-size :initarg :buffer-size :initform +buffer-size+ :reader nexus-buffer-size)
(freelist :initform nil :initarg :freelist :accessor nexus-freelist)
(all-foreign :initform nil :accessor nexus-all-foreign)
(requests :initform nil :accessor nexus-requests)))
(defmethod initialize-instance :after ((nexus nexus) &rest initargs &key nthreads buffer-count &allow-other-keys)
(declare (ignore initargs))
(let* ((bcount (or buffer-count 32))
(f (loop :for i :below bcount
:collect (allocate-foreign i (nexus-buffer-size nexus)))))
(setf (nexus-iocp nexus) (open-iocp (or nthreads 0))
(nexus-freelist nexus) f
(nexus-all-foreign nexus) f
(nexus-id nexus) bcount)))
(defun open-nexus ()
(make-instance 'nexus))
(defun close-nexus (nexus)
(declare (type nexus nexus))
;; close all devices
(dolist (d (nexus-devices nexus))
(unregister-device nexus d))
;; close iocp handle
(close-iocp (nexus-iocp nexus))
;; free all foreign
(dolist (f (nexus-all-foreign nexus))
(free-foreign f)))
(defun acquire-foreign (nexus)
(declare (type nexus nexus))
(cond
((nexus-freelist nexus)
(pop (nexus-freelist nexus)))
(t
(incf (nexus-id nexus))
(let ((f (allocate-foreign (nexus-id nexus) (nexus-buffer-size nexus))))
(push f (nexus-all-foreign nexus))
f))))
(defun release-foreign (nexus f)
(declare (type nexus nexus)
(type foreign f))
(push f (nexus-freelist nexus)))
;; --------------------------------------
(defclass device ()
((key :initform nil :accessor device-key)
(handle :initarg :handle :reader device-handle)))
(defgeneric close-device (device))
(defun register-device (nexus device &key (associate t))
(declare (type nexus nexus)
(type device device))
;; allocate this device a key
(incf (nexus-key nexus))
(let ((key (nexus-key nexus)))
;; associate with IOCP
(when associate
(iocp-associate (nexus-iocp nexus) (device-handle device) key))
(setf (device-key device) key)
;; store in assoc list
(push device (nexus-devices nexus)))
device)
(defun unregister-device (nexus device-or-key)
(declare (type nexus nexus)
(type (or integer device) device-or-key))
(etypecase device-or-key
(integer
(let ((d (find-device nexus device-or-key)))
(close-device d)
(setf (nexus-devices nexus)
(remove d (nexus-devices nexus) :test #'eq))))
(device
(close-device device-or-key)
(setf (nexus-devices nexus)
(remove device-or-key (nexus-devices nexus)
:test #'eq)))))
(defun find-device (nexus key-or-type)
(declare (type nexus nexus)
(type (or integer symbol) key-or-type))
(etypecase key-or-type
(integer (find key-or-type (nexus-devices nexus)
:test #'= :key #'device-key))
(symbol (find-if (lambda (dev)
(typep dev key-or-type))
(nexus-devices nexus)))))
;; ---------------------------------------
(defclass request ()
((foreign :initform nil :accessor request-foreign)))
(defun request-id (request)
(declare (type request request))
(foreign-id (request-foreign request)))
(defgeneric nexus-schedule-request (nexus device request))
(defun schedule-request (nexus device request &rest initargs)
(declare (type nexus nexus)
(type device device)
(type (or request symbol class) request))
(let ((r (etypecase request
(request request)
(symbol (apply #'make-instance request initargs))
(class (apply #'make-instance request initargs)))))
;; acquire a foreign and provide it to the request
(let ((f (acquire-foreign nexus)))
(setf (request-foreign r) f)
;; run the custom code to call the relevant underlying API (WriteFile, WSASend etc.)
(nexus-schedule-request nexus device r)
;; push onto the request list so we can get it later
(push r (nexus-requests nexus)))
r))
(defun get-completion-result (nexus &optional timeout alertable)
(declare (type nexus nexus)
(type (or null number) timeout))
;; call GetQueuedCompletionStatus, find the assocaited device and request,
;; then pass those to completion-result, finally return (values device request result)
(multiple-value-bind (key nbytes error-code req-id) (if alertable
(iocp-get-status-ex (nexus-iocp nexus) timeout alertable)
(iocp-get-status (nexus-iocp nexus) timeout))
(let ((dev (find-device nexus key))
(req (find req-id (nexus-requests nexus)
:test #'= :key #'request-id)))
(unless dev (error "Device not found"))
(unless req (error "Request not found"))
;; remove the request from the pending list
(setf (nexus-requests nexus)
(remove req (nexus-requests nexus)))
;; if non-zero error code then release foreign and signal error
(unless (zerop error-code)
(release-foreign nexus (request-foreign req))
(setf (request-foreign req) nil)
(error 'io-error
:code error-code
:dev dev
:req req))
(values dev req nbytes))))
(defun release-request (nexus request)
(declare (type nexus nexus)
(type request request))
(release-foreign nexus (request-foreign request)))
(defmacro with-nexus ((var &optional form) &body body)
`(let ((,var ,(or form '(open-nexus))))
(declare (type nexus ,var))
(unwind-protect (progn ,@body)
(close-nexus ,var))))
(defmacro etypecase* (keyforms &rest clauses)
(if (cdr keyforms)
;; there are more forms to evaluate yet, we need to collect all those clauses of the same initial type
(let ((first-types (remove-duplicates (mapcar #'caar clauses)))
(gvars (mapcar (lambda (form) (declare (ignore form)) (gensym)) keyforms)))
`(let (,@(mapcar (lambda (gvar form)
`(,gvar ,form))
gvars keyforms))
(etypecase ,(car gvars)
,@(mapcar (lambda (type1)
`(,type1 (etypecase* ,(cdr gvars)
,@(mapcan (lambda (clause)
(destructuring-bind (types &body body) clause
(when (eq (car types) type1)
`((,(cdr types) ,@body)))))
clauses))))
first-types))))
`(etypecase ,(car keyforms)
,@(mapcar (lambda (clause)
(destructuring-bind (types &body body) clause
`(,(car types) ,@body)))
clauses))))
|
[
{
"context": "dio-blender\n (c) 2016 Shirakumo http://tymoon.eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n",
"end": 97,
"score": 0.9999226331710815,
"start": 79,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "umo http://tymoon.eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(in-package #:org.shirak",
"end": 122,
"score": 0.9998858571052551,
"start": 108,
"tag": "NAME",
"value": "Nicolas Hafner"
},
{
"context": ".eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(in-package #:org.shirakumo.fraf.audio-blend",
"end": 142,
"score": 0.9999305009841919,
"start": 124,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
dispatch.lisp
|
Shirakumo/audio-blender
| 2 |
#|
This file is a part of audio-blender
(c) 2016 Shirakumo http://tymoon.eu ([email protected])
Author: Nicolas Hafner <[email protected]>
|#
(in-package #:org.shirakumo.fraf.audio-blender)
(defvar *dispatch-functions* (make-hash-table :test 'eql))
(defun dispatch-function (name &optional (error T))
(or (gethash name *dispatch-functions*)
(when error (error "No such dispatch function ~s." name))))
(defun (setf dispatch-function) (function name)
(setf (gethash name *dispatch-functions*) function))
(defun remove-dispatch-function (name)
(remhash name *dispatch-functions*)
(fmakunbound name))
(defclass dispatch-function ()
((name :initarg :name :initform NIL :accessor name)
(args :initarg :args :initform NIL :accessor args)
(cases :initform NIL :accessor cases)))
(defmethod shared-initialize :after ((function dispatch-function) slots &key cases)
(when cases
(setf (cases function) (sort cases #'subtypep :key #'first))))
(defmethod compile-dispatch-function ((function dispatch-function))
(with-slots (name args cases) function
(compile name `(lambda ,args
(declare (ignorable ,@args))
(typecase ,(first args)
,@(loop for (type cargs . body) in cases
collect `(,type
(let ,(mapcar #'list cargs args)
,@body)))
(T (error "Cannot dispatch to ~s, not one of ~a." ,(first args) ',(mapcar #'first cases))))))
function))
(defmethod compile-dispatch-function ((name symbol))
(compile-dispatch-function (dispatch-function name)))
(defmethod compile-dispatch-function ((name cons))
(compile-dispatch-function (dispatch-function name)))
(defun update-or-create-dispatch-function (name args &optional cases)
(let ((prev (dispatch-function name NIL)))
(compile-dispatch-function
(cond (prev
(reinitialize-instance prev :args args :cases cases))
(T
(setf (dispatch-function name)
(make-instance 'dispatch-function :name name :args args :cases cases)))))))
(defmacro define-dispatcher (name args &body cases)
`(progn (declaim (inline ,name))
(update-or-create-dispatch-function ',name ',args ',cases)
',name))
(defmacro define-dispatch-method (name type args &body body)
(let ((fun (gensym "FUN")))
`(let ((,fun (dispatch-function ',name)))
(setf (cases ,fun) (cons '(,type ,args ,@body)
(delete ',type (cases ,fun) :key #'first)))
(compile-dispatch-function ,fun))))
|
56032
|
#|
This file is a part of audio-blender
(c) 2016 Shirakumo http://tymoon.eu (<EMAIL>)
Author: <NAME> <<EMAIL>>
|#
(in-package #:org.shirakumo.fraf.audio-blender)
(defvar *dispatch-functions* (make-hash-table :test 'eql))
(defun dispatch-function (name &optional (error T))
(or (gethash name *dispatch-functions*)
(when error (error "No such dispatch function ~s." name))))
(defun (setf dispatch-function) (function name)
(setf (gethash name *dispatch-functions*) function))
(defun remove-dispatch-function (name)
(remhash name *dispatch-functions*)
(fmakunbound name))
(defclass dispatch-function ()
((name :initarg :name :initform NIL :accessor name)
(args :initarg :args :initform NIL :accessor args)
(cases :initform NIL :accessor cases)))
(defmethod shared-initialize :after ((function dispatch-function) slots &key cases)
(when cases
(setf (cases function) (sort cases #'subtypep :key #'first))))
(defmethod compile-dispatch-function ((function dispatch-function))
(with-slots (name args cases) function
(compile name `(lambda ,args
(declare (ignorable ,@args))
(typecase ,(first args)
,@(loop for (type cargs . body) in cases
collect `(,type
(let ,(mapcar #'list cargs args)
,@body)))
(T (error "Cannot dispatch to ~s, not one of ~a." ,(first args) ',(mapcar #'first cases))))))
function))
(defmethod compile-dispatch-function ((name symbol))
(compile-dispatch-function (dispatch-function name)))
(defmethod compile-dispatch-function ((name cons))
(compile-dispatch-function (dispatch-function name)))
(defun update-or-create-dispatch-function (name args &optional cases)
(let ((prev (dispatch-function name NIL)))
(compile-dispatch-function
(cond (prev
(reinitialize-instance prev :args args :cases cases))
(T
(setf (dispatch-function name)
(make-instance 'dispatch-function :name name :args args :cases cases)))))))
(defmacro define-dispatcher (name args &body cases)
`(progn (declaim (inline ,name))
(update-or-create-dispatch-function ',name ',args ',cases)
',name))
(defmacro define-dispatch-method (name type args &body body)
(let ((fun (gensym "FUN")))
`(let ((,fun (dispatch-function ',name)))
(setf (cases ,fun) (cons '(,type ,args ,@body)
(delete ',type (cases ,fun) :key #'first)))
(compile-dispatch-function ,fun))))
| true |
#|
This file is a part of audio-blender
(c) 2016 Shirakumo http://tymoon.eu (PI:EMAIL:<EMAIL>END_PI)
Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
|#
(in-package #:org.shirakumo.fraf.audio-blender)
(defvar *dispatch-functions* (make-hash-table :test 'eql))
(defun dispatch-function (name &optional (error T))
(or (gethash name *dispatch-functions*)
(when error (error "No such dispatch function ~s." name))))
(defun (setf dispatch-function) (function name)
(setf (gethash name *dispatch-functions*) function))
(defun remove-dispatch-function (name)
(remhash name *dispatch-functions*)
(fmakunbound name))
(defclass dispatch-function ()
((name :initarg :name :initform NIL :accessor name)
(args :initarg :args :initform NIL :accessor args)
(cases :initform NIL :accessor cases)))
(defmethod shared-initialize :after ((function dispatch-function) slots &key cases)
(when cases
(setf (cases function) (sort cases #'subtypep :key #'first))))
(defmethod compile-dispatch-function ((function dispatch-function))
(with-slots (name args cases) function
(compile name `(lambda ,args
(declare (ignorable ,@args))
(typecase ,(first args)
,@(loop for (type cargs . body) in cases
collect `(,type
(let ,(mapcar #'list cargs args)
,@body)))
(T (error "Cannot dispatch to ~s, not one of ~a." ,(first args) ',(mapcar #'first cases))))))
function))
(defmethod compile-dispatch-function ((name symbol))
(compile-dispatch-function (dispatch-function name)))
(defmethod compile-dispatch-function ((name cons))
(compile-dispatch-function (dispatch-function name)))
(defun update-or-create-dispatch-function (name args &optional cases)
(let ((prev (dispatch-function name NIL)))
(compile-dispatch-function
(cond (prev
(reinitialize-instance prev :args args :cases cases))
(T
(setf (dispatch-function name)
(make-instance 'dispatch-function :name name :args args :cases cases)))))))
(defmacro define-dispatcher (name args &body cases)
`(progn (declaim (inline ,name))
(update-or-create-dispatch-function ',name ',args ',cases)
',name))
(defmacro define-dispatch-method (name type args &body body)
(let ((fun (gensym "FUN")))
`(let ((,fun (dispatch-function ',name)))
(setf (cases ,fun) (cons '(,type ,args ,@body)
(delete ',type (cases ,fun) :key #'first)))
(compile-dispatch-function ,fun))))
|
[
{
"context": "l nil nil nil nil nil 'a)))\n\n;;; Test suggested by Peter Graves\n(define-test |append 7|\n (let ((x (list 'a 'b 'c",
"end": 139838,
"score": 0.9974104762077332,
"start": 139826,
"tag": "NAME",
"value": "Peter Graves"
}
] |
Code/Cons/Test/test.lisp
|
Passw/robert-strandh-SICL
| 842 |
(cl:in-package #:sicl-cons-high-test)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Helper function to defeat the type inferencing of the
;;; compiler so there are no warnings.
;;; This function always returns true when given a proper list.
(defun twisted (list)
(if (null list)
t
(twisted (cdr list))))
(declaim (notinline twisted))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAAR function.
(define-test caar.1
(assert-equal 'a (caar '((a)))))
(define-test caar.error.1
(assert-error 'type-error (caar 'a)))
(define-test caar.error.2
(assert-error 'type-error (caar '(a))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADR function.
(define-test cdar.1
(assert-equal 'b (cdar '((a . b)))))
(define-test cdar.error.1
(assert-error 'type-error (cdar 'a)))
(define-test cdar.error.2
(assert-error 'type-error (cdar '(a . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADR function.
(define-test cadr.1
(assert-equal 'b (cadr '(a b))))
(define-test cadr.error.1
(assert-error 'type-error (cadr 'a)))
(define-test cadr.error.2
(assert-error 'type-error (cadr '(a . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDR function.
(define-test cddr.1
(assert-equal 'c (cddr '(a b . c))))
(define-test cddr.error.1
(assert-error 'type-error (cddr 'a)))
(define-test cddr.error.2
(assert-error 'type-error (cddr '(a . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAAAR function.
(define-test caaar.1
(assert-equal 'a (caaar '(((a))))))
(define-test caaar.error.1
(assert-error 'type-error (caaar 'a)))
(define-test caaar.error.2
(assert-error 'type-error (caaar '(a))))
(define-test caaar.error.3
(assert-error 'type-error (caaar '((a)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDAAR function.
(define-test cdaar.1
(assert-equal 'b (cdaar '(((a . b))))))
(define-test cdaar.error.1
(assert-error 'type-error (cdaar 'a)))
(define-test cdaar.error.2
(assert-error 'type-error (cdaar '(a))))
(define-test cdaar.error.3
(assert-error 'type-error (cdaar '((a . b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADAR function.
(define-test cadar.1
(assert-equal 'b (cadar (cons (cons 'a (cons 'b 'c)) 'd))))
(define-test cadar.error.1
(assert-error 'type-error (cadar 'a)))
(define-test cadar.error.2
(assert-error 'type-error (cadar '(a . b))))
(define-test cadar.error.3
(assert-error 'type-error (cadar '((a . c) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDAR function.
(define-test cddar.1
(assert-equal 'c (cddar (cons (cons 'a (cons 'b 'c)) 'd))))
(define-test cddar.error.1
(assert-error 'type-error (cddar 'a)))
(define-test cddar.error.2
(assert-error 'type-error (cddar '(a . b))))
(define-test cddar.error.3
(assert-error 'type-error (cddar '((a . b) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAADR function.
(define-test caadr.1
(assert-equal 'b (caadr (cons 'a (cons (cons 'b 'c) 'd)))))
(define-test caadr.error.1
(assert-error 'type-error (caadr 'a)))
(define-test caadr.error.2
(assert-error 'type-error (caadr '(a . b))))
(define-test caadr.error.3
(assert-error 'type-error (caadr '(a . (b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADDR function.
(define-test caddr.1
(assert-equal 'c (caddr (cons 'a (cons 'b (cons 'c 'd))))))
(define-test caddr.error.1
(assert-error 'type-error (caddr 'a)))
(define-test caddr.error.2
(assert-error 'type-error (caddr '(a . b))))
(define-test caddr.error.3
(assert-error 'type-error (caddr '(a c . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDADR function.
(define-test cdadr.1
(assert-equal 'c (cdadr (cons 'a (cons (cons 'b 'c) 'd)))))
(define-test cdadr.error.1
(assert-error 'type-error (cdadr 'a)))
(define-test cdadr.error.2
(assert-error 'type-error (cdadr '(a . b))))
(define-test cdadr.error.3
(assert-error 'type-error (cdadr '(a b . c))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDDR function.
(define-test cdddr.1
(assert-equal 'd (cdddr (cons 'a (cons 'b (cons 'c 'd))))))
(define-test cdddr.error.1
(assert-error 'type-error (cdddr 'a)))
(define-test cdddr.error.2
(assert-error 'type-error (cdddr '(a . b))))
(define-test cdddr.error.3
(assert-error 'type-error (cdddr '(a c . b))))
;;; Tree to be used for testing some c*r functions.
(defvar *cons-test-4*
(cons (cons (cons (cons 'a 'b)
(cons 'c 'd))
(cons (cons 'e 'f)
(cons 'g 'h)))
(cons (cons (cons 'i 'j)
(cons 'k 'l))
(cons (cons 'm 'n)
(cons 'o 'p)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAAAAR function.
(define-test caaaar.1
(assert-equal 'a (caaaar *cons-test-4*)))
(define-test caaaar.error.1
(assert-error 'type-error (caaaar 'a)))
(define-test caaaar.error.2
(assert-error 'type-error (caaaar '(a))))
(define-test caaaar.error.3
(assert-error 'type-error (caaaar '((a)))))
(define-test caaaar.error.4
(assert-error 'type-error (caaaar '(((a))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAAADR function.
(define-test caaadr.1
(assert-equal 'i (caaadr *cons-test-4*)))
(define-test caaadr.error.1
(assert-error 'type-error (caaadr 'a)))
(define-test caaadr.error.2
(assert-error 'type-error (caaadr '(a . b))))
(define-test caaadr.error.3
(assert-error 'type-error (caaadr '(a . (b)))))
(define-test caaadr.error.4
(assert-error 'type-error (caaadr '(a . ((b))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAADAR function.
(define-test caadar.1
(assert-equal 'e (caadar *cons-test-4*)))
(define-test caadar.error.1
(assert-error 'type-error (caadar 'a)))
(define-test caadar.error.2
(assert-error 'type-error (caadar '(a . b))))
(define-test caadar.error.3
(assert-error 'type-error (caadar '((a . c) . b))))
(define-test caadar.error.4
(assert-error 'type-error (caadar '((a . (c)) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAADDR function.
(define-test caaddr.1
(assert-equal 'm (caaddr *cons-test-4*)))
(define-test caaddr.error.1
(assert-error 'type-error (caaddr 'a)))
(define-test caaddr.error.2
(assert-error 'type-error (caaddr '(a . b))))
(define-test caaddr.error.3
(assert-error 'type-error (caaddr '(a c . b))))
(define-test caaddr.error.4
(assert-error 'type-error (caaddr '(a c . (b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADAAR function.
(define-test cadaar.1
(assert-equal 'c (cadaar *cons-test-4*)))
(define-test cadaar.error.1
(assert-error 'type-error (cadaar 'a)))
(define-test cadaar.error.2
(assert-error 'type-error (cadaar '(a))))
(define-test cadaar.error.3
(assert-error 'type-error (cadaar '((a . b)))))
(define-test cadaar.error.4
(assert-error 'type-error (cadaar '((a . (b))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADADR function.
(define-test cadadr.1
(assert-equal 'k (cadadr *cons-test-4*)))
(define-test cadadr.error.1
(assert-error 'type-error (cadadr 'a)))
(define-test cadadr.error.2
(assert-error 'type-error (cadadr '(a . b))))
(define-test cadadr.error.3
(assert-error 'type-error (cadadr '(a b . c))))
(define-test cadadr.error.4
(assert-error 'type-error (cadadr '(a (b . e) . c))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADDAR function.
(define-test caddar.1
(assert-equal 'g (caddar *cons-test-4*)))
(define-test caddar.error.1
(assert-error 'type-error (caddar 'a)))
(define-test caddar.error.2
(assert-error 'type-error (caddar '(a . b))))
(define-test caddar.error.3
(assert-error 'type-error (caddar '((a . b) . b))))
(define-test caddar.error.4
(assert-error 'type-error (caddar '((a b . c) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADDDR function.
(define-test cadddr.1
(assert-equal 'o (cadddr *cons-test-4*)))
(define-test cadddr.error.1
(assert-error 'type-error (cadddr 'a)))
(define-test cadddr.error.2
(assert-error 'type-error (cadddr '(a . b))))
(define-test cadddr.error.3
(assert-error 'type-error (cadddr '(a c . b))))
(define-test cadddr.error.4
(assert-error 'type-error (cadddr '(a c e . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDAAAR function.
(define-test cdaaar.1
(assert-equal 'b (cdaaar *cons-test-4*)))
(define-test cdaaar.error.1
(assert-error 'type-error (cdaaar 'a)))
(define-test cdaaar.error.2
(assert-error 'type-error (cdaaar '(a))))
(define-test cdaaar.error.3
(assert-error 'type-error (cdaaar '((a)))))
(define-test cdaaar.error.4
(assert-error 'type-error (cdaaar '(((a . b))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDAADR function.
(define-test cdaadr.1
(assert-equal 'j (cdaadr *cons-test-4*)))
(define-test cdaadr.error.1
(assert-error 'type-error (cdaadr 'a)))
(define-test cdaadr.error.2
(assert-error 'type-error (cdaadr '(a . b))))
(define-test cdaadr.error.3
(assert-error 'type-error (cdaadr '(a . (b)))))
(define-test cdaadr.error.4
(assert-error 'type-error (cdaadr '(a . ((b . c))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDADAR function.
(define-test cdadar.1
(assert-equal 'f (cdadar *cons-test-4*)))
(define-test cdadar.error.1
(assert-error 'type-error (cdadar 'a)))
(define-test cdadar.error.2
(assert-error 'type-error (cdadar '(a . b))))
(define-test cdadar.error.3
(assert-error 'type-error (cdadar '((a . c) . b))))
(define-test cdadar.error.4
(assert-error 'type-error (cdadar '((a . (c . d)) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDADDR function.
(define-test cdaddr.1
(assert-equal 'n (cdaddr *cons-test-4*)))
(define-test cdaddr.error.1
(assert-error 'type-error (cdaddr 'a)))
(define-test cdaddr.error.2
(assert-error 'type-error (cdaddr '(a . b))))
(define-test cdaddr.error.3
(assert-error 'type-error (cdaddr '(a c . b))))
(define-test cdaddr.error.4
(assert-error 'type-error (cdaddr '(a c b . d))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDAAR function.
(define-test cddaar.1
(assert-equal 'd (cddaar *cons-test-4*)))
(define-test cddaar.error.1
(assert-error 'type-error (cddaar 'a)))
(define-test cddaar.error.2
(assert-error 'type-error (cddaar '(a))))
(define-test cddaar.error.3
(assert-error 'type-error (cddaar '((a . b)))))
(define-test cddaar.error.4
(assert-error 'type-error (cddaar '((a . (b))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDADR function.
(define-test cddadr.1
(assert-equal 'l (cddadr *cons-test-4*)))
(define-test cddadr.error.1
(assert-error 'type-error (cddadr 'a)))
(define-test cddadr.error.2
(assert-error 'type-error (cddadr '(a . b))))
(define-test cddadr.error.3
(assert-error 'type-error (cddadr '(a b . c))))
(define-test cddadr.error.4
(assert-error 'type-error (cddadr '(a (b . e) . c))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDDAR function.
(define-test cdddar.1
(assert-equal 'h (cdddar *cons-test-4*)))
(define-test cdddar.error.1
(assert-error 'type-error (cdddar 'a)))
(define-test cdddar.error.2
(assert-error 'type-error (cdddar '(a . b))))
(define-test cdddar.error.3
(assert-error 'type-error (cdddar '((a . b) . b))))
(define-test cdddar.error.4
(assert-error 'type-error (cdddar '((a b . c) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDDDR function.
(define-test cddddr.1
(assert-equal 'p (cddddr *cons-test-4*)))
(define-test cddddr.error.1
(assert-error 'type-error (cddddr 'a)))
(define-test cddddr.error.2
(assert-error 'type-error (cddddr '(a . b))))
(define-test cddddr.error.3
(assert-error 'type-error (cddddr '(a c . b))))
(define-test cddddr.error.4
(assert-error 'type-error (cddddr '(a c e . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the FIRST function
(define-test first.1
(assert-equal nil (first nil)))
(define-test first.2
(assert-equal 1 (first '(1))))
(define-test first.3
(assert-equal 1 (first '(1 2))))
(define-test first.error.1
(assert-error 'type-error (first 1)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the SECOND function
(define-test second.1
(assert-equal nil (second nil)))
(define-test second.2
(assert-equal nil (second '(1))))
(define-test second.3
(assert-equal 1 (second '(0 1))))
(define-test second.4
(assert-equal 1 (second '(0 1 2))))
(define-test second.error.1
(assert-error 'type-error (second 1)))
(define-test second.error.2
(assert-error 'type-error (second '(0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the THIRD function.
(define-test third.1
(assert-equal nil (third nil)))
(define-test third.2
(assert-equal nil (third '(1))))
(define-test third.3
(assert-equal nil (third '(1 1))))
(define-test third.4
(assert-equal 1 (third '(0 0 1))))
(define-test third.5
(assert-equal 1 (third '(0 0 1 2))))
(define-test third.error.1
(assert-error 'type-error (third 1)))
(define-test third.error.2
(assert-error 'type-error (third '(0 . 1))))
(define-test third.error.3
(assert-error 'type-error (third '(0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the FOURTH function.
(define-test fourth.1
(assert-equal nil (fourth nil)))
(define-test fourth.2
(assert-equal nil (fourth '(1))))
(define-test fourth.3
(assert-equal nil (fourth '(1 1))))
(define-test fourth.4
(assert-equal nil (fourth '(1 1 1))))
(define-test fourth.5
(assert-equal 1 (fourth '(0 0 0 1))))
(define-test fourth.6
(assert-equal 1 (fourth '(0 0 0 1 2))))
(define-test fourth.error.1
(assert-error 'type-error (fourth 1)))
(define-test fourth.error.2
(assert-error 'type-error (fourth '(0 . 1))))
(define-test fourth.error.3
(assert-error 'type-error (fourth '(0 0 . 1))))
(define-test fourth.error.4
(assert-error 'type-error (fourth '(0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the FIFTH function.
(define-test fifth.1
(assert-equal nil (fifth nil)))
(define-test fifth.2
(assert-equal nil (fifth '(1))))
(define-test fifth.3
(assert-equal nil (fifth '(1 1))))
(define-test fifth.4
(assert-equal nil (fifth '(1 1 1))))
(define-test fifth.5
(assert-equal nil (fifth '(1 1 1 1))))
(define-test fifth.6
(assert-equal 1 (fifth '(0 0 0 0 1))))
(define-test fifth.7
(assert-equal 1 (fifth '(0 0 0 0 1 2))))
(define-test fifth.error.1
(assert-error 'type-error (fifth 1)))
(define-test fifth.error.2
(assert-error 'type-error (fifth '(0 . 1))))
(define-test fifth.error.3
(assert-error 'type-error (fifth '(0 0 . 1))))
(define-test fifth.error.4
(assert-error 'type-error (fifth '(0 0 0 . 1))))
(define-test fifth.error.5
(assert-error 'type-error (fifth '(0 0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the SIXTH function.
(define-test sixth.1
(assert-equal nil (sixth nil)))
(define-test sixth.2
(assert-equal nil (sixth '(1))))
(define-test sixth.3
(assert-equal nil (sixth '(1 1))))
(define-test sixth.4
(assert-equal nil (sixth '(1 1 1))))
(define-test sixth.5
(assert-equal nil (sixth '(1 1 1 1))))
(define-test sixth.6
(assert-equal nil (sixth '(1 1 1 1 1))))
(define-test sixth.7
(assert-equal 1 (sixth '(0 0 0 0 0 1))))
(define-test sixth.8
(assert-equal 1 (sixth '(0 0 0 0 0 1 2))))
(define-test sixth.error.1
(assert-error 'type-error (sixth 1)))
(define-test sixth.error.2
(assert-error 'type-error (sixth '(0 . 1))))
(define-test sixth.error.3
(assert-error 'type-error (sixth '(0 0 . 1))))
(define-test sixth.error.4
(assert-error 'type-error (sixth '(0 0 0 . 1))))
(define-test sixth.error.5
(assert-error 'type-error (sixth '(0 0 0 0 . 1))))
(define-test sixth.error.6
(assert-error 'type-error (sixth '(0 0 0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the SEVENTH function.
(define-test seventh.1
(assert-equal nil (seventh nil)))
(define-test seventh.2
(assert-equal nil (seventh '(1))))
(define-test seventh.3
(assert-equal nil (seventh '(1 1))))
(define-test seventh.4
(assert-equal nil (seventh '(1 1 1))))
(define-test seventh.5
(assert-equal nil (seventh '(1 1 1 1))))
(define-test seventh.6
(assert-equal nil (seventh '(1 1 1 1 1))))
(define-test seventh.7
(assert-equal nil (seventh '(1 1 1 1 1 1))))
(define-test seventh.8
(assert-equal 1 (seventh '(0 0 0 0 0 0 1))))
(define-test seventh.9
(assert-equal 1 (seventh '(0 0 0 0 0 0 1 2))))
(define-test seventh.error.1
(assert-error 'type-error (seventh 1)))
(define-test seventh.error.2
(assert-error 'type-error (seventh '(0 . 1))))
(define-test seventh.error.3
(assert-error 'type-error (seventh '(0 0 . 1))))
(define-test seventh.error.4
(assert-error 'type-error (seventh '(0 0 0 . 1))))
(define-test seventh.error.5
(assert-error 'type-error (seventh '(0 0 0 0 . 1))))
(define-test seventh.error.6
(assert-error 'type-error (seventh '(0 0 0 0 0 . 1))))
(define-test seventh.error.7
(assert-error 'type-error (seventh '(0 0 0 0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the EIGHTH function.
(define-test eighth.1
(assert-equal nil (eighth nil)))
(define-test eighth.2
(assert-equal nil (eighth '(1))))
(define-test eighth.3
(assert-equal nil (eighth '(1 1))))
(define-test eighth.4
(assert-equal nil (eighth '(1 1 1))))
(define-test eighth.5
(assert-equal nil (eighth '(1 1 1 1))))
(define-test eighth.6
(assert-equal nil (eighth '(1 1 1 1 1))))
(define-test eighth.7
(assert-equal nil (eighth '(1 1 1 1 1 1))))
(define-test eighth.8
(assert-equal nil (eighth '(1 1 1 1 1 1 1))))
(define-test eighth.9
(assert-equal 1 (eighth '(0 0 0 0 0 0 0 1))))
(define-test eighth.10
(assert-equal 1 (eighth '(0 0 0 0 0 0 0 1 2))))
(define-test eighth.error.1
(assert-error 'type-error (eighth 1)))
(define-test eighth.error.2
(assert-error 'type-error (eighth '(0 . 1))))
(define-test eighth.error.3
(assert-error 'type-error (eighth '(0 0 . 1))))
(define-test eighth.error.4
(assert-error 'type-error (eighth '(0 0 0 . 1))))
(define-test eighth.error.5
(assert-error 'type-error (eighth '(0 0 0 0 . 1))))
(define-test eighth.error.6
(assert-error 'type-error (eighth '(0 0 0 0 0 . 1))))
(define-test eighth.error.7
(assert-error 'type-error (eighth '(0 0 0 0 0 0 . 1))))
(define-test eighth.error.8
(assert-error 'type-error (eighth '(0 0 0 0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the NINTH function.
(define-test ninth.1
(assert-equal nil (ninth nil)))
(define-test ninth.2
(assert-equal nil (ninth '(1))))
(define-test ninth.3
(assert-equal nil (ninth '(1 1))))
(define-test ninth.4
(assert-equal nil (ninth '(1 1 1))))
(define-test ninth.5
(assert-equal nil (ninth '(1 1 1 1))))
(define-test ninth.6
(assert-equal nil (ninth '(1 1 1 1 1))))
(define-test ninth.7
(assert-equal nil (ninth '(1 1 1 1 1 1))))
(define-test ninth.8
(assert-equal nil (ninth '(1 1 1 1 1 1 1))))
(define-test ninth.9
(assert-equal nil (ninth '(1 1 1 1 1 1 1 1))))
(define-test ninth.10
(assert-equal 1 (ninth '(0 0 0 0 0 0 0 0 1))))
(define-test ninth.11
(assert-equal 1 (ninth '(0 0 0 0 0 0 0 0 1 2))))
(define-test ninth.error.1
(assert-error 'type-error (ninth 1)))
(define-test ninth.error.2
(assert-error 'type-error (ninth '(0 . 1))))
(define-test ninth.error.3
(assert-error 'type-error (ninth '(0 0 . 1))))
(define-test ninth.error.4
(assert-error 'type-error (ninth '(0 0 0 . 1))))
(define-test ninth.error.5
(assert-error 'type-error (ninth '(0 0 0 0 . 1))))
(define-test ninth.error.6
(assert-error 'type-error (ninth '(0 0 0 0 0 . 1))))
(define-test ninth.error.7
(assert-error 'type-error (ninth '(0 0 0 0 0 0 . 1))))
(define-test ninth.error.8
(assert-error 'type-error (ninth '(0 0 0 0 0 0 . 1))))
(define-test ninth.error.9
(assert-error 'type-error (ninth '(0 0 0 0 0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the TENTH function.
(define-test tenth.1
(assert-equal nil (tenth nil)))
(define-test tenth.2
(assert-equal nil (tenth '(1))))
(define-test tenth.3
(assert-equal nil (tenth '(1 1))))
(define-test tenth.4
(assert-equal nil (tenth '(1 1 1))))
(define-test tenth.5
(assert-equal nil (tenth '(1 1 1 1))))
(define-test tenth.6
(assert-equal nil (tenth '(1 1 1 1 1))))
(define-test tenth.7
(assert-equal nil (tenth '(1 1 1 1 1 1))))
(define-test tenth.8
(assert-equal nil (tenth '(1 1 1 1 1 1 1))))
(define-test tenth.9
(assert-equal nil (tenth '(1 1 1 1 1 1 1 1))))
(define-test tenth.10
(assert-equal nil (tenth '(1 1 1 1 1 1 1 1 1))))
(define-test tenth.11
(assert-equal 1 (tenth '(0 0 0 0 0 0 0 0 0 1))))
(define-test tenth.12
(assert-equal 1 (tenth '(0 0 0 0 0 0 0 0 0 1 2))))
(define-test tenth.error.1
(assert-error 'type-error (tenth 1)))
(define-test tenth.error.2
(assert-error 'type-error (tenth '(0 . 1))))
(define-test tenth.error.3
(assert-error 'type-error (tenth '(0 0 . 1))))
(define-test tenth.error.4
(assert-error 'type-error (tenth '(0 0 0 . 1))))
(define-test tenth.error.5
(assert-error 'type-error (tenth '(0 0 0 0 . 1))))
(define-test tenth.error.6
(assert-error 'type-error (tenth '(0 0 0 0 0 . 1))))
(define-test tenth.error.7
(assert-error 'type-error (tenth '(0 0 0 0 0 0 . 1))))
(define-test tenth.error.8
(assert-error 'type-error (tenth '(0 0 0 0 0 0 . 1))))
(define-test tenth.error.9
(assert-error 'type-error (tenth '(0 0 0 0 0 0 0 . 1))))
(define-test tenth.error.10
(assert-error 'type-error (tenth '(0 0 0 0 0 0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAAR) function and SETF expander.
(define-test |setf caar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caar list) 1))
(assert-equal '((1 . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caar error 1|
(let ((list '()))
(assert-error 'type-error
(setf (caar list) 1))))
(define-test |setf caar error 2|
(let ((list 0))
(assert-error 'type-error
(setf (caar list) 1))))
(define-test |setf caar error 3|
(let ((list (copy-tree '(0 0))))
(assert-error 'type-error
(setf (caar list) 1))))
(define-test |setf caar error 4|
(let ((list (copy-tree '(() 0))))
(assert-error 'type-error
(setf (caar list) 1))))
(define-test |setf caar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caar) (list 1 list)))
(assert-equal '((1 . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caar apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf caar) (list 1 list)))))
(define-test |setf caar apply error 2|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caar) (list 1 list)))))
(define-test |setf caar apply error 3|
(let ((list (copy-tree '(0 0))))
(assert-error 'type-error
(apply #'(setf caar) (list 1 list)))))
(define-test |setf caar apply error 4|
(let ((list (copy-tree '(() 0))))
(assert-error 'type-error
(apply #'(setf caar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADR) function and SETF expander.
(define-test |setf cadr 1|
(let ((list (copy-tree '(0 0))))
(assert-equal 1 (setf (cadr list) 1))
(assert-equal '(0 1) list)))
(define-test |setf cadr error 1|
(let ((list '()))
(assert-error 'type-error
(setf (cadr list) 1))))
(define-test |setf cadr error 2|
(let ((list 0))
(assert-error 'type-error
(setf (cadr list) 1))))
(define-test |setf cadr error 3|
(let ((list (copy-tree '(0))))
(assert-error 'type-error
(setf (cadr list) 1))))
(define-test |setf cadr error 4|
(let ((list (copy-tree '(0 . 0))))
(assert-error 'type-error
(setf (cadr list) 1))))
(define-test |setf cadr apply 1|
(let ((list (copy-tree '(0 0))))
(assert-equal 1 (apply #'(setf cadr) (list 1 list)))
(assert-equal '(0 1) list)))
(define-test |setf cadr apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf cadr) (list 1 list)))))
(define-test |setf cadr apply error 2|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cadr) (list 1 list)))))
(define-test |setf cadr apply error 3|
(let ((list (copy-tree '(0))))
(assert-error 'type-error
(apply #'(setf cadr) (list 1 list)))))
(define-test |setf cadr apply error 4|
(let ((list (copy-tree '(0 . 0))))
(assert-error 'type-error
(apply #'(setf cadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDAR) function and SETF expander.
(define-test |setf cdar 1|
(let ((list (copy-tree '((0) 0))))
(assert-equal 1 (setf (cdar list) 1))
(assert-equal '((0 . 1) 0) list)))
(define-test |setf cdar error 1|
(let ((list '()))
(assert-error 'type-error
(setf (cdar list) 1))))
(define-test |setf cdar error 2|
(let ((list 0))
(assert-error 'type-error
(setf (cdar list) 1))))
(define-test |setf cdar error 3|
(let ((list (copy-tree '(0))))
(assert-error 'type-error
(setf (cdar list) 1))))
(define-test |setf cdar error 4|
(let ((list (copy-tree '(()))))
(assert-error 'type-error
(setf (cdar list) 1))))
(define-test |setf cdar apply 1|
(let ((list (copy-tree '((0) 0))))
(assert-equal 1 (apply #'(setf cdar) (list 1 list)))
(assert-equal '((0 . 1) 0) list)))
(define-test |setf cdar apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf cdar) (list 1 list)))))
(define-test |setf cdar apply error 2|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdar) (list 1 list)))))
(define-test |setf cdar apply error 3|
(let ((list (copy-tree '(0))))
(assert-error 'type-error
(apply #'(setf cdar) (list 1 list)))))
(define-test |setf cdar apply error 4|
(let ((list (copy-tree '(()))))
(assert-error 'type-error
(apply #'(setf cdar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDR) function and SETF expander.
(define-test |setf cddr 1|
(let ((list (copy-tree '(0 0))))
(assert-equal 1 (setf (cddr list) 1))
(assert-equal '(0 0 . 1) list)))
(define-test |setf cddr error 1|
(let ((list '()))
(assert-error 'type-error
(setf (cddr list) 1))))
(define-test |setf cddr error 2|
(let ((list 0))
(assert-error 'type-error
(setf (cddr list) 1))))
(define-test |setf cddr error 3|
(let ((list (copy-tree '(0))))
(assert-error 'type-error
(setf (cddr list) 1))))
(define-test |setf cddr error 4|
(let ((list (copy-tree '(0 . 1))))
(assert-error 'type-error
(setf (cddr list) 1))))
(define-test |setf cddr apply 1|
(let ((list (copy-tree '(0 0))))
(assert-equal 1 (apply #'(setf cddr) (list 1 list)))
(assert-equal '(0 0 . 1) list)))
(define-test |setf cddr apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf cddr) (list 1 list)))))
(define-test |setf cddr apply error 2|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cddr) (list 1 list)))))
(define-test |setf cddr apply error 3|
(let ((list (copy-tree '(0))))
(assert-error 'type-error
(apply #'(setf cddr) (list 1 list)))))
(define-test |setf cddr apply error 4|
(let ((list (copy-tree '(0 . 1))))
(assert-error 'type-error
(apply #'(setf cddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAAAR) function and SETF expander.
(define-test |setf caaar 1|
(let ((list (copy-tree '(((0 0) 0) 0))))
(assert-equal 1 (setf (caaar list) 1))
(assert-equal '(((1 0) 0) 0) list)))
(define-test |setf caaar error 1|
(let ((list '()))
(assert-error 'type-error
(setf (caaar list) 1))))
(define-test |setf caaar error 2|
(let ((list 0))
(assert-error 'type-error
(setf (caaar list) 1))))
(define-test |setf caaar error 3|
(let ((list (copy-tree '(0 0))))
(assert-error 'type-error
(setf (caaar list) 1))))
(define-test |setf caaar error 4|
(let ((list (copy-tree '((0 0) 0))))
(assert-error 'type-error
(setf (caaar list) 1))))
(define-test |setf caaar error 5|
(let ((list (copy-tree '((() 0) 0))))
(assert-error 'type-error
(setf (caaar list) 1))))
(define-test |setf caaar apply 1|
(let ((list (copy-tree '(((0 0) 0) 0))))
(assert-equal 1 (apply #'(setf caaar) (list 1 list)))
(assert-equal '(((1 0) 0) 0) list)))
(define-test |setf caaar apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf caaar) (list 1 list)))))
(define-test |setf caaar apply error 2|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caaar) (list 1 list)))))
(define-test |setf caaar apply error 3|
(let ((list (copy-tree '(0 0))))
(assert-error 'type-error
(apply #'(setf caaar) (list 1 list)))))
(define-test |setf caaar apply error 4|
(let ((list (copy-tree '((0 0) 0))))
(assert-error 'type-error
(apply #'(setf caaar) (list 1 list)))))
(define-test |setf caaar apply error 5|
(let ((list (copy-tree '((() 0) 0))))
(assert-error 'type-error
(apply #'(setf caaar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAADR) function and SETF expander.
(define-test |setf caadr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caadr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
((1 . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caadr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caadr list) 1))))
(define-test |setf caadr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
0 ))))
(assert-error 'type-error
(setf (caadr list) 1))))
(define-test |setf caadr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(0 . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (caadr list) 1))))
(define-test |setf caadr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caadr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
((1 . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caadr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caadr) (list 1 list)))))
(define-test |setf caadr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
0 ))))
(assert-error 'type-error
(apply #'(setf caadr) (list 1 list)))))
(define-test |setf caadr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(0 . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf caadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADAR) function and SETF expander.
(define-test |setf cadar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cadar list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . (1 . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cadar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cadar list) 1))))
(define-test |setf cadar error 2|
(let ((list (copy-tree '(0 .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cadar list) 1))))
(define-test |setf cadar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . 0) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cadar list) 1))))
(define-test |setf cadar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cadar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . (1 . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cadar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cadar) (list 1 list)))))
(define-test |setf cadar apply error 2|
(let ((list (copy-tree '(0 .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cadar) (list 1 list)))))
(define-test |setf cadar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . 0) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cadar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADDR) function and SETF expander.
(define-test |setf caddr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caddr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . (1 . (0 . 0))))
list)))
(define-test |setf caddr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caddr list) 1))))
(define-test |setf caddr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
0 ))))
(assert-error 'type-error
(setf (caddr list) 1))))
(define-test |setf caddr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . 0 )))))
(assert-error 'type-error
(setf (caddr list) 1))))
(define-test |setf caddr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caddr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . (1 . (0 . 0))))
list)))
(define-test |setf caddr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caddr) (list 1 list)))))
(define-test |setf caddr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
0 ))))
(assert-error 'type-error
(apply #'(setf caddr) (list 1 list)))))
(define-test |setf caddr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . 0 )))))
(assert-error 'type-error
(apply #'(setf caddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDAAR) function and SETF expander.
(define-test |setf cdaar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdaar list) 1))
(assert-equal '((((0 . 0) . 1) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdaar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdaar list) 1))))
(define-test |setf cdaar error 2|
(let ((list (copy-tree '(0 .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cdaar list) 1))))
(define-test |setf cdaar error 3|
(let ((list (copy-tree '((0 . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cdaar list) 1))))
(define-test |setf cdaar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdaar) (list 1 list)))
(assert-equal '((((0 . 0) . 1) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdaar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdaar) (list 1 list)))))
(define-test |setf cdaar apply error 2|
(let ((list (copy-tree '(0 .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cdaar) (list 1 list)))))
(define-test |setf cdaar apply error 3|
(let ((list (copy-tree '((0 . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cdaar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDADR) function and SETF expander.
(define-test |setf cdadr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdadr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . 1) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdadr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdadr list) 1))))
(define-test |setf cdadr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
0 ))))
(assert-error 'type-error
(setf (cdadr list) 1))))
(define-test |setf cdadr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(0 . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cdadr list) 1))))
(define-test |setf cdadr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdadr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . 1) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdadr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdadr) (list 1 list)))))
(define-test |setf cdadr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
0 ))))
(assert-error 'type-error
(apply #'(setf cdadr) (list 1 list)))))
(define-test |setf cdadr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(0 . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cdadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDAR) function and SETF expander.
(define-test |setf cddar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cddar list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . 1)) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cddar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cddar list) 1))))
(define-test |setf cddar error 2|
(let ((list (copy-tree '(0 .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cddar list) 1))))
(define-test |setf cddar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . 0) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cddar list) 1))))
(define-test |setf cddar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cddar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . 1)) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cddar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cddar) (list 1 list)))))
(define-test |setf cddar apply error 2|
(let ((list (copy-tree '(0 .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cddar) (list 1 list)))))
(define-test |setf cddar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . 0) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cddar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDDR) function and SETF expander.
(define-test |setf cdddr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdddr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . 1)))
list)))
(define-test |setf cdddr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdddr list) 1))))
(define-test |setf cdddr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cdddr list) 1))))
(define-test |setf cdddr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(setf (cdddr list) 1))))
(define-test |setf cdddr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdddr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . 1)))
list)))
(define-test |setf cdddr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdddr) (list 1 list)))))
(define-test |setf cdddr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cdddr) (list 1 list)))))
(define-test |setf cdddr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(apply #'(setf cdddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAAAAR) function and SETF expander.
(define-test |setf caaaar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caaaar list) 1))
(assert-equal '((((1 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caaaar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caaaar list) 1))))
(define-test |setf caaaar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (caaaar list) 1))))
(define-test |setf caaaar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(setf (caaaar list) 1))))
(define-test |setf caaaar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caaar list) 0)
(assert-error 'type-error
(setf (caaaar list) 1))))
(define-test |setf caaaar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caaaar) (list 1 list)))
(assert-equal '((((1 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caaaar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caaaar) (list 1 list)))))
(define-test |setf caaaar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf caaaar) (list 1 list)))))
(define-test |setf caaaar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(apply #'(setf caaaar) (list 1 list)))))
(define-test |setf caaaar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caaar list) 0)
(assert-error 'type-error
(apply #'(setf caaaar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAAADR) function and SETF expander.
(define-test |setf caaadr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caaadr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((1 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caaadr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caaadr list) 1))))
(define-test |setf caaadr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (caaadr list) 1))))
(define-test |setf caaadr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(setf (caaadr list) 1))))
(define-test |setf caaadr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caadr list) 0)
(assert-error 'type-error
(setf (caaadr list) 1))))
(define-test |setf caaadr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caaadr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((1 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caaadr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caaadr) (list 1 list)))))
(define-test |setf caaadr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf caaadr) (list 1 list)))))
(define-test |setf caaadr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(apply #'(setf caaadr) (list 1 list)))))
(define-test |setf caaadr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caadr list) 0)
(assert-error 'type-error
(apply #'(setf caaadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAADAR) function and SETF expander.
(define-test |setf caadar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caadar list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((1 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caadar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caadar list) 1))))
(define-test |setf caadar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (caadar list) 1))))
(define-test |setf caadar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(setf (caadar list) 1))))
(define-test |setf caadar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadar list) 0)
(assert-error 'type-error
(setf (caadar list) 1))))
(define-test |setf caadar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caadar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((1 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caadar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caadar) (list 1 list)))))
(define-test |setf caadar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf caadar) (list 1 list)))))
(define-test |setf caadar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(apply #'(setf caadar) (list 1 list)))))
(define-test |setf caadar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadar list) 0)
(assert-error 'type-error
(apply #'(setf caadar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAADDR) function and SETF expander.
(define-test |setf caaddr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caaddr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((1 . 0) . (0 . 0))))
list)))
(define-test |setf caaddr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caaddr list) 1))))
(define-test |setf caaddr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (caaddr list) 1))))
(define-test |setf caaddr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(setf (caaddr list) 1))))
(define-test |setf caaddr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caddr list) 0)
(assert-error 'type-error
(setf (caaddr list) 1))))
(define-test |setf caaddr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caaddr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((1 . 0) . (0 . 0))))
list)))
(define-test |setf caaddr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caaddr) (list 1 list)))))
(define-test |setf caaddr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf caaddr) (list 1 list)))))
(define-test |setf caaddr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(apply #'(setf caaddr) (list 1 list)))))
(define-test |setf caaddr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caddr list) 0)
(assert-error 'type-error
(apply #'(setf caaddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADAAR) function and SETF expander.
(define-test |setf cadaar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cadaar list) 1))
(assert-equal '((((0 . 0) . (1 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cadaar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cadaar list) 1))))
(define-test |setf cadaar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (cadaar list) 1))))
(define-test |setf cadaar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(setf (cadaar list) 1))))
(define-test |setf cadaar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdaar list) 0)
(assert-error 'type-error
(setf (cadaar list) 1))))
(define-test |setf cadaar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cadaar) (list 1 list)))
(assert-equal '((((0 . 0) . (1 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cadaar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cadaar) (list 1 list)))))
(define-test |setf cadaar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf cadaar) (list 1 list)))))
(define-test |setf cadaar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(apply #'(setf cadaar) (list 1 list)))))
(define-test |setf cadaar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdaar list) 0)
(assert-error 'type-error
(apply #'(setf cadaar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADADR) function and SETF expander.
(define-test |setf cadadr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cadadr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (1 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cadadr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cadadr list) 1))))
(define-test |setf cadadr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cadadr list) 1))))
(define-test |setf cadadr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(setf (cadadr list) 1))))
(define-test |setf cadadr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdadr list) 0)
(assert-error 'type-error
(setf (cadadr list) 1))))
(define-test |setf cadadr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cadadr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (1 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cadadr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cadadr) (list 1 list)))))
(define-test |setf cadadr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cadadr) (list 1 list)))))
(define-test |setf cadadr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(apply #'(setf cadadr) (list 1 list)))))
(define-test |setf cadadr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdadr list) 0)
(assert-error 'type-error
(apply #'(setf cadadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADDAR) function and SETF expander.
(define-test |setf caddar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caddar list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (1 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caddar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caddar list) 1))))
(define-test |setf caddar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (caddar list) 1))))
(define-test |setf caddar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(setf (caddar list) 1))))
(define-test |setf caddar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddar list) 0)
(assert-error 'type-error
(setf (caddar list) 1))))
(define-test |setf caddar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caddar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (1 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caddar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caddar) (list 1 list)))))
(define-test |setf caddar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf caddar) (list 1 list)))))
(define-test |setf caddar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(apply #'(setf caddar) (list 1 list)))))
(define-test |setf caddar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddar list) 0)
(assert-error 'type-error
(apply #'(setf caddar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADDDR) function and SETF expander.
(define-test |setf cadddr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cadddr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (1 . 0))))
list)))
(define-test |setf cadddr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cadddr list) 1))))
(define-test |setf cadddr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cadddr list) 1))))
(define-test |setf cadddr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(setf (cadddr list) 1))))
(define-test |setf cadddr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdddr list) 0)
(assert-error 'type-error
(setf (cadddr list) 1))))
(define-test |setf cadddr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cadddr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (1 . 0))))
list)))
(define-test |setf cadddr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cadddr) (list 1 list)))))
(define-test |setf cadddr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cadddr) (list 1 list)))))
(define-test |setf cadddr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(apply #'(setf cadddr) (list 1 list)))))
(define-test |setf cadddr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdddr list) 0)
(assert-error 'type-error
(apply #'(setf cadddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDAAAR) function and SETF expander.
(define-test |setf cdaaar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdaaar list) 1))
(assert-equal '((((0 . 1) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdaaar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdaaar list) 1))))
(define-test |setf cdaaar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (cdaaar list) 1))))
(define-test |setf cdaaar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(setf (cdaaar list) 1))))
(define-test |setf cdaaar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caaar list) 0)
(assert-error 'type-error
(setf (cdaaar list) 1))))
(define-test |setf cdaaar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdaaar) (list 1 list)))
(assert-equal '((((0 . 1) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdaaar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdaaar) (list 1 list)))))
(define-test |setf cdaaar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf cdaaar) (list 1 list)))))
(define-test |setf cdaaar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(apply #'(setf cdaaar) (list 1 list)))))
(define-test |setf cdaaar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caaar list) 0)
(assert-error 'type-error
(apply #'(setf cdaaar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDAADR) function and SETF expander.
(define-test |setf cdaadr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdaadr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 1) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdaadr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdaadr list) 1))))
(define-test |setf cdaadr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cdaadr list) 1))))
(define-test |setf cdaadr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(setf (cdaadr list) 1))))
(define-test |setf cdaadr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caadr list) 0)
(assert-error 'type-error
(setf (cdaadr list) 1))))
(define-test |setf cdaadr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdaadr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 1) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdaadr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdaadr) (list 1 list)))))
(define-test |setf cdaadr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cdaadr) (list 1 list)))))
(define-test |setf cdaadr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(apply #'(setf cdaadr) (list 1 list)))))
(define-test |setf cdaadr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caadr list) 0)
(assert-error 'type-error
(apply #'(setf cdaadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDADAR) function and SETF expander.
(define-test |setf cdadar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdadar list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 1) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdadar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdadar list) 1))))
(define-test |setf cdadar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (cdadar list) 1))))
(define-test |setf cdadar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(setf (cdadar list) 1))))
(define-test |setf cdadar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadar list) 0)
(assert-error 'type-error
(setf (cdadar list) 1))))
(define-test |setf cdadar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdadar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 1) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdadar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdadar) (list 1 list)))))
(define-test |setf cdadar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf cdadar) (list 1 list)))))
(define-test |setf cdadar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(apply #'(setf cdadar) (list 1 list)))))
(define-test |setf cdadar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadar list) 0)
(assert-error 'type-error
(apply #'(setf cdadar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDADDR) function and SETF expander.
(define-test |setf cdaddr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdaddr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 1) . (0 . 0))))
list)))
(define-test |setf cdaddr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdaddr list) 1))))
(define-test |setf cdaddr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cdaddr list) 1))))
(define-test |setf cdaddr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(setf (cdaddr list) 1))))
(define-test |setf cdaddr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caddr list) 0)
(assert-error 'type-error
(setf (cdaddr list) 1))))
(define-test |setf cdaddr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdaddr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 1) . (0 . 0))))
list)))
(define-test |setf cdaddr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdaddr) (list 1 list)))))
(define-test |setf cdaddr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cdaddr) (list 1 list)))))
(define-test |setf cdaddr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(apply #'(setf cdaddr) (list 1 list)))))
(define-test |setf cdaddr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caddr list) 0)
(assert-error 'type-error
(apply #'(setf cdaddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDAAR) function and SETF expander.
(define-test |setf cddaar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cddaar list) 1))
(assert-equal '((((0 . 0) . (0 . 1)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cddaar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cddaar list) 1))))
(define-test |setf cddaar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (cddaar list) 1))))
(define-test |setf cddaar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(setf (cddaar list) 1))))
(define-test |setf cddaar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdaar list) 0)
(assert-error 'type-error
(setf (cddaar list) 1))))
(define-test |setf cddaar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cddaar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 1)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cddaar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cddaar) (list 1 list)))))
(define-test |setf cddaar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf cddaar) (list 1 list)))))
(define-test |setf cddaar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(apply #'(setf cddaar) (list 1 list)))))
(define-test |setf cddaar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdaar list) 0)
(assert-error 'type-error
(apply #'(setf cddaar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDADR) function and SETF expander.
(define-test |setf cddadr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cddadr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 1)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cddadr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cddadr list) 1))))
(define-test |setf cddadr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cddadr list) 1))))
(define-test |setf cddadr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(setf (cddadr list) 1))))
(define-test |setf cddadr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdadr list) 0)
(assert-error 'type-error
(setf (cddadr list) 1))))
(define-test |setf cddadr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cddadr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 1)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cddadr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cddadr) (list 1 list)))))
(define-test |setf cddadr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cddadr) (list 1 list)))))
(define-test |setf cddadr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(apply #'(setf cddadr) (list 1 list)))))
(define-test |setf cddadr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdadr list) 0)
(assert-error 'type-error
(apply #'(setf cddadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDDAR) function and SETF expander.
(define-test |setf cdddar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdddar list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 1))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdddar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdddar list) 1))))
(define-test |setf cdddar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (cdddar list) 1))))
(define-test |setf cdddar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(setf (cdddar list) 1))))
(define-test |setf cdddar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddar list) 0)
(assert-error 'type-error
(setf (cdddar list) 1))))
(define-test |setf cdddar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdddar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 1))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdddar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdddar) (list 1 list)))))
(define-test |setf cdddar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf cdddar) (list 1 list)))))
(define-test |setf cdddar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(apply #'(setf cdddar) (list 1 list)))))
(define-test |setf cdddar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddar list) 0)
(assert-error 'type-error
(apply #'(setf cdddar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDDDR) function and SETF expander.
(define-test |setf cddddr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cddddr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 1))))
list)))
(define-test |setf cddddr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cddddr list) 1))))
(define-test |setf cddddr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cddddr list) 1))))
(define-test |setf cddddr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(setf (cddddr list) 1))))
(define-test |setf cddddr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdddr list) 0)
(assert-error 'type-error
(setf (cddddr list) 1))))
(define-test |setf cddddr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cddddr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 1))))
list)))
(define-test |setf cddddr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cddddr) (list 1 list)))))
(define-test |setf cddddr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cddddr) (list 1 list)))))
(define-test |setf cddddr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(apply #'(setf cddddr) (list 1 list)))))
(define-test |setf cddddr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdddr list) 0)
(assert-error 'type-error
(apply #'(setf cddddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF FIRST) function and SETF expander.
(define-test |setf first 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (first list) 1))
(assert-equal '(1 0 0 0 0 0 0 0 0 0) list)))
(define-test |setf first error 1|
(let ((list '()))
(assert-error 'type-error
(setf (first list) 1))))
(define-test |setf first 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (first list) 1))
(assert-equal '(1 0 0 0 0 0 0 0 0 0) list)))
(define-test |setf first error 1|
(let ((list '()))
(assert-error 'type-error
(setf (first list) 1))))
(define-test |setf first apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf first) (list 1 list)))
(assert-equal '(1 0 0 0 0 0 0 0 0 0) list)))
(define-test |setf first apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf first) (list 1 list)))))
(define-test |setf first apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf first) (list 1 list)))
(assert-equal '(1 0 0 0 0 0 0 0 0 0) list)))
(define-test |setf first apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf first) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF SECOND) function and SETF expander.
(define-test |setf second 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (second list) 1))
(assert-equal '(0 1 0 0 0 0 0 0 0 0) list)))
(define-test |setf second error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 0 list)) 1)
(assert-error 'type-error
(setf (second list) 1))))
(define-test |setf second 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (second list) 1))
(assert-equal '(0 1 0 0 0 0 0 0 0 0) list)))
(define-test |setf second error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 0 list)) 1)
(assert-error 'type-error
(setf (second list) 1))))
(define-test |setf second apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf second) (list 1 list)))
(assert-equal '(0 1 0 0 0 0 0 0 0 0) list)))
(define-test |setf second apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 0 list)) 1)
(assert-error 'type-error
(apply #'(setf second) (list 1 list)))))
(define-test |setf second apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf second) (list 1 list)))
(assert-equal '(0 1 0 0 0 0 0 0 0 0) list)))
(define-test |setf second apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 0 list)) 1)
(assert-error 'type-error
(apply #'(setf second) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF THIRD) function and SETF expander.
(define-test |setf third 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (third list) 1))
(assert-equal '(0 0 1 0 0 0 0 0 0 0) list)))
(define-test |setf third error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 1 list)) 1)
(assert-error 'type-error
(setf (third list) 1))))
(define-test |setf third 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (third list) 1))
(assert-equal '(0 0 1 0 0 0 0 0 0 0) list)))
(define-test |setf third error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 1 list)) 1)
(assert-error 'type-error
(setf (third list) 1))))
(define-test |setf third apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf third) (list 1 list)))
(assert-equal '(0 0 1 0 0 0 0 0 0 0) list)))
(define-test |setf third apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 1 list)) 1)
(assert-error 'type-error
(apply #'(setf third) (list 1 list)))))
(define-test |setf third apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf third) (list 1 list)))
(assert-equal '(0 0 1 0 0 0 0 0 0 0) list)))
(define-test |setf third apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 1 list)) 1)
(assert-error 'type-error
(apply #'(setf third) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF FOURTH) function and SETF expander.
(define-test |setf fourth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (fourth list) 1))
(assert-equal '(0 0 0 1 0 0 0 0 0 0) list)))
(define-test |setf fourth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 2 list)) 1)
(assert-error 'type-error
(setf (fourth list) 1))))
(define-test |setf fourth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (fourth list) 1))
(assert-equal '(0 0 0 1 0 0 0 0 0 0) list)))
(define-test |setf fourth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 2 list)) 1)
(assert-error 'type-error
(setf (fourth list) 1))))
(define-test |setf fourth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf fourth) (list 1 list)))
(assert-equal '(0 0 0 1 0 0 0 0 0 0) list)))
(define-test |setf fourth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 2 list)) 1)
(assert-error 'type-error
(apply #'(setf fourth) (list 1 list)))))
(define-test |setf fourth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf fourth) (list 1 list)))
(assert-equal '(0 0 0 1 0 0 0 0 0 0) list)))
(define-test |setf fourth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 2 list)) 1)
(assert-error 'type-error
(apply #'(setf fourth) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF FIFTH) function and SETF expander.
(define-test |setf fifth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (fifth list) 1))
(assert-equal '(0 0 0 0 1 0 0 0 0 0) list)))
(define-test |setf fifth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 3 list)) 1)
(assert-error 'type-error
(setf (fifth list) 1))))
(define-test |setf fifth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (fifth list) 1))
(assert-equal '(0 0 0 0 1 0 0 0 0 0) list)))
(define-test |setf fifth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 3 list)) 1)
(assert-error 'type-error
(setf (fifth list) 1))))
(define-test |setf fifth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf fifth) (list 1 list)))
(assert-equal '(0 0 0 0 1 0 0 0 0 0) list)))
(define-test |setf fifth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 3 list)) 1)
(assert-error 'type-error
(apply #'(setf fifth) (list 1 list)))))
(define-test |setf fifth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf fifth) (list 1 list)))
(assert-equal '(0 0 0 0 1 0 0 0 0 0) list)))
(define-test |setf fifth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 3 list)) 1)
(assert-error 'type-error
(apply #'(setf fifth) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF SIXTH) function and SETF expander.
(define-test |setf sixth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (sixth list) 1))
(assert-equal '(0 0 0 0 0 1 0 0 0 0) list)))
(define-test |setf sixth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 4 list)) 1)
(assert-error 'type-error
(setf (sixth list) 1))))
(define-test |setf sixth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (sixth list) 1))
(assert-equal '(0 0 0 0 0 1 0 0 0 0) list)))
(define-test |setf sixth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 4 list)) 1)
(assert-error 'type-error
(setf (sixth list) 1))))
(define-test |setf sixth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf sixth) (list 1 list)))
(assert-equal '(0 0 0 0 0 1 0 0 0 0) list)))
(define-test |setf sixth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 4 list)) 1)
(assert-error 'type-error
(apply #'(setf sixth) (list 1 list)))))
(define-test |setf sixth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf sixth) (list 1 list)))
(assert-equal '(0 0 0 0 0 1 0 0 0 0) list)))
(define-test |setf sixth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 4 list)) 1)
(assert-error 'type-error
(apply #'(setf sixth) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF SEVENTH) function and SETF expander.
(define-test |setf seventh 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (seventh list) 1))
(assert-equal '(0 0 0 0 0 0 1 0 0 0) list)))
(define-test |setf seventh error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 5 list)) 1)
(assert-error 'type-error
(setf (seventh list) 1))))
(define-test |setf seventh 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (seventh list) 1))
(assert-equal '(0 0 0 0 0 0 1 0 0 0) list)))
(define-test |setf seventh error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 5 list)) 1)
(assert-error 'type-error
(setf (seventh list) 1))))
(define-test |setf seventh apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf seventh) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 1 0 0 0) list)))
(define-test |setf seventh apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 5 list)) 1)
(assert-error 'type-error
(apply #'(setf seventh) (list 1 list)))))
(define-test |setf seventh apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf seventh) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 1 0 0 0) list)))
(define-test |setf seventh apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 5 list)) 1)
(assert-error 'type-error
(apply #'(setf seventh) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF EIGHTH) function and SETF expander.
(define-test |setf eighth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (eighth list) 1))
(assert-equal '(0 0 0 0 0 0 0 1 0 0) list)))
(define-test |setf eighth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 6 list)) 1)
(assert-error 'type-error
(setf (eighth list) 1))))
(define-test |setf eighth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (eighth list) 1))
(assert-equal '(0 0 0 0 0 0 0 1 0 0) list)))
(define-test |setf eighth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 6 list)) 1)
(assert-error 'type-error
(setf (eighth list) 1))))
(define-test |setf eighth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf eighth) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 0 1 0 0) list)))
(define-test |setf eighth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 6 list)) 1)
(assert-error 'type-error
(apply #'(setf eighth) (list 1 list)))))
(define-test |setf eighth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf eighth) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 0 1 0 0) list)))
(define-test |setf eighth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 6 list)) 1)
(assert-error 'type-error
(apply #'(setf eighth) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF NINTH) function and SETF expander.
(define-test |setf ninth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (ninth list) 1))
(assert-equal '(0 0 0 0 0 0 0 0 1 0) list)))
(define-test |setf ninth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 7 list)) 1)
(assert-error 'type-error
(setf (ninth list) 1))))
(define-test |setf ninth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (ninth list) 1))
(assert-equal '(0 0 0 0 0 0 0 0 1 0) list)))
(define-test |setf ninth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 7 list)) 1)
(assert-error 'type-error
(setf (ninth list) 1))))
(define-test |setf ninth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf ninth) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 0 0 1 0) list)))
(define-test |setf ninth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 7 list)) 1)
(assert-error 'type-error
(apply #'(setf ninth) (list 1 list)))))
(define-test |setf ninth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf ninth) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 0 0 1 0) list)))
(define-test |setf ninth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 7 list)) 1)
(assert-error 'type-error
(apply #'(setf ninth) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF TENTH) function and SETF expander.
(define-test |setf tenth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (tenth list) 1))
(assert-equal '(0 0 0 0 0 0 0 0 0 1) list)))
(define-test |setf tenth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 8 list)) 1)
(assert-error 'type-error
(setf (tenth list) 1))))
(define-test |setf tenth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (tenth list) 1))
(assert-equal '(0 0 0 0 0 0 0 0 0 1) list)))
(define-test |setf tenth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 8 list)) 1)
(assert-error 'type-error
(setf (tenth list) 1))))
(define-test |setf tenth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf tenth) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 0 0 0 1) list)))
(define-test |setf tenth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 8 list)) 1)
(assert-error 'type-error
(apply #'(setf tenth) (list 1 list)))))
(define-test |setf tenth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf tenth) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 0 0 0 1) list)))
(define-test |setf tenth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 8 list)) 1)
(assert-error 'type-error
(apply #'(setf tenth) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the REST function.
(define-test rest.1
(assert-equal '() (rest '())))
(define-test rest.2
(assert-equal '() (rest '(0))))
(define-test rest.3
(assert-equal '(1) (rest '(0 1))))
(define-test rest.error.1
(assert-error 'type-error
(rest 1)))
(define-test rest.apply.1
(assert-equal '(1) (apply (second (list 'a #'rest)) '((0 1)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the SETF expander and SETF function for REST.
(define-test |setf-rest 1|
(let ((list (copy-list '(0))))
(assert-equal 1 (setf (rest list) 1))
(assert-equal '(0 . 1) list)))
(define-test |setf-rest error 1|
(let ((list 1))
(assert-error 'type-error
(setf (rest list) 1))))
(define-test |setf-rest apply 1|
(let ((list (copy-list '(0))))
(assert-equal 1 (apply #'(setf rest) (list 1 list)))
(assert-equal '(0 . 1) list)))
(define-test |setf-rest apply error 1|
(let ((list 1))
(assert-error 'type-error
(apply #'(setf rest) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the LIST function.
(define-test list.1
(assert-equal '() (list)))
(define-test list.2
(assert-equal '(1) (list 1)))
(define-test list.3
(assert-equal '(1 2) (list 1 2)))
(define-test list.4
(assert-equal '(1 2 3) (list 1 2 3)))
(define-test list.5
(assert-equal '((a) (b) 1 2) (list '(a) '(b) 1 2)))
(define-test list.apply.1a
(assert-equal '() (apply (cadr (list 1 #'list)) '())))
(define-test list.apply.2a
(assert-equal '(1) (apply (cadr (list 1 #'list)) (list 1))))
(define-test list.apply.3a
(assert-equal '(1 2) (apply (cadr (list 1 #'list)) (list 1 2))))
(define-test list.apply.4a
(assert-equal '(1 2 3) (apply (cadr (list 1 #'list)) (list 1 2 3))))
(define-test list.apply.5a
(assert-equal '((a) (b) 1 2)
(apply (cadr (list 1 #'list)) (list '(a) '(b) 1 2))))
(define-test list.apply.1b
(assert-equal '() (apply (cadr (list 1 'list)) '())))
(define-test list.apply.2b
(assert-equal '(1) (apply (cadr (list 1 'list)) (list 1))))
(define-test list.apply.3b
(assert-equal '(1 2) (apply (cadr (list 1 'list)) (list 1 2))))
(define-test list.apply.4b
(assert-equal '(1 2 3) (apply (cadr (list 1 'list)) (list 1 2 3))))
(define-test list.apply.5b
(assert-equal '((a) (b) 1 2)
(apply (cadr (list 1 'list)) (list '(a) '(b) 1 2))))
(define-test list.order.1
(let ((i 0))
(assert-equal '(1 2 3) (list (incf i) (incf i) (incf i)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the LIST* function.
(define-test list*.1
(assert-equal '(1 2 3) (list* 1 '(2 3))))
(define-test list*.2
(assert-equal '(1 2 3) (list* 1 2 '(3))))
(define-test list*.3
(assert-equal '(1 2 3) (list* 1 2 3 '())))
(define-test list*.4
(assert-equal 'a (list* 'a)))
(define-test list*.5
(assert-equal '(1 2 . 3) (list* 1 2 3)))
(define-test list*.apply.1
(assert-equal '(1 2 3)
(apply (cadr (list 1 #'list*)) (list 1 '(2 3)))))
(define-test list*.apply.2
(assert-equal '(1 2 3)
(apply (cadr (list 1 #'list*)) (list 1 2 '(3)))))
(define-test list*.apply.3
(assert-equal '(1 2 3)
(apply (cadr (list 1 #'list*)) (list 1 2 3 '()))))
(define-test list*.apply.4
(assert-equal 'a
(apply (cadr (list 1 #'list*)) (list 'a))))
(define-test list*.apply.5
(assert-equal '(1 2 . 3)
(apply (cadr (list 1 #'list*)) (list 1 2 3))))
(define-test list*.error.1
(assert-error 'error
(list*)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the LAST function.
(define-test |last 1|
(assert-equal '() (last '())))
(define-test |last 2|
(assert-equal '(1) (last '(1))))
(define-test |last 3|
(assert-equal '(2) (last '(1 2))))
(define-test |last 4|
(assert-equal '(1 . 2) (last '(1 . 2))))
(define-test |last 5|
(assert-equal '(2 3) (last '(1 2 3) 2)))
(define-test |last 6|
(assert-equal '(1 2 . 3) (last '(1 2 . 3) 2)))
(define-test |last 7|
(assert-equal '(2 3 . 4) (last '(1 2 3 . 4) 2)))
(define-test |last 8|
(assert-equal '(1 2 3) (last '(1 2 3) 3)))
(define-test |last 9|
(assert-equal '(1 2 3) (last '(1 2 3) 4)))
(define-test |last error 1|
(assert-error 'type-error
(last 1)))
(define-test |last error 2|
(assert-error 'type-error
(last '(1) 'a)))
(define-test |last apply error 1|
(assert-error 'type-error
(apply #'last (list 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the COPY-LIST function.
(define-test copy-list.1
(assert-equal '() (copy-list '())))
(define-test copy-list.2
(assert-equal '(1) (copy-list '(1))))
(define-test copy-list.3
(let ((thing '(a b)))
(assert-equal thing (car (copy-list (list thing 1 2))))))
(define-test copy-list.4
(assert-equal '(1 . 2) (copy-list '(1 . 2))))
(define-test copy-list.error
(assert-error 'type-error (copy-list 1)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the LIST-LENGTH function.
(define-test |list-length proper-list 1|
(assert-equal 0
(list-length '())))
(define-test |list-length proper-list 2|
(assert-equal 1
(list-length '(0))))
(define-test |list-length proper-list 3|
(assert-equal 2
(list-length '(0 0))))
(define-test |list-length proper-list 4|
(assert-equal 3
(list-length '(0 0 0))))
(define-test |list-length proper-list 5|
(assert-equal 4
(list-length '(0 0 0 0))))
(define-test |list-length proper-list 6|
(assert-equal 5
(list-length '(0 0 0 0 0))))
(define-test |list-length circular-list 1|
(assert-equal nil
(list-length '#1=(0 . #1#))))
(define-test |list-length circular-list 2|
(assert-equal nil
(list-length '#1=(0 0 . #1#))))
(define-test |list-length circular-list 3|
(assert-equal nil
(list-length '#1=(0 0 0 . #1#))))
(define-test |list-length circular-list 4|
(assert-equal nil
(list-length '#1=(0 0 0 0 . #1#))))
(define-test |list-length dotted-list 1|
(assert-error 'type-error
(list-length '(0 . 0))))
(define-test |list-length dotted-list 2|
(assert-error 'type-error
(list-length '(0 0 . 0))))
(define-test |list-length dotted-list 3|
(assert-error 'type-error
(list-length '(0 0 0 . 0))))
(define-test |list-length dotted-list 4|
(assert-error 'type-error
(list-length '(0 0 0 0 . 0))))
(define-test |list-length not-a-list 1|
(assert-error 'type-error
(list-length 0)))
(define-test |list-length not-a-list 2|
(assert-error 'type-error
(list-length 'a)))
(define-test |list-length not-a-list 3|
(assert-error 'type-error
(list-length #(a))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the MAKE-LIST function.
(define-test make-list.1
(assert-equal '() (make-list 0)))
(define-test make-list.2
(assert-equal 1 (length (make-list 1))))
(define-test make-list.3
(assert-equal '(3 3) (make-list 2 :initial-element 3)))
(define-test make-list.error.1
(assert-error 'type-error (make-list 'a)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the NTHCDR function.
(define-test |nthcdr 1|
(assert-equal '()
(nthcdr 0 '())))
(define-test |nthcdr 2|
(assert-equal '()
(nthcdr 1 '())))
(define-test |nthcdr 3|
(assert-equal '(0 0)
(nthcdr 1 '(0 0 0))))
(define-test |nthcdr error 1|
(assert-error 'type-error
(nthcdr 'a '(0 0))))
(define-test |nthcdr error 2|
(assert-error 'type-error
(nthcdr '-1 '(0 0))))
(define-test |nthcdr error 3|
(assert-error 'type-error
(nthcdr 2 '(0 . 0))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the NTH function.
(define-test |nth 1|
(assert-equal '()
(nth 0 '())))
(define-test |nth 2|
(assert-equal '()
(nth 1 '())))
(define-test |nth 3|
(assert-equal 1
(nth 0 '(1 2))))
(define-test |nth 4|
(assert-equal 2
(nth 1 '(1 2))))
(define-test |nth 5|
(assert-equal '()
(nth 3 '(1 2))))
(define-test |nth error 1|
(assert-error 'type-error
(nth 3 '(1 2 . 0))))
(define-test |nth error 2|
(assert-error 'type-error
(nth -1 '(1))))
(define-test |nth error 2|
(assert-error 'type-error
(nth 'a '(1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF NTH) function and SETF expander.
(define-test |setf-nth 1|
(let ((list (copy-list '(0 0 0))))
(assert-equal 1
(setf (nth 0 list) 1))
(assert-equal '(1 0 0)
list)))
(define-test |setf-nth 1|
(let ((list (copy-list '(0 0 0))))
(assert-equal 1
(setf (nth 2 list) 1))
(assert-equal '(0 0 1)
list)))
(define-test |setf-nth error 1|
(assert-error 'error
(setf (nth 0 '()) 1)))
(define-test |setf-nth error 2|
(assert-error 'error
(setf (nth 1 (copy-list '(0))) 1)))
(define-test |setf-nth error 3|
(assert-error 'error
(setf (nth 2 (copy-list '(0))) 1)))
(define-test |setf-nth error 4|
(assert-error 'error
(setf (nth -1 (copy-list '(0))) 1)))
(define-test |setf-nth error 5|
(assert-error 'error
(setf (nth 'a (copy-list '(0))) 1)))
(define-test |setf-nth apply 1|
(let ((list (copy-list '(0 0 0))))
(assert-equal 1
(apply #'(setf nth) (list 1 0 list)))
(assert-equal '(1 0 0)
list)))
(define-test |setf-nth apply 1|
(let ((list (copy-list '(0 0 0))))
(assert-equal 1
(apply #'(setf nth) (list 1 2 list)))
(assert-equal '(0 0 1)
list)))
(define-test |setf-nth apply error 1|
(assert-error 'error
(apply #'(setf nth) (list 1 0 '()))))
(define-test |setf-nth apply error 2|
(assert-error 'error
(apply #'(setf nth) (list 1 1 (copy-list '(0))))))
(define-test |setf-nth apply error 3|
(assert-error 'error
(apply #'(setf nth) (list 1 2 (copy-list '(0))))))
(define-test |setf-nth apply error 4|
(assert-error 'error
(apply #'(setf nth) (list 1 -1 (copy-list '(0))))))
(define-test |setf-nth apply error 5|
(assert-error 'error
(apply #'(setf nth) (list 1 'a (copy-list '(0))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the copy-tree function
(define-test copy-tree.1
(assert-equal 'x (copy-tree 'x)))
(define-test copy-tree.2
(assert-equal '(a . b) (copy-tree '(a . b))))
(define-test copy-tree.3
(let ((tree '(((((a b . c) d (e (f g)) . h))) (i j (k)))))
(assert-equal tree (copy-tree tree))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the tree-equal function
(define-test |tree-equal test=eql 1a|
(assert-true (tree-equal nil nil)))
(define-test |tree-equal test=eql 1b|
(assert-true (tree-equal nil nil :test #'eql)))
(define-test |tree-equal test=eql 1c|
(assert-true (tree-equal nil nil :test 'eql)))
(define-test |tree-equal test=eql 2a|
(assert-true (tree-equal 1 1)))
(define-test |tree-equal test=eql 2b|
(assert-true (tree-equal 1 1 :test #'eql)))
(define-test |tree-equal test=eql 2c|
(assert-true (tree-equal 1 1 :test 'eql)))
(define-test |tree-equal test=eql 3a|
(assert-true (tree-equal '(1) '(1))))
(define-test |tree-equal test=eql 3b|
(assert-true (tree-equal '(1) '(1) :test #'eql)))
(define-test |tree-equal test=eql 3c|
(assert-true (tree-equal '(1) '(1) :test 'eql)))
(define-test |tree-equal test=eql 4a|
(assert-true (tree-equal '(1 . 2) '(1 . 2))))
(define-test |tree-equal test=eql 4b|
(assert-true (tree-equal '(1 . 2) '(1 . 2) :test #'eql)))
(define-test |tree-equal test=eql 4c|
(assert-true (tree-equal '(1 . 2) '(1 . 2) :test 'eql)))
(define-test |tree-equal test=eql 5a|
(assert-false (tree-equal 1 2)))
(define-test |tree-equal test=eql 5b|
(assert-false (tree-equal 1 2 :test #'eql)))
(define-test |tree-equal test=eql 5c|
(assert-false (tree-equal 1 2 :test 'eql)))
(define-test |tree-equal test=eql 6a|
(assert-false (tree-equal '(1) '(2))))
(define-test |tree-equal test=eql 6b|
(assert-false (tree-equal '(1) '(2) :test #'eql)))
(define-test |tree-equal test=eql 6c|
(assert-false (tree-equal '(1) '(2) :test 'eql)))
(define-test |tree-equal test=eql 7a|
(assert-false (tree-equal '(1) '((1)))))
(define-test |tree-equal test=eql 7b|
(assert-false (tree-equal '(1) '((1)) :test #'eql)))
(define-test |tree-equal test=eql 7c|
(assert-false (tree-equal '(1) '((1)) :test 'eql)))
(define-test |tree-equal test=eql 8a|
(assert-false (tree-equal '((1)) '(1))))
(define-test |tree-equal test=eql 8b|
(assert-false (tree-equal '((1)) '(1) :test #'eql)))
(define-test |tree-equal test=eql 8c|
(assert-false (tree-equal '((1)) '(1) :test 'eql)))
(define-test |tree-equal test=eq 1a|
(assert-true (tree-equal 'a 'a :test #'eq)))
(define-test |tree-equal test=eq 1b|
(assert-true (tree-equal 'a 'a :test 'eq)))
(define-test |tree-equal test=eq 2a|
(assert-false (tree-equal 'a 'b :test #'eq)))
(define-test |tree-equal test=eq 2b|
(assert-false (tree-equal 'a 'b :test 'eq)))
(define-test |tree-equal test=eq 3a|
(assert-true (tree-equal '(a) '(a) :test #'eq)))
(define-test |tree-equal test=eq 3b|
(assert-true (tree-equal '(a) '(a) :test 'eq)))
(define-test |tree-equal test=eq 4a|
(assert-false (tree-equal '(a) '((a)) :test #'eq)))
(define-test |tree-equal test=eq 4b|
(assert-false (tree-equal '(a) '((a)) :test 'eq)))
(define-test |tree-equal test=eq 5a|
(assert-false (tree-equal '((a)) '(a) :test #'eq)))
(define-test |tree-equal test=eq 5b|
(assert-false (tree-equal '((a)) '(a) :test 'eq)))
(define-test |tree-equal test-not=eql 1a|
(assert-false (tree-equal '(1) '(2) :test-not #'eql)))
(define-test |tree-equal test-not=eql 1b|
(assert-false (tree-equal '(1) '(2) :test-not 'eql)))
(define-test |tree-equal test-not=eql 2a|
(assert-false (tree-equal '(1) '((1)) :test-not #'eql)))
(define-test |tree-equal test-not=eql 2b|
(assert-false (tree-equal '(1) '((1)) :test-not 'eql)))
(define-test |tree-equal test-not=eql 3a|
(assert-false (tree-equal '((1)) '(1) :test-not #'eql)))
(define-test |tree-equal test-not=eql 3b|
(assert-false (tree-equal '((1)) '(1) :test-not 'eql)))
(define-test |tree-equal test-not=eq 1a|
(assert-true (tree-equal 'a 'b :test-not #'eq)))
(define-test |tree-equal test-not=eq 1b|
(assert-true (tree-equal 'a 'b :test-not 'eq)))
(define-test |tree-equal test-not=eq 2a|
(assert-false (tree-equal 'a 'a :test-not #'eq)))
(define-test |tree-equal test-not=eq 2b|
(assert-false (tree-equal 'a 'a :test-not 'eq)))
(define-test |tree-equal test-not=eq 3a|
(assert-false (tree-equal '(a) '(a) :test-not #'eq)))
(define-test |tree-equal test-not=eq 3b|
(assert-false (tree-equal '(a) '(a) :test-not 'eq)))
(define-test |tree-equal test-not=eq 4a|
(assert-false (tree-equal '(a) '((a)) :test-not #'eq)))
(define-test |tree-equal test-not=eq 4b|
(assert-false (tree-equal '(a) '((a)) :test-not 'eq)))
(define-test |tree-equal test-not=eq 5a|
(assert-false (tree-equal '((a)) '(a) :test-not #'eq)))
(define-test |tree-equal test-not=eq 5b|
(assert-false (tree-equal '((a)) '(a) :test-not 'eq)))
(define-test |tree-equal test-not=eq 6a|
(assert-false (tree-equal '(a) '(b) :test-not #'eq)))
(define-test |tree-equal test-not=eq 6b|
(assert-false (tree-equal '(a) '(b) :test-not 'eq)))
(define-test |tree-equal test=other 1|
(assert-true (tree-equal '(1) '(2)
:test (lambda (x y)
(or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1)))))))
(define-test |tree-equal test=other 2|
(assert-false (tree-equal '(1) '(3)
:test (lambda (x y)
(or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1)))))))
(define-test |tree-equal test=other 3|
(assert-false (tree-equal '(1) '((3))
:test (lambda (x y)
(or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1)))))))
(define-test |tree-equal test=other 4|
(assert-false (tree-equal '((1)) '(3)
:test (lambda (x y)
(or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1)))))))
(define-test |tree-equal test-not=other 1|
(assert-true (tree-equal '(1) '(2)
:test-not (lambda (x y)
(not (or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))))))
(define-test |tree-equal test-not=other 2|
(assert-false (tree-equal '(1) '(3)
:test-not (lambda (x y)
(not (or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))))))
(define-test |tree-equal test-not=other 3|
(assert-false (tree-equal '(1) '((3))
:test-not (lambda (x y)
(not (or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))))))
(define-test |tree-equal test-not=other 4|
(assert-false (tree-equal '((1)) '(3)
:test-not (lambda (x y)
(not (or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))))))
(define-test |tree-equal test=other test-not=other 1|
(assert-error 'error
(tree-equal '() '() :test #'eql :test-not #'eql)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the endp function
(define-test endp.1
(assert-true (endp '())))
(define-test endp.2
(assert-false (endp '(1 . 2))))
(define-test endp.3
(assert-error 'type-error (endp 1)))
(define-test endp.4
(assert-error 'type-error (endp #\a)))
(define-test endp.5
(assert-error 'type-error (endp "a")))
(define-test endp.6
(assert-error 'type-error (endp 'a)))
(define-test endp.7
(assert-error 'type-error (endp 1.0)))
(define-test endp.8
(assert-error 'type-error (endp #(a))))
(define-test endp.9
(assert-error 'type-error (endp *standard-input*)))
(define-test endp.10
(assert-error 'type-error (endp *package*)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the mapcar function
(define-test |mapcar 1|
(assert-equal '() (mapcar #'1+ '())))
(define-test |mapcar 2|
(assert-equal '(1) (mapcar #'1+ '(0))))
(define-test |mapcar 3|
(assert-equal '(-1 -2 -3) (mapcar #'- '(1 2 3))))
(define-test |mapcar 4|
(assert-equal '(2 4 6) (mapcar #'+ '(1 2 3) '(1 2 3))))
(define-test |mapcar 5|
(assert-equal '(3 6 9) (mapcar #'+ '(1 2 3) '(1 2 3) '(1 2 3))))
(define-test |mapcar 6|
(assert-equal '(2 4) (mapcar #'+ '(1 2 3 4 5) '(1 2))))
(define-test |mapcar 7|
(assert-equal '(2 4) (mapcar #'+ '(1 2) '(1 2 3 4 5))))
(define-test |mapcar error 1|
(assert-error 'type-error (mapcar #'1+ (if (twisted '(a b c)) 1 '(a b c)))))
(define-test |mapcar error 2|
(assert-error 'type-error (mapcar #'1+ (if (twisted '(a b c)) #(1 2 3) '(a b c)))))
(define-test |mapcar error 3|
(assert-error 'type-error (mapcar #'1+ '(1 2 . 3))))
(define-test |mapcar error 4|
(assert-error 'type-error (mapcar #'1+ (if (twisted '(a b c)) "1" '(a b c)))))
(define-test |mapcar error 5|
(assert-error 'error (mapcar #'1+)))
(define-test |mapcar error 6|
(assert-error 'type-error
(mapcar #'list '(a b c) '(d e . f))))
(define-test |mapcar order 1|
(let ((i 0)
(funs (vector #'1+ #'1-))
(lists '((1 2) (3 4) (5 6))))
(assert-equal '(4 5) (mapcar (aref funs (incf i)) (nth (incf i) lists)))))
(define-test |mapcar apply error 1|
(assert-error 'error
(apply (cadr (list 'a #'mapcar)) #'car '())))
(define-test |mapcar apply error 2|
(assert-error 'type-error
(apply (cadr (list 'a #'mapcar)) #'list '((a b c) (d e . f)))))
(define-test |mapcar apply 1|
(assert-equal '(a b c)
(apply (cadr (list 'a #'mapcar)) #'car '(((a) (b) (c))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the mapc function
(define-test mapc.1
(assert-equal '() (mapc #'1+ '())))
(define-test mapc.2
(let ((i 0))
(assert-equal '(1 2 3 6)
(append (mapc (lambda (x) (incf i x)) '(1 2 3))
(list i)))))
(define-test mapc.3
(let ((i 0))
(assert-equal '(1 2 3 12)
(append (mapc (lambda (x y) (incf i (+ x y)))
'(1 2 3)
'(1 2 3))
(list i)))))
(define-test mapc.apply.1
(let ((i 0))
(assert-equal '(1 2 3 12)
(append (apply (cadr (list 'a #'mapc))
(list (lambda (x y) (incf i (+ x y)))
'(1 2 3)
'(1 2 3)))
(list i)))))
(define-test mapc.error.1
(assert-error 'type-error (mapc #'1+ (if (twisted '(a b c)) 1 '(1 2 3)))))
(define-test mapc.error.2
(assert-error 'type-error (mapc #'1+ (if (twisted '(a b c)) #(1 2 3) '(1 2 3)))))
(define-test mapc.error.3
(assert-error 'type-error (mapc #'1+ '(1 2 . 3))))
(define-test mapc.error.4
(assert-error 'type-error (mapc #'1+ (if (twisted '(a b c)) "1" '(1 2 3)))))
(define-test mapc.error.5
(assert-error 'error (mapc #'1+)))
(define-test mapc.apply.error.1
(assert-error 'type-error
(apply #'mapc (list #'list '(1 2) '(3 . 4)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the maplist function
(define-test maplist.1
(assert-equal '() (maplist #'car '())))
(define-test maplist.2
(assert-equal '(1 2 3) (maplist #'car '(1 2 3))))
(define-test maplist.apply.1
(assert-equal '(1 2 3)
(apply (cadr (list 'a #'maplist))
(list #'car '(1 2 3)))))
(define-test maplist.error.1
(assert-error 'type-error (maplist #'car (if (twisted '(a b c)) 1 '(a b c)))))
(define-test maplist.error.2
(assert-error 'type-error (maplist #'car (if (twisted '(a b c)) #(1 2 3) '(a b c)))))
(define-test maplist.error.3
(assert-error 'type-error (maplist #'car '(1 2 . 3))))
(define-test maplist.error.4
(assert-error 'type-error (maplist #'car (if (twisted '(a b c)) "1" '(a b c)))))
(define-test maplist.error.5
(assert-error 'error (maplist #'car)))
(define-test maplist.apply.error.1
(assert-error 'type-error
(apply #'maplist (list #'list '(1 2) '(3 . 4)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the mapl function
(define-test mapl.1
(assert-equal '() (mapl #'car '())))
(define-test mapl.2
(assert-equal '(1) (mapl #'car '(1))))
(define-test mapl.3
(let ((i 0))
(assert-equal 6
(progn (mapl (lambda (sublist) (incf i (car sublist)))
'(1 2 3))
i))))
(define-test mapl.apply.1
(let ((i 0))
(assert-equal 6
(progn (apply (cadr (list 'a #'mapl))
(list (lambda (sublist) (incf i (car sublist)))
'(1 2 3)))
i))))
(define-test mapl.error.1
(assert-error 'type-error (mapl #'car (if (twisted '(a b c)) 1 '(a b c)))))
(define-test mapl.error.2
(assert-error 'type-error (mapl #'car (if (twisted '(a b c)) #(1 2 3) '(a b c)))))
(define-test mapl.error.3
(assert-error 'type-error (mapl #'car '(1 2 . 3))))
(define-test mapl.error.4
(assert-error 'type-error (mapl #'car (if (twisted '(a b c)) "1" '(a b c)))))
(define-test mapl.error.5
(assert-error 'error (mapl #'car)))
(define-test mapl.apply.error.1
(assert-error 'type-error
(apply #'mapl (list #'list '(1 2) '(3 . 4)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the mapcan function
(define-test mapcan.1
(assert-equal '(a b c)
(mapcan #'list '(a b c))))
(define-test mapcan.2
(assert-equal '(a d b e c f)
(mapcan #'list '(a b c) '(d e f))))
(define-test mapcan.3
(assert-equal '(a b c . f)
(mapcan #'cons '(a b c) '(d e f))))
(define-test mapcan.4
(let ((a (list 'a))
(b (list 'b))
(c (list 'c)))
(assert-eq c
(cddr (mapcan #'identity (list a b c))))))
(define-test mapcan.5
(assert-equal '()
(mapcan #'identity '())))
(define-test mapcan.apply.1
(let ((a (list 'a))
(b (list 'b))
(c (list 'c)))
(assert-eq c
(cddr (apply (cadr (list 'a #'mapcan))
(list #'identity (list a b c)))))))
(define-test mapcan.error.1
(assert-error 'type-error
(mapcan #'car (if (twisted '(a b c)) 1 '((a) (b) (c))))))
(define-test mapcan.error.2
(assert-error 'type-error
(mapcan #'car (if (twisted '(a b c)) #(1 2 3) '((a) (b) (c))))))
(define-test mapcan.error.3
(assert-error 'type-error (mapcan #'car '(1 2 . 3))))
(define-test mapcan.error.4
(assert-error 'type-error
(mapcan #'car (if (twisted '(a b c)) "1" '((a) (b) (c))))))
(define-test mapcan.error.5
(assert-error 'error (mapcan #'car)))
(define-test mapcan.apply.error.1
(assert-error 'type-error
(apply #'mapcan (list #'list '(1 2) '(3 . 4)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the mapcon function
(define-test |macon 1|
(assert-equal nil
(mapcon #'identity '())))
(define-test |mapcon 2|
(assert-equal '(1 2 2)
(mapcon #'copy-list '(1 2))))
(define-test |mapcon 3|
(assert-equal '((1 2) (3 4) (2) (4))
(mapcon #'list '(1 2) '(3 4))))
(define-test |mapcon apply 1|
(assert-equal '((1 2) (3 4) (2) (4))
(apply #'mapcon #'list '(1 2) '(3 4) '())))
(define-test |mapcon error 1|
(assert-error 'type-error
(mapcon #'copy-list '(1 . 2))))
(define-test |mapcon error 2|
(assert-error 'type-error
(mapcon #'car (if (twisted '(a b c)) "1" '((a) (b) (c))))))
(define-test |mapcon error 3|
(assert-error 'error
(mapcon #'car)))
(define-test |mapcon apply error 1|
(assert-error 'type-error
(apply #'mapcon (list #'list '(1 2) '(3 . 4)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the append function
(define-test |append 1|
(assert-equal nil (append)))
(define-test |append 2|
(assert-equal 'x (append 'x)))
(define-test |append 4|
(assert-equal
'(a b c d e f g . h)
(append (list 'a) (list 'b) (list 'c)
(list 'd) (list 'e) (list 'f)
(list 'g) 'h)))
(define-test |append 5|
(assert-equal 'a (append nil nil nil nil nil nil nil nil 'a)))
;;; Test suggested by Peter Graves
(define-test |append 7|
(let ((x (list 'a 'b 'c 'd)))
(assert-false (eq (append x nil) x))))
;;; Order of evaluation tests
(define-test |append order 1|
(assert-equal
'((a b c d e f g h i) 3 1 2 3)
(let ((i 0) x y z)
(list
(append (progn (setf x (incf i)) (copy-list '(a b c)))
(progn (setf y (incf i)) (copy-list '(d e f)))
(progn (setf z (incf i)) (copy-list '(g h i))))
i x y z))))
(define-test |append order 2|
(assert-equal '(1 1) (let ((i 0)) (append (list (incf i)) (list i)))))
;;; Error tests
(define-test |append error 1|
(assert-error 'type-error (append '(a . b) '(z))))
(define-test |append error 2|
(assert-error 'type-error (append '(x y z) '(a . b) '(z))))
;;; This test verifies that append preserves the structure of
;;; the last list.
(define-test |append sharing 1|
(let ((list1 '(1 2))
(list2 '(3 4)))
(assert-eq (cddr (append list1 list2)) list2)))
(define-test |append apply 1|
(let ((list1 '(1 2))
(list2 '(3 4)))
(assert-equal '(1 2 3 4)
(apply (cadr (list 'a #'append)) (list list1 list2)))
(assert-equal '(1 2 3 4)
(apply (cadr (list 'a 'append)) (list list1 list2)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nconc function
(define-test |nconc 1|
(assert-eq '() (nconc)))
(define-test |nconc 2|
(let ((list (copy-tree '(a b c))))
(assert-eq list (nconc list))))
(define-test |nconc 3|
(let ((list (copy-tree '(a b c))))
(assert-eq list (nconc '() list))))
(define-test |nconc 4|
(let ((list1 (copy-tree '(a b c)))
(list2 (copy-tree '(d e f))))
(assert-eq list1 (nconc list1 list2))
(assert-eq list2 (cdddr list1))))
(define-test |nconc 5|
(assert-equal '(a z)
(nconc (copy-tree '(a . b))
(copy-tree '(z)))))
(define-test |nconc 6|
(assert-equal '(x y z a z)
(nconc (copy-tree '(x y z))
(copy-tree '(a . b))
(copy-tree '(z)))))
(define-test |nconc order 1|
(assert-equal
'((a b c d e f g h i) 3 1 2 3)
(let ((i 0) x y z)
(list
(nconc (progn (setf x (incf i)) (copy-list '(a b c)))
(progn (setf y (incf i)) (copy-list '(d e f)))
(progn (setf z (incf i)) (copy-list '(g h i))))
i x y z))))
(define-test |nconc apply 1|
(let ((list1 '(1 2))
(list2 '(3 4)))
(assert-equal '(1 2 3 4)
(apply (cadr (list 'a #'nconc))
(copy-tree (list list1 list2))))
(assert-equal '(1 2 3 4)
(apply (cadr (list 'a 'nconc))
(copy-tree (list list1 list2))))))
(define-test |nconc error 1|
(assert-error 'type-error
(nconc (copy-tree '(a b c)) 'd (copy-tree '(e f)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the revappend function
(define-test revappend.1
(assert-equal '()
(revappend '() '())))
(define-test revappend.2
(assert-equal '(a)
(revappend '(a) '())))
(define-test revappend.3
(assert-equal '(b a)
(revappend '(a b) '())))
(define-test revappend.4
(assert-equal '(b a c)
(revappend '(a b) '(c))))
(define-test revappend.5
(assert-equal '(b a . c)
(revappend '(a b) 'c)))
(define-test revappend.6
(assert-equal 'c
(revappend '() 'c)))
(define-test revappend.7
(let ((l '(x)))
(assert-equal l
(cdr (revappend '(a) l)))))
(define-test revappend.error.1
(assert-error 'type-error
(revappend 'a '())))
(define-test revappend.error.2
(assert-error 'type-error
(revappend '(a . b) '())))
(define-test revappend.error.3
(assert-error 'type-error
(revappend 1 '())))
(define-test revappend.error.4
(assert-error 'type-error
(revappend #(a b) '())))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nreconc function
(define-test nreconc.1
(assert-equal '()
(nreconc '() '())))
(define-test nreconc.2
(assert-equal '(a)
(nreconc (copy-list '(a)) '())))
(define-test nreconc.3
(assert-equal '(b a)
(nreconc (copy-list '(a b)) '())))
(define-test nreconc.4
(assert-equal '(b a c)
(nreconc (copy-list '(a b)) '(c))))
(define-test nreconc.5
(assert-equal '(b a . c)
(nreconc (copy-list '(a b)) 'c)))
(define-test nreconc.6
(assert-equal 'c
(nreconc '() 'c)))
(define-test nreconc.7
(let ((l '(x)))
(assert-equal l
(cdr (nreconc (copy-list '(a)) l)))))
(define-test nreconc.error.1
(assert-error 'type-error
(nreconc 'a '())))
(define-test nreconc.error.2
(assert-error 'type-error
(nreconc (copy-tree '(a . b)) '())))
(define-test nreconc.error.3
(assert-error 'type-error
(nreconc 1 '())))
(define-test nreconc.error.4
(assert-error 'type-error
(nreconc #(a b) '())))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the butlast function
(define-test butlast.1
(assert-equal '() (butlast '())))
(define-test butlast.2
(assert-equal '() (butlast '(0))))
(define-test butlast.3
(assert-equal '(0) (butlast '(0 1))))
(define-test butlast.4
(assert-equal '() (butlast '(0 . 1))))
(define-test butlast.5
(assert-equal '(0) (butlast '(0 1 . 2))))
(define-test butlast.6
(assert-equal '() (butlast '() 0)))
(define-test butlast.7
(assert-equal '() (butlast '() 1)))
(define-test butlast.8
(assert-equal '() (butlast '() 2)))
(define-test butlast.9
(assert-equal '(0) (butlast '(0) 0)))
(define-test butlast.10
(assert-equal '(0 1) (butlast '(0 1) 0)))
(define-test butlast.11
(assert-equal '(0) (butlast '(0 . 1) 0)))
(define-test butlast.12
(assert-equal '(0) (butlast '(0 1 2) 2)))
(define-test butlast.13
(assert-equal '() (butlast '(0 1 2) 3)))
(define-test butlast.13
(assert-equal '() (butlast '(0 1 2) 4)))
(define-test butlast.error.1
(assert-error 'type-error
(butlast '(0 1 2) (if (twisted '(1 2 3)) -1 1))))
(define-test butlast.error.2
(assert-error 'type-error
(butlast '(0 1 2) (if (twisted '(1 2 3)) 'a 1))))
(define-test butlast.error.3
(assert-error 'type-error
(butlast '#1=(0 . #1#))))
(define-test butlast.error.4
(assert-error 'type-error
(butlast 1)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nbutlast function
(define-test |nbutlast n=1 1a|
(assert-equal '()
(nbutlast '())))
(define-test |nbutlast n=1 1b|
(assert-equal '()
(nbutlast '() 1)))
(define-test |nbutlast n=1 2a|
(let ((list (copy-list '(1))))
(assert-equal '()
(nbutlast list))))
(define-test |nbutlast n=1 2b|
(let ((list (copy-list '(1))))
(assert-equal '()
(nbutlast list 1))))
(define-test |nbutlast n=1 3a|
(let ((list (copy-list '(1 2))))
(assert-equal '(1)
(nbutlast list))
(assert-equal '(1)
list)))
(define-test |nbutlast n=1 3b|
(let ((list (copy-list '(1 2))))
(assert-equal '(1)
(nbutlast list 1))
(assert-equal '(1)
list)))
(define-test |nbutlast n=1 4a|
(let ((list (copy-list '(1 . 2))))
(assert-equal '()
(nbutlast list))))
(define-test |nbutlast n=1 4b|
(let ((list (copy-list '(1 . 2))))
(assert-equal '()
(nbutlast list 1))))
(define-test |nbutlast n=1 5a|
(let ((list (copy-list '(1 2 . 3))))
(assert-equal '(1)
(nbutlast list))
(assert-equal '(1)
list)))
(define-test |nbutlast n=1 5b|
(let ((list (copy-list '(1 2 . 3))))
(assert-equal '(1)
(nbutlast list 1))
(assert-equal '(1)
list)))
(define-test |nbutlast n=1 6a|
(let ((list (copy-list '(1 2 3 . 4))))
(assert-equal '(1 2)
(nbutlast list))
(assert-equal '(1 2)
list)))
(define-test |nbutlast n=1 6b|
(let ((list (copy-list '(1 2 3 . 4))))
(assert-equal '(1 2)
(nbutlast list 1))
(assert-equal '(1 2)
list)))
(define-test |nbutlast n=1 7a|
(let ((list (copy-list '(1 2 3 4))))
(assert-equal '(1 2 3)
(nbutlast list))
(assert-equal '(1 2 3)
list)))
(define-test |nbutlast n=1 7b|
(let ((list (copy-list '(1 2 3 4))))
(assert-equal '(1 2 3)
(nbutlast list 1))
(assert-equal '(1 2 3)
list)))
(define-test |nbutlast n=other 1|
(assert-equal '()
(nbutlast '() 2)))
(define-test |nbutlast n=other 2|
(let ((list (copy-list '(1))))
(assert-equal '()
(nbutlast list 2))))
(define-test |nbutlast n=other 3|
(let ((list (copy-list '(1 2))))
(assert-equal '()
(nbutlast list 2))))
(define-test |nbutlast n=other 4|
(let ((list (copy-list '(1 2 3))))
(assert-equal '(1)
(nbutlast list 2))
(assert-equal '(1)
list)))
(define-test |nbutlast n=other 5|
(let ((list (copy-list '(1 2 . 3))))
(assert-equal '()
(nbutlast list 2))))
(define-test |nbutlast n=other 6|
(let ((list (copy-list '(1 2 3 . 4))))
(assert-equal '(1)
(nbutlast list 2))
(assert-equal '(1)
list)))
(define-test |nbutlast error 1|
(assert-error 'type-error
(nbutlast 1)))
(define-test |nbutlast error 2|
(assert-error 'type-error
(nbutlast '() 'a)))
(define-test |nbutlast error 3|
(let ((list (copy-list '(0))))
(setf (cdr list) list)
(assert-error 'type-error
(nbutlast list 1))))
(define-test |nbutlast error 4|
(let ((list (copy-list '(0))))
(setf (cdr list) list)
(assert-error 'type-error
(nbutlast list 2))))
(define-test |nbutlast error 5|
(let ((list (copy-list '(0))))
(setf (cdr list) list)
(assert-error 'type-error
(nbutlast list 3))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the subst function
(define-test |subst test=eql key=identity 1a|
(assert-equal '()
(subst 'a 0 '())))
(define-test |subst test=eql key=identity 1b|
(assert-equal '()
(subst 'a 0 '() :test #'eql)))
(define-test |subst test=eql key=identity 1c|
(assert-equal '()
(subst 'a 0 '() :test 'eql)))
(define-test |subst test=eql key=identity 2a|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 0 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0))))))
(define-test |subst test=eql key=identity 2b|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 0 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test #'eql)))
(define-test |subst test=eql key=identity 2c|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 0 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test 'eql)))
(define-test |subst test=eql key=nil 1|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a
0
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key nil)))
(define-test |subst test=eq key=identity 1|
(assert-equal '()
(subst 'a 'b '()
:test #'eq)))
(define-test |subst test=eq key=identity 2|
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(subst 'a 'b '(((b . c) . (f . b)) . ((b . d) . (e . b)))
:test #'eq)))
(define-test |subst test=other key=identity 1|
(assert-equal '()
(subst 'a 0 '()
:test (lambda (x y) (and (numberp y) (= x (1- y)))))))
(define-test |subst test=other key=identity 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 0 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test (lambda (x y) (and (numberp y) (= x y))))))
(define-test |subst test=eql key=other 1a|
(assert-equal '()
(subst 'a 0 '()
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst test=eql key=other 1b|
(assert-equal '()
(subst 'a 0 '()
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql)))
(define-test |subst test=eql key=other 1c|
(assert-equal '()
(subst 'a 0 '()
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(define-test |subst test=eql key=other 2a|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 1 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst test=eql key=other 2b|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 1 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql)))
(define-test |subst test=eql key=other 2c|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 1 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(define-test |subst test=eq key=other 1|
(assert-equal '()
(subst 'a 'bb '()
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(define-test |subst test=eq key=other 2|
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(subst 'a 'bb '(((b . c) . (f . b)) . ((b . d) . (e . b)))
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(define-test |subst test=other key=other 1|
(assert-equal '()
(subst 'a 0 '()
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst test=other key=other 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 0 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst test-not=any key=other 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 0 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y)))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst test=other test-not=other|
(assert-error 'error
(subst 0 1 2 :test #'= :test-not #'=)))
;;; old one left over. Is it still needed?
(define-test subst.1
(assert-equal '(a (c))
(subst 'c '(b) '(a ((b))) :test-not (complement #'equal))))
(define-test |subst test=nil key=identity 1|
(assert-error 'error
(subst 'a
0
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test nil)))
(define-test |subst test-not=nil key=identity 1|
(assert-error 'error
(subst 'a
0
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the subst-if function
(define-test |subst-if key=identity 1|
(assert-equal '()
(subst-if 'a
(lambda (y) (and (numberp y) (zerop (1- y))))
'())))
(define-test |subst-if key=identity 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst-if 'a
(lambda (y) (and (numberp y) (zerop y)))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0))))))
(define-test |subst-if key=other 1|
(assert-equal '()
(subst-if 'a
(lambda (y) (and (numberp y) (zerop (1- y))))
'()
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst-if key=other 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst-if 'a
(lambda (y) (and (numberp y) (zerop (1- y))))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the subst-if-not function
(define-test |subst-if-not key=identity 1|
(assert-equal '()
(subst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop (1- y)))))
'())))
(define-test |subst-if-not key=identity 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop y))))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0))))))
(define-test |subst-if-not key=other 1|
(assert-equal '()
(subst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop (1- y)))))
'()
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst-if-not key=other 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop (1- y)))))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nsubst function
(define-test |nsubst test=eql key=identity 1a|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree))))
(define-test |nsubst test=eql key=identity 1b|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree :test #'eql))))
(define-test |nsubst test=eql key=identity 1c|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree :test 'eql))))
(define-test |nsubst test=eql key=identity 2a|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree)))
(assert-eq tree tree2)))
(define-test |nsubst test=eql key=identity 2b|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree :test #'eql)))
(assert-eq tree tree2)))
(define-test |nsubst test=eql key=identity 2c|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree :test 'eql)))
(assert-eq tree tree2)))
(define-test |nsubst test=eql key=identity 3a|
(assert-equal 2
(nsubst 2 1 1)))
(define-test |nsubst test=eql key=identity 3b|
(assert-equal 2
(nsubst 2 1 1 :test #'eql)))
(define-test |nsubst test=eql key=identity 3c|
(assert-equal 2
(nsubst 2 1 1 :test 'eql)))
(define-test |nsubst test=eql key=nil 1|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree :key nil)))
(assert-eq tree tree2)))
(define-test |nsubst test=eq key=identity 1a|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 'b tree :test #'eq))))
(define-test |nsubst test=eq key=identity 1b|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 'b tree :test 'eq))))
(define-test |nsubst test=eq key=identity 2a|
(let ((tree (copy-tree '(((b . c) . (f . b)) . ((b . d) . (e . b)))))
(tree2))
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(setf tree2 (nsubst 'a 'b tree :test #'eq)))
(assert-eq tree tree2)))
(define-test |nsubst test=eq key=identity 2a|
(let ((tree (copy-tree '(((b . c) . (f . b)) . ((b . d) . (e . b)))))
(tree2))
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(setf tree2 (nsubst 'a 'b tree :test 'eq)))
(assert-eq tree tree2)))
(define-test |nsubst test=eq key=identity 3a|
(assert-equal 'b
(nsubst 'b 'a 'a :test #'eq)))
(define-test |nsubst test=eq key=identity 3b|
(assert-equal 'b
(nsubst 'b 'a 'a :test 'eq)))
(define-test |nsubst test=other key=identity 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree
:test (lambda (x y) (and (numberp y) (= x (1- y))))))))
(define-test |nsubst test=other key=identity 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree
:test (lambda (x y) (and (numberp y) (= x y))))))
(assert-eq tree tree2)))
(define-test |nsubst test=other key=identity 3|
(assert-equal 2
(nsubst 2 1 0 :test (lambda (x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))))
(define-test |nsubst test=eql key=other 1a|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree
:key (lambda (x) (if (numberp x) (1+ x) x))))))
(define-test |nsubst test=eql key=other 1b|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql))))
(define-test |nsubst test=eql key=other 1c|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql))))
(define-test |nsubst test=eql key=other 2a|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 1 tree
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsubst test=eql key=other 2b|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 1 tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql)))
(assert-eq tree tree2)))
(define-test |nsubst test=eql key=other 2c|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 1 tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(assert-eq tree tree2)))
(define-test |nsubst test=eql key=other 3a|
(assert-equal 2
(nsubst 2 1 0 :key #'1+)))
(define-test |nsubst test=eql key=other 3b|
(assert-equal 2
(nsubst 2 1 0 :key #'1+ :test #'eql)))
(define-test |nsubst test=eql key=other 3c|
(assert-equal 2
(nsubst 2 1 0 :key #'1+ :test 'eql)))
(define-test |nsubst test=eq key=other 1a|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 'bb tree
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x))))))
(define-test |nsubst test=eq key=other 1b|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 'bb tree
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x))))))
(define-test |nsubst test=eq key=other 2a|
(let ((tree (copy-tree '(((b . c) . (f . b)) . ((b . d) . (e . b)))))
(tree2))
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(setf tree2 (nsubst 'a 'bb tree
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(assert-eq tree tree2)))
(define-test |nsubst test=eq key=other 2b|
(let ((tree (copy-tree '(((b . c) . (f . b)) . ((b . d) . (e . b)))))
(tree2))
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(setf tree2 (nsubst 'a 'bb tree
:test 'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(assert-eq tree tree2)))
(define-test |nsubst test=eq key=other 3a|
(assert-equal 'b
(nsubst 'b 'a 'c
:test #'eq
:key (lambda (x) (if (eq x 'c) 'a x)))))
(define-test |nsubst test=eq key=other 3b|
(assert-equal 'b
(nsubst 'b 'a 'c
:test 'eq
:key (lambda (x) (if (eq x 'c) 'a x)))))
(define-test |nsubst test=other key=other 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x))))))
(define-test |nsubst test=other key=other 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsubst test=other key=other 3|
(assert-equal 2
(nsubst 2 1 -1
:test (lambda (x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1)))
:key #'1+)))
(define-test |nsubst test-not=other key=identity 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree
:test-not (lambda (x y)
(not (and (numberp y) (= x (1- y)))))))))
(define-test |nsubst test-not=other key=identity 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree
:test-not (lambda (x y)
(not (and (numberp y) (= x y)))))))
(assert-eq tree tree2)))
(define-test |nsubst test-not=other key=identity 3|
(assert-equal 2
(nsubst 2 1 0
:test-not (lambda (x y)
(not (and (numberp x)
(numberp y)
(<= (abs (- x y)) 1)))))))
(define-test |nsubst test-not=any key=other 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y)))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsubst test-not=other key=other 3|
(assert-equal 2
(nsubst 2 1 -1
:test-not (lambda (x y)
(not (and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))
:key #'1+)))
(define-test |nsubst test-not=other key=other 4|
(assert-equal -1
(nsubst 2 1 -1
:test-not (lambda (x y)
(not (and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))
:key #'1-)))
(define-test |nsubst test=other test-not=other|
(assert-error 'error
(nsubst 0 1 2 :test #'= :test-not #'=)))
(define-test |nsubst test=nil key=identity 1|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-error 'error
(setf tree2 (nsubst 'a 0 tree :test nil)))))
(define-test |nsubst test-not=nil key=identity 1|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-error 'error
(setf tree2 (nsubst 'a 0 tree :test-not nil)))))
;;; old one left over. Is it still needed?
(define-test nsubst.1
(let ((tree (copy-tree '(a ((b))))))
(assert-equal '(a (c))
(nsubst 'c '(b) tree :test-not (complement #'equal)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nsubst-if function
(define-test |nsubst-if key=identity 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst-if 'a
(lambda (y) (and (numberp y) (zerop (1- y))))
tree))))
(define-test |nsubst-if key=identity 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst-if 'a
(lambda (y) (and (numberp y) (zerop y)))
tree)))
(assert-eq tree tree2)))
(define-test |nsubst-if key=identity 3|
(assert-equal 2
(nsubst-if 2 #'zerop 0)))
(define-test |nsubst-if key=identity 4|
(assert-equal 1
(nsubst-if 2 #'zerop 1)))
(define-test |nsubst-if key=other 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst-if 'a
(lambda (y) (and (numberp y) (zerop (1- y))))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))))))
(define-test |nsubst-if key=other 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst-if 'a
(lambda (y) (and (numberp y) (zerop (1- y))))
tree
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsubst-if key=other 3|
(assert-equal 2
(nsubst-if 2 #'zerop 1 :key #'1-)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nsubst-if-not function
(define-test |nsubst-if-not key=identity 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop (1- y)))))
tree))))
(define-test |nsubst-if-not key=identity 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop y))))
tree)))
(assert-eq tree tree2)))
(define-test |nsubst-if-not key=identity 3|
(assert-equal 2
(nsubst-if-not 2 #'zerop 1)))
(define-test |nsubst-if-not key=other 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop (1- y)))))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))))))
(define-test |nsubst-if-not key=other 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop (1- y)))))
tree
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsubst-if-not key=other 3|
(assert-equal 2
(nsubst-if-not 2 #'zerop 0 :key #'1+)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the null function
(define-test null.1
(assert-equal t
(null '())))
(define-test null.2
(assert-equal nil
(null 1)))
(define-test null.3
(assert-equal nil
(null #\a)))
(define-test null.4
(assert-equal nil
(null #())))
(define-test null.5
(assert-equal nil
(null "")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the acons function
(define-test acons.1
(assert-equal '((a . b))
(acons 'a 'b '())))
(define-test acons.2
(assert-equal '((a . b) c)
(acons 'a 'b '(c))))
(define-test acons.3
(assert-equal '((a . b) . c)
(acons 'a 'b 'c)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the member function
(define-test |member test=eql key=identity 1|
(assert-equal nil
(member 234 '())))
(define-test |member test=eql key=identity 2a|
(assert-equal '(123 b c)
(member 123 '(a b 123 b c))))
(define-test |member test=eql key=identity 2b|
(assert-equal '(123 b c)
(member 123 '(a b 123 b c) :test #'eql)))
(define-test |member test=eql key=identity 2c|
(assert-equal '(123 b c)
(member 123 '(a b 123 b c) :test 'eql)))
(define-test |member test=eql key=identity 3|
(assert-equal nil
(member 123 '(a b c d e))))
(define-test |member test=eql key=other 1|
(assert-equal '(123 b c)
(member 124 '(a b 123 b c)
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |member test=eql key=other 2|
(assert-equal '(123 b c)
(member 124 '(a b 123 b c)
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(define-test |member test=eql key=nil 1|
(assert-equal '(123 b c)
(member 123 '(a b 123 b c) :key nil)))
(define-test |member test=eq key=identity 1|
(assert-equal '(d e)
(member 'd '(a b c d e)
:test #'eq)))
(define-test |member test=eq key=identity 2|
(assert-equal nil
(member 'f '(a b c d e)
:test #'eq)))
(define-test |member test=eq key=other 1|
(assert-equal '((d) (e))
(member 'd '((a) (b) (c) (d) (e))
:key #'car
:test #'eq)))
(define-test |member test=eq key=other 2|
(assert-equal nil
(member 'f '((a) (b) (c) (d) (e))
:key #'car
:test #'eq)))
(define-test |member test-not=eql key=identity 1|
(assert-equal '(3 4 5 2)
(member 2 '(2 2 2 3 4 5 2)
:test-not #'eql)))
(define-test |member test-not=eql key=identity 2|
(assert-equal nil
(member 2 '(2 2 2)
:test-not #'eql)))
(define-test |member test-not=eql key=other 1|
(assert-equal '(3 4 5 2)
(member 3 '(2 2 2 3 4 5 2)
:key #'1+
:test-not #'eql)))
(define-test |member test-not=eql key=other 2|
(assert-equal nil
(member 3 '(2 2 2)
:key #'1+
:test-not #'eql)))
(define-test |member test-not=eq key=identity 1|
(assert-equal '(3 4 5 a)
(member 'a '(a a a 3 4 5 a)
:test-not #'eq)))
(define-test |member test-not=eq key=identity 2|
(assert-equal nil
(member 'a '(a a a)
:test-not #'eq)))
(define-test |member test-not=eq key=other 1|
(assert-equal '((3) 4 5 a)
(member 'a '((a) (a) (a) (3) 4 5 a)
:key #'car
:test-not #'eq)))
(define-test |member test-not=eq key=other 2|
(assert-equal nil
(member 'a '((a) (a) (a))
:key #'car
:test-not #'eq)))
(define-test |member test=other key=identity 1|
(assert-equal '((123) b c)
(member '(123) '(a b (123) b c)
:test #'equal)))
(define-test |member test=other key=other 1|
(assert-equal '(3 4 5)
(member 5 '(1 2 3 4 5)
:key #'1+
:test (lambda (x y) (= x (1+ y))))))
(define-test |member test=other key=other 2|
(assert-equal nil
(member 10 '(1 2 3 4 5)
:key #'1+
:test (lambda (x y) (= x (1+ y))))))
(define-test |member test-not=other key=other 1|
(assert-equal '(3 4 5)
(member 4 '(1 2 3 4 5)
:key #'1+
:test-not (lambda (x y) (not (zerop (mod y x)))))))
(define-test |member test-not=other key=other 2|
(assert-equal nil
(member 10 '(1 2 3 4 5)
:key #'1+
:test-not (lambda (x y) (not (zerop (mod y x)))))))
(define-test |member error 1|
(assert-error 'type-error
(member 123 '(a b . 123))))
(define-test |member error 2|
(assert-error 'error
(member 123 '(1 2 3)
:test #'eql
:test-not #'eq)))
(define-test |member test=nil key=identity 1|
(assert-error 'error
(member 123 '(a b 123 b c) :test nil)))
(define-test |member test-not=nil key=identity 1|
(assert-error 'error
(member 123 '(a b 123 b c) :test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the member-if function
(define-test |member-if key=identity 1|
(assert-equal nil
(member-if #'oddp '(2 4 6))))
(define-test |member-if key=identity 2|
(assert-equal '(3 4)
(member-if #'oddp '(2 6 3 4))))
(define-test |member-if key=other 1|
(assert-equal '(3 4)
(member-if #'evenp '(2 6 3 4)
:key #'1+)))
(define-test |member-if key=other 2|
(assert-equal nil
(member-if #'evenp '(2 6 4)
:key #'1+)))
(define-test |member-if error 1|
(assert-error 'type-error
(member-if #'oddp '(2 4 6 . 7))))
(define-test |member-if key=other error 1|
(assert-error 'type-error
(member-if #'oddp '(2 4 6 . 7) :key #'identity)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the member-if-not function
(define-test |member-if-not key=identity 1|
(assert-equal nil
(member-if-not #'evenp '(2 4 6))))
(define-test |member-if-not key=identity 2|
(assert-equal '(3 4)
(member-if-not #'evenp '(2 6 3 4))))
(define-test |member-if-not key=other 1|
(assert-equal nil
(member-if-not #'oddp '(2 4 6)
:key #'1+)))
(define-test |member-if-not key=other 2|
(assert-equal '(3 4)
(member-if-not #'oddp '(2 6 3 4)
:key #'1+)))
(define-test |member-if-not error 1|
(assert-error 'type-error
(member-if-not #'evenp '(2 4 6 . 7))))
(define-test |member-if-not key=other error 1|
(assert-error 'type-error
(member-if-not #'evenp '(2 4 6 . 7) :key #'identity)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the assoc function
(define-test |assoc test=eql key=identity 1a|
(assert-equal '(a . b)
(assoc 'a '((b) nil (a . b) (a . c)))))
(define-test |assoc test=eql key=identity 1b|
(assert-equal '(a . b)
(assoc 'a '((b) nil (a . b) (a . c))
:test #'eql)))
(define-test |assoc test=eql key=identity 1c|
(assert-equal '(a . b)
(assoc 'a '((b) nil (a . b) (a . c))
:test 'eql)))
(define-test |assoc test=eql key=identity 2a|
(assert-equal nil
(assoc 'c '((b) nil (a . b) (a . c)))))
(define-test |assoc test=eql key=identity 2b|
(assert-equal nil
(assoc 'c '((b) nil (a . b) (a . c))
:test #'eql)))
(define-test |assoc test=eql key=identity 2c|
(assert-equal nil
(assoc 'c '((b) nil (a . b) (a . c))
:test 'eql)))
(define-test |assoc test=eql key=identity 3a|
(assert-equal '(nil . c)
(assoc 'nil '((b) nil (a . b) (nil . c)))))
(define-test |assoc test=eql key=identity 3b|
(assert-equal '(nil . c)
(assoc 'nil '((b) nil (a . b) (nil . c))
:test #'eql)))
(define-test |assoc test=eql key=identity 3c|
(assert-equal '(nil . c)
(assoc 'nil '((b) nil (a . b) (nil . c))
:test 'eql)))
(define-test |assoc test=eql key=identity 4a|
(assert-equal '(123 . b)
(assoc 123 '((b) nil (123 . b) (nil . c)))))
(define-test |assoc test=eql key=identity 4b|
(assert-equal '(123 . b)
(assoc 123 '((b) nil (123 . b) (nil . c))
:test #'eql)))
(define-test |assoc test=eql key=identity 4c|
(assert-equal '(123 . b)
(assoc 123 '((b) nil (123 . b) (nil . c))
:test 'eql)))
(define-test |assoc test=eql key=identity 5a|
(assert-equal '(#\a . b)
(assoc #\a '((b) nil (#\a . b) (nil . c)))))
(define-test |assoc test=eql key=identity 5b|
(assert-equal '(#\a . b)
(assoc #\a '((b) nil (#\a . b) (nil . c))
:test #'eql)))
(define-test |assoc test=eql key=identity 5c|
(assert-equal '(#\a . b)
(assoc #\a '((b) nil (#\a . b) (nil . c))
:test 'eql)))
(define-test |assoc test=eql key=nil 1|
(assert-equal '(nil . c)
(assoc 'nil '((b) nil (a . b) (nil . c))
:key nil)))
(define-test |assoc test=eq key=identity 1a|
(assert-equal '(a . b)
(assoc 'a '((b) nil (a . b) (a . c))
:test #'eq)))
(define-test |assoc test=eq key=identity 1b|
(assert-equal '(a . b)
(assoc 'a '((b) nil (a . b) (a . c))
:test 'eq)))
(define-test |assoc test=eq key=identity 2a|
(assert-equal nil
(assoc 'c '((b) nil (a . b) (a . c))
:test #'eq)))
(define-test |assoc test=eq key=identity 2b|
(assert-equal nil
(assoc 'c '((b) nil (a . b) (a . c))
:test 'eq)))
(define-test |assoc test=eq key=identity 3a|
(assert-equal '(nil . c)
(assoc 'nil '((b) nil (a . b) (nil . c))
:test #'eq)))
(define-test |assoc test=eq key=identity 3b|
(assert-equal '(nil . c)
(assoc 'nil '((b) nil (a . b) (nil . c))
:test 'eq)))
(define-test |assoc test=other key=identity 1|
(assert-equal '((a b) c)
(assoc '(a b) '((a . b) nil ((a b) c) (d e))
:test #'equal)))
(define-test |assoc test-not=other key=identity 1|
(assert-equal '((a b) c)
(assoc '(a b) '((a . b) nil ((a b) c) (d e))
:test-not (complement #'equal))))
(define-test |assoc test=eql key=other 1a|
(assert-equal '((a b) c)
(assoc 'a '(((b a) . b) nil ((a b) c) ((d) e))
:key #'car)))
(define-test |assoc test=eql key=other 1b|
(assert-equal '((a b) c)
(assoc 'a '(((b a) . b) nil ((a b) c) ((d) e))
:test #'eql
:key #'car)))
(define-test |assoc test=eql key=other 1c|
(assert-equal '((a b) c)
(assoc 'a '(((b a) . b) nil ((a b) c) ((d) e))
:test 'eql
:key #'car)))
(define-test |assoc test=eq key=other 1|
(assert-equal '((a b) c)
(assoc 'a '(((b a) . b) nil ((a b) c) ((d) e))
:test #'eq
:key #'car)))
(define-test |assoc test=other key=other 1|
(assert-equal '((a b) c)
(assoc 'a '(((b a) . b) nil ((a b) c) ((d) e))
:test (lambda (x y) (eq x y))
:key #'car)))
(define-test |assoc test-not=eql key=identity 1a|
(assert-equal '(345 b)
(assoc '234 '((234 a) (345 b) (234 c))
:test-not #'eql)))
(define-test |assoc test-not=eql key=identity 1b|
(assert-equal '(345 b)
(assoc '234 '((234 a) (345 b) (234 c))
:test-not 'eql)))
(define-test |assoc test-not=eql key=identity 2|
(assert-equal nil
(assoc '234 '((234 a) (234 b) (234 c))
:test-not #'eql)))
(define-test |assoc test-not=eql key=identity 3|
(assert-equal '(345 b)
(assoc '234 '((234 a) nil (345 b) (234 c))
:test-not #'eql)))
(define-test |assoc test-not=eq key=identity 1a|
(assert-equal '(y b)
(assoc 'x '((x a) (y b) (x c))
:test-not #'eq)))
(define-test |assoc test-not=eq key=identity 1b|
(assert-equal '(y b)
(assoc 'x '((x a) (y b) (x c))
:test-not 'eq)))
(define-test |assoc test-not=eq key=identity 2|
(assert-equal nil
(assoc 'x '((x a) (x b) (x c))
:test-not #'eq)))
(define-test |assoc test-not=eq key=identity 3|
(assert-equal '(y b)
(assoc 'x '((x a) nil (y b) (x c))
:test-not #'eq)))
(define-test assoc.error.1
(assert-error 'type-error
(assoc 'a '((b . c) nil d (a b)))))
(define-test |assoc test-not=eql key=other 1a|
(assert-equal '(345 b)
(assoc '235 '((234 a) (345 b) (234 c))
:test-not #'eql
:key #'1+)))
(define-test |assoc test-not=eql key=other 1b|
(assert-equal '(345 b)
(assoc '235 '((234 a) (345 b) (234 c))
:test-not 'eql
:key #'1+)))
(define-test |assoc test-not=eql key=other 2|
(assert-equal nil
(assoc '235 '((234 a) (234 b) (234 c))
:test-not #'eql
:key #'1+)))
(define-test |assoc test-not=eql key=other 3|
(assert-equal '(345 b)
(assoc '235 '((234 a) nil (345 b) (234 c))
:test-not #'eql
:key #'1+)))
(define-test |assoc test-not=eq key=other 1a|
(assert-equal '((y) b)
(assoc 'x '(((x) a) ((y) b) ((x) c))
:test-not #'eq
:key #'car)))
(define-test |assoc test-not=eq key=other 1b|
(assert-equal '((y) b)
(assoc 'x '(((x) a) ((y) b) ((x) c))
:test-not 'eq
:key #'car)))
(define-test |assoc test-not=eq key=other 2|
(assert-equal nil
(assoc 'x '(((x) a) ((x) b) ((x) c))
:test-not #'eq
:key #'car)))
(define-test |assoc test-not=eq key=other 3|
(assert-equal '((y) b)
(assoc 'x '(((x) a) nil ((y) b) ((x) c))
:test-not #'eq
:key #'car)))
(define-test |assoc test-not=other key=other 1a|
(assert-equal '(345 b)
(assoc '234 '((234 a) (345 b) (234 c))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |assoc test-not=other key=other 1b|
(assert-equal '(345 b)
(assoc '234 '((234 a) (345 b) (234 c))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |assoc test-not=other key=other 2|
(assert-equal nil
(assoc '234 '((234 a) (234 b) (234 c))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |assoc test-not=other key=other 3|
(assert-equal '(345 b)
(assoc '234 '((234 a) nil (345 b) (234 c))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |assoc error 1|
(assert-error 'type-error
(assoc 'a '((b . c) nil d (a b)))))
(define-test |assoc error 2|
(assert-error 'error
(assoc 'a '((b . c) nil d (a b))
:test #'eq
:test-not #'eq)))
(define-test |assoc test=nil key=identity 1|
(assert-error 'error
(assoc 'nil '((b) nil (a . b) (nil . c))
:test nil)))
(define-test |assoc test-not=nil key=identity 1|
(assert-error 'error
(assoc 'nil '((b) nil (a . b) (nil . c))
:test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the assoc-if function
(define-test |assoc-if key=identity 1|
(assert-equal '(a . b)
(assoc-if (lambda (x) (eq x 'a))
'((b) nil (a . b) (a . c)))))
(define-test |assoc-if key=identity 2|
(assert-equal nil
(assoc-if (lambda (x) (eq x 'c))
'((b) nil (a . b) (a . c)))))
(define-test |assoc-if key=identity 3|
(assert-equal '(nil . c)
(assoc-if #'null
'((b) nil (a . b) (nil . c)))))
(define-test |assoc-if key=identity 4|
(assert-equal '(123 . b)
(assoc-if (lambda (x) (eql x 123))
'((b) nil (123 . b) (nil . c)))))
(define-test |assoc-if key=identity 5|
(assert-equal '(#\a . b)
(assoc-if (lambda (x) (eql x #\a))
'((b) nil (#\a . b) (nil . c)))))
(define-test |assoc-if key=other 1|
(assert-equal '((a b) c)
(assoc-if (lambda (x) (eq x 'a))
'(((b a) . b) nil ((a b) c) ((d) e))
:key #'car)))
(define-test |assoc-if error 1|
(assert-error 'type-error
(assoc-if (lambda (x) (eq x 'a))
'((b . c) nil d (a b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the assoc-if-not function
(define-test |assoc-if-not key=identity 1|
(assert-equal '(a . b)
(assoc-if-not (complement (lambda (x) (eq x 'a)))
'((b) nil (a . b) (a . c)))))
(define-test |assoc-if-not key=identity 2|
(assert-equal nil
(assoc-if-not (complement (lambda (x) (eq x 'c)))
'((b) nil (a . b) (a . c)))))
(define-test |assoc-if-not key=identity 3|
(assert-equal '(nil . c)
(assoc-if-not (complement #'null)
'((b) nil (a . b) (nil . c)))))
(define-test |assoc-if-not key=identity 4|
(assert-equal '(123 . b)
(assoc-if-not (complement (lambda (x) (eql x 123)))
'((b) nil (123 . b) (nil . c)))))
(define-test |assoc-if-not key=identity 5|
(assert-equal '(#\a . b)
(assoc-if-not (complement (lambda (x) (eql x #\a)))
'((b) nil (#\a . b) (nil . c)))))
(define-test |assoc-if-not key=other 6|
(assert-equal '((a b) c)
(assoc-if-not (complement (lambda (x) (eq x 'a)))
'(((b a) . b) nil ((a b) c) ((d) e))
:key #'car)))
(define-test |assoc-if-not error 1|
(assert-error 'type-error
(assoc-if-not (complement (lambda (x) (eq x 'a)))
'((b . c) nil d (a b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the rassoc function
(define-test |rassoc test=eql key=identity 1a|
(assert-equal '(b . a)
(rassoc 'a '((b) nil (b . a) (c . a)))))
(define-test |rassoc test=eql key=identity 1b|
(assert-equal '(b . a)
(rassoc 'a '((b) nil (b . a) (c . a))
:test #'eql)))
(define-test |rassoc test=eql key=identity 1c|
(assert-equal '(b . a)
(rassoc 'a '((b) nil (b . a) (c . a))
:test 'eql)))
(define-test |rassoc test=eql key=identity 2a|
(assert-equal nil
(rassoc 'c '((b) nil (b . a) (c . a)))))
(define-test |rassoc test=eql key=identity 2b|
(assert-equal nil
(rassoc 'c '((b) nil (b . a) (c . a))
:test #'eql)))
(define-test |rassoc test=eql key=identity 2c|
(assert-equal nil
(rassoc 'c '((b) nil (b . a) (c . a))
:test 'eql)))
(define-test |rassoc test=eql key=identity 3a|
(assert-equal '(c . nil)
(rassoc 'nil '((b . x) nil (b . a) (c . nil)))))
(define-test |rassoc test=eql key=identity 3b|
(assert-equal '(c . nil)
(rassoc 'nil '((x . b) nil (b . a) (c . nil))
:test #'eql)))
(define-test |rassoc test=eql key=identity 3c|
(assert-equal '(c . nil)
(rassoc 'nil '((b . x) nil (b . a) (c . nil))
:test 'eql)))
(define-test |rassoc test=eql key=identity 4a|
(assert-equal '(b . 123)
(rassoc 123 '((b . x) nil (b . 123) (c . nil)))))
(define-test |rassoc test=eql key=identity 4b|
(assert-equal '(b . 123)
(rassoc 123 '((b . x) nil (b . 123) (c . nil))
:test #'eql)))
(define-test |rassoc test=eql key=identity 4c|
(assert-equal '(b . 123)
(rassoc 123 '((b . x) nil (b . 123) (c . nil))
:test 'eql)))
(define-test |rassoc test=eql key=identity 5a|
(assert-equal '(b . #\a)
(rassoc #\a '((b . x) nil (b . #\a) (c . nil)))))
(define-test |rassoc test=eql key=identity 5b|
(assert-equal '(b . #\a)
(rassoc #\a '((b . x) nil (b . #\a) (c . nil))
:test #'eql)))
(define-test |rassoc test=eql key=identity 5c|
(assert-equal '(b . #\a)
(rassoc #\a '((b . x) nil (b . #\a) (c . nil))
:test 'eql)))
(define-test |rassoc test=eql key=nil 1|
(assert-equal '(b . 123)
(rassoc 123 '((b . x) nil (b . 123) (c . nil))
:key nil)))
(define-test |rassoc test=eq key=identity 1a|
(assert-equal '(b . a)
(rassoc 'a '((b . x) nil (b . a) (c . a))
:test #'eq)))
(define-test |rassoc test=eq key=identity 1b|
(assert-equal '(b . a)
(rassoc 'a '((b . x) nil (b . a) (c . a))
:test 'eq)))
(define-test |rassoc test=eq key=identity 2a|
(assert-equal nil
(rassoc 'c '((b . x) nil (b . a) (c . a))
:test #'eq)))
(define-test |rassoc test=eq key=identity 2b|
(assert-equal nil
(rassoc 'c '((b . x) nil (b . a) (c . a))
:test 'eq)))
(define-test |rassoc test=eq key=identity 3a|
(assert-equal '(c . nil)
(rassoc 'nil '((b . x) nil (b . a) (c . nil))
:test #'eq)))
(define-test |rassoc test=eq key=identity 3b|
(assert-equal '(c . nil)
(rassoc 'nil '((b . x) nil (b . a) (c . nil))
:test 'eq)))
(define-test |rassoc test=other key=identity 1|
(assert-equal '(c . (a b))
(rassoc '(a b) '((b . a) nil (c . (a b)) (e . d))
:test #'equal)))
(define-test |rassoc test-not=other key=identity 1|
(assert-equal '(c . (a b))
(rassoc '(a b) '((b . a) nil (c . (a b)) (e . d))
:test-not (complement #'equal))))
(define-test |rassoc test=eql key=other 1a|
(assert-equal '(c . (a b))
(rassoc 'a '((b . (b a)) nil (c . (a b)) (e . (d)))
:key #'car)))
(define-test |rassoc test=eql key=other 1b|
(assert-equal '(c . (a b))
(rassoc 'a '((b . (b a)) nil (c . (a b)) (e . (d)))
:test #'eql
:key #'car)))
(define-test |rassoc test=eql key=other 1c|
(assert-equal '(c . (a b))
(rassoc 'a '((b . (b a)) nil (c . (a b)) (e . (d)))
:test 'eql
:key #'car)))
(define-test |rassoc test=eq key=other 1|
(assert-equal '(c . (a b))
(rassoc 'a '((b . (b a)) nil (c . (a b)) (e . (d)))
:test #'eq
:key #'car)))
(define-test |rassoc test=other key=other 1|
(assert-equal '(c . (a b))
(rassoc 'a '((b . (b a)) nil (c . (a b)) (e . (d)))
:test (lambda (x y) (eq x y))
:key #'car)))
(define-test |rassoc test-not=eql key=identity 1a|
(assert-equal '(b . 345)
(rassoc '234 '((a . 234) (b . 345) (c . 234))
:test-not #'eql)))
(define-test |rassoc test-not=eql key=identity 1b|
(assert-equal '(b . 345)
(rassoc '234 '((a . 234) (b . 345) (c . 234))
:test-not 'eql)))
(define-test |rassoc test-not=eql key=identity 2|
(assert-equal nil
(rassoc '234 '((a . 234) (b . 234) (c . 234))
:test-not #'eql)))
(define-test |rassoc test-not=eql key=identity 3|
(assert-equal '(b . 345)
(rassoc '234 '((a . 234) nil (b . 345) (c . 234))
:test-not #'eql)))
(define-test |rassoc test-not=eq key=identity 1a|
(assert-equal '(b . y)
(rassoc 'x '((a . x) (b . y) (c . x))
:test-not #'eq)))
(define-test |rassoc test-not=eq key=identity 1b|
(assert-equal '(b . y)
(rassoc 'x '((a . x) (b . y) (c . x))
:test-not 'eq)))
(define-test |rassoc test-not=eq key=identity 2|
(assert-equal nil
(rassoc 'x '((a . x) (b . x) (c . x))
:test-not #'eq)))
(define-test |rassoc test-not=eq key=identity 3|
(assert-equal '(b . y)
(rassoc 'x '((a . x) nil (b . y) (c . x))
:test-not #'eq)))
(define-test rassoc.error.1
(assert-error 'type-error
(rassoc 'a '((b . c) nil d (a b)))))
(define-test |rassoc test-not=eql key=other 1a|
(assert-equal '(b . 345)
(rassoc '235 '((a . 234) (b . 345) (c . 234))
:test-not #'eql
:key #'1+)))
(define-test |rassoc test-not=eql key=other 1b|
(assert-equal '(b . 345)
(rassoc '235 '((a . 234) (b . 345) (c . 234))
:test-not 'eql
:key #'1+)))
(define-test |rassoc test-not=eql key=other 2|
(assert-equal nil
(rassoc '235 '((a . 234) (b . 234) (c . 234))
:test-not #'eql
:key #'1+)))
(define-test |rassoc test-not=eql key=other 3|
(assert-equal '(b . 345)
(rassoc '235 '((a . 234) nil (b . 345) (c . 234))
:test-not #'eql
:key #'1+)))
(define-test |rassoc test-not=eq key=other 1a|
(assert-equal '(b . (y))
(rassoc 'x '((a . (x)) (b . (y)) (c . (x)))
:test-not #'eq
:key #'car)))
(define-test |rassoc test-not=eq key=other 1b|
(assert-equal '(b . (y))
(rassoc 'x '((a . (x)) (b . (y)) (c . (x)))
:test-not 'eq
:key #'car)))
(define-test |rassoc test-not=eq key=other 2|
(assert-equal nil
(rassoc 'x '((a . (x)) (b . (x)) (c . (x)))
:test-not #'eq
:key #'car)))
(define-test |rassoc test-not=eq key=other 3|
(assert-equal '(b . (y))
(rassoc 'x '((a . (x)) nil (b . (y)) (c . (x)))
:test-not #'eq
:key #'car)))
(define-test |rassoc test-not=other key=other 1a|
(assert-equal '(b . 345)
(rassoc '234 '((a . 234) (b . 345) (c . 234))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |rassoc test-not=other key=other 1b|
(assert-equal '(b . 345)
(rassoc '234 '((a . 234) (b . 345) (c . 234))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |rassoc test-not=other key=other 2|
(assert-equal nil
(rassoc '234 '((a . 234) (b . 234) (c . 234))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |rassoc test-not=other key=other 3|
(assert-equal '(b . 345)
(rassoc '234 '((a . 234) nil (b . 345) (c . 234))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |rassoc error 1|
(assert-error 'type-error
(rassoc 'a '((b . c) nil d (a b)))))
(define-test |rassoc error 2|
(assert-error 'error
(rassoc 'a '((b . c) nil d (a b))
:test #'eq
:test-not #'eq)))
(define-test |rassoc test=nil key=identity 1|
(assert-error 'error
(rassoc 123 '((b . x) nil (b . 123) (c . nil))
:test nil)))
(define-test |rassoc test-not=nil key=identity 1|
(assert-error 'error
(rassoc 123 '((b . x) nil (b . 123) (c . nil))
:test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the rassoc-if function
(define-test rassoc-if.1
(assert-equal '(a . b)
(rassoc-if (lambda (x) (eq x 'b))
'((b) nil (a . b) (a . c)))))
(define-test rassoc-if.2
(assert-equal nil
(rassoc-if (lambda (x) (eq x 'd))
'((b) nil (a . b) (a . c)))))
(define-test rassoc-if.3
(assert-equal '(b)
(rassoc-if #'null
'((b) nil (a . b) (nil . c)))))
(define-test rassoc-if.4
(assert-equal '(b . 123)
(rassoc-if (lambda (x) (eql x 123))
'((b) nil (b . 123) (nil . c)))))
(define-test rassoc-if.5
(assert-equal '(b . #\a)
(rassoc-if (lambda (x) (eql x #\a))
'((b) nil (b . #\a) (nil . c)))))
(define-test rassoc-if.6
(assert-equal '((a b) c)
(rassoc-if (lambda (x) (eq x 'c))
'(((b a) b) ((a b) . (c)) ((d) . e))
:key #'car)))
(define-test rassoc-if.7
(assert-equal '((a b) c)
(rassoc-if (lambda (x) (eq x 'c))
'(((b a) b) nil ((a b) . (c)) ((d) . e))
:key #'car)))
(define-test rassoc-if.error.1
(assert-error 'type-error
(rassoc-if (lambda (x) (eq x 'a))
'((b . c) nil d (a b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the rassoc-if-not function
(define-test rassoc-if-not.1
(assert-equal '(a . b)
(rassoc-if-not (complement (lambda (x) (eq x 'b)))
'((b) nil (a . b) (a . c)))))
(define-test rassoc-if-not.2
(assert-equal nil
(rassoc-if-not (complement (lambda (x) (eq x 'd)))
'((b) nil (a . b) (a . c)))))
(define-test rassoc-if-not.3
(assert-equal '(b)
(rassoc-if-not (complement #'null)
'((b) nil (a . b) (nil . c)))))
(define-test rassoc-if-not.4
(assert-equal '(b . 123)
(rassoc-if-not (complement (lambda (x) (eql x 123)))
'((b) nil (b . 123) (nil . c)))))
(define-test rassoc-if-not.5
(assert-equal '(b . #\a)
(rassoc-if-not (complement (lambda (x) (eql x #\a)))
'((b) nil (b . #\a) (nil . c)))))
(define-test rassoc-if-not.6
(assert-equal '((a b) c)
(rassoc-if-not (complement (lambda (x) (eq x 'c)))
'(((b a) b) nil ((a b) c) ((d) e))
:key #'car)))
(define-test rassoc-if-not.error.1
(assert-error 'type-error
(rassoc-if-not (complement (lambda (x) (eq x 'a)))
'((b . c) nil d (a b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the sublis function
(define-test |sublis test=eql key=identity 1a|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'())))
(define-test |sublis test=eql key=identity 1b|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:test #'eql)))
(define-test |sublis test=eql key=identity 1c|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:test 'eql)))
(define-test |sublis test=eql key=identity 2a|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0))))))
(define-test |sublis test=eql key=identity 2b|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test #'eql)))
(define-test |sublis test=eql key=identity 2c|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test 'eql)))
(define-test |sublis test=eql key=nil 1|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key nil)))
(define-test |sublis test=eq key=identity 1|
(assert-equal '()
(sublis '((xx . y) (b . a)) '()
:test #'eq)))
(define-test |sublis test=eq key=identity 2|
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(sublis '((xx . y) (b . a))
'(((b . c) . (f . b)) . ((b . d) . (e . b)))
:test #'eq)))
(define-test |sublis test=other key=identity 1|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:test (lambda (x y) (and (numberp y) (= x (1- y)))))))
(define-test |sublis test=other key=identity 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test (lambda (x y) (and (numberp y) (= x y))))))
(define-test |sublis test=eql key=other 1a|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |sublis test=eql key=other 1b|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql)))
(define-test |sublis test=eql key=other 1c|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(define-test |sublis test=eql key=other 2a|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (1 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |sublis test=eql key=other 2b|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (1 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql)))
(define-test |sublis test=eql key=other 2c|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (1 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(define-test |sublis test=eq key=other 1|
(assert-equal '()
(sublis '((xx . y) (bb . a))
'()
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(define-test |sublis test=eq key=other 2|
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(sublis '((xx . y) (bb . a))
'(((b . c) . (f . b)) . ((b . d) . (e . b)))
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(define-test |sublis test=other key=other 1|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |sublis test=other key=other 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |sublis test-not=any key=identity 2|
(assert-equal '(((a . 5) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((1 . 5) . (2 . 1)) . ((1 . 3) . (4 . 1)))
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y))))))))
(define-test |sublis test-not=any key=other 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y)))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |sublis test=other test-not=other 1|
(assert-error 'error
(sublis 0 '((1 . 2)) :test #'= :test-not #'=)))
(define-test |sublis test=nil key=identity 1|
(assert-error 'error
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test nil)))
(define-test |sublis test-not=nil key=identity 1|
(assert-error 'error
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nsublis function
(define-test |nsublis test=eql key=identity 1a|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree))))
(define-test |nsublis test=eql key=identity 1b|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:test #'eql))))
(define-test |nsublis test=eql key=identity 1c|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:test 'eql))))
(define-test |nsublis test=eql key=identity 2a|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis
'((10 . xx) (0 . a))
tree)))
(assert-eq tree tree2)))
(define-test |nsublis test=eql key=identity 2b|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis
'((10 . xx) (0 . a))
tree
:test #'eql)))
(assert-eq tree tree2)))
(define-test |nsublis test=eql key=identity 2c|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (0 . a))
tree
:test 'eql)))
(assert-eq tree tree2)))
(define-test |nsublis test=eql key=identity 3a|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
0)))
(define-test |nsublis test=eql key=identity 3b|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
0
:test #'eql)))
(define-test |nsublis test=eql key=identity 3c|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
0
:test 'eql)))
(define-test |nsublis test=eql key=nil 1|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis
'((10 . xx) (0 . a))
tree
:key nil)))
(assert-eq tree tree2)))
(define-test |nsublis test=eq key=identity 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis
'((xx . y) (b . a))
tree
:test #'eq))))
(define-test |nsublis test=eq key=identity 2|
(let ((tree (copy-tree '(((b . c) . (f . b)) . ((b . d) . (e . b)))))
(tree2))
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(setf tree2 (nsublis
'((xx . y) (b . a))
tree
:test #'eq)))
(assert-eq tree tree2)))
(define-test |nsublis test=eq key=identity 3a|
(assert-equal 'a
(nsublis '((10 . xx) (c . a))
'c
:test #'eq)))
(define-test |nsublis test=eq key=identity 3b|
(assert-equal 'a
(nsublis '((10 . xx) (c . a))
'c
:test 'eq)))
(define-test |nsublis test=other key=identity 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:test (lambda (x y) (and (numberp y) (= x (1- y))))))))
(define-test |nsublis test=other key=identity 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (0 . a))
tree
:test (lambda (x y) (and (numberp y) (= x y))))))
(assert-eq tree tree2)))
(define-test |nsublis test=other key=identity 3|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
1
:test (lambda (x y) (and (numberp y) (= x (1- y)))))))
(define-test |nsublis test=eql key=other 1a|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))))))
(define-test |nsublis test=eql key=other 1b|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql))))
(define-test |nsublis test=eql key=other 1c|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql))))
(define-test |nsublis test=eql key=other 2a|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (1 . a))
tree
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsublis test=eql key=other 2b|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (1 . a))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql)))
(assert-eq tree tree2)))
(define-test |nsublis test=eql key=other 2c|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (1 . a))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(assert-eq tree tree2)))
(define-test |nsublis test=eql key=other 3a|
(assert-equal 'a
(nsublis '((10 . xx) (1 . a))
0
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |nsublis test=eq key=other 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((xx . y) (bb . a))
tree
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x))))))
(define-test |nsublis test=eq key=other 2|
(let ((tree (copy-tree '(((b . c) . (f . b)) . ((b . d) . (e . b)))))
(tree2))
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(setf tree2 (nsublis '((xx . y) (bb . a))
tree
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(assert-eq tree tree2)))
(define-test |nsublis test=eq key=other 3|
(assert-equal 'a
(nsublis '((xx . y) (bb . a))
'b
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(define-test |nsublis test=other key=other 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x))))))
(define-test |nsublis test=other key=other 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (0 . a))
tree
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsublis test=other key=other 3|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
0
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |nsublis test-not=any key=identity 2|
(let ((tree (copy-tree '(((1 . 5) . (2 . 1)) . ((1 . 3) . (4 . 1)))))
(tree2))
(assert-equal '(((a . 5) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (0 . a))
tree
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y))))))))
(assert-eq tree tree2)))
(define-test |nsublis test-not=any key=identity 3|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
1
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y))))))))
(define-test |nsublis test-not=any key=identity 4|
(assert-equal 123
(nsublis '((10 . xx) (0 . a))
123
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y))))))))
(define-test |nsublis test-not=any key=other 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (0 . a))
tree
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y)))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsublis test-not=any key=other 3|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
0
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y)))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |nsublis test-not=any key=other 4|
(assert-equal 123
(nsublis '((10 . xx) (0 . a))
123
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y)))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |nsublis test=other test-not=other|
(assert-error 'error
(nsublis 0 '((1 . 2)) :test #'= :test-not #'=)))
(define-test |nsublis test=nil key=identity 1|
(assert-error 'error
(sublis '((10 . xx) (0 . a))
(copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0))))
:test nil)))
(define-test |nsublis test-not=nil key=identity 1|
(assert-error 'error
(nsublis '((10 . xx) (0 . a))
(copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0))))
:test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the pairlis function
(define-test |pairlis 1|
(assert-equal '()
(pairlis '() '())))
(define-test |pairlis 2|
(let ((tail '((a b) (c d))))
(assert-eq tail
(cddr (pairlis '(1 2) '(2 3) tail)))))
(define-test |pairlis 3|
(assert-equal '((c . d) (a . b) (e f))
(pairlis '(a c) '(b d) '((e f)))))
(define-test |pairlis error 1|
(assert-error 'type-error
(pairlis '(a . b) '(c d) '((e f)))))
(define-test |pairlis error 2|
(assert-error 'type-error
(pairlis '(c d) '(a . b) '((e f)))))
(define-test |pairlis error 3|
(assert-error 'error
(pairlis '(a b) '(c d e))))
(define-test |pairlis error 4|
(assert-error 'error
(pairlis '(c d e) '(a b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the copy-alist function
(define-test |copy-alist 1|
(assert-equal '()
(copy-alist '())))
(define-test |copy-alist 2|
(assert-equal '((a) (b))
(copy-alist '((a) (b)))))
(define-test |copy-alist 3|
(assert-false (let ((alist '((a) (b))))
(eq (car alist)
(car (copy-alist alist))))))
(define-test |copy-alist 4|
(assert-equal '((a b) c (d e))
(copy-alist '((a b) c (d e)))))
(define-test |copy-alist 5|
(assert-equal '((a b) nil (d e))
(copy-alist '((a b) nil (d e)))))
(define-test |copy-alist error 2|
(assert-error 'type-error
(copy-alist '((a) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the tailp function
(define-test tailp.1
(assert-false (tailp 123 '())))
(define-test tailp.2
(assert-false (tailp 123 '(123))))
(define-test tailp.3
(assert-true (tailp 123 123)))
(define-test tailp.4
(assert-true (tailp 123 '(a . 123))))
(define-test tailp.5
(let ((tail '(a b)))
(assert-true (tailp tail (list* 1 2 tail)))))
(define-test tailp.6
(let ((tail '(a b)))
(assert-false (tailp tail (list* 1 2 (copy-list tail))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the ldiff function
(define-test ldiff.1
(let ((list '(a b c . d)))
(assert-equal nil (ldiff list list))))
(define-test ldiff.2
(let ((list '(a b c . d)))
(assert-equal '(a) (ldiff list (cdr list)))))
(define-test ldiff.3
(let ((list '(a b c . d)))
(assert-equal '(a b c) (ldiff list 'd))))
(define-test ldiff.4
(let ((list '(a b c . d)))
(assert-equal '(a b c . d) (ldiff list (cons 'c 'd)))))
(define-test ldiff.5
(let ((list '(a b c . d)))
(assert-equal '(a b c . d) (ldiff list 234))))
(define-test ldiff.6
(let ((list '(a b c . d)))
(assert-equal '(a b c . d) (ldiff list nil))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the union function
(define-test |union test=eql key=identity 1a|
(assert-equal '()
(union '() '())))
(define-test |union test=eql key=identity 1b|
(assert-equal '()
(union '() '() :test #'eql)))
(define-test |union test=eql key=identity 1c|
(assert-equal '()
(union '() '() :test 'eql)))
(define-test |union test=eql key=identity 2a|
(assert-equal '()
(set-difference (union '(1 2 3) '(3 4 5))
'(1 2 3 4 5))))
(define-test |union test=eql key=identity 2b|
(assert-equal '()
(set-difference (union '(1 2 3) '(3 4 5) :test #'eql)
'(1 2 3 4 5))))
(define-test |union test=eql key=identity 2|
(assert-equal '()
(set-difference (union '(1 2 3) '(3 4 5) :test 'eql)
'(1 2 3 4 5))))
(define-test |union test=eql key=identity 3a|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (union (append l1 l2) (append l2 l3))
(append l1 l2 l3)))))
(define-test |union test=eql key=identity 3b|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:test #'eql)
(append l1 l2 l3)
:test #'eql))))
(define-test |union test=eql key=identity 3c|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:test 'eql)
(append l1 l2 l3)
:test 'eql))))
(define-test |union test=eql key=identity dotted-list 1|
(assert-error 'type-error
(union '(1 2 . 3) '(2 3 4))))
(define-test |union test=eql key=identity dotted-list 2|
(assert-error 'type-error
(union '(1 2 3) '(2 3 . 4))))
(define-test |union test=eql key=nil 2a|
(assert-equal '()
(set-difference (union '(1 2 3) '(3 4 5) :key nil)
'(1 2 3 4 5))))
(define-test |union test=eq key=identity 1|
(assert-equal '()
(union '() '() :test #'eq)))
(define-test |union test=eq key=identity 2|
(assert-equal '()
(set-difference (union '(abc def) '(abc ghi)
:test #'eq)
'(abc def ghi)
:test #'eq)))
(define-test |union test=eq key=identity 3|
(let ((l1 (loop for code from 30 below 40 collect (string (code-char code))))
(l2 (loop for code from 40 below 100 collect (string (code-char code))))
(l3 (loop for code from 100 below 110 collect (string (code-char code)))))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:test #'eq)
(append l1 l2 l3)
:test #'eq))))
(define-test |union test=eq key=identity dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'eq)))
(define-test |union test=eq key=identity dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'eq)))
(define-test |union test=equal key=identity 1|
(assert-equal '()
(union '() '() :test #'equal)))
(define-test |union test=equal key=identity 2|
(assert-equal '()
(set-difference (union '("abc" "def") '("abc" "ghi")
:test #'equal)
'("abc" "def" "ghi")
:test #'equal)))
(define-test |union test=equal key=identity 3|
(let ((l1 (loop for code from 30 below 100 collect (string (code-char code))))
(l2 (loop for code from 40 below 110 collect (string (code-char code))))
(l3 (loop for code from 30 below 110 collect (string (code-char code)))))
(assert-equal '()
(set-difference (union l1 l2 :test #'equal)
l3
:test #'equal))))
(define-test |union test=equal key=identity dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'equal)))
(define-test |union test=equal key=identity dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'equal)))
(define-test |union test=equalp key=identity 1|
(assert-equal '()
(union '() '() :test #'equalp)))
(define-test |union test=equalp key=identity 3|
(let ((l1 (loop for i from 30 below 100
collect (make-array 1 :initial-element i)))
(l2 (loop for i from 40 below 110
collect (make-array 1 :initial-element i)))
(l3 (loop for i from 30 below 110
collect (make-array 1 :initial-element i))))
(assert-equal '()
(set-difference (union l1 l2 :test #'equalp)
l3
:test #'equalp))))
(define-test |union test=equalp key=identity dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'equalp)))
(define-test |union test=equalp key=identity dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'equalp)))
(define-test |union test=other key=identity 1|
(assert-equal '()
(union '() '() :test #'<)))
(define-test |union test=other key=identity dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'(lambda (x y) (eq x y)))))
(define-test |union test=other key=identity dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'(lambda (x y) (eq x y)))))
(define-test |union test=eql key=other 1a|
(assert-equal 1
(length (union '(1) '(3) :key #'oddp))))
(define-test |union test=eql key=other 1b|
(assert-equal 1
(length (union '(1) '(3) :key #'oddp :test #'eql))))
(define-test |union test=eql key=other 1c|
(assert-equal 1
(length (union '(1) '(3) :key #'oddp :test 'eql))))
(define-test |union test=eql key=other 2a|
(assert-equal 2
(length (union '(4 1) '(3) :key #'oddp))))
(define-test |union test=eql key=other 2b|
(assert-equal 2
(length (union '(4 1) '(3) :key #'oddp :test #'eql))))
(define-test |union test=eql key=other 2c|
(assert-equal 2
(length (union '(4 1) '(3) :key #'oddp :test 'eql))))
(define-test |union test=eql key=other 3|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:key #'car)
(append l1 l2 l3)
:key #'car))))
(define-test |union test=eql key=other 4|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:test #'eql
:key #'car)
(append l1 l2 l3)
:test #'eql
:key #'car))))
(define-test |union test=eql key=other 5|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:test 'eql
:key #'car)
(append l1 l2 l3)
:test 'eql
:key #'car))))
(define-test |union test=eql key=other dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :key #'identity)))
(define-test |union test=eql key=other dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :key #'identity)))
(define-test |union test=eq key=other 1|
(assert-equal '()
(set-difference
(union '((a) (b) (c))
'((b) (c) (d))
:key #'car
:test #'eq)
'((a) (b) (c) (d))
:key #'car
:test #'eq)))
(define-test |union test=eq key=other 3|
(let ((l1 (loop for code from 30 below 40 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 100 collect (list (string (code-char code)))))
(l3 (loop for code from 100 below 110 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:key #'car
:test #'eq)
(append l1 l2 l3)
:test #'eq
:key #'car))))
(define-test |union test=eq key=other dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'eq :key #'identity)))
(define-test |union test=eq key=other dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'eq :key #'identity)))
(define-test |union test=equal key=other 1|
(assert-equal '()
(union '() '() :test #'equal :key #'car)))
(define-test |union test=equal key=other 2|
(assert-equal '()
(set-difference (union '(("abc") ("def")) '(("abc") ("ghi"))
:key #'car
:test #'equal)
'(("abc") ("def") ("ghi"))
:key #'car
:test #'equal)))
(define-test |union test=equal key=other 3|
(let ((l1 (loop for code from 30 below 100 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 110 collect (list (string (code-char code)))))
(l3 (loop for code from 30 below 110 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (union l1 l2 :test #'equal :key #'car)
l3
:test #'equal :key #'car))))
(define-test |union test=equal key=other dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'equal :key #'identity)))
(define-test |union test=equal key=other dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'equal :key #'identity)))
(define-test |union test=equalp key=other 1|
(assert-equal '()
(union '() '() :test #'equalp :key #'car)))
(define-test |union test=equalp key=other 2|
(assert-equal '()
(set-difference (union '((#(1)) (#(2))) '((#(1)) (#(3)))
:key #'car
:test #'equalp)
'((#(1)) (#(2)) (#(3)))
:key #'car
:test #'equalp)))
(define-test |union test=equalp key=other 3|
(let ((l1 (loop for i from 30 below 100
collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 40 below 110
collect (list (make-array 1 :initial-element i))))
(l3 (loop for i from 30 below 110
collect (list (make-array 1 :initial-element i)))))
(assert-equal '()
(set-difference (union l1 l2 :test #'equalp :key #'car)
l3
:test #'equalp :key #'car))))
(define-test |union test=equalp key=other dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'equalp :key #'identity)))
(define-test |union test=equalp key=other dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'equalp :key #'identity)))
(define-test |union test=other key=other 1|
(assert-equal '()
(set-difference
(union '(1 3 5 7)
'(2 4 10 3)
:key (lambda (x) (mod x 5))
:test #'=)
'(0 1 2 3 4) :key (lambda (x) (mod x 5)))))
(define-test |union test=other key=other dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test (lambda (x y) (eq x y)) :key #'identity)))
(define-test |union test=other key=other dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test (lambda (x y) (eq x y)) :key #'identity)))
(define-test |union test-not=other key=identity 1|
(assert-equal '()
(set-difference
(union '(1 2 3 4)
'(3 4 5 6)
:test-not #'/=)
'(1 2 3 4 5 6))))
(define-test |union test-not=other key=other 1|
(assert-equal '()
(set-difference
(union '(1 3 5 7)
'(2 4 10 3)
:key (lambda (x) (mod x 5))
:test-not #'/=)
'(0 1 2 3 4) :key (lambda (x) (mod x 5)))))
(define-test |union test=other test-not=other 1|
(assert-error 'error
(union '(1 2 3) '(2 3 4) :test #'eql :test-not #'eql)))
(define-test |union test=nil key=identity 2a|
(assert-error 'error
(set-difference (union '(1 2 3) '(3 4 5) :test nil)
'(1 2 3 4 5))))
(define-test |union test-not=nil key=identity 2a|
(assert-error 'error
(set-difference (union '(1 2 3) '(3 4 5) :test-not nil)
'(1 2 3 4 5))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nunion function
(define-test |nunion test=eql key=identity 1a|
(assert-equal '()
(nunion '() '())))
(define-test |nunion test=eql key=identity 1b|
(assert-equal '()
(nunion '() '() :test #'eql)))
(define-test |nunion test=eql key=identity 1c|
(assert-equal '()
(nunion '() '() :test 'eql)))
(define-test |nunion test=eql key=identity 2a|
(assert-equal '()
(set-difference (nunion (copy-list '(1 2 3))
(copy-list '(3 4 5)))
'(1 2 3 4 5))))
(define-test |nunion test=eql key=identity 2b|
(assert-equal '()
(set-difference (nunion (copy-list '(1 2 3))
(copy-list '(3 4 5))
:test #'eql)
'(1 2 3 4 5))))
(define-test |nunion test=eql key=identity 2|
(assert-equal '()
(set-difference (nunion (copy-list '(1 2 3))
(copy-list '(3 4 5))
:test 'eql)
'(1 2 3 4 5))))
(define-test |nunion test=eql key=identity 3a|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3)))
(append l1 l2 l3)))))
(define-test |nunion test=eql key=identity 3b|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eql)
(append l1 l2 l3)
:test #'eql))))
(define-test |nunion test=eql key=identity 3c|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test 'eql)
(append l1 l2 l3)
:test 'eql))))
(define-test |nunion test=eql key=nil 1|
(assert-equal '()
(set-difference (nunion (copy-list '(1 2 3))
(copy-list '(3 4 5))
:key nil)
'(1 2 3 4 5))))
(define-test |nunion test=eq key=identity 1|
(assert-equal '()
(nunion '() '() :test #'eq)))
(define-test |nunion test=eq key=identity 2|
(assert-equal '()
(set-difference (nunion '(abc def) '(abc ghi)
:test #'eq)
'(abc def ghi)
:test #'eq)))
(define-test |nunion test=eq key=identity 3|
(let ((l1 (loop for code from 30 below 40 collect (string (code-char code))))
(l2 (loop for code from 40 below 100 collect (string (code-char code))))
(l3 (loop for code from 100 below 110 collect (string (code-char code)))))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eq)
(append l1 l2 l3)
:test #'eq))))
(define-test |nunion test=equal key=identity 1|
(assert-equal '()
(nunion '() '() :test #'equal)))
(define-test |nunion test=equal key=identity 2|
(assert-equal '()
(set-difference (nunion (copy-list '("abc" "def"))
(copy-list '("abc" "ghi"))
:test #'equal)
'("abc" "def" "ghi")
:test #'equal)))
(define-test |nunion test=equal key=identity 3|
(let ((l1 (loop for code from 30 below 100 collect (string (code-char code))))
(l2 (loop for code from 40 below 110 collect (string (code-char code))))
(l3 (loop for code from 30 below 110 collect (string (code-char code)))))
(assert-equal '()
(set-difference (nunion (copy-list l1)
(copy-list l2)
:test #'equal)
l3
:test #'equal))))
(define-test |nunion test=equalp key=identity 1|
(assert-equal '()
(nunion '() '() :test #'equalp)))
(define-test |nunion test=equalp key=identity 3|
(let ((l1 (loop for i from 30 below 100
collect (make-array 1 :initial-element i)))
(l2 (loop for i from 40 below 110
collect (make-array 1 :initial-element i)))
(l3 (loop for i from 30 below 110
collect (make-array 1 :initial-element i))))
(assert-equal '()
(set-difference (nunion (copy-list l1)
(copy-list l2)
:test #'equalp)
l3
:test #'equalp))))
(define-test |nunion test=other key=identity 1|
(assert-equal '()
(nunion '() '() :test #'<)))
(define-test |nunion test=eql key=other 1a|
(assert-equal 1
(length (nunion (copy-list '(1))
(copy-list '(3))
:key #'oddp))))
(define-test |nunion test=eql key=other 1b|
(assert-equal 1
(length (nunion (copy-list '(1))
(copy-list '(3))
:key #'oddp
:test #'eql))))
(define-test |nunion test=eql key=other 1c|
(assert-equal 1
(length (nunion (copy-list '(1))
(copy-list '(3))
:key #'oddp
:test 'eql))))
(define-test |nunion test=eql key=other 2a|
(assert-equal 2
(length (nunion (copy-list '(4 1))
(copy-list '(3))
:key #'oddp))))
(define-test |nunion test=eql key=other 2b|
(assert-equal 2
(length (nunion (copy-list '(4 1))
(copy-list '(3))
:key #'oddp
:test #'eql))))
(define-test |nunion test=eql key=other 2c|
(assert-equal 2
(length (nunion (copy-list '(4 1))
(copy-list '(3))
:key #'oddp
:test 'eql))))
(define-test |nunion test=eql key=other 3|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key #'car)
(append l1 l2 l3)
:key #'car))))
(define-test |nunion test=eql key=other 4|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eql
:key #'car)
(append l1 l2 l3)
:test #'eql
:key #'car))))
(define-test |nunion test=eql key=other 5|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test 'eql
:key #'car)
(append l1 l2 l3)
:test 'eql
:key #'car))))
(define-test |nunion test=eq key=other 1|
(assert-equal '()
(set-difference
(nunion (copy-list '((a) (b) (c)))
(copy-list '((b) (c) (d)))
:key #'car
:test #'eq)
'((a) (b) (c) (d))
:key #'car
:test #'eq)))
(define-test |nunion test=eq key=other 3|
(let ((l1 (loop for code from 30 below 40 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 100 collect (list (string (code-char code)))))
(l3 (loop for code from 100 below 110 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key #'car
:test #'eq)
(append l1 l2 l3)
:test #'eq
:key #'car))))
(define-test |nunion test=equal key=other 1|
(assert-equal '()
(nunion '() '() :test #'equal :key #'car)))
(define-test |nunion test=equal key=other 2|
(assert-equal '()
(set-difference (nunion (copy-list '(("abc") ("def")))
(copy-list '(("abc") ("ghi")))
:key #'car
:test #'equal)
'(("abc") ("def") ("ghi"))
:key #'car
:test #'equal)))
(define-test |nunion test=equal key=other 3|
(let ((l1 (loop for code from 30 below 100 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 110 collect (list (string (code-char code)))))
(l3 (loop for code from 30 below 110 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (nunion (copy-list l1)
(copy-list l2)
:test #'equal
:key #'car)
l3
:test #'equal :key #'car))))
(define-test |nunion test=equalp key=other 1|
(assert-equal '()
(nunion '() '() :test #'equalp :key #'car)))
(define-test |nunion test=equalp key=other 2|
(assert-equal '()
(set-difference (nunion (copy-list '((#(1)) (#(2))))
(copy-list '((#(1)) (#(3))))
:key #'car
:test #'equalp)
'((#(1)) (#(2)) (#(3)))
:key #'car
:test #'equalp)))
(define-test |nunion test=equalp key=other 3|
(let ((l1 (loop for i from 30 below 100
collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 40 below 110
collect (list (make-array 1 :initial-element i))))
(l3 (loop for i from 30 below 110
collect (list (make-array 1 :initial-element i)))))
(assert-equal '()
(set-difference (nunion (copy-list l1)
(copy-list l2)
:test #'equalp
:key #'car)
l3
:test #'equalp :key #'car))))
(define-test |nunion test=other key=other 1|
(assert-equal '()
(set-difference
(nunion (copy-list '(1 3 5 7))
(copy-list '(2 4 10 3))
:key (lambda (x) (mod x 5))
:test #'=)
'(0 1 2 3 4) :key (lambda (x) (mod x 5)))))
(define-test |nunion test-not=other key=identity 1|
(assert-equal '()
(set-difference
(nunion (copy-list '(1 2 3 4))
(copy-list '(3 4 5 6))
:test-not #'/=)
'(1 2 3 4 5 6))))
(define-test |nunion test-not=other key=other 1|
(assert-equal '()
(set-difference
(nunion (copy-list '(1 3 5 7))
(copy-list '(2 4 10 3))
:key (lambda (x) (mod x 5))
:test-not #'/=)
'(0 1 2 3 4) :key (lambda (x) (mod x 5)))))
(define-test |nunion test=other test-not=other 1|
(assert-error 'error
(nunion (copy-list '(1 2 3))
(copy-list '(2 3 4))
:test #'eql
:test-not #'eql)))
(define-test |nunion test=nil key=identity 1|
(assert-error 'error
(set-difference (nunion (copy-list '(1 2 3))
(copy-list '(3 4 5))
:test nil)
'(1 2 3 4 5))))
(define-test |nunion test-not=nil key=identity 1|
(assert-error 'error
(set-difference (nunion (copy-list '(1 2 3))
(copy-list '(3 4 5))
:test-not nil)
'(1 2 3 4 5))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the intersection function
(define-test |intersection test=eql key=identity 1a|
(assert-equal '()
(intersection '() '())))
(define-test |intersection test=eql key=identity 1b|
(assert-equal '()
(intersection '() '() :test #'eql)))
(define-test |intersection test=eql key=identity 1c|
(assert-equal '()
(intersection '() '() :test 'eql)))
(define-test |intersection test=eql key=identity 2a|
(assert-equal '()
(set-difference (intersection (copy-list '(1 2 3 4))
(copy-list '(2 3 4 5)))
'(2 3 4))))
(define-test |intersection test=eql key=identity 2b|
(assert-equal '()
(set-difference (intersection (copy-list '(1 2 3 4))
(copy-list '(2 3 4 5))
:test #'eql)
'(2 3 4))))
(define-test |intersection test=eql key=identity 2|
(assert-equal '()
(set-difference (intersection (copy-list '(1 2 3 4))
(copy-list '(2 3 4 5))
:test 'eql)
'(2 3 4))))
(define-test |intersection test=eql key=identity 3a|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3)))
l2))))
(define-test |intersection test=eql key=identity 3b|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eql)
l2
:test #'eql))))
(define-test |intersection test=eql key=identity 3c|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test 'eql)
l2
:test 'eql))))
(define-test |intersection test=eql key=nil 1|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key nil)
l2))))
(define-test |intersection test=eq key=identity 1|
(assert-equal '()
(intersection '() '() :test #'eq)))
(define-test |intersection test=eq key=identity 2|
(assert-equal '()
(set-difference (intersection '(abc def) '(abc ghi)
:test #'eq)
'(abc)
:test #'eq)))
(define-test |intersection test=eq key=identity 3|
(let ((l1 (loop for code from 30 below 40 collect (string (code-char code))))
(l2 (loop for code from 40 below 100 collect (string (code-char code))))
(l3 (loop for code from 100 below 110 collect (string (code-char code)))))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eq)
l2
:test #'eq))))
(define-test |intersection test=equal key=identity 1|
(assert-equal '()
(intersection '() '() :test #'equal)))
(define-test |intersection test=equal key=identity 2|
(assert-equal '()
(set-difference (intersection (copy-list '("abc" "def"))
(copy-list '("abc" "ghi"))
:test #'equal)
'("abc")
:test #'equal)))
(define-test |intersection test=equal key=identity 3|
(let ((l1 (loop for code from 30 below 100 collect (string (code-char code))))
(l2 (loop for code from 40 below 110 collect (string (code-char code))))
(l3 (loop for code from 40 below 100 collect (string (code-char code)))))
(assert-equal '()
(set-difference (intersection (copy-list l1)
(copy-list l2)
:test #'equal)
l3
:test #'equal))))
(define-test |intersection test=equalp key=identity 1|
(assert-equal '()
(intersection '() '() :test #'equalp)))
(define-test |intersection test=equalp key=identity 3|
(let ((l1 (loop for i from 30 below 100
collect (make-array 1 :initial-element i)))
(l2 (loop for i from 40 below 110
collect (make-array 1 :initial-element i)))
(l3 (loop for i from 40 below 100
collect (make-array 1 :initial-element i))))
(assert-equal '()
(set-difference (intersection (copy-list l1)
(copy-list l2)
:test #'equalp)
l3
:test #'equalp))))
(define-test |intersection test=other key=identity 1|
(assert-equal '()
(intersection '() '() :test #'<)))
(define-test |intersection test=eql key=other 1a|
(assert-equal 1
(length (intersection (copy-list '(1))
(copy-list '(3))
:key #'oddp))))
(define-test |intersection test=eql key=other 1b|
(assert-equal 1
(length (intersection (copy-list '(1))
(copy-list '(3))
:key #'oddp
:test #'eql))))
(define-test |intersection test=eql key=other 1c|
(assert-equal 1
(length (intersection (copy-list '(1))
(copy-list '(3))
:key #'oddp
:test 'eql))))
(define-test |intersection test=eql key=other 2a|
(assert-equal 1
(length (intersection (copy-list '(4 1))
(copy-list '(3))
:key #'oddp))))
(define-test |intersection test=eql key=other 2b|
(assert-equal 1
(length (intersection (copy-list '(4 1))
(copy-list '(3))
:key #'oddp
:test #'eql))))
(define-test |intersection test=eql key=other 2c|
(assert-equal 1
(length (intersection (copy-list '(4 1))
(copy-list '(3))
:key #'oddp
:test 'eql))))
(define-test |intersection test=eql key=other 3|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key #'car)
l2
:key #'car))))
(define-test |intersection test=eql key=other 4|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eql
:key #'car)
l2
:test #'eql
:key #'car))))
(define-test |intersection test=eql key=other 5|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test 'eql
:key #'car)
l2
:test 'eql
:key #'car))))
(define-test |intersection test=eq key=other 1|
(assert-equal '()
(set-difference
(intersection (copy-list '((a) (b) (c)))
(copy-list '((b) (c) (d)))
:key #'car
:test #'eq)
'((b) (c))
:key #'car
:test #'eq)))
(define-test |intersection test=eq key=other 3|
(let ((l1 (loop for code from 30 below 40 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 100 collect (list (string (code-char code)))))
(l3 (loop for code from 100 below 110 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key #'car
:test #'eq)
l2
:test #'eq
:key #'car))))
(define-test |intersection test=equal key=other 1|
(assert-equal '()
(intersection '()
'()
:test #'equal
:key #'car)))
(define-test |intersection test=equal key=other 2|
(assert-equal '()
(set-difference (intersection (copy-list '(("abc") ("def")))
(copy-list '(("abc") ("ghi")))
:key #'car
:test #'equal)
'(("abc"))
:key #'car
:test #'equal)))
(define-test |intersection test=equal key=other 3|
(let ((l1 (loop for code from 30 below 100 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 110 collect (list (string (code-char code)))))
(l3 (loop for code from 40 below 100 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (intersection (copy-list l1)
(copy-list l2)
:test #'equal
:key #'car)
l3
:test #'equal :key #'car))))
(define-test |intersection test=equalp key=other 1|
(assert-equal '()
(intersection '() '() :test #'equalp :key #'car)))
(define-test |intersection test=equalp key=other 2|
(assert-equal '()
(set-difference (intersection (copy-list '((#(1)) (#(2))))
(copy-list '((#(1)) (#(3))))
:key #'car
:test #'equalp)
'((#(1)))
:key #'car
:test #'equalp)))
(define-test |intersection test=equalp key=other 3|
(let ((l1 (loop for i from 30 below 100
collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 40 below 110
collect (list (make-array 1 :initial-element i))))
(l3 (loop for i from 40 below 100
collect (list (make-array 1 :initial-element i)))))
(assert-equal '()
(set-difference (intersection (copy-list l1)
(copy-list l2)
:test #'equalp
:key #'car)
l3
:test #'equalp :key #'car))))
(define-test |intersection test=other key=other 1|
(assert-equal '()
(set-difference
(intersection (copy-list '(1 3 5 7))
(copy-list '(2 4 10 3))
:key (lambda (x) (mod x 5))
:test #'=)
'(3 5 7) :key (lambda (x) (mod x 5)))))
(define-test |intersection test-not=other key=identity 1|
(assert-equal '()
(set-difference
(intersection (copy-list '(1 2 3 4))
(copy-list '(3 4 5 6))
:test-not #'/=)
'(3 4))))
(define-test |intersection test-not=other key=other 1|
(assert-equal '()
(set-difference
(intersection (copy-list '(1 3 5 7))
(copy-list '(2 4 10 3))
:key (lambda (x) (mod x 5))
:test-not #'/=)
'(3 5 7) :key (lambda (x) (mod x 5)))))
(define-test |intersection test=other test-not=other 1|
(assert-error 'error
(intersection (copy-list '(1 2 3))
(copy-list '(2 3 4))
:test #'eql
:test-not #'eql)))
(define-test |intersection test=nil key=identity 1|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-error 'error
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test nil)
l2))))
(define-test |intersection test-not=nil key=identity 1|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-error 'error
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test-not nil)
l2))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nintersection function
(define-test |nintersection test=eql key=identity 1a|
(assert-equal '()
(nintersection '() '())))
(define-test |nintersection test=eql key=identity 1b|
(assert-equal '()
(nintersection '() '() :test #'eql)))
(define-test |nintersection test=eql key=identity 1c|
(assert-equal '()
(nintersection '() '() :test 'eql)))
(define-test |nintersection test=eql key=identity 2a|
(assert-equal '()
(set-difference (nintersection (copy-list '(1 2 3 4))
(copy-list '(2 3 4 5)))
'(2 3 4))))
(define-test |nintersection test=eql key=identity 2b|
(assert-equal '()
(set-difference (nintersection (copy-list '(1 2 3 4))
(copy-list '(2 3 4 5))
:test #'eql)
'(2 3 4))))
(define-test |nintersection test=eql key=identity 2|
(assert-equal '()
(set-difference (nintersection (copy-list '(1 2 3 4))
(copy-list '(2 3 4 5))
:test 'eql)
'(2 3 4))))
(define-test |nintersection test=eql key=identity 3a|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3)))
l2))))
(define-test |nintersection test=eql key=identity 3b|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eql)
l2
:test #'eql))))
(define-test |nintersection test=eql key=identity 3c|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test 'eql)
l2
:test 'eql))))
(define-test |nintersection test=eql key=nil 1|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key nil)
l2))))
(define-test |nintersection test=eq key=identity 1|
(assert-equal '()
(nintersection '() '() :test #'eq)))
(define-test |nintersection test=eq key=identity 2|
(assert-equal '()
(set-difference (nintersection '(abc def) '(abc ghi)
:test #'eq)
'(abc)
:test #'eq)))
(define-test |nintersection test=eq key=identity 3|
(let ((l1 (loop for code from 30 below 40 collect (string (code-char code))))
(l2 (loop for code from 40 below 100 collect (string (code-char code))))
(l3 (loop for code from 100 below 110 collect (string (code-char code)))))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eq)
l2
:test #'eq))))
(define-test |nintersection test=equal key=identity 1|
(assert-equal '()
(nintersection '() '() :test #'equal)))
(define-test |nintersection test=equal key=identity 2|
(assert-equal '()
(set-difference (nintersection (copy-list '("abc" "def"))
(copy-list '("abc" "ghi"))
:test #'equal)
'("abc")
:test #'equal)))
(define-test |nintersection test=equal key=identity 3|
(let ((l1 (loop for code from 30 below 100 collect (string (code-char code))))
(l2 (loop for code from 40 below 110 collect (string (code-char code))))
(l3 (loop for code from 40 below 100 collect (string (code-char code)))))
(assert-equal '()
(set-difference (nintersection (copy-list l1)
(copy-list l2)
:test #'equal)
l3
:test #'equal))))
(define-test |nintersection test=equalp key=identity 1|
(assert-equal '()
(nintersection '() '() :test #'equalp)))
(define-test |nintersection test=equalp key=identity 3|
(let ((l1 (loop for i from 30 below 100
collect (make-array 1 :initial-element i)))
(l2 (loop for i from 40 below 110
collect (make-array 1 :initial-element i)))
(l3 (loop for i from 40 below 100
collect (make-array 1 :initial-element i))))
(assert-equal '()
(set-difference (nintersection (copy-list l1)
(copy-list l2)
:test #'equalp)
l3
:test #'equalp))))
(define-test |nintersection test=other key=identity 1|
(assert-equal '()
(nintersection '() '() :test #'<)))
(define-test |nintersection test=eql key=other 1a|
(assert-equal 1
(length (nintersection (copy-list '(1))
(copy-list '(3))
:key #'oddp))))
(define-test |nintersection test=eql key=other 1b|
(assert-equal 1
(length (nintersection (copy-list '(1))
(copy-list '(3))
:key #'oddp
:test #'eql))))
(define-test |nintersection test=eql key=other 1c|
(assert-equal 1
(length (nintersection (copy-list '(1))
(copy-list '(3))
:key #'oddp
:test 'eql))))
(define-test |nintersection test=eql key=other 2a|
(assert-equal 1
(length (nintersection (copy-list '(4 1))
(copy-list '(3))
:key #'oddp))))
(define-test |nintersection test=eql key=other 2b|
(assert-equal 1
(length (nintersection (copy-list '(4 1))
(copy-list '(3))
:key #'oddp
:test #'eql))))
(define-test |nintersection test=eql key=other 2c|
(assert-equal 1
(length (nintersection (copy-list '(4 1))
(copy-list '(3))
:key #'oddp
:test 'eql))))
(define-test |nintersection test=eql key=other 3|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key #'car)
l2
:key #'car))))
(define-test |nintersection test=eql key=other 4|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eql
:key #'car)
l2
:test #'eql
:key #'car))))
(define-test |nintersection test=eql key=other 5|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test 'eql
:key #'car)
l2
:test 'eql
:key #'car))))
(define-test |nintersection test=eq key=other 1|
(assert-equal '()
(set-difference
(nintersection (copy-list '((a) (b) (c)))
(copy-list '((b) (c) (d)))
:key #'car
:test #'eq)
'((b) (c))
:key #'car
:test #'eq)))
(define-test |nintersection test=eq key=other 3|
(let ((l1 (loop for code from 30 below 40 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 100 collect (list (string (code-char code)))))
(l3 (loop for code from 100 below 110 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key #'car
:test #'eq)
l2
:test #'eq
:key #'car))))
(define-test |nintersection test=equal key=other 1|
(assert-equal '()
(nintersection '()
'()
:test #'equal
:key #'car)))
(define-test |nintersection test=equal key=other 2|
(assert-equal '()
(set-difference (nintersection (copy-list '(("abc") ("def")))
(copy-list '(("abc") ("ghi")))
:key #'car
:test #'equal)
'(("abc"))
:key #'car
:test #'equal)))
(define-test |nintersection test=equal key=other 3|
(let ((l1 (loop for code from 30 below 100 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 110 collect (list (string (code-char code)))))
(l3 (loop for code from 40 below 100 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (nintersection (copy-list l1)
(copy-list l2)
:test #'equal
:key #'car)
l3
:test #'equal :key #'car))))
(define-test |nintersection test=equalp key=other 1|
(assert-equal '()
(nintersection '() '() :test #'equalp :key #'car)))
(define-test |nintersection test=equalp key=other 2|
(assert-equal '()
(set-difference (nintersection (copy-list '((#(1)) (#(2))))
(copy-list '((#(1)) (#(3))))
:key #'car
:test #'equalp)
'((#(1)))
:key #'car
:test #'equalp)))
(define-test |nintersection test=equalp key=other 3|
(let ((l1 (loop for i from 30 below 100
collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 40 below 110
collect (list (make-array 1 :initial-element i))))
(l3 (loop for i from 40 below 100
collect (list (make-array 1 :initial-element i)))))
(assert-equal '()
(set-difference (nintersection (copy-list l1)
(copy-list l2)
:test #'equalp
:key #'car)
l3
:test #'equalp :key #'car))))
(define-test |nintersection test=other key=other 1|
(assert-equal '()
(set-difference
(nintersection (copy-list '(1 3 5 7))
(copy-list '(2 4 10 3))
:key (lambda (x) (mod x 5))
:test #'=)
'(3 5 7) :key (lambda (x) (mod x 5)))))
(define-test |nintersection test-not=other key=identity 1|
(assert-equal '()
(set-difference
(nintersection (copy-list '(1 2 3 4))
(copy-list '(3 4 5 6))
:test-not #'/=)
'(3 4))))
(define-test |nintersection test-not=other key=other 1|
(assert-equal '()
(set-difference
(nintersection (copy-list '(1 3 5 7))
(copy-list '(2 4 10 3))
:key (lambda (x) (mod x 5))
:test-not #'/=)
'(3 5 7) :key (lambda (x) (mod x 5)))))
(define-test |nintersection test=other test-not=other 1|
(assert-error 'error
(nintersection (copy-list '(1 2 3))
(copy-list '(2 3 4))
:test #'eql
:test-not #'eql)))
(define-test |nintersection test=nil key=identity 1|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-error 'error
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test nil)
l2))))
(define-test |nintersection test-not=nil key=identity 1|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-error 'error
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test-not nil)
l2))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the set-difference function
(define-test |set-difference test=eql key=identity 1a|
(assert-equal '()
(set-difference '() '())))
(define-test |set-difference test=eql key=identity 1b|
(assert-equal '()
(set-difference '()
'()
:test #'eql)))
(define-test |set-difference test=eql key=identity 1c|
(assert-equal '()
(set-difference '()
'()
:test 'eql)))
(define-test |set-difference test=eql key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)))))
(define-test |set-difference test=eql key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:test #'eql))))
(define-test |set-difference test=eql key=identity 2c|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:test 'eql))))
(define-test |set-difference test=eql key=identity 3a|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 200 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)))))
(define-test |set-difference test=eql key=identity 3b|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 200 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:test #'eql))))
(define-test |set-difference test=eql key=identity 3c|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 200 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:test 'eql))))
(define-test |set-difference test=eql key=nil 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:key nil))))
(define-test |set-difference test=eq key=identity 1|
(assert-equal '()
(set-difference '()
'()
:test #'eq)))
(define-test |set-difference test=eq key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal 1
(length (set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))
(assert-eq (car l1)
(car (set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))))
(define-test |set-difference test=eq key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal 1
(length (set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'eq)))
(assert-eq (car l1)
(car (set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'eq)))))
(define-test |set-difference test=eq key=identity 3|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal 1
(length (set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))
(assert-eq (car l1)
(car (set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))))
(define-test |set-difference test=equal key=identity 1|
(assert-equal '()
(set-difference '()
'()
:test #'equal)))
(define-test |set-difference test=equal key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equal))))
(define-test |set-difference test=equal key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'equal))))
(define-test |set-difference test=equal key=identity 3|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equal))))
(define-test |set-difference test=equalp key=identity 1|
(assert-equal '()
(set-difference '()
'()
:test #'equalp)))
(define-test |set-difference test=equalp key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 20 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equalp))))
(define-test |set-difference test=equalp key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 20 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'equalp))))
(define-test |set-difference test=equalp key=identity 3a|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 200 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equalp))))
(define-test |set-difference test=equalp key=identity 3b|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 200 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equalp))))
(define-test |set-difference test=other key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 1 below 20 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:test #'>))))
(define-test |set-difference test-not=other key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 1 below 20 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:test-not #'<=))))
(define-test |set-difference test=eql key=other 1a|
(assert-equal '()
(set-difference '()
'()
:key #'car)))
(define-test |set-difference test=eql key=other 1b|
(assert-equal '()
(set-difference '()
'()
:key #'car
:test #'eql)))
(define-test |set-difference test=eql key=other 1c|
(assert-equal '()
(set-difference '()
'()
:key #'car
:test 'eql)))
(define-test |set-difference test=eql key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car))))
(define-test |set-difference test=eql key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car
:test #'eql))))
(define-test |set-difference test=eql key=other 2c|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car
:test 'eql))))
(define-test |set-difference test=eql key=other 3a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car))))
(define-test |set-difference test=eql key=other 3b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car
:test #'eql))))
(define-test |set-difference test=eql key=other 3c|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car
:test 'eql))))
(define-test |set-difference test=eq key=other 1|
(assert-equal '()
(set-difference '()
'()
:key #'car
:test #'eq)))
(define-test |set-difference test=eq key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal 1
(length (set-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))
(assert-eq (car l1)
(car (set-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))))
(define-test |set-difference test=eq key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal 1
(length (set-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test 'eq)))
(assert-eq (car l1)
(car (set-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test 'eq)))))
(define-test |set-difference test=eq key=other 3|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 200 collect (list (list i)))))
(assert-equal 1
(length (set-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))
(assert-eq (car l1)
(car (set-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))))
(define-test |set-difference test=equal key=other 1|
(assert-equal '()
(set-difference '()
'()
:key #'car
:test #'equal)))
(define-test |set-difference test=equal key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal '(((1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equal))))
(define-test |set-difference test=equal key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal '(((1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test 'equal))))
(define-test |set-difference test=equal key=other 3|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 200 collect (list (list i)))))
(assert-equal '(((1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equal))))
(define-test |set-difference test=equalp key=other 1|
(assert-equal '()
(set-difference '()
'()
:key #'car
:test #'equalp)))
(define-test |set-difference test=equalp key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 20 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equalp))))
(define-test |set-difference test=equalp key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 20 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test 'equalp))))
(define-test |set-difference test=equalp key=other 3a|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 200 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equalp))))
(define-test |set-difference test=equalp key=other 3b|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 200 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test 'equalp))))
(define-test |set-difference test=other key=other 1|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 1 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car
:test #'>))))
(define-test |set-difference test-not=other key=other 1|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 1 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car
:test-not #'<=))))
(define-test |set-difference test=other test-not=other 1|
(assert-error 'error
(set-difference '(1 2 3) '(2 3 4)
:test #'eql
:test-not #'eql)))
(define-test |set-difference test=nil key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-error 'error
(set-difference (copy-list l1)
(copy-list l2)
:test nil))))
(define-test |set-difference test-not=nil key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-error 'error
(set-difference (copy-list l1)
(copy-list l2)
:test-not nil))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nset-difference function
(define-test |nset-difference test=eql key=identity 1a|
(assert-equal '()
(nset-difference '() '())))
(define-test |nset-difference test=eql key=identity 1b|
(assert-equal '()
(nset-difference '()
'()
:test #'eql)))
(define-test |nset-difference test=eql key=identity 1c|
(assert-equal '()
(nset-difference '()
'()
:test 'eql)))
(define-test |nset-difference test=eql key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)))))
(define-test |nset-difference test=eql key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:test #'eql))))
(define-test |nset-difference test=eql key=identity 2c|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:test 'eql))))
(define-test |nset-difference test=eql key=identity 3a|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 200 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)))))
(define-test |nset-difference test=eql key=identity 3b|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 200 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:test #'eql))))
(define-test |nset-difference test=eql key=identity 3c|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 200 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:test 'eql))))
(define-test |nset-difference test=eql key=nil 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:key nil))))
(define-test |nset-difference test=eq key=identity 1|
(assert-equal '()
(nset-difference '()
'()
:test #'eq)))
(define-test |nset-difference test=eq key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal 1
(length (nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))
(assert-eq (car l1)
(car (nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))))
(define-test |nset-difference test=eq key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal 1
(length (nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'eq)))
(assert-eq (car l1)
(car (nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'eq)))))
(define-test |nset-difference test=eq key=identity 3|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal 1
(length (nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))
(assert-eq (car l1)
(car (nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))))
(define-test |nset-difference test=equal key=identity 1|
(assert-equal '()
(nset-difference '()
'()
:test #'equal)))
(define-test |nset-difference test=equal key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equal))))
(define-test |nset-difference test=equal key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'equal))))
(define-test |nset-difference test=equal key=identity 3|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equal))))
(define-test |nset-difference test=equalp key=identity 1|
(assert-equal '()
(nset-difference '()
'()
:test #'equalp)))
(define-test |nset-difference test=equalp key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 20 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equalp))))
(define-test |nset-difference test=equalp key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 20 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'equalp))))
(define-test |nset-difference test=equalp key=identity 3a|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 200 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equalp))))
(define-test |nset-difference test=equalp key=identity 3b|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 200 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equalp))))
(define-test |nset-difference test=other key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 1 below 20 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:test #'>))))
(define-test |nset-difference test-not=other key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 1 below 20 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:test-not #'<=))))
(define-test |nset-difference test=eql key=other 1a|
(assert-equal '()
(nset-difference '()
'()
:key #'car)))
(define-test |nset-difference test=eql key=other 1b|
(assert-equal '()
(nset-difference '()
'()
:key #'car
:test #'eql)))
(define-test |nset-difference test=eql key=other 1c|
(assert-equal '()
(nset-difference '()
'()
:key #'car
:test 'eql)))
(define-test |nset-difference test=eql key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car))))
(define-test |nset-difference test=eql key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car
:test #'eql))))
(define-test |nset-difference test=eql key=other 2c|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car
:test 'eql))))
(define-test |nset-difference test=eql key=other 3a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car))))
(define-test |nset-difference test=eql key=other 3b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car
:test #'eql))))
(define-test |nset-difference test=eql key=other 3c|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car
:test 'eql))))
(define-test |nset-difference test=eq key=other 1|
(assert-equal '()
(nset-difference '()
'()
:key #'car
:test #'eq)))
(define-test |nset-difference test=eq key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal 1
(length (nset-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))
(assert-eq (car l1)
(car (nset-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))))
(define-test |nset-difference test=eq key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal 1
(length (nset-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test 'eq)))
(assert-eq (car l1)
(car (nset-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test 'eq)))))
(define-test |nset-difference test=eq key=other 3|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal 1
(length (nset-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))
(assert-eq (car l1)
(car (nset-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))))
(define-test |nset-difference test=equal key=other 1|
(assert-equal '()
(nset-difference '()
'()
:key #'car
:test #'equal)))
(define-test |nset-difference test=equal key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal '(((1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equal))))
(define-test |nset-difference test=equal key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal '(((1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test 'equal))))
(define-test |nset-difference test=equal key=other 3|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 200 collect (list (list i)))))
(assert-equal '(((1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equal))))
(define-test |nset-difference test=equalp key=other 1|
(assert-equal '()
(nset-difference '()
'()
:key #'car
:test #'equalp)))
(define-test |nset-difference test=equalp key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 20 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equalp))))
(define-test |nset-difference test=equalp key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 20 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test 'equalp))))
(define-test |nset-difference test=equalp key=other 3a|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 200 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equalp))))
(define-test |nset-difference test=equalp key=other 3b|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 200 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test 'equalp))))
(define-test |nset-difference test=other key=other 1|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 1 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car
:test #'>))))
(define-test |nset-difference test-not=other key=other 1|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 1 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car
:test-not #'<=))))
(define-test |nset-difference test=other test-not=other 1|
(assert-error 'error
(nset-difference '(1 2 3) '(2 3 4)
:test #'eql
:test-not #'eql)))
(define-test |nset-difference test=nil key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-error 'error
(nset-difference (copy-list l1)
(copy-list l2)
:test nil))))
(define-test |nset-difference test-not=nil key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-error 'error
(nset-difference (copy-list l1)
(copy-list l2)
:test-not nil))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the adjoin function
(define-test |adjoin test=eql key=identity 1a|
(assert-equal '(1)
(adjoin 1 '())))
(define-test |adjoin test=eql key=identity 1b|
(assert-equal '(1)
(adjoin 1 '() :test #'eql)))
(define-test |adjoin test=eql key=identity 1c|
(assert-equal '(1)
(adjoin 1 '() :test 'eql)))
(define-test |adjoin test=eql key=identity 2a|
(assert-equal '(1 2)
(adjoin 1 '(2))))
(define-test |adjoin test=eql key=identity 2b|
(assert-equal '(1 2)
(adjoin 1 '(2) :test #'eql)))
(define-test |adjoin test=eql key=identity 2c|
(assert-equal '(1 2)
(adjoin 1 '(2) :test 'eql)))
(define-test |adjoin test=eql key=identity 3a|
(assert-equal '(2 1)
(adjoin 1 '(2 1))))
(define-test |adjoin test=eql key=identity 3b|
(assert-equal '(2 1)
(adjoin 1 '(2 1) :test #'eql)))
(define-test |adjoin test=eql key=identity 3c|
(assert-equal '(2 1)
(adjoin 1 '(2 1) :test 'eql)))
(define-test |adjoin test=eql key=nil 3b|
(assert-equal '(2 1)
(adjoin 1 '(2 1) :key nil)))
(define-test |adjoin test=eq key=identity 1a|
(assert-equal '(a)
(adjoin 'a '() :test #'eq)))
(define-test |adjoin test=eq key=identity 1b|
(assert-equal '(a)
(adjoin 'a '() :test 'eq)))
(define-test |adjoin test=eq key=identity 2a|
(assert-equal '(a b)
(adjoin 'a '(b) :test #'eq)))
(define-test |adjoin test=eq key=identity 2b|
(assert-equal '(a b)
(adjoin 'a '(b) :test 'eq)))
(define-test |adjoin test=eq key=identity 3a|
(assert-equal '(b a)
(adjoin 'a '(b a) :test #'eq)))
(define-test |adjoin test=eq key=identity 3b|
(assert-equal '(b a)
(adjoin 'a '(b a) :test 'eq)))
(define-test |adjoin test=other key=identity 1|
(assert-equal '(1 2)
(adjoin 1 '(2) :test #'=)))
(define-test |adjoin test=other key=identity 2|
(assert-equal '(2 1)
(adjoin 1 '(2 1) :test #'=)))
(define-test |adjoin test-not=other key=identity 1|
(assert-equal '(1 2)
(adjoin 1 '(2) :test-not #'/=)))
(define-test |adjoin test-not=other key=identity 2|
(assert-equal '(2 1)
(adjoin 1 '(2 1) :test-not #'/=)))
(define-test |adjoin test=eql key=other 1a|
(assert-equal '((1))
(adjoin '(1) '() :key #'car)))
(define-test |adjoin test=eql key=other 1b|
(assert-equal '((1))
(adjoin '(1) '() :key #'car :test #'eql)))
(define-test |adjoin test=eql key=other 1c|
(assert-equal '((1))
(adjoin '(1) '() :key #'car :test 'eql)))
(define-test |adjoin test=eql key=other 2a|
(assert-equal '((1) (2))
(adjoin '(1) '((2)) :key #'car)))
(define-test |adjoin test=eql key=other 2b|
(assert-equal '((1) (2))
(adjoin '(1) '((2)) :key #'car :test #'eql)))
(define-test |adjoin test=eql key=other 2c|
(assert-equal '((1) (2))
(adjoin '(1) '((2)) :key #'car :test 'eql)))
(define-test |adjoin test=eql key=other 3a|
(assert-equal '((2) (1))
(adjoin '(1) '((2) (1)) :key #'car)))
(define-test |adjoin test=eql key=other 3b|
(assert-equal '((2) (1))
(adjoin '(1) '((2) (1)) :key #'car :test #'eql)))
(define-test |adjoin test=eql key=other 3c|
(assert-equal '((2) (1))
(adjoin '(1) '((2) (1)) :key #'car :test 'eql)))
(define-test |adjoin test=eq key=other 1a|
(assert-equal '((a))
(adjoin '(a) '() :key #'car :test #'eq)))
(define-test |adjoin test=eq key=other 1b|
(assert-equal '((a))
(adjoin '(a) '() :key #'car :test 'eq)))
(define-test |adjoin test=eq key=other 2a|
(assert-equal '((a) (b))
(adjoin '(a) '((b)) :key #'car :test #'eq)))
(define-test |adjoin test=eq key=other 2b|
(assert-equal '((a) (b))
(adjoin '(a) '((b)) :key #'car :test 'eq)))
(define-test |adjoin test=eq key=other 3a|
(assert-equal '((b) (a))
(adjoin '(a) '((b) (a)) :key #'car :test #'eq)))
(define-test |adjoin test=eq key=other 3b|
(assert-equal '((b) (a))
(adjoin '(a) '((b) (a)) :key #'car :test 'eq)))
(define-test |adjoin test=other key=other 1|
(assert-equal '((1) (2))
(adjoin '(1) '((2)) :key #'car :test #'=)))
(define-test |adjoin test=other key=other 2|
(assert-equal '((2) (1))
(adjoin '(1) '((2) (1)) :key #'car :test #'=)))
(define-test |adjoin test-not=other key=other 1|
(assert-equal '((1) (2))
(adjoin '(1) '((2)) :key #'car :test-not #'/=)))
(define-test |adjoin test-not=other key=other 2|
(assert-equal '((2) (1))
(adjoin '(1) '((2) (1)) :key #'car :test-not #'/=)))
(define-test |adjoin test=other test-not=other 1|
(assert-error 'error (adjoin 1 '() :test #'eql :test-not #'eql)))
(define-test |adjoin test=nil key=identity 3b|
(assert-error 'error
(adjoin 1 '(2 1) :test nil)))
(define-test |adjoin test-not=nil key=identity 3b|
(assert-error 'error
(adjoin 1 '(2 1) :test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the set-exclusiv-or function
(define-test |set-exclusive-or test=eql key=identity 1|
(assert-equal '()
(set-exclusive-or '() '())))
(define-test |set-exclusive-or test=eql key=identity 2a|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))))
#'<))))
(define-test |set-exclusive-or test=eql key=identity 2b|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test #'eql))
#'<))))
(define-test |set-exclusive-or test=eql key=identity 2c|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test 'eql))
#'<))))
(define-test |set-exclusive-or test=eql key=identity 3a|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))))
#'<))))
(define-test |set-exclusive-or test=eql key=identity 3b|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test #'eql))
#'<))))
(define-test |set-exclusive-or test=eql key=identity 3c|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test 'eql))
#'<))))
(define-test |set-exclusive-or test=eql key=nil 1|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:key nil))
#'<))))
(define-test |set-exclusive-or test=eq key=identity 2a|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:test #'eq))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eq key=identity 2b|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:test 'eq))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eq key=identity 3a|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:test #'eq))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eq key=identity 3b|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:test 'eq))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equal key=identity 2a|
(let ((l1 (loop for i from 2 to 10 collect (list i)))
(l2 (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test #'equal))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equal key=identity 2b|
(let ((l1 (loop for i from 2 to 10 collect (list i)))
(l2 (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test 'equal))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equal key=identity 3a|
(let ((l1 (loop for i from 2 to 50 collect (list i)))
(l2 (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test #'equal))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equal key=identity 3b|
(let ((l1 (loop for i from 2 to 50 collect (list i)))
(l2 (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test 'equal))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=identity 2a|
(let ((l1 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test #'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=identity 2b|
(let ((l1 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test 'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=identity 3a|
(let ((l1 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test #'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=identity 3b|
(let ((l1 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test 'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=other key=identity 1|
(assert-equal '()
(set-exclusive-or '() '() :test #'=)))
(define-test |set-exclusive-or test=other key=identity 2|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test '=))
#'<))))
(define-test |set-exclusive-or test=other key=identity 3|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test '=))
#'<))))
(define-test |set-exclusive-or test-not=other key=identity 2|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test-not '/=))
#'<))))
(define-test |set-exclusive-or test-not=other key=identity 3|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test-not '/=))
#'<))))
(define-test |set-exclusive-or test=eql key=other 1|
(assert-equal '()
(set-exclusive-or '() '() :key #'car)))
(define-test |set-exclusive-or test=eql key=other 2a|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eql key=other 2b|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test #'eql))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eql key=other 2c|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test 'eql))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eql key=other 3a|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eql key=other 3b|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test #'eql))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eql key=other 3c|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test 'eql))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eq key=other 2a|
(let ((l (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l)
(append l (list (list (list 1))))
:key #'car
:test #'eq))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=eq key=other 2b|
(let ((l (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l)
(append l (list (list (list 1))))
:key #'car
:test 'eq))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=eq key=other 3a|
(let ((l (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l)
(append l (list (list (list 1))))
:key #'car
:test #'eq))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=eq key=other 3b|
(let ((l (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l)
(append l (list (list (list 1))))
:key #'car
:test 'eq))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=equal key=other 2a|
(let ((l1 (loop for i from 2 to 10 collect (list (list i))))
(l2 (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l1)
(append l2 (list (list (list 1))))
:key #'car
:test #'equal))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=equal key=other 2b|
(let ((l1 (loop for i from 2 to 10 collect (list (list i))))
(l2 (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l1)
(append l2 (list (list (list 1))))
:key #'car
:test 'equal))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=equal key=other 3a|
(let ((l1 (loop for i from 2 to 50 collect (list (list i))))
(l2 (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l1)
(append l2 (list (list (list 1))))
:key #'car
:test #'equal))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=equal key=other 3b|
(let ((l1 (loop for i from 2 to 50 collect (list (list i))))
(l2 (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l1)
(append l2 (list (list (list 1))))
:key #'car
:test 'equal))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=equalp key=other 2a|
(let ((l1 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:key #'car
:test #'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=other 2b|
(let ((l1 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:key #'car
:test 'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=other 3a|
(let ((l1 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:key #'car
:test #'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=other 3b|
(let ((l1 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:key #'car
:test 'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=other key=other 1|
(assert-equal '()
(set-exclusive-or '() '() :test #'= :key #'car)))
(define-test |set-exclusive-or test=other key=other 2|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test '=))
#'<
:key #'car))))
(define-test |set-exclusive-or test=other key=other 3|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test '=))
#'<
:key #'car))))
(define-test |set-exclusive-or test-not=other key=other 2|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test-not '/=))
#'<
:key #'car))))
(define-test |set-exclusive-or test-not=other key=other 3|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test-not '/=))
#'<
:key #'car))))
(define-test |set-exclusive-or test=other test-not=other 1|
(assert-error 'error
(set-exclusive-or '() '() :test #'eql :test-not #'eql)))
(define-test |set-exclusive-or test=nil key=identity 1|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-error
'error
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test nil))
#'<))))
(define-test |set-exclusive-or test-not=nil key=identity 1|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-error
'error
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test-not nil))
#'<))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nset-exclusiv-or function
(define-test |nset-exclusive-or test=eql key=identity 1|
(assert-equal '()
(nset-exclusive-or '() '())))
(define-test |nset-exclusive-or test=eql key=identity 2a|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))))
#'<))))
(define-test |nset-exclusive-or test=eql key=identity 2b|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test #'eql))
#'<))))
(define-test |nset-exclusive-or test=eql key=identity 2c|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test 'eql))
#'<))))
(define-test |nset-exclusive-or test=eql key=identity 3a|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))))
#'<))))
(define-test |nset-exclusive-or test=eql key=identity 3b|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test #'eql))
#'<))))
(define-test |nset-exclusive-or test=eql key=identity 3c|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test 'eql))
#'<))))
(define-test |nset-exclusive-or test=eql key=nil 3b|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:key nil))
#'<))))
(define-test |nset-exclusive-or test=eq key=identity 2a|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:test #'eq))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eq key=identity 2b|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:test 'eq))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eq key=identity 3a|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:test #'eq))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eq key=identity 3b|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:test 'eq))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equal key=identity 2a|
(let ((l1 (loop for i from 2 to 10 collect (list i)))
(l2 (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test #'equal))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equal key=identity 2b|
(let ((l1 (loop for i from 2 to 10 collect (list i)))
(l2 (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test 'equal))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equal key=identity 3a|
(let ((l1 (loop for i from 2 to 50 collect (list i)))
(l2 (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test #'equal))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equal key=identity 3b|
(let ((l1 (loop for i from 2 to 50 collect (list i)))
(l2 (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test 'equal))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=identity 2a|
(let ((l1 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test #'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=identity 2b|
(let ((l1 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test 'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=identity 3a|
(let ((l1 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test #'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=identity 3b|
(let ((l1 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test 'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=other key=identity 1|
(assert-equal '()
(nset-exclusive-or '() '() :test #'=)))
(define-test |nset-exclusive-or test=other key=identity 2|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test '=))
#'<))))
(define-test |nset-exclusive-or test=other key=identity 3|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test '=))
#'<))))
(define-test |nset-exclusive-or test-not=other key=identity 2|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test-not '/=))
#'<))))
(define-test |nset-exclusive-or test-not=other key=identity 3|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test-not '/=))
#'<))))
(define-test |nset-exclusive-or test=eql key=other 1|
(assert-equal '()
(nset-exclusive-or '() '() :key #'car)))
(define-test |nset-exclusive-or test=eql key=other 2a|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eql key=other 2b|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test #'eql))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eql key=other 2c|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test 'eql))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eql key=other 3a|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eql key=other 3b|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test #'eql))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eql key=other 3c|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test 'eql))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eq key=other 2a|
(let ((l (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l))
(copy-list (append l (list (list (list 1)))))
:key #'car
:test #'eq))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=eq key=other 2b|
(let ((l (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l))
(copy-list (append l (list (list (list 1)))))
:key #'car
:test 'eq))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=eq key=other 3a|
(let ((l (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l))
(copy-list (append l (list (list (list 1)))))
:key #'car
:test #'eq))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=eq key=other 3b|
(let ((l (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l))
(copy-list (append l (list (list (list 1)))))
:key #'car
:test 'eq))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=equal key=other 2a|
(let ((l1 (loop for i from 2 to 10 collect (list (list i))))
(l2 (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l1))
(copy-list (append l2 (list (list (list 1)))))
:key #'car
:test #'equal))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=equal key=other 2b|
(let ((l1 (loop for i from 2 to 10 collect (list (list i))))
(l2 (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l1))
(copy-list (append l2 (list (list (list 1)))))
:key #'car
:test 'equal))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=equal key=other 3a|
(let ((l1 (loop for i from 2 to 50 collect (list (list i))))
(l2 (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l1))
(copy-list (append l2 (list (list (list 1)))))
:key #'car
:test #'equal))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=equal key=other 3b|
(let ((l1 (loop for i from 2 to 50 collect (list (list i))))
(l2 (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l1))
(copy-list (append l2 (list (list (list 1)))))
:key #'car
:test 'equal))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=equalp key=other 2a|
(let ((l1 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:key #'car
:test #'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=other 2b|
(let ((l1 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:key #'car
:test 'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=other 3a|
(let ((l1 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:key #'car
:test #'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=other 3b|
(let ((l1 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:key #'car
:test 'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=other key=other 1|
(assert-equal '()
(nset-exclusive-or '() '() :test #'= :key #'car)))
(define-test |nset-exclusive-or test=other key=other 2|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test '=))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=other key=other 3|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test '=))
#'<
:key #'car))))
(define-test |nset-exclusive-or test-not=other key=other 2|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test-not '/=))
#'<
:key #'car))))
(define-test |nset-exclusive-or test-not=other key=other 3|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test-not '/=))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=other test-not=other 1|
(assert-error 'error
(nset-exclusive-or '() '() :test #'eql :test-not #'eql)))
(define-test |nset-exclusive-or test=nil key=identity 3b|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-error
'error
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test nil))
#'<))))
(define-test |nset-exclusive-or test-not=nil key=identity 3b|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-error
'error
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test-not nil))
#'<))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the subsetp function
(define-test |subsetp test=eql key=identity 1a|
(assert-true (subsetp '()
'())))
(define-test |subsetp test=eql key=identity 1b|
(assert-true (subsetp '()
'()
:test #'eql)))
(define-test |subsetp test=eql key=identity 1c|
(assert-true (subsetp '()
'()
:test 'eql)))
(define-test |subsetp test=eql key=identity 2a|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-true (subsetp l1
l2))))
(define-test |subsetp test=eql key=identity 2b|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-true (subsetp l1
l2
:test #'eql))))
(define-test |subsetp test=eql key=identity 2c|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-true (subsetp l1
l2
:test 'eql))))
(define-test |subsetp test=eql key=identity 3a|
(let ((l1 (loop for i from 1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-true (subsetp l1
l2))))
(define-test |subsetp test=eql key=identity 3b|
(let ((l1 (loop for i from 1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-true (subsetp l1
l2
:test #'eql))))
(define-test |subsetp test=eql key=identity 3c|
(let ((l1 (loop for i from 1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-true (subsetp l1
l2
:test 'eql))))
(define-test |subsetp test=eql key=identity 4a|
(let ((l1 (loop for i from -1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-false (subsetp l1
l2))))
(define-test |subsetp test=eql key=identity 4b|
(let ((l1 (loop for i from -1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-false (subsetp l1
l2
:test #'eql))))
(define-test |subsetp test=eql key=identity 4c|
(let ((l1 (loop for i from -1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-false (subsetp l1
l2
:test 'eql))))
(define-test |subsetp test=eql key=identity 5a|
(let ((l1 (loop for i from -1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-false (subsetp l1
l2))))
(define-test |subsetp test=eql key=identity 5b|
(let ((l1 (loop for i from -1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-false (subsetp l1
l2
:test #'eql))))
(define-test |subsetp test=eql key=identity 5c|
(let ((l1 (loop for i from -1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-false (subsetp l1
l2
:test 'eql))))
(define-test |subsetp test=eql key=nil 1|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-true (subsetp l1
l2
:key nil))))
(define-test |subsetp test=eq key=identity 2a|
(let ((l (loop repeat 10 collect (make-array 1 :initial-element 1))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:test #'eq))))
(define-test |subsetp test=eq key=identity 2b|
(let ((l (loop repeat 10 collect (make-array 1 :initial-element 1))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:test 'eq))))
(define-test |subsetp test=eq key=identity 3a|
(let ((l (loop repeat 50 collect (make-array 1 :initial-element 1))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:test #'eq))))
(define-test |subsetp test=eq key=identity 3b|
(let ((l (loop repeat 50 collect (make-array 1 :initial-element 1))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:test 'eq))))
(define-test |subsetp test=eq key=identity 4a|
(let ((l (loop repeat 10 collect (make-array 1 :initial-element 1))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:test #'eq))))
(define-test |subsetp test=eq key=identity 4b|
(let ((l (loop repeat 10 collect (make-array 1 :initial-element 1))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:test 'eq))))
(define-test |subsetp test=eq key=identity 5a|
(let ((l (loop repeat 50 collect (make-array 1 :initial-element 1))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:test #'eq))))
(define-test |subsetp test=eq key=identity 5b|
(let ((l (loop repeat 50 collect (make-array 1 :initial-element 1))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:test 'eq))))
(define-test |subsetp test=equal key=identity 2a|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:test #'equal))))
(define-test |subsetp test=equal key=identity 2b|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:test 'equal))))
(define-test |subsetp test=equal key=identity 3a|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:test #'equal))))
(define-test |subsetp test=equal key=identity 3b|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:test 'equal))))
(define-test |subsetp test=equal key=identity 4a|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:test #'equal))))
(define-test |subsetp test=equal key=identity 4b|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:test 'equal))))
(define-test |subsetp test=equal key=identity 5a|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:test #'equal))))
(define-test |subsetp test=equal key=identity 5b|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:test 'equal))))
(define-test |subsetp test=equalp key=identity 2a|
(let ((l1 (loop for i from 1 to 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 10 to 0 collect (make-array 1 :initial-element i))))
(assert-true (subsetp l1
l2
:test #'equalp))))
(define-test |subsetp test=equalp key=identity 2b|
(let ((l1 (loop for i from 1 to 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 10 to 0 collect (make-array 1 :initial-element i))))
(assert-true (subsetp l1
l2
:test 'equalp))))
(define-test |subsetp test=equalp key=identity 3a|
(let ((l1 (loop for i from 1 to 50 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 50 to 0 collect (make-array 1 :initial-element i))))
(assert-true (subsetp l1
l2
:test #'equalp))))
(define-test |subsetp test=equalp key=identity 3b|
(let ((l1 (loop for i from 1 to 50 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 50 to 0 collect (make-array 1 :initial-element i))))
(assert-true (subsetp l1
l2
:test 'equalp))))
(define-test |subsetp test=equalp key=identity 4a|
(let ((l1 (loop for i from -1 to 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 10 to 0 collect (make-array 1 :initial-element i))))
(assert-false (subsetp l1
l2
:test #'equalp))))
(define-test |subsetp test=equalp key=identity 4b|
(let ((l1 (loop for i from -1 to 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 10 to 0 collect (make-array 1 :initial-element i))))
(assert-false (subsetp l1
l2
:test 'equalp))))
(define-test |subsetp test=equalp key=identity 5a|
(let ((l1 (loop for i from -1 to 50 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 50 to 0 collect (make-array 1 :initial-element i))))
(assert-false (subsetp l1
l2
:test #'equalp))))
(define-test |subsetp test=equalp key=identity 5b|
(let ((l1 (loop for i from -1 to 50 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 50 to 0 collect (make-array 1 :initial-element i))))
(assert-false (subsetp l1
l2
:test 'equalp))))
(define-test |subsetp test=other key=identity 2b|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-true (subsetp l1
l2
:test #'=))))
(define-test |subsetp test=other key=identity 3b|
(let ((l1 (loop for i from 1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-true (subsetp l1
l2
:test #'=))))
(define-test |subsetp test=other key=identity 4b|
(let ((l1 (loop for i from -1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-false (subsetp l1
l2
:test #'=))))
(define-test |subsetp test=other key=identity 5b|
(let ((l1 (loop for i from -1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-false (subsetp l1
l2
:test #'=))))
(define-test |subsetp test-not=other key=identity 2b|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-true (subsetp l1
l2
:test-not #'/=))))
(define-test |subsetp test-not=other key=identity 3b|
(let ((l1 (loop for i from 1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-true (subsetp l1
l2
:test-not #'/=))))
(define-test |subsetp test-not=other key=identity 4b|
(let ((l1 (loop for i from -1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-false (subsetp l1
l2
:test-not #'/=))))
(define-test |subsetp test-not=other key=identity 5b|
(let ((l1 (loop for i from -1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-false (subsetp l1
l2
:test-not #'/=))))
(define-test |subsetp test=eql key=other 1a|
(assert-true (subsetp '()
'()
:key #'car)))
(define-test |subsetp test=eql key=other 1b|
(assert-true (subsetp '()
'()
:key #'car
:test #'eql)))
(define-test |subsetp test=eql key=other 1c|
(assert-true (subsetp '()
'()
:key #'car
:test 'eql)))
(define-test |subsetp test=eql key=other 2a|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car))))
(define-test |subsetp test=eql key=other 2b|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test #'eql))))
(define-test |subsetp test=eql key=other 2c|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test 'eql))))
(define-test |subsetp test=eql key=other 3a|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car))))
(define-test |subsetp test=eql key=other 3b|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test #'eql))))
(define-test |subsetp test=eql key=other 3c|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test 'eql))))
(define-test |subsetp test=eql key=other 4a|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car))))
(define-test |subsetp test=eql key=other 4b|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test #'eql))))
(define-test |subsetp test=eql key=other 4c|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test 'eql))))
(define-test |subsetp test=eql key=other 5a|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car))))
(define-test |subsetp test=eql key=other 5b|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test #'eql))))
(define-test |subsetp test=eql key=other 5c|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test 'eql))))
(define-test |subsetp test=eq key=other 2a|
(let ((l (loop repeat 10 collect (list (make-array 1 :initial-element 1)))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:key #'car
:test #'eq))))
(define-test |subsetp test=eq key=other 2b|
(let ((l (loop repeat 10 collect (list (make-array 1 :initial-element 1)))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:key #'car
:test 'eq))))
(define-test |subsetp test=eq key=other 3a|
(let ((l (loop repeat 50 collect (list (make-array 1 :initial-element 1)))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:key #'car
:test #'eq))))
(define-test |subsetp test=eq key=other 3b|
(let ((l (loop repeat 50 collect (list (make-array 1 :initial-element 1)))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:key #'car
:test 'eq))))
(define-test |subsetp test=eq key=other 4a|
(let ((l (loop repeat 10 collect (list (make-array 1 :initial-element 1)))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:key #'car
:test #'eq))))
(define-test |subsetp test=eq key=other 4b|
(let ((l (loop repeat 10 collect (list (make-array 1 :initial-element 1)))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:key #'car
:test 'eq))))
(define-test |subsetp test=eq key=other 5a|
(let ((l (loop repeat 50 collect (list (make-array 1 :initial-element 1)))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:key #'car
:test #'eq))))
(define-test |subsetp test=eq key=other 5b|
(let ((l (loop repeat 50 collect (list (make-array 1 :initial-element 1)))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:key #'car
:test 'eq))))
(define-test |subsetp test=equal key=other 2a|
(let ((l1 (loop for i from 1 to 10 collect (list (list i))))
(l2 (loop for i downfrom 10 to 0 collect (list (list i)))))
(assert-true (subsetp l1
l2
:key #'car
:test #'equal))))
(define-test |subsetp test=equal key=other 2b|
(let ((l1 (loop for i from 1 to 10 collect (list (list i))))
(l2 (loop for i downfrom 10 to 0 collect (list (list i)))))
(assert-true (subsetp l1
l2
:key #'car
:test 'equal))))
(define-test |subsetp test=equal key=other 3a|
(let ((l1 (loop for i from 1 to 50 collect (list (list i))))
(l2 (loop for i downfrom 50 to 0 collect (list (list i)))))
(assert-true (subsetp l1
l2
:key #'car
:test #'equal))))
(define-test |subsetp test=equal key=other 3b|
(let ((l1 (loop for i from 1 to 50 collect (list (list i))))
(l2 (loop for i downfrom 50 to 0 collect (list (list i)))))
(assert-true (subsetp l1
l2
:key #'car
:test 'equal))))
(define-test |subsetp test=equal key=other 4a|
(let ((l1 (loop for i from -1 to 10 collect (list (list i))))
(l2 (loop for i downfrom 10 to 0 collect (list (list i)))))
(assert-false (subsetp l1
l2
:key #'car
:test #'equal))))
(define-test |subsetp test=equal key=other 4b|
(let ((l1 (loop for i from -1 to 10 collect (list (list i))))
(l2 (loop for i downfrom 10 to 0 collect (list (list i)))))
(assert-false (subsetp l1
l2
:key #'car
:test 'equal))))
(define-test |subsetp test=equal key=other 5a|
(let ((l1 (loop for i from -1 to 50 collect (list (list i))))
(l2 (loop for i downfrom 50 to 0 collect (list (list i)))))
(assert-false (subsetp l1
l2
:key #'car
:test #'equal))))
(define-test |subsetp test=equal key=other 5b|
(let ((l1 (loop for i from -1 to 50 collect (list (list i))))
(l2 (loop for i downfrom 50 to 0 collect (list (list i)))))
(assert-false (subsetp l1
l2
:key #'car
:test 'equal))))
(define-test |subsetp test=equalp key=other 2a|
(let ((l1 (loop for i from 1 to 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 10 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-true (subsetp l1
l2
:key #'car
:test #'equalp))))
(define-test |subsetp test=equalp key=other 2b|
(let ((l1 (loop for i from 1 to 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 10 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-true (subsetp l1
l2
:key #'car
:test 'equalp))))
(define-test |subsetp test=equalp key=other 3a|
(let ((l1 (loop for i from 1 to 50 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 50 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-true (subsetp l1
l2
:key #'car
:test #'equalp))))
(define-test |subsetp test=equalp key=other 3b|
(let ((l1 (loop for i from 1 to 50 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 50 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-true (subsetp l1
l2
:key #'car
:test 'equalp))))
(define-test |subsetp test=equalp key=other 4a|
(let ((l1 (loop for i from -1 to 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 10 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-false (subsetp l1
l2
:key #'car
:test #'equalp))))
(define-test |subsetp test=equalp key=other 4b|
(let ((l1 (loop for i from -1 to 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 10 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-false (subsetp l1
l2
:key #'car
:test 'equalp))))
(define-test |subsetp test=equalp key=other 5a|
(let ((l1 (loop for i from -1 to 50 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 50 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-false (subsetp l1
l2
:key #'car
:test #'equalp))))
(define-test |subsetp test=equalp key=other 5b|
(let ((l1 (loop for i from -1 to 50 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 50 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-false (subsetp l1
l2
:key #'car
:test 'equalp))))
(define-test |subsetp test=other key=other 2b|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test #'=))))
(define-test |subsetp test=other key=other 3b|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test #'=))))
(define-test |subsetp test=other key=other 4b|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test #'=))))
(define-test |subsetp test=other key=other 5b|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test #'=))))
(define-test |subsetp test-not=other key=other 2b|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test-not #'/=))))
(define-test |subsetp test-not=other key=other 3b|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test-not #'/=))))
(define-test |subsetp test-not=other key=other 4b|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test-not #'/=))))
(define-test |subsetp test-not=other key=other 5b|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test-not #'/=))))
(define-test |subsetp test=other test-not=other 1|
(assert-error 'error
(subsetp '() '() :test #'eql :test-not #'eql)))
(define-test |subsetp test=nil key=identity 1|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-error 'error
(subsetp l1
l2
:test nil))))
(define-test |subsetp test-not=nil key=identity 1|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-error 'error
(subsetp l1
l2
:test-not nil))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the pushnew macro
(define-test |pushnew test=eql key=identity 1a|
(let ((list '()))
(assert-equal '(1)
(pushnew 1 list))
(assert-equal '(1)
list)))
(define-test |pushnew test=eql key=identity 1b|
(let ((list '()))
(assert-equal '(1)
(pushnew 1 list :test #'eql))
(assert-equal '(1)
list)))
(define-test |pushnew test=eql key=identity 1c|
(let ((list '()))
(assert-equal '(1)
(pushnew 1 list :test 'eql))
(assert-equal '(1)
list)))
(define-test |pushnew test=eql key=identity 2a|
(let ((list '(1)))
(assert-equal '(1)
(pushnew 1 list))
(assert-equal '(1)
list)))
(define-test |pushnew test=eql key=identity 2b|
(let ((list '(1)))
(assert-equal '(1)
(pushnew 1 list :test #'eql))
(assert-equal '(1)
list)))
(define-test |pushnew test=eql key=identity 2c|
(let ((list '(1)))
(assert-equal '(1)
(pushnew 1 list :test 'eql))
(assert-equal '(1)
list)))
(define-test |pushnew test=eql key=identity 3a|
(let ((list '(2)))
(assert-equal '(1 2)
(pushnew 1 list))
(assert-equal '(1 2)
list)))
(define-test |pushnew test=eql key=identity 3b|
(let ((list '(2)))
(assert-equal '(1 2)
(pushnew 1 list :test #'eql))
(assert-equal '(1 2)
list)))
(define-test |pushnew test=eql key=identity 3c|
(let ((list '(2)))
(assert-equal '(1 2)
(pushnew 1 list :test 'eql))
(assert-equal '(1 2)
list)))
(define-test |pushnew test=eql key=identity 4a|
(let ((list '(2 1)))
(assert-equal '(2 1)
(pushnew 1 list))
(assert-equal '(2 1)
list)))
(define-test |pushnew test=eql key=identity 4b|
(let ((list '(2 1)))
(assert-equal '(2 1)
(pushnew 1 list :test #'eql))
(assert-equal '(2 1)
list)))
(define-test |pushnew test=eql key=identity 4c|
(let ((list '(2 1)))
(assert-equal '(2 1)
(pushnew 1 list :test 'eql))
(assert-equal '(2 1)
list)))
(define-test |pushnew test=eql key=nil 3b|
(let ((list '(2)))
(assert-equal '(1 2)
(pushnew 1 list :key nil))
(assert-equal '(1 2)
list)))
(define-test |pushnew test=eq key=identity 1b|
(let ((list '()))
(assert-equal '(a)
(pushnew 'a list :test #'eq))
(assert-equal '(a)
list)))
(define-test |pushnew test=eq key=identity 1c|
(let ((list '()))
(assert-equal '(a)
(pushnew 'a list :test 'eq))
(assert-equal '(a)
list)))
(define-test |pushnew test=eq key=identity 2b|
(let ((list '(a)))
(assert-equal '(a)
(pushnew 'a list :test #'eq))
(assert-equal '(a)
list)))
(define-test |pushnew test=eq key=identity 2c|
(let ((list '(a)))
(assert-equal '(a)
(pushnew 'a list :test 'eq))
(assert-equal '(a)
list)))
(define-test |pushnew test=eq key=identity 3b|
(let ((list '(b)))
(assert-equal '(a b)
(pushnew 'a list :test #'eq))
(assert-equal '(a b)
list)))
(define-test |pushnew test=eq key=identity 3c|
(let ((list '(b)))
(assert-equal '(a b)
(pushnew 'a list :test 'eq))
(assert-equal '(a b)
list)))
(define-test |pushnew test=eq key=identity 4b|
(let ((list '(b a)))
(assert-equal '(b a)
(pushnew 'a list :test #'eq))
(assert-equal '(b a)
list)))
(define-test |pushnew test=eq key=identity 4c|
(let ((list '(b a)))
(assert-equal '(b a)
(pushnew 'a list :test 'eq))
(assert-equal '(b a)
list)))
(define-test |pushnew test=eql key=other 1|
(let ((list '()))
(assert-equal '((1))
(pushnew '(1) list :key #'car))
(assert-equal '((1))
list)))
(define-test |pushnew test=eql key=other 2|
(let ((list '((1))))
(assert-equal '((1))
(pushnew '(1) list :key #'car))
(assert-equal '((1))
list)))
(define-test |pushnew test=eql key=other 3|
(let ((list '((2))))
(assert-equal '((1) (2))
(pushnew '(1) list :key #'car))
(assert-equal '((1) (2))
list)))
(define-test |pushnew test=eql key=other 4|
(let ((list '((2) (1))))
(assert-equal '((2) (1))
(pushnew '(1) list :key #'car))
(assert-equal '((2) (1))
list)))
(define-test |pushnew test=eq key=other 1|
(let ((list '()))
(assert-equal '((a))
(pushnew '(a) list :test #'eq :key #'car))
(assert-equal '((a))
list)))
(define-test |pushnew test=eq key=other 2|
(let ((list '((a))))
(assert-equal '((a))
(pushnew '(a) list :test #'eq :key #'car))
(assert-equal '((a))
list)))
(define-test |pushnew test=eq key=other 3|
(let ((list '((b))))
(assert-equal '((a) (b))
(pushnew '(a) list :test #'eq :key #'car))
(assert-equal '((a) (b))
list)))
(define-test |pushnew test=eq key=other 4|
(let ((list '((b) (a))))
(assert-equal '((b) (a))
(pushnew '(a) list :test #'eq :key #'car))
(assert-equal '((b) (a))
list)))
(define-test |pushnew test=other key=identity 1b|
(let ((list '()))
(assert-equal '(1)
(pushnew 1 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(1)
list)))
(define-test |pushnew test=other key=identity 2b|
(let ((list '(1)))
(assert-equal '(1 1)
(pushnew 1 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(1 1)
list)))
(define-test |pushnew test=other key=identity 3b|
(let ((list '(2)))
(assert-equal '(1 2)
(pushnew 1 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(1 2)
list)))
(define-test |pushnew test=other key=identity 4b|
(let ((list '(2 1)))
(assert-equal '(1 2 1)
(pushnew 1 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(1 2 1)
list)))
(define-test |pushnew test=other key=identity 5b|
(let ((list '(1)))
(assert-equal '(1)
(pushnew 2 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(1)
list)))
(define-test |pushnew test=other key=identity 6b|
(let ((list '(2)))
(assert-equal '(2 2)
(pushnew 2 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(2 2)
list)))
(define-test |pushnew test=other key=identity 7b|
(let ((list '(2 1)))
(assert-equal '(2 1)
(pushnew 2 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(2 1)
list)))
(define-test |pushnew test=other key=other 3b|
(let ((list '((2))))
(assert-equal '((1) (2))
(pushnew '(1) list
:test (lambda (x y) (= (1- x) y))
:key #'car))
(assert-equal '((1) (2))
list)))
(define-test |pushnew test=other key=other 4b|
(let ((list '((2) (1))))
(assert-equal '((1) (2) (1))
(pushnew '(1) list
:test (lambda (x y) (= (1- x) y))
:key #'car))
(assert-equal '((1) (2) (1))
list)))
(define-test |pushnew test=other key=other 5b|
(let ((list '((1))))
(assert-equal '((1))
(pushnew '(2) list
:test (lambda (x y) (= (1- x) y))
:key #'car))
(assert-equal '((1))
list)))
(define-test |pushnew test=other key=other 6b|
(let ((list '((2))))
(assert-equal '((2) (2))
(pushnew '(2) list
:test (lambda (x y) (= (1- x) y))
:key #'car))
(assert-equal '((2) (2))
list)))
(define-test |pushnew test=other key=other 7b|
(let ((list '((2) (1))))
(assert-equal '((2) (1))
(pushnew '(2) list
:test (lambda (x y) (= (1- x) y))
:key #'car))
(assert-equal '((2) (1))
list)))
(define-test |pushnew test-not=other key=identity 1b|
(let ((list '()))
(assert-equal '(1)
(pushnew 1 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(1)
list)))
(define-test |pushnew test-not=other key=identity 2b|
(let ((list '(1)))
(assert-equal '(1 1)
(pushnew 1 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(1 1)
list)))
(define-test |pushnew test-not=other key=identity 3b|
(let ((list '(2)))
(assert-equal '(1 2)
(pushnew 1 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(1 2)
list)))
(define-test |pushnew test-not=other key=identity 4b|
(let ((list '(2 1)))
(assert-equal '(1 2 1)
(pushnew 1 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(1 2 1)
list)))
(define-test |pushnew test-not=other key=identity 5b|
(let ((list '(1)))
(assert-equal '(1)
(pushnew 2 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(1)
list)))
(define-test |pushnew test-not=other key=identity 6b|
(let ((list '(2)))
(assert-equal '(2 2)
(pushnew 2 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(2 2)
list)))
(define-test |pushnew test-not=other key=identity 7b|
(let ((list '(2 1)))
(assert-equal '(2 1)
(pushnew 2 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(2 1)
list)))
(define-test |pushnew test-not=other key=other 3b|
(let ((list '((2))))
(assert-equal '((1) (2))
(pushnew '(1) list
:test-not (lambda (x y) (/= (1- x) y))
:key #'car))
(assert-equal '((1) (2))
list)))
(define-test |pushnew test-not=other key=other 4b|
(let ((list '((2) (1))))
(assert-equal '((1) (2) (1))
(pushnew '(1) list
:test-not (lambda (x y) (/= (1- x) y))
:key #'car))
(assert-equal '((1) (2) (1))
list)))
(define-test |pushnew test-not=other key=other 5b|
(let ((list '((1))))
(assert-equal '((1))
(pushnew '(2) list
:test-not (lambda (x y) (/= (1- x) y))
:key #'car))
(assert-equal '((1))
list)))
(define-test |pushnew test-not=other key=other 6b|
(let ((list '((2))))
(assert-equal '((2) (2))
(pushnew '(2) list
:test-not (lambda (x y) (/= (1- x) y))
:key #'car))
(assert-equal '((2) (2))
list)))
(define-test |pushnew test-not=other key=other 7b|
(let ((list '((2) (1))))
(assert-equal '((2) (1))
(pushnew '(2) list
:test-not (lambda (x y) (/= (1- x) y))
:key #'car))
(assert-equal '((2) (1))
list)))
(define-test |pushnew test=other test-not=other 1|
(let ((fun nil)
(warned nil))
(handler-bind ((warning (lambda (condition)
(setf warned t)
(muffle-warning condition))))
(setf fun
(compile nil '(lambda ()
(declare (special list))
(pushnew '2 list
:test #'eql
:test-not #'eql)))))
(assert-true warned)
(assert-error 'error (funcall fun))))
(define-test |pushnew test=nil key=identity 3b|
(let ((list '(2)))
(assert-error 'error
(pushnew 1 list :test nil))))
(define-test |pushnew test-not=nil key=identity 3b|
(let ((list '(2)))
(assert-error 'error
(pushnew 1 list :test-not nil))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the POP macro.
(define-test |pop 1|
(let ((var (list 1)))
(assert-equal 1
(pop var))
(assert-equal '()
var)))
(define-test |pop 2|
(let ((var (list 1 2)))
(assert-equal 1
(pop var))
(assert-equal '(2)
var)))
(define-test |pop 3|
(let ((list (list (list 1))))
(assert-equal 1
(pop (car list)))
(assert-equal '(())
list)))
(define-test |pop 4|
(let ((list (list (list 1 2))))
(assert-equal 1
(pop (car list)))
(assert-equal '((2))
list)))
(define-test |pop error 1|
(let ((list (copy-tree '(1 . 2))))
(assert-equal 1
(pop list))
(assert-error 'type-error
(pop list))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the NSUBST function.
(define-test nsubst.1
(assert-equal '(a (c))
(nsubst 'c '(b) (copy-tree '(a ((b)))) :test-not (complement #'equal))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the GETF function.
(define-test |getf 1|
(assert-equal nil
(getf '() 'a)))
(define-test |getf 2|
(assert-equal 1
(getf '(a 1) 'a)))
(define-test |getf 3|
(assert-equal 1
(getf '(b 2 a 1) 'a)))
(define-test |getf 4|
(assert-equal nil
(getf '(b 2 a 1) 'c)))
(define-test |getf error 1|
(assert-error 'type-error
(getf '(b 2 a) 'c)))
(define-test |getf error 2|
(assert-error 'type-error
(getf 1 'c)))
(define-test |getf error 3|
(assert-error 'type-error
(getf '(b 2 a 3 . f) 'c)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the GET-PROPERTIES function.
(define-test |get-properties 1|
(multiple-value-bind (indicator value tail)
(get-properties '() '(a))
(assert-equal nil indicator)
(assert-equal nil value)
(assert-equal nil tail)))
(define-test |get-properties 2|
(multiple-value-bind (indicator value tail)
(get-properties '(a 1) '(b a))
(assert-equal 'a indicator)
(assert-equal 1 value)
(assert-equal '(a 1) tail)))
(define-test |get-properties 3|
(multiple-value-bind (indicator value tail)
(get-properties '(b 2 a 1) '(c a d))
(assert-equal 'a indicator)
(assert-equal 1 value)
(assert-equal '(a 1) tail)))
(define-test |get-properties 4|
(multiple-value-bind (indicator value tail)
(get-properties '(b 2 a 1) '(c d e))
(assert-equal nil indicator)
(assert-equal nil value)
(assert-equal nil tail)))
(define-test |get-properties 5|
(multiple-value-bind (indicator value tail)
(get-properties '(b 2 a 1 e 10) '(c a d))
(assert-equal 'a indicator)
(assert-equal 1 value)
(assert-equal '(a 1 e 10) tail)))
(define-test |get-properties error 1|
(assert-error 'type-error
(get-properties '(b 2 a) '(c d e))))
(define-test |get-properties error 2|
(assert-error 'type-error
(get-properties '(b 2 a 3 . f) '(c d e))))
(define-test |get-properties error 3|
(assert-error 'type-error
(get-properties 1 '(c d e))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the SETF expander for GETF.
(define-test |(setf getf) 1|
(let ((list (copy-list '(:a 0 :c 1 :e 2 :c 3))))
(assert-equal 4
(setf (getf list :c) 4))
(assert-equal '(:a 0 :c 4 :e 2 :c 3)
list)))
(define-test |(setf getf) 2|
(let ((list (copy-list '(:a 0 :c 1 :e 2 :c 3)))
(thing 0))
(assert-equal 4
(setf (getf list :d (incf thing)) 4))
(assert-equal 4
(getf list :d))
(assert-equal 1 thing)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the REMF macro.
(define-test remf.1
(let ((list (copy-tree '(a 1 b 2 c 3))))
(assert-true (remf list 'c))
(assert-equal '(a 1 b 2)
list)))
|
63643
|
(cl:in-package #:sicl-cons-high-test)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Helper function to defeat the type inferencing of the
;;; compiler so there are no warnings.
;;; This function always returns true when given a proper list.
(defun twisted (list)
(if (null list)
t
(twisted (cdr list))))
(declaim (notinline twisted))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAAR function.
(define-test caar.1
(assert-equal 'a (caar '((a)))))
(define-test caar.error.1
(assert-error 'type-error (caar 'a)))
(define-test caar.error.2
(assert-error 'type-error (caar '(a))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADR function.
(define-test cdar.1
(assert-equal 'b (cdar '((a . b)))))
(define-test cdar.error.1
(assert-error 'type-error (cdar 'a)))
(define-test cdar.error.2
(assert-error 'type-error (cdar '(a . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADR function.
(define-test cadr.1
(assert-equal 'b (cadr '(a b))))
(define-test cadr.error.1
(assert-error 'type-error (cadr 'a)))
(define-test cadr.error.2
(assert-error 'type-error (cadr '(a . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDR function.
(define-test cddr.1
(assert-equal 'c (cddr '(a b . c))))
(define-test cddr.error.1
(assert-error 'type-error (cddr 'a)))
(define-test cddr.error.2
(assert-error 'type-error (cddr '(a . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAAAR function.
(define-test caaar.1
(assert-equal 'a (caaar '(((a))))))
(define-test caaar.error.1
(assert-error 'type-error (caaar 'a)))
(define-test caaar.error.2
(assert-error 'type-error (caaar '(a))))
(define-test caaar.error.3
(assert-error 'type-error (caaar '((a)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDAAR function.
(define-test cdaar.1
(assert-equal 'b (cdaar '(((a . b))))))
(define-test cdaar.error.1
(assert-error 'type-error (cdaar 'a)))
(define-test cdaar.error.2
(assert-error 'type-error (cdaar '(a))))
(define-test cdaar.error.3
(assert-error 'type-error (cdaar '((a . b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADAR function.
(define-test cadar.1
(assert-equal 'b (cadar (cons (cons 'a (cons 'b 'c)) 'd))))
(define-test cadar.error.1
(assert-error 'type-error (cadar 'a)))
(define-test cadar.error.2
(assert-error 'type-error (cadar '(a . b))))
(define-test cadar.error.3
(assert-error 'type-error (cadar '((a . c) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDAR function.
(define-test cddar.1
(assert-equal 'c (cddar (cons (cons 'a (cons 'b 'c)) 'd))))
(define-test cddar.error.1
(assert-error 'type-error (cddar 'a)))
(define-test cddar.error.2
(assert-error 'type-error (cddar '(a . b))))
(define-test cddar.error.3
(assert-error 'type-error (cddar '((a . b) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAADR function.
(define-test caadr.1
(assert-equal 'b (caadr (cons 'a (cons (cons 'b 'c) 'd)))))
(define-test caadr.error.1
(assert-error 'type-error (caadr 'a)))
(define-test caadr.error.2
(assert-error 'type-error (caadr '(a . b))))
(define-test caadr.error.3
(assert-error 'type-error (caadr '(a . (b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADDR function.
(define-test caddr.1
(assert-equal 'c (caddr (cons 'a (cons 'b (cons 'c 'd))))))
(define-test caddr.error.1
(assert-error 'type-error (caddr 'a)))
(define-test caddr.error.2
(assert-error 'type-error (caddr '(a . b))))
(define-test caddr.error.3
(assert-error 'type-error (caddr '(a c . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDADR function.
(define-test cdadr.1
(assert-equal 'c (cdadr (cons 'a (cons (cons 'b 'c) 'd)))))
(define-test cdadr.error.1
(assert-error 'type-error (cdadr 'a)))
(define-test cdadr.error.2
(assert-error 'type-error (cdadr '(a . b))))
(define-test cdadr.error.3
(assert-error 'type-error (cdadr '(a b . c))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDDR function.
(define-test cdddr.1
(assert-equal 'd (cdddr (cons 'a (cons 'b (cons 'c 'd))))))
(define-test cdddr.error.1
(assert-error 'type-error (cdddr 'a)))
(define-test cdddr.error.2
(assert-error 'type-error (cdddr '(a . b))))
(define-test cdddr.error.3
(assert-error 'type-error (cdddr '(a c . b))))
;;; Tree to be used for testing some c*r functions.
(defvar *cons-test-4*
(cons (cons (cons (cons 'a 'b)
(cons 'c 'd))
(cons (cons 'e 'f)
(cons 'g 'h)))
(cons (cons (cons 'i 'j)
(cons 'k 'l))
(cons (cons 'm 'n)
(cons 'o 'p)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAAAAR function.
(define-test caaaar.1
(assert-equal 'a (caaaar *cons-test-4*)))
(define-test caaaar.error.1
(assert-error 'type-error (caaaar 'a)))
(define-test caaaar.error.2
(assert-error 'type-error (caaaar '(a))))
(define-test caaaar.error.3
(assert-error 'type-error (caaaar '((a)))))
(define-test caaaar.error.4
(assert-error 'type-error (caaaar '(((a))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAAADR function.
(define-test caaadr.1
(assert-equal 'i (caaadr *cons-test-4*)))
(define-test caaadr.error.1
(assert-error 'type-error (caaadr 'a)))
(define-test caaadr.error.2
(assert-error 'type-error (caaadr '(a . b))))
(define-test caaadr.error.3
(assert-error 'type-error (caaadr '(a . (b)))))
(define-test caaadr.error.4
(assert-error 'type-error (caaadr '(a . ((b))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAADAR function.
(define-test caadar.1
(assert-equal 'e (caadar *cons-test-4*)))
(define-test caadar.error.1
(assert-error 'type-error (caadar 'a)))
(define-test caadar.error.2
(assert-error 'type-error (caadar '(a . b))))
(define-test caadar.error.3
(assert-error 'type-error (caadar '((a . c) . b))))
(define-test caadar.error.4
(assert-error 'type-error (caadar '((a . (c)) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAADDR function.
(define-test caaddr.1
(assert-equal 'm (caaddr *cons-test-4*)))
(define-test caaddr.error.1
(assert-error 'type-error (caaddr 'a)))
(define-test caaddr.error.2
(assert-error 'type-error (caaddr '(a . b))))
(define-test caaddr.error.3
(assert-error 'type-error (caaddr '(a c . b))))
(define-test caaddr.error.4
(assert-error 'type-error (caaddr '(a c . (b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADAAR function.
(define-test cadaar.1
(assert-equal 'c (cadaar *cons-test-4*)))
(define-test cadaar.error.1
(assert-error 'type-error (cadaar 'a)))
(define-test cadaar.error.2
(assert-error 'type-error (cadaar '(a))))
(define-test cadaar.error.3
(assert-error 'type-error (cadaar '((a . b)))))
(define-test cadaar.error.4
(assert-error 'type-error (cadaar '((a . (b))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADADR function.
(define-test cadadr.1
(assert-equal 'k (cadadr *cons-test-4*)))
(define-test cadadr.error.1
(assert-error 'type-error (cadadr 'a)))
(define-test cadadr.error.2
(assert-error 'type-error (cadadr '(a . b))))
(define-test cadadr.error.3
(assert-error 'type-error (cadadr '(a b . c))))
(define-test cadadr.error.4
(assert-error 'type-error (cadadr '(a (b . e) . c))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADDAR function.
(define-test caddar.1
(assert-equal 'g (caddar *cons-test-4*)))
(define-test caddar.error.1
(assert-error 'type-error (caddar 'a)))
(define-test caddar.error.2
(assert-error 'type-error (caddar '(a . b))))
(define-test caddar.error.3
(assert-error 'type-error (caddar '((a . b) . b))))
(define-test caddar.error.4
(assert-error 'type-error (caddar '((a b . c) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADDDR function.
(define-test cadddr.1
(assert-equal 'o (cadddr *cons-test-4*)))
(define-test cadddr.error.1
(assert-error 'type-error (cadddr 'a)))
(define-test cadddr.error.2
(assert-error 'type-error (cadddr '(a . b))))
(define-test cadddr.error.3
(assert-error 'type-error (cadddr '(a c . b))))
(define-test cadddr.error.4
(assert-error 'type-error (cadddr '(a c e . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDAAAR function.
(define-test cdaaar.1
(assert-equal 'b (cdaaar *cons-test-4*)))
(define-test cdaaar.error.1
(assert-error 'type-error (cdaaar 'a)))
(define-test cdaaar.error.2
(assert-error 'type-error (cdaaar '(a))))
(define-test cdaaar.error.3
(assert-error 'type-error (cdaaar '((a)))))
(define-test cdaaar.error.4
(assert-error 'type-error (cdaaar '(((a . b))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDAADR function.
(define-test cdaadr.1
(assert-equal 'j (cdaadr *cons-test-4*)))
(define-test cdaadr.error.1
(assert-error 'type-error (cdaadr 'a)))
(define-test cdaadr.error.2
(assert-error 'type-error (cdaadr '(a . b))))
(define-test cdaadr.error.3
(assert-error 'type-error (cdaadr '(a . (b)))))
(define-test cdaadr.error.4
(assert-error 'type-error (cdaadr '(a . ((b . c))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDADAR function.
(define-test cdadar.1
(assert-equal 'f (cdadar *cons-test-4*)))
(define-test cdadar.error.1
(assert-error 'type-error (cdadar 'a)))
(define-test cdadar.error.2
(assert-error 'type-error (cdadar '(a . b))))
(define-test cdadar.error.3
(assert-error 'type-error (cdadar '((a . c) . b))))
(define-test cdadar.error.4
(assert-error 'type-error (cdadar '((a . (c . d)) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDADDR function.
(define-test cdaddr.1
(assert-equal 'n (cdaddr *cons-test-4*)))
(define-test cdaddr.error.1
(assert-error 'type-error (cdaddr 'a)))
(define-test cdaddr.error.2
(assert-error 'type-error (cdaddr '(a . b))))
(define-test cdaddr.error.3
(assert-error 'type-error (cdaddr '(a c . b))))
(define-test cdaddr.error.4
(assert-error 'type-error (cdaddr '(a c b . d))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDAAR function.
(define-test cddaar.1
(assert-equal 'd (cddaar *cons-test-4*)))
(define-test cddaar.error.1
(assert-error 'type-error (cddaar 'a)))
(define-test cddaar.error.2
(assert-error 'type-error (cddaar '(a))))
(define-test cddaar.error.3
(assert-error 'type-error (cddaar '((a . b)))))
(define-test cddaar.error.4
(assert-error 'type-error (cddaar '((a . (b))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDADR function.
(define-test cddadr.1
(assert-equal 'l (cddadr *cons-test-4*)))
(define-test cddadr.error.1
(assert-error 'type-error (cddadr 'a)))
(define-test cddadr.error.2
(assert-error 'type-error (cddadr '(a . b))))
(define-test cddadr.error.3
(assert-error 'type-error (cddadr '(a b . c))))
(define-test cddadr.error.4
(assert-error 'type-error (cddadr '(a (b . e) . c))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDDAR function.
(define-test cdddar.1
(assert-equal 'h (cdddar *cons-test-4*)))
(define-test cdddar.error.1
(assert-error 'type-error (cdddar 'a)))
(define-test cdddar.error.2
(assert-error 'type-error (cdddar '(a . b))))
(define-test cdddar.error.3
(assert-error 'type-error (cdddar '((a . b) . b))))
(define-test cdddar.error.4
(assert-error 'type-error (cdddar '((a b . c) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDDDR function.
(define-test cddddr.1
(assert-equal 'p (cddddr *cons-test-4*)))
(define-test cddddr.error.1
(assert-error 'type-error (cddddr 'a)))
(define-test cddddr.error.2
(assert-error 'type-error (cddddr '(a . b))))
(define-test cddddr.error.3
(assert-error 'type-error (cddddr '(a c . b))))
(define-test cddddr.error.4
(assert-error 'type-error (cddddr '(a c e . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the FIRST function
(define-test first.1
(assert-equal nil (first nil)))
(define-test first.2
(assert-equal 1 (first '(1))))
(define-test first.3
(assert-equal 1 (first '(1 2))))
(define-test first.error.1
(assert-error 'type-error (first 1)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the SECOND function
(define-test second.1
(assert-equal nil (second nil)))
(define-test second.2
(assert-equal nil (second '(1))))
(define-test second.3
(assert-equal 1 (second '(0 1))))
(define-test second.4
(assert-equal 1 (second '(0 1 2))))
(define-test second.error.1
(assert-error 'type-error (second 1)))
(define-test second.error.2
(assert-error 'type-error (second '(0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the THIRD function.
(define-test third.1
(assert-equal nil (third nil)))
(define-test third.2
(assert-equal nil (third '(1))))
(define-test third.3
(assert-equal nil (third '(1 1))))
(define-test third.4
(assert-equal 1 (third '(0 0 1))))
(define-test third.5
(assert-equal 1 (third '(0 0 1 2))))
(define-test third.error.1
(assert-error 'type-error (third 1)))
(define-test third.error.2
(assert-error 'type-error (third '(0 . 1))))
(define-test third.error.3
(assert-error 'type-error (third '(0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the FOURTH function.
(define-test fourth.1
(assert-equal nil (fourth nil)))
(define-test fourth.2
(assert-equal nil (fourth '(1))))
(define-test fourth.3
(assert-equal nil (fourth '(1 1))))
(define-test fourth.4
(assert-equal nil (fourth '(1 1 1))))
(define-test fourth.5
(assert-equal 1 (fourth '(0 0 0 1))))
(define-test fourth.6
(assert-equal 1 (fourth '(0 0 0 1 2))))
(define-test fourth.error.1
(assert-error 'type-error (fourth 1)))
(define-test fourth.error.2
(assert-error 'type-error (fourth '(0 . 1))))
(define-test fourth.error.3
(assert-error 'type-error (fourth '(0 0 . 1))))
(define-test fourth.error.4
(assert-error 'type-error (fourth '(0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the FIFTH function.
(define-test fifth.1
(assert-equal nil (fifth nil)))
(define-test fifth.2
(assert-equal nil (fifth '(1))))
(define-test fifth.3
(assert-equal nil (fifth '(1 1))))
(define-test fifth.4
(assert-equal nil (fifth '(1 1 1))))
(define-test fifth.5
(assert-equal nil (fifth '(1 1 1 1))))
(define-test fifth.6
(assert-equal 1 (fifth '(0 0 0 0 1))))
(define-test fifth.7
(assert-equal 1 (fifth '(0 0 0 0 1 2))))
(define-test fifth.error.1
(assert-error 'type-error (fifth 1)))
(define-test fifth.error.2
(assert-error 'type-error (fifth '(0 . 1))))
(define-test fifth.error.3
(assert-error 'type-error (fifth '(0 0 . 1))))
(define-test fifth.error.4
(assert-error 'type-error (fifth '(0 0 0 . 1))))
(define-test fifth.error.5
(assert-error 'type-error (fifth '(0 0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the SIXTH function.
(define-test sixth.1
(assert-equal nil (sixth nil)))
(define-test sixth.2
(assert-equal nil (sixth '(1))))
(define-test sixth.3
(assert-equal nil (sixth '(1 1))))
(define-test sixth.4
(assert-equal nil (sixth '(1 1 1))))
(define-test sixth.5
(assert-equal nil (sixth '(1 1 1 1))))
(define-test sixth.6
(assert-equal nil (sixth '(1 1 1 1 1))))
(define-test sixth.7
(assert-equal 1 (sixth '(0 0 0 0 0 1))))
(define-test sixth.8
(assert-equal 1 (sixth '(0 0 0 0 0 1 2))))
(define-test sixth.error.1
(assert-error 'type-error (sixth 1)))
(define-test sixth.error.2
(assert-error 'type-error (sixth '(0 . 1))))
(define-test sixth.error.3
(assert-error 'type-error (sixth '(0 0 . 1))))
(define-test sixth.error.4
(assert-error 'type-error (sixth '(0 0 0 . 1))))
(define-test sixth.error.5
(assert-error 'type-error (sixth '(0 0 0 0 . 1))))
(define-test sixth.error.6
(assert-error 'type-error (sixth '(0 0 0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the SEVENTH function.
(define-test seventh.1
(assert-equal nil (seventh nil)))
(define-test seventh.2
(assert-equal nil (seventh '(1))))
(define-test seventh.3
(assert-equal nil (seventh '(1 1))))
(define-test seventh.4
(assert-equal nil (seventh '(1 1 1))))
(define-test seventh.5
(assert-equal nil (seventh '(1 1 1 1))))
(define-test seventh.6
(assert-equal nil (seventh '(1 1 1 1 1))))
(define-test seventh.7
(assert-equal nil (seventh '(1 1 1 1 1 1))))
(define-test seventh.8
(assert-equal 1 (seventh '(0 0 0 0 0 0 1))))
(define-test seventh.9
(assert-equal 1 (seventh '(0 0 0 0 0 0 1 2))))
(define-test seventh.error.1
(assert-error 'type-error (seventh 1)))
(define-test seventh.error.2
(assert-error 'type-error (seventh '(0 . 1))))
(define-test seventh.error.3
(assert-error 'type-error (seventh '(0 0 . 1))))
(define-test seventh.error.4
(assert-error 'type-error (seventh '(0 0 0 . 1))))
(define-test seventh.error.5
(assert-error 'type-error (seventh '(0 0 0 0 . 1))))
(define-test seventh.error.6
(assert-error 'type-error (seventh '(0 0 0 0 0 . 1))))
(define-test seventh.error.7
(assert-error 'type-error (seventh '(0 0 0 0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the EIGHTH function.
(define-test eighth.1
(assert-equal nil (eighth nil)))
(define-test eighth.2
(assert-equal nil (eighth '(1))))
(define-test eighth.3
(assert-equal nil (eighth '(1 1))))
(define-test eighth.4
(assert-equal nil (eighth '(1 1 1))))
(define-test eighth.5
(assert-equal nil (eighth '(1 1 1 1))))
(define-test eighth.6
(assert-equal nil (eighth '(1 1 1 1 1))))
(define-test eighth.7
(assert-equal nil (eighth '(1 1 1 1 1 1))))
(define-test eighth.8
(assert-equal nil (eighth '(1 1 1 1 1 1 1))))
(define-test eighth.9
(assert-equal 1 (eighth '(0 0 0 0 0 0 0 1))))
(define-test eighth.10
(assert-equal 1 (eighth '(0 0 0 0 0 0 0 1 2))))
(define-test eighth.error.1
(assert-error 'type-error (eighth 1)))
(define-test eighth.error.2
(assert-error 'type-error (eighth '(0 . 1))))
(define-test eighth.error.3
(assert-error 'type-error (eighth '(0 0 . 1))))
(define-test eighth.error.4
(assert-error 'type-error (eighth '(0 0 0 . 1))))
(define-test eighth.error.5
(assert-error 'type-error (eighth '(0 0 0 0 . 1))))
(define-test eighth.error.6
(assert-error 'type-error (eighth '(0 0 0 0 0 . 1))))
(define-test eighth.error.7
(assert-error 'type-error (eighth '(0 0 0 0 0 0 . 1))))
(define-test eighth.error.8
(assert-error 'type-error (eighth '(0 0 0 0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the NINTH function.
(define-test ninth.1
(assert-equal nil (ninth nil)))
(define-test ninth.2
(assert-equal nil (ninth '(1))))
(define-test ninth.3
(assert-equal nil (ninth '(1 1))))
(define-test ninth.4
(assert-equal nil (ninth '(1 1 1))))
(define-test ninth.5
(assert-equal nil (ninth '(1 1 1 1))))
(define-test ninth.6
(assert-equal nil (ninth '(1 1 1 1 1))))
(define-test ninth.7
(assert-equal nil (ninth '(1 1 1 1 1 1))))
(define-test ninth.8
(assert-equal nil (ninth '(1 1 1 1 1 1 1))))
(define-test ninth.9
(assert-equal nil (ninth '(1 1 1 1 1 1 1 1))))
(define-test ninth.10
(assert-equal 1 (ninth '(0 0 0 0 0 0 0 0 1))))
(define-test ninth.11
(assert-equal 1 (ninth '(0 0 0 0 0 0 0 0 1 2))))
(define-test ninth.error.1
(assert-error 'type-error (ninth 1)))
(define-test ninth.error.2
(assert-error 'type-error (ninth '(0 . 1))))
(define-test ninth.error.3
(assert-error 'type-error (ninth '(0 0 . 1))))
(define-test ninth.error.4
(assert-error 'type-error (ninth '(0 0 0 . 1))))
(define-test ninth.error.5
(assert-error 'type-error (ninth '(0 0 0 0 . 1))))
(define-test ninth.error.6
(assert-error 'type-error (ninth '(0 0 0 0 0 . 1))))
(define-test ninth.error.7
(assert-error 'type-error (ninth '(0 0 0 0 0 0 . 1))))
(define-test ninth.error.8
(assert-error 'type-error (ninth '(0 0 0 0 0 0 . 1))))
(define-test ninth.error.9
(assert-error 'type-error (ninth '(0 0 0 0 0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the TENTH function.
(define-test tenth.1
(assert-equal nil (tenth nil)))
(define-test tenth.2
(assert-equal nil (tenth '(1))))
(define-test tenth.3
(assert-equal nil (tenth '(1 1))))
(define-test tenth.4
(assert-equal nil (tenth '(1 1 1))))
(define-test tenth.5
(assert-equal nil (tenth '(1 1 1 1))))
(define-test tenth.6
(assert-equal nil (tenth '(1 1 1 1 1))))
(define-test tenth.7
(assert-equal nil (tenth '(1 1 1 1 1 1))))
(define-test tenth.8
(assert-equal nil (tenth '(1 1 1 1 1 1 1))))
(define-test tenth.9
(assert-equal nil (tenth '(1 1 1 1 1 1 1 1))))
(define-test tenth.10
(assert-equal nil (tenth '(1 1 1 1 1 1 1 1 1))))
(define-test tenth.11
(assert-equal 1 (tenth '(0 0 0 0 0 0 0 0 0 1))))
(define-test tenth.12
(assert-equal 1 (tenth '(0 0 0 0 0 0 0 0 0 1 2))))
(define-test tenth.error.1
(assert-error 'type-error (tenth 1)))
(define-test tenth.error.2
(assert-error 'type-error (tenth '(0 . 1))))
(define-test tenth.error.3
(assert-error 'type-error (tenth '(0 0 . 1))))
(define-test tenth.error.4
(assert-error 'type-error (tenth '(0 0 0 . 1))))
(define-test tenth.error.5
(assert-error 'type-error (tenth '(0 0 0 0 . 1))))
(define-test tenth.error.6
(assert-error 'type-error (tenth '(0 0 0 0 0 . 1))))
(define-test tenth.error.7
(assert-error 'type-error (tenth '(0 0 0 0 0 0 . 1))))
(define-test tenth.error.8
(assert-error 'type-error (tenth '(0 0 0 0 0 0 . 1))))
(define-test tenth.error.9
(assert-error 'type-error (tenth '(0 0 0 0 0 0 0 . 1))))
(define-test tenth.error.10
(assert-error 'type-error (tenth '(0 0 0 0 0 0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAAR) function and SETF expander.
(define-test |setf caar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caar list) 1))
(assert-equal '((1 . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caar error 1|
(let ((list '()))
(assert-error 'type-error
(setf (caar list) 1))))
(define-test |setf caar error 2|
(let ((list 0))
(assert-error 'type-error
(setf (caar list) 1))))
(define-test |setf caar error 3|
(let ((list (copy-tree '(0 0))))
(assert-error 'type-error
(setf (caar list) 1))))
(define-test |setf caar error 4|
(let ((list (copy-tree '(() 0))))
(assert-error 'type-error
(setf (caar list) 1))))
(define-test |setf caar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caar) (list 1 list)))
(assert-equal '((1 . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caar apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf caar) (list 1 list)))))
(define-test |setf caar apply error 2|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caar) (list 1 list)))))
(define-test |setf caar apply error 3|
(let ((list (copy-tree '(0 0))))
(assert-error 'type-error
(apply #'(setf caar) (list 1 list)))))
(define-test |setf caar apply error 4|
(let ((list (copy-tree '(() 0))))
(assert-error 'type-error
(apply #'(setf caar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADR) function and SETF expander.
(define-test |setf cadr 1|
(let ((list (copy-tree '(0 0))))
(assert-equal 1 (setf (cadr list) 1))
(assert-equal '(0 1) list)))
(define-test |setf cadr error 1|
(let ((list '()))
(assert-error 'type-error
(setf (cadr list) 1))))
(define-test |setf cadr error 2|
(let ((list 0))
(assert-error 'type-error
(setf (cadr list) 1))))
(define-test |setf cadr error 3|
(let ((list (copy-tree '(0))))
(assert-error 'type-error
(setf (cadr list) 1))))
(define-test |setf cadr error 4|
(let ((list (copy-tree '(0 . 0))))
(assert-error 'type-error
(setf (cadr list) 1))))
(define-test |setf cadr apply 1|
(let ((list (copy-tree '(0 0))))
(assert-equal 1 (apply #'(setf cadr) (list 1 list)))
(assert-equal '(0 1) list)))
(define-test |setf cadr apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf cadr) (list 1 list)))))
(define-test |setf cadr apply error 2|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cadr) (list 1 list)))))
(define-test |setf cadr apply error 3|
(let ((list (copy-tree '(0))))
(assert-error 'type-error
(apply #'(setf cadr) (list 1 list)))))
(define-test |setf cadr apply error 4|
(let ((list (copy-tree '(0 . 0))))
(assert-error 'type-error
(apply #'(setf cadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDAR) function and SETF expander.
(define-test |setf cdar 1|
(let ((list (copy-tree '((0) 0))))
(assert-equal 1 (setf (cdar list) 1))
(assert-equal '((0 . 1) 0) list)))
(define-test |setf cdar error 1|
(let ((list '()))
(assert-error 'type-error
(setf (cdar list) 1))))
(define-test |setf cdar error 2|
(let ((list 0))
(assert-error 'type-error
(setf (cdar list) 1))))
(define-test |setf cdar error 3|
(let ((list (copy-tree '(0))))
(assert-error 'type-error
(setf (cdar list) 1))))
(define-test |setf cdar error 4|
(let ((list (copy-tree '(()))))
(assert-error 'type-error
(setf (cdar list) 1))))
(define-test |setf cdar apply 1|
(let ((list (copy-tree '((0) 0))))
(assert-equal 1 (apply #'(setf cdar) (list 1 list)))
(assert-equal '((0 . 1) 0) list)))
(define-test |setf cdar apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf cdar) (list 1 list)))))
(define-test |setf cdar apply error 2|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdar) (list 1 list)))))
(define-test |setf cdar apply error 3|
(let ((list (copy-tree '(0))))
(assert-error 'type-error
(apply #'(setf cdar) (list 1 list)))))
(define-test |setf cdar apply error 4|
(let ((list (copy-tree '(()))))
(assert-error 'type-error
(apply #'(setf cdar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDR) function and SETF expander.
(define-test |setf cddr 1|
(let ((list (copy-tree '(0 0))))
(assert-equal 1 (setf (cddr list) 1))
(assert-equal '(0 0 . 1) list)))
(define-test |setf cddr error 1|
(let ((list '()))
(assert-error 'type-error
(setf (cddr list) 1))))
(define-test |setf cddr error 2|
(let ((list 0))
(assert-error 'type-error
(setf (cddr list) 1))))
(define-test |setf cddr error 3|
(let ((list (copy-tree '(0))))
(assert-error 'type-error
(setf (cddr list) 1))))
(define-test |setf cddr error 4|
(let ((list (copy-tree '(0 . 1))))
(assert-error 'type-error
(setf (cddr list) 1))))
(define-test |setf cddr apply 1|
(let ((list (copy-tree '(0 0))))
(assert-equal 1 (apply #'(setf cddr) (list 1 list)))
(assert-equal '(0 0 . 1) list)))
(define-test |setf cddr apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf cddr) (list 1 list)))))
(define-test |setf cddr apply error 2|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cddr) (list 1 list)))))
(define-test |setf cddr apply error 3|
(let ((list (copy-tree '(0))))
(assert-error 'type-error
(apply #'(setf cddr) (list 1 list)))))
(define-test |setf cddr apply error 4|
(let ((list (copy-tree '(0 . 1))))
(assert-error 'type-error
(apply #'(setf cddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAAAR) function and SETF expander.
(define-test |setf caaar 1|
(let ((list (copy-tree '(((0 0) 0) 0))))
(assert-equal 1 (setf (caaar list) 1))
(assert-equal '(((1 0) 0) 0) list)))
(define-test |setf caaar error 1|
(let ((list '()))
(assert-error 'type-error
(setf (caaar list) 1))))
(define-test |setf caaar error 2|
(let ((list 0))
(assert-error 'type-error
(setf (caaar list) 1))))
(define-test |setf caaar error 3|
(let ((list (copy-tree '(0 0))))
(assert-error 'type-error
(setf (caaar list) 1))))
(define-test |setf caaar error 4|
(let ((list (copy-tree '((0 0) 0))))
(assert-error 'type-error
(setf (caaar list) 1))))
(define-test |setf caaar error 5|
(let ((list (copy-tree '((() 0) 0))))
(assert-error 'type-error
(setf (caaar list) 1))))
(define-test |setf caaar apply 1|
(let ((list (copy-tree '(((0 0) 0) 0))))
(assert-equal 1 (apply #'(setf caaar) (list 1 list)))
(assert-equal '(((1 0) 0) 0) list)))
(define-test |setf caaar apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf caaar) (list 1 list)))))
(define-test |setf caaar apply error 2|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caaar) (list 1 list)))))
(define-test |setf caaar apply error 3|
(let ((list (copy-tree '(0 0))))
(assert-error 'type-error
(apply #'(setf caaar) (list 1 list)))))
(define-test |setf caaar apply error 4|
(let ((list (copy-tree '((0 0) 0))))
(assert-error 'type-error
(apply #'(setf caaar) (list 1 list)))))
(define-test |setf caaar apply error 5|
(let ((list (copy-tree '((() 0) 0))))
(assert-error 'type-error
(apply #'(setf caaar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAADR) function and SETF expander.
(define-test |setf caadr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caadr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
((1 . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caadr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caadr list) 1))))
(define-test |setf caadr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
0 ))))
(assert-error 'type-error
(setf (caadr list) 1))))
(define-test |setf caadr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(0 . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (caadr list) 1))))
(define-test |setf caadr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caadr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
((1 . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caadr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caadr) (list 1 list)))))
(define-test |setf caadr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
0 ))))
(assert-error 'type-error
(apply #'(setf caadr) (list 1 list)))))
(define-test |setf caadr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(0 . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf caadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADAR) function and SETF expander.
(define-test |setf cadar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cadar list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . (1 . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cadar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cadar list) 1))))
(define-test |setf cadar error 2|
(let ((list (copy-tree '(0 .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cadar list) 1))))
(define-test |setf cadar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . 0) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cadar list) 1))))
(define-test |setf cadar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cadar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . (1 . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cadar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cadar) (list 1 list)))))
(define-test |setf cadar apply error 2|
(let ((list (copy-tree '(0 .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cadar) (list 1 list)))))
(define-test |setf cadar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . 0) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cadar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADDR) function and SETF expander.
(define-test |setf caddr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caddr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . (1 . (0 . 0))))
list)))
(define-test |setf caddr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caddr list) 1))))
(define-test |setf caddr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
0 ))))
(assert-error 'type-error
(setf (caddr list) 1))))
(define-test |setf caddr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . 0 )))))
(assert-error 'type-error
(setf (caddr list) 1))))
(define-test |setf caddr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caddr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . (1 . (0 . 0))))
list)))
(define-test |setf caddr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caddr) (list 1 list)))))
(define-test |setf caddr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
0 ))))
(assert-error 'type-error
(apply #'(setf caddr) (list 1 list)))))
(define-test |setf caddr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . 0 )))))
(assert-error 'type-error
(apply #'(setf caddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDAAR) function and SETF expander.
(define-test |setf cdaar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdaar list) 1))
(assert-equal '((((0 . 0) . 1) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdaar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdaar list) 1))))
(define-test |setf cdaar error 2|
(let ((list (copy-tree '(0 .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cdaar list) 1))))
(define-test |setf cdaar error 3|
(let ((list (copy-tree '((0 . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cdaar list) 1))))
(define-test |setf cdaar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdaar) (list 1 list)))
(assert-equal '((((0 . 0) . 1) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdaar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdaar) (list 1 list)))))
(define-test |setf cdaar apply error 2|
(let ((list (copy-tree '(0 .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cdaar) (list 1 list)))))
(define-test |setf cdaar apply error 3|
(let ((list (copy-tree '((0 . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cdaar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDADR) function and SETF expander.
(define-test |setf cdadr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdadr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . 1) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdadr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdadr list) 1))))
(define-test |setf cdadr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
0 ))))
(assert-error 'type-error
(setf (cdadr list) 1))))
(define-test |setf cdadr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(0 . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cdadr list) 1))))
(define-test |setf cdadr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdadr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . 1) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdadr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdadr) (list 1 list)))))
(define-test |setf cdadr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
0 ))))
(assert-error 'type-error
(apply #'(setf cdadr) (list 1 list)))))
(define-test |setf cdadr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(0 . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cdadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDAR) function and SETF expander.
(define-test |setf cddar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cddar list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . 1)) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cddar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cddar list) 1))))
(define-test |setf cddar error 2|
(let ((list (copy-tree '(0 .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cddar list) 1))))
(define-test |setf cddar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . 0) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cddar list) 1))))
(define-test |setf cddar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cddar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . 1)) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cddar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cddar) (list 1 list)))))
(define-test |setf cddar apply error 2|
(let ((list (copy-tree '(0 .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cddar) (list 1 list)))))
(define-test |setf cddar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . 0) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cddar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDDR) function and SETF expander.
(define-test |setf cdddr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdddr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . 1)))
list)))
(define-test |setf cdddr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdddr list) 1))))
(define-test |setf cdddr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cdddr list) 1))))
(define-test |setf cdddr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(setf (cdddr list) 1))))
(define-test |setf cdddr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdddr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . 1)))
list)))
(define-test |setf cdddr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdddr) (list 1 list)))))
(define-test |setf cdddr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cdddr) (list 1 list)))))
(define-test |setf cdddr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(apply #'(setf cdddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAAAAR) function and SETF expander.
(define-test |setf caaaar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caaaar list) 1))
(assert-equal '((((1 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caaaar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caaaar list) 1))))
(define-test |setf caaaar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (caaaar list) 1))))
(define-test |setf caaaar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(setf (caaaar list) 1))))
(define-test |setf caaaar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caaar list) 0)
(assert-error 'type-error
(setf (caaaar list) 1))))
(define-test |setf caaaar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caaaar) (list 1 list)))
(assert-equal '((((1 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caaaar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caaaar) (list 1 list)))))
(define-test |setf caaaar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf caaaar) (list 1 list)))))
(define-test |setf caaaar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(apply #'(setf caaaar) (list 1 list)))))
(define-test |setf caaaar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caaar list) 0)
(assert-error 'type-error
(apply #'(setf caaaar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAAADR) function and SETF expander.
(define-test |setf caaadr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caaadr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((1 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caaadr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caaadr list) 1))))
(define-test |setf caaadr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (caaadr list) 1))))
(define-test |setf caaadr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(setf (caaadr list) 1))))
(define-test |setf caaadr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caadr list) 0)
(assert-error 'type-error
(setf (caaadr list) 1))))
(define-test |setf caaadr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caaadr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((1 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caaadr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caaadr) (list 1 list)))))
(define-test |setf caaadr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf caaadr) (list 1 list)))))
(define-test |setf caaadr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(apply #'(setf caaadr) (list 1 list)))))
(define-test |setf caaadr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caadr list) 0)
(assert-error 'type-error
(apply #'(setf caaadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAADAR) function and SETF expander.
(define-test |setf caadar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caadar list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((1 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caadar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caadar list) 1))))
(define-test |setf caadar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (caadar list) 1))))
(define-test |setf caadar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(setf (caadar list) 1))))
(define-test |setf caadar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadar list) 0)
(assert-error 'type-error
(setf (caadar list) 1))))
(define-test |setf caadar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caadar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((1 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caadar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caadar) (list 1 list)))))
(define-test |setf caadar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf caadar) (list 1 list)))))
(define-test |setf caadar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(apply #'(setf caadar) (list 1 list)))))
(define-test |setf caadar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadar list) 0)
(assert-error 'type-error
(apply #'(setf caadar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAADDR) function and SETF expander.
(define-test |setf caaddr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caaddr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((1 . 0) . (0 . 0))))
list)))
(define-test |setf caaddr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caaddr list) 1))))
(define-test |setf caaddr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (caaddr list) 1))))
(define-test |setf caaddr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(setf (caaddr list) 1))))
(define-test |setf caaddr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caddr list) 0)
(assert-error 'type-error
(setf (caaddr list) 1))))
(define-test |setf caaddr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caaddr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((1 . 0) . (0 . 0))))
list)))
(define-test |setf caaddr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caaddr) (list 1 list)))))
(define-test |setf caaddr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf caaddr) (list 1 list)))))
(define-test |setf caaddr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(apply #'(setf caaddr) (list 1 list)))))
(define-test |setf caaddr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caddr list) 0)
(assert-error 'type-error
(apply #'(setf caaddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADAAR) function and SETF expander.
(define-test |setf cadaar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cadaar list) 1))
(assert-equal '((((0 . 0) . (1 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cadaar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cadaar list) 1))))
(define-test |setf cadaar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (cadaar list) 1))))
(define-test |setf cadaar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(setf (cadaar list) 1))))
(define-test |setf cadaar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdaar list) 0)
(assert-error 'type-error
(setf (cadaar list) 1))))
(define-test |setf cadaar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cadaar) (list 1 list)))
(assert-equal '((((0 . 0) . (1 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cadaar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cadaar) (list 1 list)))))
(define-test |setf cadaar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf cadaar) (list 1 list)))))
(define-test |setf cadaar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(apply #'(setf cadaar) (list 1 list)))))
(define-test |setf cadaar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdaar list) 0)
(assert-error 'type-error
(apply #'(setf cadaar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADADR) function and SETF expander.
(define-test |setf cadadr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cadadr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (1 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cadadr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cadadr list) 1))))
(define-test |setf cadadr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cadadr list) 1))))
(define-test |setf cadadr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(setf (cadadr list) 1))))
(define-test |setf cadadr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdadr list) 0)
(assert-error 'type-error
(setf (cadadr list) 1))))
(define-test |setf cadadr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cadadr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (1 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cadadr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cadadr) (list 1 list)))))
(define-test |setf cadadr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cadadr) (list 1 list)))))
(define-test |setf cadadr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(apply #'(setf cadadr) (list 1 list)))))
(define-test |setf cadadr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdadr list) 0)
(assert-error 'type-error
(apply #'(setf cadadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADDAR) function and SETF expander.
(define-test |setf caddar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caddar list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (1 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caddar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caddar list) 1))))
(define-test |setf caddar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (caddar list) 1))))
(define-test |setf caddar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(setf (caddar list) 1))))
(define-test |setf caddar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddar list) 0)
(assert-error 'type-error
(setf (caddar list) 1))))
(define-test |setf caddar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caddar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (1 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caddar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caddar) (list 1 list)))))
(define-test |setf caddar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf caddar) (list 1 list)))))
(define-test |setf caddar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(apply #'(setf caddar) (list 1 list)))))
(define-test |setf caddar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddar list) 0)
(assert-error 'type-error
(apply #'(setf caddar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADDDR) function and SETF expander.
(define-test |setf cadddr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cadddr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (1 . 0))))
list)))
(define-test |setf cadddr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cadddr list) 1))))
(define-test |setf cadddr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cadddr list) 1))))
(define-test |setf cadddr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(setf (cadddr list) 1))))
(define-test |setf cadddr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdddr list) 0)
(assert-error 'type-error
(setf (cadddr list) 1))))
(define-test |setf cadddr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cadddr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (1 . 0))))
list)))
(define-test |setf cadddr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cadddr) (list 1 list)))))
(define-test |setf cadddr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cadddr) (list 1 list)))))
(define-test |setf cadddr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(apply #'(setf cadddr) (list 1 list)))))
(define-test |setf cadddr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdddr list) 0)
(assert-error 'type-error
(apply #'(setf cadddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDAAAR) function and SETF expander.
(define-test |setf cdaaar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdaaar list) 1))
(assert-equal '((((0 . 1) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdaaar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdaaar list) 1))))
(define-test |setf cdaaar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (cdaaar list) 1))))
(define-test |setf cdaaar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(setf (cdaaar list) 1))))
(define-test |setf cdaaar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caaar list) 0)
(assert-error 'type-error
(setf (cdaaar list) 1))))
(define-test |setf cdaaar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdaaar) (list 1 list)))
(assert-equal '((((0 . 1) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdaaar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdaaar) (list 1 list)))))
(define-test |setf cdaaar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf cdaaar) (list 1 list)))))
(define-test |setf cdaaar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(apply #'(setf cdaaar) (list 1 list)))))
(define-test |setf cdaaar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caaar list) 0)
(assert-error 'type-error
(apply #'(setf cdaaar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDAADR) function and SETF expander.
(define-test |setf cdaadr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdaadr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 1) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdaadr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdaadr list) 1))))
(define-test |setf cdaadr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cdaadr list) 1))))
(define-test |setf cdaadr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(setf (cdaadr list) 1))))
(define-test |setf cdaadr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caadr list) 0)
(assert-error 'type-error
(setf (cdaadr list) 1))))
(define-test |setf cdaadr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdaadr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 1) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdaadr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdaadr) (list 1 list)))))
(define-test |setf cdaadr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cdaadr) (list 1 list)))))
(define-test |setf cdaadr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(apply #'(setf cdaadr) (list 1 list)))))
(define-test |setf cdaadr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caadr list) 0)
(assert-error 'type-error
(apply #'(setf cdaadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDADAR) function and SETF expander.
(define-test |setf cdadar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdadar list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 1) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdadar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdadar list) 1))))
(define-test |setf cdadar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (cdadar list) 1))))
(define-test |setf cdadar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(setf (cdadar list) 1))))
(define-test |setf cdadar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadar list) 0)
(assert-error 'type-error
(setf (cdadar list) 1))))
(define-test |setf cdadar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdadar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 1) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdadar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdadar) (list 1 list)))))
(define-test |setf cdadar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf cdadar) (list 1 list)))))
(define-test |setf cdadar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(apply #'(setf cdadar) (list 1 list)))))
(define-test |setf cdadar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadar list) 0)
(assert-error 'type-error
(apply #'(setf cdadar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDADDR) function and SETF expander.
(define-test |setf cdaddr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdaddr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 1) . (0 . 0))))
list)))
(define-test |setf cdaddr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdaddr list) 1))))
(define-test |setf cdaddr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cdaddr list) 1))))
(define-test |setf cdaddr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(setf (cdaddr list) 1))))
(define-test |setf cdaddr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caddr list) 0)
(assert-error 'type-error
(setf (cdaddr list) 1))))
(define-test |setf cdaddr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdaddr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 1) . (0 . 0))))
list)))
(define-test |setf cdaddr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdaddr) (list 1 list)))))
(define-test |setf cdaddr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cdaddr) (list 1 list)))))
(define-test |setf cdaddr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(apply #'(setf cdaddr) (list 1 list)))))
(define-test |setf cdaddr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caddr list) 0)
(assert-error 'type-error
(apply #'(setf cdaddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDAAR) function and SETF expander.
(define-test |setf cddaar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cddaar list) 1))
(assert-equal '((((0 . 0) . (0 . 1)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cddaar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cddaar list) 1))))
(define-test |setf cddaar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (cddaar list) 1))))
(define-test |setf cddaar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(setf (cddaar list) 1))))
(define-test |setf cddaar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdaar list) 0)
(assert-error 'type-error
(setf (cddaar list) 1))))
(define-test |setf cddaar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cddaar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 1)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cddaar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cddaar) (list 1 list)))))
(define-test |setf cddaar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf cddaar) (list 1 list)))))
(define-test |setf cddaar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(apply #'(setf cddaar) (list 1 list)))))
(define-test |setf cddaar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdaar list) 0)
(assert-error 'type-error
(apply #'(setf cddaar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDADR) function and SETF expander.
(define-test |setf cddadr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cddadr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 1)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cddadr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cddadr list) 1))))
(define-test |setf cddadr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cddadr list) 1))))
(define-test |setf cddadr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(setf (cddadr list) 1))))
(define-test |setf cddadr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdadr list) 0)
(assert-error 'type-error
(setf (cddadr list) 1))))
(define-test |setf cddadr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cddadr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 1)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cddadr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cddadr) (list 1 list)))))
(define-test |setf cddadr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cddadr) (list 1 list)))))
(define-test |setf cddadr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(apply #'(setf cddadr) (list 1 list)))))
(define-test |setf cddadr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdadr list) 0)
(assert-error 'type-error
(apply #'(setf cddadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDDAR) function and SETF expander.
(define-test |setf cdddar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdddar list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 1))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdddar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdddar list) 1))))
(define-test |setf cdddar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (cdddar list) 1))))
(define-test |setf cdddar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(setf (cdddar list) 1))))
(define-test |setf cdddar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddar list) 0)
(assert-error 'type-error
(setf (cdddar list) 1))))
(define-test |setf cdddar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdddar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 1))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdddar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdddar) (list 1 list)))))
(define-test |setf cdddar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf cdddar) (list 1 list)))))
(define-test |setf cdddar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(apply #'(setf cdddar) (list 1 list)))))
(define-test |setf cdddar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddar list) 0)
(assert-error 'type-error
(apply #'(setf cdddar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDDDR) function and SETF expander.
(define-test |setf cddddr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cddddr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 1))))
list)))
(define-test |setf cddddr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cddddr list) 1))))
(define-test |setf cddddr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cddddr list) 1))))
(define-test |setf cddddr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(setf (cddddr list) 1))))
(define-test |setf cddddr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdddr list) 0)
(assert-error 'type-error
(setf (cddddr list) 1))))
(define-test |setf cddddr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cddddr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 1))))
list)))
(define-test |setf cddddr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cddddr) (list 1 list)))))
(define-test |setf cddddr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cddddr) (list 1 list)))))
(define-test |setf cddddr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(apply #'(setf cddddr) (list 1 list)))))
(define-test |setf cddddr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdddr list) 0)
(assert-error 'type-error
(apply #'(setf cddddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF FIRST) function and SETF expander.
(define-test |setf first 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (first list) 1))
(assert-equal '(1 0 0 0 0 0 0 0 0 0) list)))
(define-test |setf first error 1|
(let ((list '()))
(assert-error 'type-error
(setf (first list) 1))))
(define-test |setf first 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (first list) 1))
(assert-equal '(1 0 0 0 0 0 0 0 0 0) list)))
(define-test |setf first error 1|
(let ((list '()))
(assert-error 'type-error
(setf (first list) 1))))
(define-test |setf first apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf first) (list 1 list)))
(assert-equal '(1 0 0 0 0 0 0 0 0 0) list)))
(define-test |setf first apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf first) (list 1 list)))))
(define-test |setf first apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf first) (list 1 list)))
(assert-equal '(1 0 0 0 0 0 0 0 0 0) list)))
(define-test |setf first apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf first) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF SECOND) function and SETF expander.
(define-test |setf second 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (second list) 1))
(assert-equal '(0 1 0 0 0 0 0 0 0 0) list)))
(define-test |setf second error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 0 list)) 1)
(assert-error 'type-error
(setf (second list) 1))))
(define-test |setf second 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (second list) 1))
(assert-equal '(0 1 0 0 0 0 0 0 0 0) list)))
(define-test |setf second error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 0 list)) 1)
(assert-error 'type-error
(setf (second list) 1))))
(define-test |setf second apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf second) (list 1 list)))
(assert-equal '(0 1 0 0 0 0 0 0 0 0) list)))
(define-test |setf second apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 0 list)) 1)
(assert-error 'type-error
(apply #'(setf second) (list 1 list)))))
(define-test |setf second apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf second) (list 1 list)))
(assert-equal '(0 1 0 0 0 0 0 0 0 0) list)))
(define-test |setf second apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 0 list)) 1)
(assert-error 'type-error
(apply #'(setf second) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF THIRD) function and SETF expander.
(define-test |setf third 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (third list) 1))
(assert-equal '(0 0 1 0 0 0 0 0 0 0) list)))
(define-test |setf third error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 1 list)) 1)
(assert-error 'type-error
(setf (third list) 1))))
(define-test |setf third 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (third list) 1))
(assert-equal '(0 0 1 0 0 0 0 0 0 0) list)))
(define-test |setf third error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 1 list)) 1)
(assert-error 'type-error
(setf (third list) 1))))
(define-test |setf third apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf third) (list 1 list)))
(assert-equal '(0 0 1 0 0 0 0 0 0 0) list)))
(define-test |setf third apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 1 list)) 1)
(assert-error 'type-error
(apply #'(setf third) (list 1 list)))))
(define-test |setf third apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf third) (list 1 list)))
(assert-equal '(0 0 1 0 0 0 0 0 0 0) list)))
(define-test |setf third apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 1 list)) 1)
(assert-error 'type-error
(apply #'(setf third) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF FOURTH) function and SETF expander.
(define-test |setf fourth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (fourth list) 1))
(assert-equal '(0 0 0 1 0 0 0 0 0 0) list)))
(define-test |setf fourth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 2 list)) 1)
(assert-error 'type-error
(setf (fourth list) 1))))
(define-test |setf fourth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (fourth list) 1))
(assert-equal '(0 0 0 1 0 0 0 0 0 0) list)))
(define-test |setf fourth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 2 list)) 1)
(assert-error 'type-error
(setf (fourth list) 1))))
(define-test |setf fourth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf fourth) (list 1 list)))
(assert-equal '(0 0 0 1 0 0 0 0 0 0) list)))
(define-test |setf fourth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 2 list)) 1)
(assert-error 'type-error
(apply #'(setf fourth) (list 1 list)))))
(define-test |setf fourth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf fourth) (list 1 list)))
(assert-equal '(0 0 0 1 0 0 0 0 0 0) list)))
(define-test |setf fourth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 2 list)) 1)
(assert-error 'type-error
(apply #'(setf fourth) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF FIFTH) function and SETF expander.
(define-test |setf fifth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (fifth list) 1))
(assert-equal '(0 0 0 0 1 0 0 0 0 0) list)))
(define-test |setf fifth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 3 list)) 1)
(assert-error 'type-error
(setf (fifth list) 1))))
(define-test |setf fifth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (fifth list) 1))
(assert-equal '(0 0 0 0 1 0 0 0 0 0) list)))
(define-test |setf fifth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 3 list)) 1)
(assert-error 'type-error
(setf (fifth list) 1))))
(define-test |setf fifth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf fifth) (list 1 list)))
(assert-equal '(0 0 0 0 1 0 0 0 0 0) list)))
(define-test |setf fifth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 3 list)) 1)
(assert-error 'type-error
(apply #'(setf fifth) (list 1 list)))))
(define-test |setf fifth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf fifth) (list 1 list)))
(assert-equal '(0 0 0 0 1 0 0 0 0 0) list)))
(define-test |setf fifth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 3 list)) 1)
(assert-error 'type-error
(apply #'(setf fifth) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF SIXTH) function and SETF expander.
(define-test |setf sixth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (sixth list) 1))
(assert-equal '(0 0 0 0 0 1 0 0 0 0) list)))
(define-test |setf sixth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 4 list)) 1)
(assert-error 'type-error
(setf (sixth list) 1))))
(define-test |setf sixth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (sixth list) 1))
(assert-equal '(0 0 0 0 0 1 0 0 0 0) list)))
(define-test |setf sixth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 4 list)) 1)
(assert-error 'type-error
(setf (sixth list) 1))))
(define-test |setf sixth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf sixth) (list 1 list)))
(assert-equal '(0 0 0 0 0 1 0 0 0 0) list)))
(define-test |setf sixth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 4 list)) 1)
(assert-error 'type-error
(apply #'(setf sixth) (list 1 list)))))
(define-test |setf sixth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf sixth) (list 1 list)))
(assert-equal '(0 0 0 0 0 1 0 0 0 0) list)))
(define-test |setf sixth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 4 list)) 1)
(assert-error 'type-error
(apply #'(setf sixth) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF SEVENTH) function and SETF expander.
(define-test |setf seventh 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (seventh list) 1))
(assert-equal '(0 0 0 0 0 0 1 0 0 0) list)))
(define-test |setf seventh error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 5 list)) 1)
(assert-error 'type-error
(setf (seventh list) 1))))
(define-test |setf seventh 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (seventh list) 1))
(assert-equal '(0 0 0 0 0 0 1 0 0 0) list)))
(define-test |setf seventh error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 5 list)) 1)
(assert-error 'type-error
(setf (seventh list) 1))))
(define-test |setf seventh apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf seventh) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 1 0 0 0) list)))
(define-test |setf seventh apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 5 list)) 1)
(assert-error 'type-error
(apply #'(setf seventh) (list 1 list)))))
(define-test |setf seventh apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf seventh) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 1 0 0 0) list)))
(define-test |setf seventh apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 5 list)) 1)
(assert-error 'type-error
(apply #'(setf seventh) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF EIGHTH) function and SETF expander.
(define-test |setf eighth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (eighth list) 1))
(assert-equal '(0 0 0 0 0 0 0 1 0 0) list)))
(define-test |setf eighth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 6 list)) 1)
(assert-error 'type-error
(setf (eighth list) 1))))
(define-test |setf eighth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (eighth list) 1))
(assert-equal '(0 0 0 0 0 0 0 1 0 0) list)))
(define-test |setf eighth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 6 list)) 1)
(assert-error 'type-error
(setf (eighth list) 1))))
(define-test |setf eighth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf eighth) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 0 1 0 0) list)))
(define-test |setf eighth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 6 list)) 1)
(assert-error 'type-error
(apply #'(setf eighth) (list 1 list)))))
(define-test |setf eighth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf eighth) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 0 1 0 0) list)))
(define-test |setf eighth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 6 list)) 1)
(assert-error 'type-error
(apply #'(setf eighth) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF NINTH) function and SETF expander.
(define-test |setf ninth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (ninth list) 1))
(assert-equal '(0 0 0 0 0 0 0 0 1 0) list)))
(define-test |setf ninth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 7 list)) 1)
(assert-error 'type-error
(setf (ninth list) 1))))
(define-test |setf ninth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (ninth list) 1))
(assert-equal '(0 0 0 0 0 0 0 0 1 0) list)))
(define-test |setf ninth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 7 list)) 1)
(assert-error 'type-error
(setf (ninth list) 1))))
(define-test |setf ninth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf ninth) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 0 0 1 0) list)))
(define-test |setf ninth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 7 list)) 1)
(assert-error 'type-error
(apply #'(setf ninth) (list 1 list)))))
(define-test |setf ninth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf ninth) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 0 0 1 0) list)))
(define-test |setf ninth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 7 list)) 1)
(assert-error 'type-error
(apply #'(setf ninth) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF TENTH) function and SETF expander.
(define-test |setf tenth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (tenth list) 1))
(assert-equal '(0 0 0 0 0 0 0 0 0 1) list)))
(define-test |setf tenth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 8 list)) 1)
(assert-error 'type-error
(setf (tenth list) 1))))
(define-test |setf tenth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (tenth list) 1))
(assert-equal '(0 0 0 0 0 0 0 0 0 1) list)))
(define-test |setf tenth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 8 list)) 1)
(assert-error 'type-error
(setf (tenth list) 1))))
(define-test |setf tenth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf tenth) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 0 0 0 1) list)))
(define-test |setf tenth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 8 list)) 1)
(assert-error 'type-error
(apply #'(setf tenth) (list 1 list)))))
(define-test |setf tenth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf tenth) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 0 0 0 1) list)))
(define-test |setf tenth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 8 list)) 1)
(assert-error 'type-error
(apply #'(setf tenth) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the REST function.
(define-test rest.1
(assert-equal '() (rest '())))
(define-test rest.2
(assert-equal '() (rest '(0))))
(define-test rest.3
(assert-equal '(1) (rest '(0 1))))
(define-test rest.error.1
(assert-error 'type-error
(rest 1)))
(define-test rest.apply.1
(assert-equal '(1) (apply (second (list 'a #'rest)) '((0 1)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the SETF expander and SETF function for REST.
(define-test |setf-rest 1|
(let ((list (copy-list '(0))))
(assert-equal 1 (setf (rest list) 1))
(assert-equal '(0 . 1) list)))
(define-test |setf-rest error 1|
(let ((list 1))
(assert-error 'type-error
(setf (rest list) 1))))
(define-test |setf-rest apply 1|
(let ((list (copy-list '(0))))
(assert-equal 1 (apply #'(setf rest) (list 1 list)))
(assert-equal '(0 . 1) list)))
(define-test |setf-rest apply error 1|
(let ((list 1))
(assert-error 'type-error
(apply #'(setf rest) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the LIST function.
(define-test list.1
(assert-equal '() (list)))
(define-test list.2
(assert-equal '(1) (list 1)))
(define-test list.3
(assert-equal '(1 2) (list 1 2)))
(define-test list.4
(assert-equal '(1 2 3) (list 1 2 3)))
(define-test list.5
(assert-equal '((a) (b) 1 2) (list '(a) '(b) 1 2)))
(define-test list.apply.1a
(assert-equal '() (apply (cadr (list 1 #'list)) '())))
(define-test list.apply.2a
(assert-equal '(1) (apply (cadr (list 1 #'list)) (list 1))))
(define-test list.apply.3a
(assert-equal '(1 2) (apply (cadr (list 1 #'list)) (list 1 2))))
(define-test list.apply.4a
(assert-equal '(1 2 3) (apply (cadr (list 1 #'list)) (list 1 2 3))))
(define-test list.apply.5a
(assert-equal '((a) (b) 1 2)
(apply (cadr (list 1 #'list)) (list '(a) '(b) 1 2))))
(define-test list.apply.1b
(assert-equal '() (apply (cadr (list 1 'list)) '())))
(define-test list.apply.2b
(assert-equal '(1) (apply (cadr (list 1 'list)) (list 1))))
(define-test list.apply.3b
(assert-equal '(1 2) (apply (cadr (list 1 'list)) (list 1 2))))
(define-test list.apply.4b
(assert-equal '(1 2 3) (apply (cadr (list 1 'list)) (list 1 2 3))))
(define-test list.apply.5b
(assert-equal '((a) (b) 1 2)
(apply (cadr (list 1 'list)) (list '(a) '(b) 1 2))))
(define-test list.order.1
(let ((i 0))
(assert-equal '(1 2 3) (list (incf i) (incf i) (incf i)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the LIST* function.
(define-test list*.1
(assert-equal '(1 2 3) (list* 1 '(2 3))))
(define-test list*.2
(assert-equal '(1 2 3) (list* 1 2 '(3))))
(define-test list*.3
(assert-equal '(1 2 3) (list* 1 2 3 '())))
(define-test list*.4
(assert-equal 'a (list* 'a)))
(define-test list*.5
(assert-equal '(1 2 . 3) (list* 1 2 3)))
(define-test list*.apply.1
(assert-equal '(1 2 3)
(apply (cadr (list 1 #'list*)) (list 1 '(2 3)))))
(define-test list*.apply.2
(assert-equal '(1 2 3)
(apply (cadr (list 1 #'list*)) (list 1 2 '(3)))))
(define-test list*.apply.3
(assert-equal '(1 2 3)
(apply (cadr (list 1 #'list*)) (list 1 2 3 '()))))
(define-test list*.apply.4
(assert-equal 'a
(apply (cadr (list 1 #'list*)) (list 'a))))
(define-test list*.apply.5
(assert-equal '(1 2 . 3)
(apply (cadr (list 1 #'list*)) (list 1 2 3))))
(define-test list*.error.1
(assert-error 'error
(list*)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the LAST function.
(define-test |last 1|
(assert-equal '() (last '())))
(define-test |last 2|
(assert-equal '(1) (last '(1))))
(define-test |last 3|
(assert-equal '(2) (last '(1 2))))
(define-test |last 4|
(assert-equal '(1 . 2) (last '(1 . 2))))
(define-test |last 5|
(assert-equal '(2 3) (last '(1 2 3) 2)))
(define-test |last 6|
(assert-equal '(1 2 . 3) (last '(1 2 . 3) 2)))
(define-test |last 7|
(assert-equal '(2 3 . 4) (last '(1 2 3 . 4) 2)))
(define-test |last 8|
(assert-equal '(1 2 3) (last '(1 2 3) 3)))
(define-test |last 9|
(assert-equal '(1 2 3) (last '(1 2 3) 4)))
(define-test |last error 1|
(assert-error 'type-error
(last 1)))
(define-test |last error 2|
(assert-error 'type-error
(last '(1) 'a)))
(define-test |last apply error 1|
(assert-error 'type-error
(apply #'last (list 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the COPY-LIST function.
(define-test copy-list.1
(assert-equal '() (copy-list '())))
(define-test copy-list.2
(assert-equal '(1) (copy-list '(1))))
(define-test copy-list.3
(let ((thing '(a b)))
(assert-equal thing (car (copy-list (list thing 1 2))))))
(define-test copy-list.4
(assert-equal '(1 . 2) (copy-list '(1 . 2))))
(define-test copy-list.error
(assert-error 'type-error (copy-list 1)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the LIST-LENGTH function.
(define-test |list-length proper-list 1|
(assert-equal 0
(list-length '())))
(define-test |list-length proper-list 2|
(assert-equal 1
(list-length '(0))))
(define-test |list-length proper-list 3|
(assert-equal 2
(list-length '(0 0))))
(define-test |list-length proper-list 4|
(assert-equal 3
(list-length '(0 0 0))))
(define-test |list-length proper-list 5|
(assert-equal 4
(list-length '(0 0 0 0))))
(define-test |list-length proper-list 6|
(assert-equal 5
(list-length '(0 0 0 0 0))))
(define-test |list-length circular-list 1|
(assert-equal nil
(list-length '#1=(0 . #1#))))
(define-test |list-length circular-list 2|
(assert-equal nil
(list-length '#1=(0 0 . #1#))))
(define-test |list-length circular-list 3|
(assert-equal nil
(list-length '#1=(0 0 0 . #1#))))
(define-test |list-length circular-list 4|
(assert-equal nil
(list-length '#1=(0 0 0 0 . #1#))))
(define-test |list-length dotted-list 1|
(assert-error 'type-error
(list-length '(0 . 0))))
(define-test |list-length dotted-list 2|
(assert-error 'type-error
(list-length '(0 0 . 0))))
(define-test |list-length dotted-list 3|
(assert-error 'type-error
(list-length '(0 0 0 . 0))))
(define-test |list-length dotted-list 4|
(assert-error 'type-error
(list-length '(0 0 0 0 . 0))))
(define-test |list-length not-a-list 1|
(assert-error 'type-error
(list-length 0)))
(define-test |list-length not-a-list 2|
(assert-error 'type-error
(list-length 'a)))
(define-test |list-length not-a-list 3|
(assert-error 'type-error
(list-length #(a))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the MAKE-LIST function.
(define-test make-list.1
(assert-equal '() (make-list 0)))
(define-test make-list.2
(assert-equal 1 (length (make-list 1))))
(define-test make-list.3
(assert-equal '(3 3) (make-list 2 :initial-element 3)))
(define-test make-list.error.1
(assert-error 'type-error (make-list 'a)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the NTHCDR function.
(define-test |nthcdr 1|
(assert-equal '()
(nthcdr 0 '())))
(define-test |nthcdr 2|
(assert-equal '()
(nthcdr 1 '())))
(define-test |nthcdr 3|
(assert-equal '(0 0)
(nthcdr 1 '(0 0 0))))
(define-test |nthcdr error 1|
(assert-error 'type-error
(nthcdr 'a '(0 0))))
(define-test |nthcdr error 2|
(assert-error 'type-error
(nthcdr '-1 '(0 0))))
(define-test |nthcdr error 3|
(assert-error 'type-error
(nthcdr 2 '(0 . 0))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the NTH function.
(define-test |nth 1|
(assert-equal '()
(nth 0 '())))
(define-test |nth 2|
(assert-equal '()
(nth 1 '())))
(define-test |nth 3|
(assert-equal 1
(nth 0 '(1 2))))
(define-test |nth 4|
(assert-equal 2
(nth 1 '(1 2))))
(define-test |nth 5|
(assert-equal '()
(nth 3 '(1 2))))
(define-test |nth error 1|
(assert-error 'type-error
(nth 3 '(1 2 . 0))))
(define-test |nth error 2|
(assert-error 'type-error
(nth -1 '(1))))
(define-test |nth error 2|
(assert-error 'type-error
(nth 'a '(1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF NTH) function and SETF expander.
(define-test |setf-nth 1|
(let ((list (copy-list '(0 0 0))))
(assert-equal 1
(setf (nth 0 list) 1))
(assert-equal '(1 0 0)
list)))
(define-test |setf-nth 1|
(let ((list (copy-list '(0 0 0))))
(assert-equal 1
(setf (nth 2 list) 1))
(assert-equal '(0 0 1)
list)))
(define-test |setf-nth error 1|
(assert-error 'error
(setf (nth 0 '()) 1)))
(define-test |setf-nth error 2|
(assert-error 'error
(setf (nth 1 (copy-list '(0))) 1)))
(define-test |setf-nth error 3|
(assert-error 'error
(setf (nth 2 (copy-list '(0))) 1)))
(define-test |setf-nth error 4|
(assert-error 'error
(setf (nth -1 (copy-list '(0))) 1)))
(define-test |setf-nth error 5|
(assert-error 'error
(setf (nth 'a (copy-list '(0))) 1)))
(define-test |setf-nth apply 1|
(let ((list (copy-list '(0 0 0))))
(assert-equal 1
(apply #'(setf nth) (list 1 0 list)))
(assert-equal '(1 0 0)
list)))
(define-test |setf-nth apply 1|
(let ((list (copy-list '(0 0 0))))
(assert-equal 1
(apply #'(setf nth) (list 1 2 list)))
(assert-equal '(0 0 1)
list)))
(define-test |setf-nth apply error 1|
(assert-error 'error
(apply #'(setf nth) (list 1 0 '()))))
(define-test |setf-nth apply error 2|
(assert-error 'error
(apply #'(setf nth) (list 1 1 (copy-list '(0))))))
(define-test |setf-nth apply error 3|
(assert-error 'error
(apply #'(setf nth) (list 1 2 (copy-list '(0))))))
(define-test |setf-nth apply error 4|
(assert-error 'error
(apply #'(setf nth) (list 1 -1 (copy-list '(0))))))
(define-test |setf-nth apply error 5|
(assert-error 'error
(apply #'(setf nth) (list 1 'a (copy-list '(0))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the copy-tree function
(define-test copy-tree.1
(assert-equal 'x (copy-tree 'x)))
(define-test copy-tree.2
(assert-equal '(a . b) (copy-tree '(a . b))))
(define-test copy-tree.3
(let ((tree '(((((a b . c) d (e (f g)) . h))) (i j (k)))))
(assert-equal tree (copy-tree tree))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the tree-equal function
(define-test |tree-equal test=eql 1a|
(assert-true (tree-equal nil nil)))
(define-test |tree-equal test=eql 1b|
(assert-true (tree-equal nil nil :test #'eql)))
(define-test |tree-equal test=eql 1c|
(assert-true (tree-equal nil nil :test 'eql)))
(define-test |tree-equal test=eql 2a|
(assert-true (tree-equal 1 1)))
(define-test |tree-equal test=eql 2b|
(assert-true (tree-equal 1 1 :test #'eql)))
(define-test |tree-equal test=eql 2c|
(assert-true (tree-equal 1 1 :test 'eql)))
(define-test |tree-equal test=eql 3a|
(assert-true (tree-equal '(1) '(1))))
(define-test |tree-equal test=eql 3b|
(assert-true (tree-equal '(1) '(1) :test #'eql)))
(define-test |tree-equal test=eql 3c|
(assert-true (tree-equal '(1) '(1) :test 'eql)))
(define-test |tree-equal test=eql 4a|
(assert-true (tree-equal '(1 . 2) '(1 . 2))))
(define-test |tree-equal test=eql 4b|
(assert-true (tree-equal '(1 . 2) '(1 . 2) :test #'eql)))
(define-test |tree-equal test=eql 4c|
(assert-true (tree-equal '(1 . 2) '(1 . 2) :test 'eql)))
(define-test |tree-equal test=eql 5a|
(assert-false (tree-equal 1 2)))
(define-test |tree-equal test=eql 5b|
(assert-false (tree-equal 1 2 :test #'eql)))
(define-test |tree-equal test=eql 5c|
(assert-false (tree-equal 1 2 :test 'eql)))
(define-test |tree-equal test=eql 6a|
(assert-false (tree-equal '(1) '(2))))
(define-test |tree-equal test=eql 6b|
(assert-false (tree-equal '(1) '(2) :test #'eql)))
(define-test |tree-equal test=eql 6c|
(assert-false (tree-equal '(1) '(2) :test 'eql)))
(define-test |tree-equal test=eql 7a|
(assert-false (tree-equal '(1) '((1)))))
(define-test |tree-equal test=eql 7b|
(assert-false (tree-equal '(1) '((1)) :test #'eql)))
(define-test |tree-equal test=eql 7c|
(assert-false (tree-equal '(1) '((1)) :test 'eql)))
(define-test |tree-equal test=eql 8a|
(assert-false (tree-equal '((1)) '(1))))
(define-test |tree-equal test=eql 8b|
(assert-false (tree-equal '((1)) '(1) :test #'eql)))
(define-test |tree-equal test=eql 8c|
(assert-false (tree-equal '((1)) '(1) :test 'eql)))
(define-test |tree-equal test=eq 1a|
(assert-true (tree-equal 'a 'a :test #'eq)))
(define-test |tree-equal test=eq 1b|
(assert-true (tree-equal 'a 'a :test 'eq)))
(define-test |tree-equal test=eq 2a|
(assert-false (tree-equal 'a 'b :test #'eq)))
(define-test |tree-equal test=eq 2b|
(assert-false (tree-equal 'a 'b :test 'eq)))
(define-test |tree-equal test=eq 3a|
(assert-true (tree-equal '(a) '(a) :test #'eq)))
(define-test |tree-equal test=eq 3b|
(assert-true (tree-equal '(a) '(a) :test 'eq)))
(define-test |tree-equal test=eq 4a|
(assert-false (tree-equal '(a) '((a)) :test #'eq)))
(define-test |tree-equal test=eq 4b|
(assert-false (tree-equal '(a) '((a)) :test 'eq)))
(define-test |tree-equal test=eq 5a|
(assert-false (tree-equal '((a)) '(a) :test #'eq)))
(define-test |tree-equal test=eq 5b|
(assert-false (tree-equal '((a)) '(a) :test 'eq)))
(define-test |tree-equal test-not=eql 1a|
(assert-false (tree-equal '(1) '(2) :test-not #'eql)))
(define-test |tree-equal test-not=eql 1b|
(assert-false (tree-equal '(1) '(2) :test-not 'eql)))
(define-test |tree-equal test-not=eql 2a|
(assert-false (tree-equal '(1) '((1)) :test-not #'eql)))
(define-test |tree-equal test-not=eql 2b|
(assert-false (tree-equal '(1) '((1)) :test-not 'eql)))
(define-test |tree-equal test-not=eql 3a|
(assert-false (tree-equal '((1)) '(1) :test-not #'eql)))
(define-test |tree-equal test-not=eql 3b|
(assert-false (tree-equal '((1)) '(1) :test-not 'eql)))
(define-test |tree-equal test-not=eq 1a|
(assert-true (tree-equal 'a 'b :test-not #'eq)))
(define-test |tree-equal test-not=eq 1b|
(assert-true (tree-equal 'a 'b :test-not 'eq)))
(define-test |tree-equal test-not=eq 2a|
(assert-false (tree-equal 'a 'a :test-not #'eq)))
(define-test |tree-equal test-not=eq 2b|
(assert-false (tree-equal 'a 'a :test-not 'eq)))
(define-test |tree-equal test-not=eq 3a|
(assert-false (tree-equal '(a) '(a) :test-not #'eq)))
(define-test |tree-equal test-not=eq 3b|
(assert-false (tree-equal '(a) '(a) :test-not 'eq)))
(define-test |tree-equal test-not=eq 4a|
(assert-false (tree-equal '(a) '((a)) :test-not #'eq)))
(define-test |tree-equal test-not=eq 4b|
(assert-false (tree-equal '(a) '((a)) :test-not 'eq)))
(define-test |tree-equal test-not=eq 5a|
(assert-false (tree-equal '((a)) '(a) :test-not #'eq)))
(define-test |tree-equal test-not=eq 5b|
(assert-false (tree-equal '((a)) '(a) :test-not 'eq)))
(define-test |tree-equal test-not=eq 6a|
(assert-false (tree-equal '(a) '(b) :test-not #'eq)))
(define-test |tree-equal test-not=eq 6b|
(assert-false (tree-equal '(a) '(b) :test-not 'eq)))
(define-test |tree-equal test=other 1|
(assert-true (tree-equal '(1) '(2)
:test (lambda (x y)
(or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1)))))))
(define-test |tree-equal test=other 2|
(assert-false (tree-equal '(1) '(3)
:test (lambda (x y)
(or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1)))))))
(define-test |tree-equal test=other 3|
(assert-false (tree-equal '(1) '((3))
:test (lambda (x y)
(or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1)))))))
(define-test |tree-equal test=other 4|
(assert-false (tree-equal '((1)) '(3)
:test (lambda (x y)
(or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1)))))))
(define-test |tree-equal test-not=other 1|
(assert-true (tree-equal '(1) '(2)
:test-not (lambda (x y)
(not (or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))))))
(define-test |tree-equal test-not=other 2|
(assert-false (tree-equal '(1) '(3)
:test-not (lambda (x y)
(not (or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))))))
(define-test |tree-equal test-not=other 3|
(assert-false (tree-equal '(1) '((3))
:test-not (lambda (x y)
(not (or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))))))
(define-test |tree-equal test-not=other 4|
(assert-false (tree-equal '((1)) '(3)
:test-not (lambda (x y)
(not (or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))))))
(define-test |tree-equal test=other test-not=other 1|
(assert-error 'error
(tree-equal '() '() :test #'eql :test-not #'eql)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the endp function
(define-test endp.1
(assert-true (endp '())))
(define-test endp.2
(assert-false (endp '(1 . 2))))
(define-test endp.3
(assert-error 'type-error (endp 1)))
(define-test endp.4
(assert-error 'type-error (endp #\a)))
(define-test endp.5
(assert-error 'type-error (endp "a")))
(define-test endp.6
(assert-error 'type-error (endp 'a)))
(define-test endp.7
(assert-error 'type-error (endp 1.0)))
(define-test endp.8
(assert-error 'type-error (endp #(a))))
(define-test endp.9
(assert-error 'type-error (endp *standard-input*)))
(define-test endp.10
(assert-error 'type-error (endp *package*)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the mapcar function
(define-test |mapcar 1|
(assert-equal '() (mapcar #'1+ '())))
(define-test |mapcar 2|
(assert-equal '(1) (mapcar #'1+ '(0))))
(define-test |mapcar 3|
(assert-equal '(-1 -2 -3) (mapcar #'- '(1 2 3))))
(define-test |mapcar 4|
(assert-equal '(2 4 6) (mapcar #'+ '(1 2 3) '(1 2 3))))
(define-test |mapcar 5|
(assert-equal '(3 6 9) (mapcar #'+ '(1 2 3) '(1 2 3) '(1 2 3))))
(define-test |mapcar 6|
(assert-equal '(2 4) (mapcar #'+ '(1 2 3 4 5) '(1 2))))
(define-test |mapcar 7|
(assert-equal '(2 4) (mapcar #'+ '(1 2) '(1 2 3 4 5))))
(define-test |mapcar error 1|
(assert-error 'type-error (mapcar #'1+ (if (twisted '(a b c)) 1 '(a b c)))))
(define-test |mapcar error 2|
(assert-error 'type-error (mapcar #'1+ (if (twisted '(a b c)) #(1 2 3) '(a b c)))))
(define-test |mapcar error 3|
(assert-error 'type-error (mapcar #'1+ '(1 2 . 3))))
(define-test |mapcar error 4|
(assert-error 'type-error (mapcar #'1+ (if (twisted '(a b c)) "1" '(a b c)))))
(define-test |mapcar error 5|
(assert-error 'error (mapcar #'1+)))
(define-test |mapcar error 6|
(assert-error 'type-error
(mapcar #'list '(a b c) '(d e . f))))
(define-test |mapcar order 1|
(let ((i 0)
(funs (vector #'1+ #'1-))
(lists '((1 2) (3 4) (5 6))))
(assert-equal '(4 5) (mapcar (aref funs (incf i)) (nth (incf i) lists)))))
(define-test |mapcar apply error 1|
(assert-error 'error
(apply (cadr (list 'a #'mapcar)) #'car '())))
(define-test |mapcar apply error 2|
(assert-error 'type-error
(apply (cadr (list 'a #'mapcar)) #'list '((a b c) (d e . f)))))
(define-test |mapcar apply 1|
(assert-equal '(a b c)
(apply (cadr (list 'a #'mapcar)) #'car '(((a) (b) (c))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the mapc function
(define-test mapc.1
(assert-equal '() (mapc #'1+ '())))
(define-test mapc.2
(let ((i 0))
(assert-equal '(1 2 3 6)
(append (mapc (lambda (x) (incf i x)) '(1 2 3))
(list i)))))
(define-test mapc.3
(let ((i 0))
(assert-equal '(1 2 3 12)
(append (mapc (lambda (x y) (incf i (+ x y)))
'(1 2 3)
'(1 2 3))
(list i)))))
(define-test mapc.apply.1
(let ((i 0))
(assert-equal '(1 2 3 12)
(append (apply (cadr (list 'a #'mapc))
(list (lambda (x y) (incf i (+ x y)))
'(1 2 3)
'(1 2 3)))
(list i)))))
(define-test mapc.error.1
(assert-error 'type-error (mapc #'1+ (if (twisted '(a b c)) 1 '(1 2 3)))))
(define-test mapc.error.2
(assert-error 'type-error (mapc #'1+ (if (twisted '(a b c)) #(1 2 3) '(1 2 3)))))
(define-test mapc.error.3
(assert-error 'type-error (mapc #'1+ '(1 2 . 3))))
(define-test mapc.error.4
(assert-error 'type-error (mapc #'1+ (if (twisted '(a b c)) "1" '(1 2 3)))))
(define-test mapc.error.5
(assert-error 'error (mapc #'1+)))
(define-test mapc.apply.error.1
(assert-error 'type-error
(apply #'mapc (list #'list '(1 2) '(3 . 4)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the maplist function
(define-test maplist.1
(assert-equal '() (maplist #'car '())))
(define-test maplist.2
(assert-equal '(1 2 3) (maplist #'car '(1 2 3))))
(define-test maplist.apply.1
(assert-equal '(1 2 3)
(apply (cadr (list 'a #'maplist))
(list #'car '(1 2 3)))))
(define-test maplist.error.1
(assert-error 'type-error (maplist #'car (if (twisted '(a b c)) 1 '(a b c)))))
(define-test maplist.error.2
(assert-error 'type-error (maplist #'car (if (twisted '(a b c)) #(1 2 3) '(a b c)))))
(define-test maplist.error.3
(assert-error 'type-error (maplist #'car '(1 2 . 3))))
(define-test maplist.error.4
(assert-error 'type-error (maplist #'car (if (twisted '(a b c)) "1" '(a b c)))))
(define-test maplist.error.5
(assert-error 'error (maplist #'car)))
(define-test maplist.apply.error.1
(assert-error 'type-error
(apply #'maplist (list #'list '(1 2) '(3 . 4)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the mapl function
(define-test mapl.1
(assert-equal '() (mapl #'car '())))
(define-test mapl.2
(assert-equal '(1) (mapl #'car '(1))))
(define-test mapl.3
(let ((i 0))
(assert-equal 6
(progn (mapl (lambda (sublist) (incf i (car sublist)))
'(1 2 3))
i))))
(define-test mapl.apply.1
(let ((i 0))
(assert-equal 6
(progn (apply (cadr (list 'a #'mapl))
(list (lambda (sublist) (incf i (car sublist)))
'(1 2 3)))
i))))
(define-test mapl.error.1
(assert-error 'type-error (mapl #'car (if (twisted '(a b c)) 1 '(a b c)))))
(define-test mapl.error.2
(assert-error 'type-error (mapl #'car (if (twisted '(a b c)) #(1 2 3) '(a b c)))))
(define-test mapl.error.3
(assert-error 'type-error (mapl #'car '(1 2 . 3))))
(define-test mapl.error.4
(assert-error 'type-error (mapl #'car (if (twisted '(a b c)) "1" '(a b c)))))
(define-test mapl.error.5
(assert-error 'error (mapl #'car)))
(define-test mapl.apply.error.1
(assert-error 'type-error
(apply #'mapl (list #'list '(1 2) '(3 . 4)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the mapcan function
(define-test mapcan.1
(assert-equal '(a b c)
(mapcan #'list '(a b c))))
(define-test mapcan.2
(assert-equal '(a d b e c f)
(mapcan #'list '(a b c) '(d e f))))
(define-test mapcan.3
(assert-equal '(a b c . f)
(mapcan #'cons '(a b c) '(d e f))))
(define-test mapcan.4
(let ((a (list 'a))
(b (list 'b))
(c (list 'c)))
(assert-eq c
(cddr (mapcan #'identity (list a b c))))))
(define-test mapcan.5
(assert-equal '()
(mapcan #'identity '())))
(define-test mapcan.apply.1
(let ((a (list 'a))
(b (list 'b))
(c (list 'c)))
(assert-eq c
(cddr (apply (cadr (list 'a #'mapcan))
(list #'identity (list a b c)))))))
(define-test mapcan.error.1
(assert-error 'type-error
(mapcan #'car (if (twisted '(a b c)) 1 '((a) (b) (c))))))
(define-test mapcan.error.2
(assert-error 'type-error
(mapcan #'car (if (twisted '(a b c)) #(1 2 3) '((a) (b) (c))))))
(define-test mapcan.error.3
(assert-error 'type-error (mapcan #'car '(1 2 . 3))))
(define-test mapcan.error.4
(assert-error 'type-error
(mapcan #'car (if (twisted '(a b c)) "1" '((a) (b) (c))))))
(define-test mapcan.error.5
(assert-error 'error (mapcan #'car)))
(define-test mapcan.apply.error.1
(assert-error 'type-error
(apply #'mapcan (list #'list '(1 2) '(3 . 4)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the mapcon function
(define-test |macon 1|
(assert-equal nil
(mapcon #'identity '())))
(define-test |mapcon 2|
(assert-equal '(1 2 2)
(mapcon #'copy-list '(1 2))))
(define-test |mapcon 3|
(assert-equal '((1 2) (3 4) (2) (4))
(mapcon #'list '(1 2) '(3 4))))
(define-test |mapcon apply 1|
(assert-equal '((1 2) (3 4) (2) (4))
(apply #'mapcon #'list '(1 2) '(3 4) '())))
(define-test |mapcon error 1|
(assert-error 'type-error
(mapcon #'copy-list '(1 . 2))))
(define-test |mapcon error 2|
(assert-error 'type-error
(mapcon #'car (if (twisted '(a b c)) "1" '((a) (b) (c))))))
(define-test |mapcon error 3|
(assert-error 'error
(mapcon #'car)))
(define-test |mapcon apply error 1|
(assert-error 'type-error
(apply #'mapcon (list #'list '(1 2) '(3 . 4)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the append function
(define-test |append 1|
(assert-equal nil (append)))
(define-test |append 2|
(assert-equal 'x (append 'x)))
(define-test |append 4|
(assert-equal
'(a b c d e f g . h)
(append (list 'a) (list 'b) (list 'c)
(list 'd) (list 'e) (list 'f)
(list 'g) 'h)))
(define-test |append 5|
(assert-equal 'a (append nil nil nil nil nil nil nil nil 'a)))
;;; Test suggested by <NAME>
(define-test |append 7|
(let ((x (list 'a 'b 'c 'd)))
(assert-false (eq (append x nil) x))))
;;; Order of evaluation tests
(define-test |append order 1|
(assert-equal
'((a b c d e f g h i) 3 1 2 3)
(let ((i 0) x y z)
(list
(append (progn (setf x (incf i)) (copy-list '(a b c)))
(progn (setf y (incf i)) (copy-list '(d e f)))
(progn (setf z (incf i)) (copy-list '(g h i))))
i x y z))))
(define-test |append order 2|
(assert-equal '(1 1) (let ((i 0)) (append (list (incf i)) (list i)))))
;;; Error tests
(define-test |append error 1|
(assert-error 'type-error (append '(a . b) '(z))))
(define-test |append error 2|
(assert-error 'type-error (append '(x y z) '(a . b) '(z))))
;;; This test verifies that append preserves the structure of
;;; the last list.
(define-test |append sharing 1|
(let ((list1 '(1 2))
(list2 '(3 4)))
(assert-eq (cddr (append list1 list2)) list2)))
(define-test |append apply 1|
(let ((list1 '(1 2))
(list2 '(3 4)))
(assert-equal '(1 2 3 4)
(apply (cadr (list 'a #'append)) (list list1 list2)))
(assert-equal '(1 2 3 4)
(apply (cadr (list 'a 'append)) (list list1 list2)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nconc function
(define-test |nconc 1|
(assert-eq '() (nconc)))
(define-test |nconc 2|
(let ((list (copy-tree '(a b c))))
(assert-eq list (nconc list))))
(define-test |nconc 3|
(let ((list (copy-tree '(a b c))))
(assert-eq list (nconc '() list))))
(define-test |nconc 4|
(let ((list1 (copy-tree '(a b c)))
(list2 (copy-tree '(d e f))))
(assert-eq list1 (nconc list1 list2))
(assert-eq list2 (cdddr list1))))
(define-test |nconc 5|
(assert-equal '(a z)
(nconc (copy-tree '(a . b))
(copy-tree '(z)))))
(define-test |nconc 6|
(assert-equal '(x y z a z)
(nconc (copy-tree '(x y z))
(copy-tree '(a . b))
(copy-tree '(z)))))
(define-test |nconc order 1|
(assert-equal
'((a b c d e f g h i) 3 1 2 3)
(let ((i 0) x y z)
(list
(nconc (progn (setf x (incf i)) (copy-list '(a b c)))
(progn (setf y (incf i)) (copy-list '(d e f)))
(progn (setf z (incf i)) (copy-list '(g h i))))
i x y z))))
(define-test |nconc apply 1|
(let ((list1 '(1 2))
(list2 '(3 4)))
(assert-equal '(1 2 3 4)
(apply (cadr (list 'a #'nconc))
(copy-tree (list list1 list2))))
(assert-equal '(1 2 3 4)
(apply (cadr (list 'a 'nconc))
(copy-tree (list list1 list2))))))
(define-test |nconc error 1|
(assert-error 'type-error
(nconc (copy-tree '(a b c)) 'd (copy-tree '(e f)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the revappend function
(define-test revappend.1
(assert-equal '()
(revappend '() '())))
(define-test revappend.2
(assert-equal '(a)
(revappend '(a) '())))
(define-test revappend.3
(assert-equal '(b a)
(revappend '(a b) '())))
(define-test revappend.4
(assert-equal '(b a c)
(revappend '(a b) '(c))))
(define-test revappend.5
(assert-equal '(b a . c)
(revappend '(a b) 'c)))
(define-test revappend.6
(assert-equal 'c
(revappend '() 'c)))
(define-test revappend.7
(let ((l '(x)))
(assert-equal l
(cdr (revappend '(a) l)))))
(define-test revappend.error.1
(assert-error 'type-error
(revappend 'a '())))
(define-test revappend.error.2
(assert-error 'type-error
(revappend '(a . b) '())))
(define-test revappend.error.3
(assert-error 'type-error
(revappend 1 '())))
(define-test revappend.error.4
(assert-error 'type-error
(revappend #(a b) '())))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nreconc function
(define-test nreconc.1
(assert-equal '()
(nreconc '() '())))
(define-test nreconc.2
(assert-equal '(a)
(nreconc (copy-list '(a)) '())))
(define-test nreconc.3
(assert-equal '(b a)
(nreconc (copy-list '(a b)) '())))
(define-test nreconc.4
(assert-equal '(b a c)
(nreconc (copy-list '(a b)) '(c))))
(define-test nreconc.5
(assert-equal '(b a . c)
(nreconc (copy-list '(a b)) 'c)))
(define-test nreconc.6
(assert-equal 'c
(nreconc '() 'c)))
(define-test nreconc.7
(let ((l '(x)))
(assert-equal l
(cdr (nreconc (copy-list '(a)) l)))))
(define-test nreconc.error.1
(assert-error 'type-error
(nreconc 'a '())))
(define-test nreconc.error.2
(assert-error 'type-error
(nreconc (copy-tree '(a . b)) '())))
(define-test nreconc.error.3
(assert-error 'type-error
(nreconc 1 '())))
(define-test nreconc.error.4
(assert-error 'type-error
(nreconc #(a b) '())))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the butlast function
(define-test butlast.1
(assert-equal '() (butlast '())))
(define-test butlast.2
(assert-equal '() (butlast '(0))))
(define-test butlast.3
(assert-equal '(0) (butlast '(0 1))))
(define-test butlast.4
(assert-equal '() (butlast '(0 . 1))))
(define-test butlast.5
(assert-equal '(0) (butlast '(0 1 . 2))))
(define-test butlast.6
(assert-equal '() (butlast '() 0)))
(define-test butlast.7
(assert-equal '() (butlast '() 1)))
(define-test butlast.8
(assert-equal '() (butlast '() 2)))
(define-test butlast.9
(assert-equal '(0) (butlast '(0) 0)))
(define-test butlast.10
(assert-equal '(0 1) (butlast '(0 1) 0)))
(define-test butlast.11
(assert-equal '(0) (butlast '(0 . 1) 0)))
(define-test butlast.12
(assert-equal '(0) (butlast '(0 1 2) 2)))
(define-test butlast.13
(assert-equal '() (butlast '(0 1 2) 3)))
(define-test butlast.13
(assert-equal '() (butlast '(0 1 2) 4)))
(define-test butlast.error.1
(assert-error 'type-error
(butlast '(0 1 2) (if (twisted '(1 2 3)) -1 1))))
(define-test butlast.error.2
(assert-error 'type-error
(butlast '(0 1 2) (if (twisted '(1 2 3)) 'a 1))))
(define-test butlast.error.3
(assert-error 'type-error
(butlast '#1=(0 . #1#))))
(define-test butlast.error.4
(assert-error 'type-error
(butlast 1)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nbutlast function
(define-test |nbutlast n=1 1a|
(assert-equal '()
(nbutlast '())))
(define-test |nbutlast n=1 1b|
(assert-equal '()
(nbutlast '() 1)))
(define-test |nbutlast n=1 2a|
(let ((list (copy-list '(1))))
(assert-equal '()
(nbutlast list))))
(define-test |nbutlast n=1 2b|
(let ((list (copy-list '(1))))
(assert-equal '()
(nbutlast list 1))))
(define-test |nbutlast n=1 3a|
(let ((list (copy-list '(1 2))))
(assert-equal '(1)
(nbutlast list))
(assert-equal '(1)
list)))
(define-test |nbutlast n=1 3b|
(let ((list (copy-list '(1 2))))
(assert-equal '(1)
(nbutlast list 1))
(assert-equal '(1)
list)))
(define-test |nbutlast n=1 4a|
(let ((list (copy-list '(1 . 2))))
(assert-equal '()
(nbutlast list))))
(define-test |nbutlast n=1 4b|
(let ((list (copy-list '(1 . 2))))
(assert-equal '()
(nbutlast list 1))))
(define-test |nbutlast n=1 5a|
(let ((list (copy-list '(1 2 . 3))))
(assert-equal '(1)
(nbutlast list))
(assert-equal '(1)
list)))
(define-test |nbutlast n=1 5b|
(let ((list (copy-list '(1 2 . 3))))
(assert-equal '(1)
(nbutlast list 1))
(assert-equal '(1)
list)))
(define-test |nbutlast n=1 6a|
(let ((list (copy-list '(1 2 3 . 4))))
(assert-equal '(1 2)
(nbutlast list))
(assert-equal '(1 2)
list)))
(define-test |nbutlast n=1 6b|
(let ((list (copy-list '(1 2 3 . 4))))
(assert-equal '(1 2)
(nbutlast list 1))
(assert-equal '(1 2)
list)))
(define-test |nbutlast n=1 7a|
(let ((list (copy-list '(1 2 3 4))))
(assert-equal '(1 2 3)
(nbutlast list))
(assert-equal '(1 2 3)
list)))
(define-test |nbutlast n=1 7b|
(let ((list (copy-list '(1 2 3 4))))
(assert-equal '(1 2 3)
(nbutlast list 1))
(assert-equal '(1 2 3)
list)))
(define-test |nbutlast n=other 1|
(assert-equal '()
(nbutlast '() 2)))
(define-test |nbutlast n=other 2|
(let ((list (copy-list '(1))))
(assert-equal '()
(nbutlast list 2))))
(define-test |nbutlast n=other 3|
(let ((list (copy-list '(1 2))))
(assert-equal '()
(nbutlast list 2))))
(define-test |nbutlast n=other 4|
(let ((list (copy-list '(1 2 3))))
(assert-equal '(1)
(nbutlast list 2))
(assert-equal '(1)
list)))
(define-test |nbutlast n=other 5|
(let ((list (copy-list '(1 2 . 3))))
(assert-equal '()
(nbutlast list 2))))
(define-test |nbutlast n=other 6|
(let ((list (copy-list '(1 2 3 . 4))))
(assert-equal '(1)
(nbutlast list 2))
(assert-equal '(1)
list)))
(define-test |nbutlast error 1|
(assert-error 'type-error
(nbutlast 1)))
(define-test |nbutlast error 2|
(assert-error 'type-error
(nbutlast '() 'a)))
(define-test |nbutlast error 3|
(let ((list (copy-list '(0))))
(setf (cdr list) list)
(assert-error 'type-error
(nbutlast list 1))))
(define-test |nbutlast error 4|
(let ((list (copy-list '(0))))
(setf (cdr list) list)
(assert-error 'type-error
(nbutlast list 2))))
(define-test |nbutlast error 5|
(let ((list (copy-list '(0))))
(setf (cdr list) list)
(assert-error 'type-error
(nbutlast list 3))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the subst function
(define-test |subst test=eql key=identity 1a|
(assert-equal '()
(subst 'a 0 '())))
(define-test |subst test=eql key=identity 1b|
(assert-equal '()
(subst 'a 0 '() :test #'eql)))
(define-test |subst test=eql key=identity 1c|
(assert-equal '()
(subst 'a 0 '() :test 'eql)))
(define-test |subst test=eql key=identity 2a|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 0 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0))))))
(define-test |subst test=eql key=identity 2b|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 0 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test #'eql)))
(define-test |subst test=eql key=identity 2c|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 0 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test 'eql)))
(define-test |subst test=eql key=nil 1|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a
0
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key nil)))
(define-test |subst test=eq key=identity 1|
(assert-equal '()
(subst 'a 'b '()
:test #'eq)))
(define-test |subst test=eq key=identity 2|
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(subst 'a 'b '(((b . c) . (f . b)) . ((b . d) . (e . b)))
:test #'eq)))
(define-test |subst test=other key=identity 1|
(assert-equal '()
(subst 'a 0 '()
:test (lambda (x y) (and (numberp y) (= x (1- y)))))))
(define-test |subst test=other key=identity 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 0 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test (lambda (x y) (and (numberp y) (= x y))))))
(define-test |subst test=eql key=other 1a|
(assert-equal '()
(subst 'a 0 '()
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst test=eql key=other 1b|
(assert-equal '()
(subst 'a 0 '()
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql)))
(define-test |subst test=eql key=other 1c|
(assert-equal '()
(subst 'a 0 '()
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(define-test |subst test=eql key=other 2a|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 1 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst test=eql key=other 2b|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 1 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql)))
(define-test |subst test=eql key=other 2c|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 1 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(define-test |subst test=eq key=other 1|
(assert-equal '()
(subst 'a 'bb '()
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(define-test |subst test=eq key=other 2|
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(subst 'a 'bb '(((b . c) . (f . b)) . ((b . d) . (e . b)))
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(define-test |subst test=other key=other 1|
(assert-equal '()
(subst 'a 0 '()
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst test=other key=other 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 0 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst test-not=any key=other 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 0 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y)))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst test=other test-not=other|
(assert-error 'error
(subst 0 1 2 :test #'= :test-not #'=)))
;;; old one left over. Is it still needed?
(define-test subst.1
(assert-equal '(a (c))
(subst 'c '(b) '(a ((b))) :test-not (complement #'equal))))
(define-test |subst test=nil key=identity 1|
(assert-error 'error
(subst 'a
0
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test nil)))
(define-test |subst test-not=nil key=identity 1|
(assert-error 'error
(subst 'a
0
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the subst-if function
(define-test |subst-if key=identity 1|
(assert-equal '()
(subst-if 'a
(lambda (y) (and (numberp y) (zerop (1- y))))
'())))
(define-test |subst-if key=identity 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst-if 'a
(lambda (y) (and (numberp y) (zerop y)))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0))))))
(define-test |subst-if key=other 1|
(assert-equal '()
(subst-if 'a
(lambda (y) (and (numberp y) (zerop (1- y))))
'()
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst-if key=other 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst-if 'a
(lambda (y) (and (numberp y) (zerop (1- y))))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the subst-if-not function
(define-test |subst-if-not key=identity 1|
(assert-equal '()
(subst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop (1- y)))))
'())))
(define-test |subst-if-not key=identity 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop y))))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0))))))
(define-test |subst-if-not key=other 1|
(assert-equal '()
(subst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop (1- y)))))
'()
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst-if-not key=other 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop (1- y)))))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nsubst function
(define-test |nsubst test=eql key=identity 1a|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree))))
(define-test |nsubst test=eql key=identity 1b|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree :test #'eql))))
(define-test |nsubst test=eql key=identity 1c|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree :test 'eql))))
(define-test |nsubst test=eql key=identity 2a|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree)))
(assert-eq tree tree2)))
(define-test |nsubst test=eql key=identity 2b|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree :test #'eql)))
(assert-eq tree tree2)))
(define-test |nsubst test=eql key=identity 2c|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree :test 'eql)))
(assert-eq tree tree2)))
(define-test |nsubst test=eql key=identity 3a|
(assert-equal 2
(nsubst 2 1 1)))
(define-test |nsubst test=eql key=identity 3b|
(assert-equal 2
(nsubst 2 1 1 :test #'eql)))
(define-test |nsubst test=eql key=identity 3c|
(assert-equal 2
(nsubst 2 1 1 :test 'eql)))
(define-test |nsubst test=eql key=nil 1|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree :key nil)))
(assert-eq tree tree2)))
(define-test |nsubst test=eq key=identity 1a|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 'b tree :test #'eq))))
(define-test |nsubst test=eq key=identity 1b|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 'b tree :test 'eq))))
(define-test |nsubst test=eq key=identity 2a|
(let ((tree (copy-tree '(((b . c) . (f . b)) . ((b . d) . (e . b)))))
(tree2))
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(setf tree2 (nsubst 'a 'b tree :test #'eq)))
(assert-eq tree tree2)))
(define-test |nsubst test=eq key=identity 2a|
(let ((tree (copy-tree '(((b . c) . (f . b)) . ((b . d) . (e . b)))))
(tree2))
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(setf tree2 (nsubst 'a 'b tree :test 'eq)))
(assert-eq tree tree2)))
(define-test |nsubst test=eq key=identity 3a|
(assert-equal 'b
(nsubst 'b 'a 'a :test #'eq)))
(define-test |nsubst test=eq key=identity 3b|
(assert-equal 'b
(nsubst 'b 'a 'a :test 'eq)))
(define-test |nsubst test=other key=identity 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree
:test (lambda (x y) (and (numberp y) (= x (1- y))))))))
(define-test |nsubst test=other key=identity 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree
:test (lambda (x y) (and (numberp y) (= x y))))))
(assert-eq tree tree2)))
(define-test |nsubst test=other key=identity 3|
(assert-equal 2
(nsubst 2 1 0 :test (lambda (x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))))
(define-test |nsubst test=eql key=other 1a|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree
:key (lambda (x) (if (numberp x) (1+ x) x))))))
(define-test |nsubst test=eql key=other 1b|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql))))
(define-test |nsubst test=eql key=other 1c|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql))))
(define-test |nsubst test=eql key=other 2a|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 1 tree
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsubst test=eql key=other 2b|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 1 tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql)))
(assert-eq tree tree2)))
(define-test |nsubst test=eql key=other 2c|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 1 tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(assert-eq tree tree2)))
(define-test |nsubst test=eql key=other 3a|
(assert-equal 2
(nsubst 2 1 0 :key #'1+)))
(define-test |nsubst test=eql key=other 3b|
(assert-equal 2
(nsubst 2 1 0 :key #'1+ :test #'eql)))
(define-test |nsubst test=eql key=other 3c|
(assert-equal 2
(nsubst 2 1 0 :key #'1+ :test 'eql)))
(define-test |nsubst test=eq key=other 1a|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 'bb tree
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x))))))
(define-test |nsubst test=eq key=other 1b|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 'bb tree
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x))))))
(define-test |nsubst test=eq key=other 2a|
(let ((tree (copy-tree '(((b . c) . (f . b)) . ((b . d) . (e . b)))))
(tree2))
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(setf tree2 (nsubst 'a 'bb tree
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(assert-eq tree tree2)))
(define-test |nsubst test=eq key=other 2b|
(let ((tree (copy-tree '(((b . c) . (f . b)) . ((b . d) . (e . b)))))
(tree2))
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(setf tree2 (nsubst 'a 'bb tree
:test 'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(assert-eq tree tree2)))
(define-test |nsubst test=eq key=other 3a|
(assert-equal 'b
(nsubst 'b 'a 'c
:test #'eq
:key (lambda (x) (if (eq x 'c) 'a x)))))
(define-test |nsubst test=eq key=other 3b|
(assert-equal 'b
(nsubst 'b 'a 'c
:test 'eq
:key (lambda (x) (if (eq x 'c) 'a x)))))
(define-test |nsubst test=other key=other 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x))))))
(define-test |nsubst test=other key=other 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsubst test=other key=other 3|
(assert-equal 2
(nsubst 2 1 -1
:test (lambda (x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1)))
:key #'1+)))
(define-test |nsubst test-not=other key=identity 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree
:test-not (lambda (x y)
(not (and (numberp y) (= x (1- y)))))))))
(define-test |nsubst test-not=other key=identity 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree
:test-not (lambda (x y)
(not (and (numberp y) (= x y)))))))
(assert-eq tree tree2)))
(define-test |nsubst test-not=other key=identity 3|
(assert-equal 2
(nsubst 2 1 0
:test-not (lambda (x y)
(not (and (numberp x)
(numberp y)
(<= (abs (- x y)) 1)))))))
(define-test |nsubst test-not=any key=other 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y)))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsubst test-not=other key=other 3|
(assert-equal 2
(nsubst 2 1 -1
:test-not (lambda (x y)
(not (and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))
:key #'1+)))
(define-test |nsubst test-not=other key=other 4|
(assert-equal -1
(nsubst 2 1 -1
:test-not (lambda (x y)
(not (and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))
:key #'1-)))
(define-test |nsubst test=other test-not=other|
(assert-error 'error
(nsubst 0 1 2 :test #'= :test-not #'=)))
(define-test |nsubst test=nil key=identity 1|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-error 'error
(setf tree2 (nsubst 'a 0 tree :test nil)))))
(define-test |nsubst test-not=nil key=identity 1|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-error 'error
(setf tree2 (nsubst 'a 0 tree :test-not nil)))))
;;; old one left over. Is it still needed?
(define-test nsubst.1
(let ((tree (copy-tree '(a ((b))))))
(assert-equal '(a (c))
(nsubst 'c '(b) tree :test-not (complement #'equal)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nsubst-if function
(define-test |nsubst-if key=identity 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst-if 'a
(lambda (y) (and (numberp y) (zerop (1- y))))
tree))))
(define-test |nsubst-if key=identity 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst-if 'a
(lambda (y) (and (numberp y) (zerop y)))
tree)))
(assert-eq tree tree2)))
(define-test |nsubst-if key=identity 3|
(assert-equal 2
(nsubst-if 2 #'zerop 0)))
(define-test |nsubst-if key=identity 4|
(assert-equal 1
(nsubst-if 2 #'zerop 1)))
(define-test |nsubst-if key=other 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst-if 'a
(lambda (y) (and (numberp y) (zerop (1- y))))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))))))
(define-test |nsubst-if key=other 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst-if 'a
(lambda (y) (and (numberp y) (zerop (1- y))))
tree
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsubst-if key=other 3|
(assert-equal 2
(nsubst-if 2 #'zerop 1 :key #'1-)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nsubst-if-not function
(define-test |nsubst-if-not key=identity 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop (1- y)))))
tree))))
(define-test |nsubst-if-not key=identity 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop y))))
tree)))
(assert-eq tree tree2)))
(define-test |nsubst-if-not key=identity 3|
(assert-equal 2
(nsubst-if-not 2 #'zerop 1)))
(define-test |nsubst-if-not key=other 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop (1- y)))))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))))))
(define-test |nsubst-if-not key=other 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop (1- y)))))
tree
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsubst-if-not key=other 3|
(assert-equal 2
(nsubst-if-not 2 #'zerop 0 :key #'1+)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the null function
(define-test null.1
(assert-equal t
(null '())))
(define-test null.2
(assert-equal nil
(null 1)))
(define-test null.3
(assert-equal nil
(null #\a)))
(define-test null.4
(assert-equal nil
(null #())))
(define-test null.5
(assert-equal nil
(null "")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the acons function
(define-test acons.1
(assert-equal '((a . b))
(acons 'a 'b '())))
(define-test acons.2
(assert-equal '((a . b) c)
(acons 'a 'b '(c))))
(define-test acons.3
(assert-equal '((a . b) . c)
(acons 'a 'b 'c)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the member function
(define-test |member test=eql key=identity 1|
(assert-equal nil
(member 234 '())))
(define-test |member test=eql key=identity 2a|
(assert-equal '(123 b c)
(member 123 '(a b 123 b c))))
(define-test |member test=eql key=identity 2b|
(assert-equal '(123 b c)
(member 123 '(a b 123 b c) :test #'eql)))
(define-test |member test=eql key=identity 2c|
(assert-equal '(123 b c)
(member 123 '(a b 123 b c) :test 'eql)))
(define-test |member test=eql key=identity 3|
(assert-equal nil
(member 123 '(a b c d e))))
(define-test |member test=eql key=other 1|
(assert-equal '(123 b c)
(member 124 '(a b 123 b c)
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |member test=eql key=other 2|
(assert-equal '(123 b c)
(member 124 '(a b 123 b c)
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(define-test |member test=eql key=nil 1|
(assert-equal '(123 b c)
(member 123 '(a b 123 b c) :key nil)))
(define-test |member test=eq key=identity 1|
(assert-equal '(d e)
(member 'd '(a b c d e)
:test #'eq)))
(define-test |member test=eq key=identity 2|
(assert-equal nil
(member 'f '(a b c d e)
:test #'eq)))
(define-test |member test=eq key=other 1|
(assert-equal '((d) (e))
(member 'd '((a) (b) (c) (d) (e))
:key #'car
:test #'eq)))
(define-test |member test=eq key=other 2|
(assert-equal nil
(member 'f '((a) (b) (c) (d) (e))
:key #'car
:test #'eq)))
(define-test |member test-not=eql key=identity 1|
(assert-equal '(3 4 5 2)
(member 2 '(2 2 2 3 4 5 2)
:test-not #'eql)))
(define-test |member test-not=eql key=identity 2|
(assert-equal nil
(member 2 '(2 2 2)
:test-not #'eql)))
(define-test |member test-not=eql key=other 1|
(assert-equal '(3 4 5 2)
(member 3 '(2 2 2 3 4 5 2)
:key #'1+
:test-not #'eql)))
(define-test |member test-not=eql key=other 2|
(assert-equal nil
(member 3 '(2 2 2)
:key #'1+
:test-not #'eql)))
(define-test |member test-not=eq key=identity 1|
(assert-equal '(3 4 5 a)
(member 'a '(a a a 3 4 5 a)
:test-not #'eq)))
(define-test |member test-not=eq key=identity 2|
(assert-equal nil
(member 'a '(a a a)
:test-not #'eq)))
(define-test |member test-not=eq key=other 1|
(assert-equal '((3) 4 5 a)
(member 'a '((a) (a) (a) (3) 4 5 a)
:key #'car
:test-not #'eq)))
(define-test |member test-not=eq key=other 2|
(assert-equal nil
(member 'a '((a) (a) (a))
:key #'car
:test-not #'eq)))
(define-test |member test=other key=identity 1|
(assert-equal '((123) b c)
(member '(123) '(a b (123) b c)
:test #'equal)))
(define-test |member test=other key=other 1|
(assert-equal '(3 4 5)
(member 5 '(1 2 3 4 5)
:key #'1+
:test (lambda (x y) (= x (1+ y))))))
(define-test |member test=other key=other 2|
(assert-equal nil
(member 10 '(1 2 3 4 5)
:key #'1+
:test (lambda (x y) (= x (1+ y))))))
(define-test |member test-not=other key=other 1|
(assert-equal '(3 4 5)
(member 4 '(1 2 3 4 5)
:key #'1+
:test-not (lambda (x y) (not (zerop (mod y x)))))))
(define-test |member test-not=other key=other 2|
(assert-equal nil
(member 10 '(1 2 3 4 5)
:key #'1+
:test-not (lambda (x y) (not (zerop (mod y x)))))))
(define-test |member error 1|
(assert-error 'type-error
(member 123 '(a b . 123))))
(define-test |member error 2|
(assert-error 'error
(member 123 '(1 2 3)
:test #'eql
:test-not #'eq)))
(define-test |member test=nil key=identity 1|
(assert-error 'error
(member 123 '(a b 123 b c) :test nil)))
(define-test |member test-not=nil key=identity 1|
(assert-error 'error
(member 123 '(a b 123 b c) :test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the member-if function
(define-test |member-if key=identity 1|
(assert-equal nil
(member-if #'oddp '(2 4 6))))
(define-test |member-if key=identity 2|
(assert-equal '(3 4)
(member-if #'oddp '(2 6 3 4))))
(define-test |member-if key=other 1|
(assert-equal '(3 4)
(member-if #'evenp '(2 6 3 4)
:key #'1+)))
(define-test |member-if key=other 2|
(assert-equal nil
(member-if #'evenp '(2 6 4)
:key #'1+)))
(define-test |member-if error 1|
(assert-error 'type-error
(member-if #'oddp '(2 4 6 . 7))))
(define-test |member-if key=other error 1|
(assert-error 'type-error
(member-if #'oddp '(2 4 6 . 7) :key #'identity)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the member-if-not function
(define-test |member-if-not key=identity 1|
(assert-equal nil
(member-if-not #'evenp '(2 4 6))))
(define-test |member-if-not key=identity 2|
(assert-equal '(3 4)
(member-if-not #'evenp '(2 6 3 4))))
(define-test |member-if-not key=other 1|
(assert-equal nil
(member-if-not #'oddp '(2 4 6)
:key #'1+)))
(define-test |member-if-not key=other 2|
(assert-equal '(3 4)
(member-if-not #'oddp '(2 6 3 4)
:key #'1+)))
(define-test |member-if-not error 1|
(assert-error 'type-error
(member-if-not #'evenp '(2 4 6 . 7))))
(define-test |member-if-not key=other error 1|
(assert-error 'type-error
(member-if-not #'evenp '(2 4 6 . 7) :key #'identity)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the assoc function
(define-test |assoc test=eql key=identity 1a|
(assert-equal '(a . b)
(assoc 'a '((b) nil (a . b) (a . c)))))
(define-test |assoc test=eql key=identity 1b|
(assert-equal '(a . b)
(assoc 'a '((b) nil (a . b) (a . c))
:test #'eql)))
(define-test |assoc test=eql key=identity 1c|
(assert-equal '(a . b)
(assoc 'a '((b) nil (a . b) (a . c))
:test 'eql)))
(define-test |assoc test=eql key=identity 2a|
(assert-equal nil
(assoc 'c '((b) nil (a . b) (a . c)))))
(define-test |assoc test=eql key=identity 2b|
(assert-equal nil
(assoc 'c '((b) nil (a . b) (a . c))
:test #'eql)))
(define-test |assoc test=eql key=identity 2c|
(assert-equal nil
(assoc 'c '((b) nil (a . b) (a . c))
:test 'eql)))
(define-test |assoc test=eql key=identity 3a|
(assert-equal '(nil . c)
(assoc 'nil '((b) nil (a . b) (nil . c)))))
(define-test |assoc test=eql key=identity 3b|
(assert-equal '(nil . c)
(assoc 'nil '((b) nil (a . b) (nil . c))
:test #'eql)))
(define-test |assoc test=eql key=identity 3c|
(assert-equal '(nil . c)
(assoc 'nil '((b) nil (a . b) (nil . c))
:test 'eql)))
(define-test |assoc test=eql key=identity 4a|
(assert-equal '(123 . b)
(assoc 123 '((b) nil (123 . b) (nil . c)))))
(define-test |assoc test=eql key=identity 4b|
(assert-equal '(123 . b)
(assoc 123 '((b) nil (123 . b) (nil . c))
:test #'eql)))
(define-test |assoc test=eql key=identity 4c|
(assert-equal '(123 . b)
(assoc 123 '((b) nil (123 . b) (nil . c))
:test 'eql)))
(define-test |assoc test=eql key=identity 5a|
(assert-equal '(#\a . b)
(assoc #\a '((b) nil (#\a . b) (nil . c)))))
(define-test |assoc test=eql key=identity 5b|
(assert-equal '(#\a . b)
(assoc #\a '((b) nil (#\a . b) (nil . c))
:test #'eql)))
(define-test |assoc test=eql key=identity 5c|
(assert-equal '(#\a . b)
(assoc #\a '((b) nil (#\a . b) (nil . c))
:test 'eql)))
(define-test |assoc test=eql key=nil 1|
(assert-equal '(nil . c)
(assoc 'nil '((b) nil (a . b) (nil . c))
:key nil)))
(define-test |assoc test=eq key=identity 1a|
(assert-equal '(a . b)
(assoc 'a '((b) nil (a . b) (a . c))
:test #'eq)))
(define-test |assoc test=eq key=identity 1b|
(assert-equal '(a . b)
(assoc 'a '((b) nil (a . b) (a . c))
:test 'eq)))
(define-test |assoc test=eq key=identity 2a|
(assert-equal nil
(assoc 'c '((b) nil (a . b) (a . c))
:test #'eq)))
(define-test |assoc test=eq key=identity 2b|
(assert-equal nil
(assoc 'c '((b) nil (a . b) (a . c))
:test 'eq)))
(define-test |assoc test=eq key=identity 3a|
(assert-equal '(nil . c)
(assoc 'nil '((b) nil (a . b) (nil . c))
:test #'eq)))
(define-test |assoc test=eq key=identity 3b|
(assert-equal '(nil . c)
(assoc 'nil '((b) nil (a . b) (nil . c))
:test 'eq)))
(define-test |assoc test=other key=identity 1|
(assert-equal '((a b) c)
(assoc '(a b) '((a . b) nil ((a b) c) (d e))
:test #'equal)))
(define-test |assoc test-not=other key=identity 1|
(assert-equal '((a b) c)
(assoc '(a b) '((a . b) nil ((a b) c) (d e))
:test-not (complement #'equal))))
(define-test |assoc test=eql key=other 1a|
(assert-equal '((a b) c)
(assoc 'a '(((b a) . b) nil ((a b) c) ((d) e))
:key #'car)))
(define-test |assoc test=eql key=other 1b|
(assert-equal '((a b) c)
(assoc 'a '(((b a) . b) nil ((a b) c) ((d) e))
:test #'eql
:key #'car)))
(define-test |assoc test=eql key=other 1c|
(assert-equal '((a b) c)
(assoc 'a '(((b a) . b) nil ((a b) c) ((d) e))
:test 'eql
:key #'car)))
(define-test |assoc test=eq key=other 1|
(assert-equal '((a b) c)
(assoc 'a '(((b a) . b) nil ((a b) c) ((d) e))
:test #'eq
:key #'car)))
(define-test |assoc test=other key=other 1|
(assert-equal '((a b) c)
(assoc 'a '(((b a) . b) nil ((a b) c) ((d) e))
:test (lambda (x y) (eq x y))
:key #'car)))
(define-test |assoc test-not=eql key=identity 1a|
(assert-equal '(345 b)
(assoc '234 '((234 a) (345 b) (234 c))
:test-not #'eql)))
(define-test |assoc test-not=eql key=identity 1b|
(assert-equal '(345 b)
(assoc '234 '((234 a) (345 b) (234 c))
:test-not 'eql)))
(define-test |assoc test-not=eql key=identity 2|
(assert-equal nil
(assoc '234 '((234 a) (234 b) (234 c))
:test-not #'eql)))
(define-test |assoc test-not=eql key=identity 3|
(assert-equal '(345 b)
(assoc '234 '((234 a) nil (345 b) (234 c))
:test-not #'eql)))
(define-test |assoc test-not=eq key=identity 1a|
(assert-equal '(y b)
(assoc 'x '((x a) (y b) (x c))
:test-not #'eq)))
(define-test |assoc test-not=eq key=identity 1b|
(assert-equal '(y b)
(assoc 'x '((x a) (y b) (x c))
:test-not 'eq)))
(define-test |assoc test-not=eq key=identity 2|
(assert-equal nil
(assoc 'x '((x a) (x b) (x c))
:test-not #'eq)))
(define-test |assoc test-not=eq key=identity 3|
(assert-equal '(y b)
(assoc 'x '((x a) nil (y b) (x c))
:test-not #'eq)))
(define-test assoc.error.1
(assert-error 'type-error
(assoc 'a '((b . c) nil d (a b)))))
(define-test |assoc test-not=eql key=other 1a|
(assert-equal '(345 b)
(assoc '235 '((234 a) (345 b) (234 c))
:test-not #'eql
:key #'1+)))
(define-test |assoc test-not=eql key=other 1b|
(assert-equal '(345 b)
(assoc '235 '((234 a) (345 b) (234 c))
:test-not 'eql
:key #'1+)))
(define-test |assoc test-not=eql key=other 2|
(assert-equal nil
(assoc '235 '((234 a) (234 b) (234 c))
:test-not #'eql
:key #'1+)))
(define-test |assoc test-not=eql key=other 3|
(assert-equal '(345 b)
(assoc '235 '((234 a) nil (345 b) (234 c))
:test-not #'eql
:key #'1+)))
(define-test |assoc test-not=eq key=other 1a|
(assert-equal '((y) b)
(assoc 'x '(((x) a) ((y) b) ((x) c))
:test-not #'eq
:key #'car)))
(define-test |assoc test-not=eq key=other 1b|
(assert-equal '((y) b)
(assoc 'x '(((x) a) ((y) b) ((x) c))
:test-not 'eq
:key #'car)))
(define-test |assoc test-not=eq key=other 2|
(assert-equal nil
(assoc 'x '(((x) a) ((x) b) ((x) c))
:test-not #'eq
:key #'car)))
(define-test |assoc test-not=eq key=other 3|
(assert-equal '((y) b)
(assoc 'x '(((x) a) nil ((y) b) ((x) c))
:test-not #'eq
:key #'car)))
(define-test |assoc test-not=other key=other 1a|
(assert-equal '(345 b)
(assoc '234 '((234 a) (345 b) (234 c))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |assoc test-not=other key=other 1b|
(assert-equal '(345 b)
(assoc '234 '((234 a) (345 b) (234 c))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |assoc test-not=other key=other 2|
(assert-equal nil
(assoc '234 '((234 a) (234 b) (234 c))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |assoc test-not=other key=other 3|
(assert-equal '(345 b)
(assoc '234 '((234 a) nil (345 b) (234 c))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |assoc error 1|
(assert-error 'type-error
(assoc 'a '((b . c) nil d (a b)))))
(define-test |assoc error 2|
(assert-error 'error
(assoc 'a '((b . c) nil d (a b))
:test #'eq
:test-not #'eq)))
(define-test |assoc test=nil key=identity 1|
(assert-error 'error
(assoc 'nil '((b) nil (a . b) (nil . c))
:test nil)))
(define-test |assoc test-not=nil key=identity 1|
(assert-error 'error
(assoc 'nil '((b) nil (a . b) (nil . c))
:test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the assoc-if function
(define-test |assoc-if key=identity 1|
(assert-equal '(a . b)
(assoc-if (lambda (x) (eq x 'a))
'((b) nil (a . b) (a . c)))))
(define-test |assoc-if key=identity 2|
(assert-equal nil
(assoc-if (lambda (x) (eq x 'c))
'((b) nil (a . b) (a . c)))))
(define-test |assoc-if key=identity 3|
(assert-equal '(nil . c)
(assoc-if #'null
'((b) nil (a . b) (nil . c)))))
(define-test |assoc-if key=identity 4|
(assert-equal '(123 . b)
(assoc-if (lambda (x) (eql x 123))
'((b) nil (123 . b) (nil . c)))))
(define-test |assoc-if key=identity 5|
(assert-equal '(#\a . b)
(assoc-if (lambda (x) (eql x #\a))
'((b) nil (#\a . b) (nil . c)))))
(define-test |assoc-if key=other 1|
(assert-equal '((a b) c)
(assoc-if (lambda (x) (eq x 'a))
'(((b a) . b) nil ((a b) c) ((d) e))
:key #'car)))
(define-test |assoc-if error 1|
(assert-error 'type-error
(assoc-if (lambda (x) (eq x 'a))
'((b . c) nil d (a b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the assoc-if-not function
(define-test |assoc-if-not key=identity 1|
(assert-equal '(a . b)
(assoc-if-not (complement (lambda (x) (eq x 'a)))
'((b) nil (a . b) (a . c)))))
(define-test |assoc-if-not key=identity 2|
(assert-equal nil
(assoc-if-not (complement (lambda (x) (eq x 'c)))
'((b) nil (a . b) (a . c)))))
(define-test |assoc-if-not key=identity 3|
(assert-equal '(nil . c)
(assoc-if-not (complement #'null)
'((b) nil (a . b) (nil . c)))))
(define-test |assoc-if-not key=identity 4|
(assert-equal '(123 . b)
(assoc-if-not (complement (lambda (x) (eql x 123)))
'((b) nil (123 . b) (nil . c)))))
(define-test |assoc-if-not key=identity 5|
(assert-equal '(#\a . b)
(assoc-if-not (complement (lambda (x) (eql x #\a)))
'((b) nil (#\a . b) (nil . c)))))
(define-test |assoc-if-not key=other 6|
(assert-equal '((a b) c)
(assoc-if-not (complement (lambda (x) (eq x 'a)))
'(((b a) . b) nil ((a b) c) ((d) e))
:key #'car)))
(define-test |assoc-if-not error 1|
(assert-error 'type-error
(assoc-if-not (complement (lambda (x) (eq x 'a)))
'((b . c) nil d (a b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the rassoc function
(define-test |rassoc test=eql key=identity 1a|
(assert-equal '(b . a)
(rassoc 'a '((b) nil (b . a) (c . a)))))
(define-test |rassoc test=eql key=identity 1b|
(assert-equal '(b . a)
(rassoc 'a '((b) nil (b . a) (c . a))
:test #'eql)))
(define-test |rassoc test=eql key=identity 1c|
(assert-equal '(b . a)
(rassoc 'a '((b) nil (b . a) (c . a))
:test 'eql)))
(define-test |rassoc test=eql key=identity 2a|
(assert-equal nil
(rassoc 'c '((b) nil (b . a) (c . a)))))
(define-test |rassoc test=eql key=identity 2b|
(assert-equal nil
(rassoc 'c '((b) nil (b . a) (c . a))
:test #'eql)))
(define-test |rassoc test=eql key=identity 2c|
(assert-equal nil
(rassoc 'c '((b) nil (b . a) (c . a))
:test 'eql)))
(define-test |rassoc test=eql key=identity 3a|
(assert-equal '(c . nil)
(rassoc 'nil '((b . x) nil (b . a) (c . nil)))))
(define-test |rassoc test=eql key=identity 3b|
(assert-equal '(c . nil)
(rassoc 'nil '((x . b) nil (b . a) (c . nil))
:test #'eql)))
(define-test |rassoc test=eql key=identity 3c|
(assert-equal '(c . nil)
(rassoc 'nil '((b . x) nil (b . a) (c . nil))
:test 'eql)))
(define-test |rassoc test=eql key=identity 4a|
(assert-equal '(b . 123)
(rassoc 123 '((b . x) nil (b . 123) (c . nil)))))
(define-test |rassoc test=eql key=identity 4b|
(assert-equal '(b . 123)
(rassoc 123 '((b . x) nil (b . 123) (c . nil))
:test #'eql)))
(define-test |rassoc test=eql key=identity 4c|
(assert-equal '(b . 123)
(rassoc 123 '((b . x) nil (b . 123) (c . nil))
:test 'eql)))
(define-test |rassoc test=eql key=identity 5a|
(assert-equal '(b . #\a)
(rassoc #\a '((b . x) nil (b . #\a) (c . nil)))))
(define-test |rassoc test=eql key=identity 5b|
(assert-equal '(b . #\a)
(rassoc #\a '((b . x) nil (b . #\a) (c . nil))
:test #'eql)))
(define-test |rassoc test=eql key=identity 5c|
(assert-equal '(b . #\a)
(rassoc #\a '((b . x) nil (b . #\a) (c . nil))
:test 'eql)))
(define-test |rassoc test=eql key=nil 1|
(assert-equal '(b . 123)
(rassoc 123 '((b . x) nil (b . 123) (c . nil))
:key nil)))
(define-test |rassoc test=eq key=identity 1a|
(assert-equal '(b . a)
(rassoc 'a '((b . x) nil (b . a) (c . a))
:test #'eq)))
(define-test |rassoc test=eq key=identity 1b|
(assert-equal '(b . a)
(rassoc 'a '((b . x) nil (b . a) (c . a))
:test 'eq)))
(define-test |rassoc test=eq key=identity 2a|
(assert-equal nil
(rassoc 'c '((b . x) nil (b . a) (c . a))
:test #'eq)))
(define-test |rassoc test=eq key=identity 2b|
(assert-equal nil
(rassoc 'c '((b . x) nil (b . a) (c . a))
:test 'eq)))
(define-test |rassoc test=eq key=identity 3a|
(assert-equal '(c . nil)
(rassoc 'nil '((b . x) nil (b . a) (c . nil))
:test #'eq)))
(define-test |rassoc test=eq key=identity 3b|
(assert-equal '(c . nil)
(rassoc 'nil '((b . x) nil (b . a) (c . nil))
:test 'eq)))
(define-test |rassoc test=other key=identity 1|
(assert-equal '(c . (a b))
(rassoc '(a b) '((b . a) nil (c . (a b)) (e . d))
:test #'equal)))
(define-test |rassoc test-not=other key=identity 1|
(assert-equal '(c . (a b))
(rassoc '(a b) '((b . a) nil (c . (a b)) (e . d))
:test-not (complement #'equal))))
(define-test |rassoc test=eql key=other 1a|
(assert-equal '(c . (a b))
(rassoc 'a '((b . (b a)) nil (c . (a b)) (e . (d)))
:key #'car)))
(define-test |rassoc test=eql key=other 1b|
(assert-equal '(c . (a b))
(rassoc 'a '((b . (b a)) nil (c . (a b)) (e . (d)))
:test #'eql
:key #'car)))
(define-test |rassoc test=eql key=other 1c|
(assert-equal '(c . (a b))
(rassoc 'a '((b . (b a)) nil (c . (a b)) (e . (d)))
:test 'eql
:key #'car)))
(define-test |rassoc test=eq key=other 1|
(assert-equal '(c . (a b))
(rassoc 'a '((b . (b a)) nil (c . (a b)) (e . (d)))
:test #'eq
:key #'car)))
(define-test |rassoc test=other key=other 1|
(assert-equal '(c . (a b))
(rassoc 'a '((b . (b a)) nil (c . (a b)) (e . (d)))
:test (lambda (x y) (eq x y))
:key #'car)))
(define-test |rassoc test-not=eql key=identity 1a|
(assert-equal '(b . 345)
(rassoc '234 '((a . 234) (b . 345) (c . 234))
:test-not #'eql)))
(define-test |rassoc test-not=eql key=identity 1b|
(assert-equal '(b . 345)
(rassoc '234 '((a . 234) (b . 345) (c . 234))
:test-not 'eql)))
(define-test |rassoc test-not=eql key=identity 2|
(assert-equal nil
(rassoc '234 '((a . 234) (b . 234) (c . 234))
:test-not #'eql)))
(define-test |rassoc test-not=eql key=identity 3|
(assert-equal '(b . 345)
(rassoc '234 '((a . 234) nil (b . 345) (c . 234))
:test-not #'eql)))
(define-test |rassoc test-not=eq key=identity 1a|
(assert-equal '(b . y)
(rassoc 'x '((a . x) (b . y) (c . x))
:test-not #'eq)))
(define-test |rassoc test-not=eq key=identity 1b|
(assert-equal '(b . y)
(rassoc 'x '((a . x) (b . y) (c . x))
:test-not 'eq)))
(define-test |rassoc test-not=eq key=identity 2|
(assert-equal nil
(rassoc 'x '((a . x) (b . x) (c . x))
:test-not #'eq)))
(define-test |rassoc test-not=eq key=identity 3|
(assert-equal '(b . y)
(rassoc 'x '((a . x) nil (b . y) (c . x))
:test-not #'eq)))
(define-test rassoc.error.1
(assert-error 'type-error
(rassoc 'a '((b . c) nil d (a b)))))
(define-test |rassoc test-not=eql key=other 1a|
(assert-equal '(b . 345)
(rassoc '235 '((a . 234) (b . 345) (c . 234))
:test-not #'eql
:key #'1+)))
(define-test |rassoc test-not=eql key=other 1b|
(assert-equal '(b . 345)
(rassoc '235 '((a . 234) (b . 345) (c . 234))
:test-not 'eql
:key #'1+)))
(define-test |rassoc test-not=eql key=other 2|
(assert-equal nil
(rassoc '235 '((a . 234) (b . 234) (c . 234))
:test-not #'eql
:key #'1+)))
(define-test |rassoc test-not=eql key=other 3|
(assert-equal '(b . 345)
(rassoc '235 '((a . 234) nil (b . 345) (c . 234))
:test-not #'eql
:key #'1+)))
(define-test |rassoc test-not=eq key=other 1a|
(assert-equal '(b . (y))
(rassoc 'x '((a . (x)) (b . (y)) (c . (x)))
:test-not #'eq
:key #'car)))
(define-test |rassoc test-not=eq key=other 1b|
(assert-equal '(b . (y))
(rassoc 'x '((a . (x)) (b . (y)) (c . (x)))
:test-not 'eq
:key #'car)))
(define-test |rassoc test-not=eq key=other 2|
(assert-equal nil
(rassoc 'x '((a . (x)) (b . (x)) (c . (x)))
:test-not #'eq
:key #'car)))
(define-test |rassoc test-not=eq key=other 3|
(assert-equal '(b . (y))
(rassoc 'x '((a . (x)) nil (b . (y)) (c . (x)))
:test-not #'eq
:key #'car)))
(define-test |rassoc test-not=other key=other 1a|
(assert-equal '(b . 345)
(rassoc '234 '((a . 234) (b . 345) (c . 234))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |rassoc test-not=other key=other 1b|
(assert-equal '(b . 345)
(rassoc '234 '((a . 234) (b . 345) (c . 234))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |rassoc test-not=other key=other 2|
(assert-equal nil
(rassoc '234 '((a . 234) (b . 234) (c . 234))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |rassoc test-not=other key=other 3|
(assert-equal '(b . 345)
(rassoc '234 '((a . 234) nil (b . 345) (c . 234))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |rassoc error 1|
(assert-error 'type-error
(rassoc 'a '((b . c) nil d (a b)))))
(define-test |rassoc error 2|
(assert-error 'error
(rassoc 'a '((b . c) nil d (a b))
:test #'eq
:test-not #'eq)))
(define-test |rassoc test=nil key=identity 1|
(assert-error 'error
(rassoc 123 '((b . x) nil (b . 123) (c . nil))
:test nil)))
(define-test |rassoc test-not=nil key=identity 1|
(assert-error 'error
(rassoc 123 '((b . x) nil (b . 123) (c . nil))
:test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the rassoc-if function
(define-test rassoc-if.1
(assert-equal '(a . b)
(rassoc-if (lambda (x) (eq x 'b))
'((b) nil (a . b) (a . c)))))
(define-test rassoc-if.2
(assert-equal nil
(rassoc-if (lambda (x) (eq x 'd))
'((b) nil (a . b) (a . c)))))
(define-test rassoc-if.3
(assert-equal '(b)
(rassoc-if #'null
'((b) nil (a . b) (nil . c)))))
(define-test rassoc-if.4
(assert-equal '(b . 123)
(rassoc-if (lambda (x) (eql x 123))
'((b) nil (b . 123) (nil . c)))))
(define-test rassoc-if.5
(assert-equal '(b . #\a)
(rassoc-if (lambda (x) (eql x #\a))
'((b) nil (b . #\a) (nil . c)))))
(define-test rassoc-if.6
(assert-equal '((a b) c)
(rassoc-if (lambda (x) (eq x 'c))
'(((b a) b) ((a b) . (c)) ((d) . e))
:key #'car)))
(define-test rassoc-if.7
(assert-equal '((a b) c)
(rassoc-if (lambda (x) (eq x 'c))
'(((b a) b) nil ((a b) . (c)) ((d) . e))
:key #'car)))
(define-test rassoc-if.error.1
(assert-error 'type-error
(rassoc-if (lambda (x) (eq x 'a))
'((b . c) nil d (a b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the rassoc-if-not function
(define-test rassoc-if-not.1
(assert-equal '(a . b)
(rassoc-if-not (complement (lambda (x) (eq x 'b)))
'((b) nil (a . b) (a . c)))))
(define-test rassoc-if-not.2
(assert-equal nil
(rassoc-if-not (complement (lambda (x) (eq x 'd)))
'((b) nil (a . b) (a . c)))))
(define-test rassoc-if-not.3
(assert-equal '(b)
(rassoc-if-not (complement #'null)
'((b) nil (a . b) (nil . c)))))
(define-test rassoc-if-not.4
(assert-equal '(b . 123)
(rassoc-if-not (complement (lambda (x) (eql x 123)))
'((b) nil (b . 123) (nil . c)))))
(define-test rassoc-if-not.5
(assert-equal '(b . #\a)
(rassoc-if-not (complement (lambda (x) (eql x #\a)))
'((b) nil (b . #\a) (nil . c)))))
(define-test rassoc-if-not.6
(assert-equal '((a b) c)
(rassoc-if-not (complement (lambda (x) (eq x 'c)))
'(((b a) b) nil ((a b) c) ((d) e))
:key #'car)))
(define-test rassoc-if-not.error.1
(assert-error 'type-error
(rassoc-if-not (complement (lambda (x) (eq x 'a)))
'((b . c) nil d (a b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the sublis function
(define-test |sublis test=eql key=identity 1a|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'())))
(define-test |sublis test=eql key=identity 1b|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:test #'eql)))
(define-test |sublis test=eql key=identity 1c|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:test 'eql)))
(define-test |sublis test=eql key=identity 2a|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0))))))
(define-test |sublis test=eql key=identity 2b|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test #'eql)))
(define-test |sublis test=eql key=identity 2c|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test 'eql)))
(define-test |sublis test=eql key=nil 1|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key nil)))
(define-test |sublis test=eq key=identity 1|
(assert-equal '()
(sublis '((xx . y) (b . a)) '()
:test #'eq)))
(define-test |sublis test=eq key=identity 2|
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(sublis '((xx . y) (b . a))
'(((b . c) . (f . b)) . ((b . d) . (e . b)))
:test #'eq)))
(define-test |sublis test=other key=identity 1|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:test (lambda (x y) (and (numberp y) (= x (1- y)))))))
(define-test |sublis test=other key=identity 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test (lambda (x y) (and (numberp y) (= x y))))))
(define-test |sublis test=eql key=other 1a|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |sublis test=eql key=other 1b|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql)))
(define-test |sublis test=eql key=other 1c|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(define-test |sublis test=eql key=other 2a|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (1 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |sublis test=eql key=other 2b|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (1 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql)))
(define-test |sublis test=eql key=other 2c|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (1 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(define-test |sublis test=eq key=other 1|
(assert-equal '()
(sublis '((xx . y) (bb . a))
'()
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(define-test |sublis test=eq key=other 2|
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(sublis '((xx . y) (bb . a))
'(((b . c) . (f . b)) . ((b . d) . (e . b)))
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(define-test |sublis test=other key=other 1|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |sublis test=other key=other 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |sublis test-not=any key=identity 2|
(assert-equal '(((a . 5) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((1 . 5) . (2 . 1)) . ((1 . 3) . (4 . 1)))
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y))))))))
(define-test |sublis test-not=any key=other 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y)))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |sublis test=other test-not=other 1|
(assert-error 'error
(sublis 0 '((1 . 2)) :test #'= :test-not #'=)))
(define-test |sublis test=nil key=identity 1|
(assert-error 'error
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test nil)))
(define-test |sublis test-not=nil key=identity 1|
(assert-error 'error
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nsublis function
(define-test |nsublis test=eql key=identity 1a|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree))))
(define-test |nsublis test=eql key=identity 1b|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:test #'eql))))
(define-test |nsublis test=eql key=identity 1c|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:test 'eql))))
(define-test |nsublis test=eql key=identity 2a|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis
'((10 . xx) (0 . a))
tree)))
(assert-eq tree tree2)))
(define-test |nsublis test=eql key=identity 2b|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis
'((10 . xx) (0 . a))
tree
:test #'eql)))
(assert-eq tree tree2)))
(define-test |nsublis test=eql key=identity 2c|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (0 . a))
tree
:test 'eql)))
(assert-eq tree tree2)))
(define-test |nsublis test=eql key=identity 3a|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
0)))
(define-test |nsublis test=eql key=identity 3b|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
0
:test #'eql)))
(define-test |nsublis test=eql key=identity 3c|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
0
:test 'eql)))
(define-test |nsublis test=eql key=nil 1|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis
'((10 . xx) (0 . a))
tree
:key nil)))
(assert-eq tree tree2)))
(define-test |nsublis test=eq key=identity 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis
'((xx . y) (b . a))
tree
:test #'eq))))
(define-test |nsublis test=eq key=identity 2|
(let ((tree (copy-tree '(((b . c) . (f . b)) . ((b . d) . (e . b)))))
(tree2))
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(setf tree2 (nsublis
'((xx . y) (b . a))
tree
:test #'eq)))
(assert-eq tree tree2)))
(define-test |nsublis test=eq key=identity 3a|
(assert-equal 'a
(nsublis '((10 . xx) (c . a))
'c
:test #'eq)))
(define-test |nsublis test=eq key=identity 3b|
(assert-equal 'a
(nsublis '((10 . xx) (c . a))
'c
:test 'eq)))
(define-test |nsublis test=other key=identity 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:test (lambda (x y) (and (numberp y) (= x (1- y))))))))
(define-test |nsublis test=other key=identity 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (0 . a))
tree
:test (lambda (x y) (and (numberp y) (= x y))))))
(assert-eq tree tree2)))
(define-test |nsublis test=other key=identity 3|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
1
:test (lambda (x y) (and (numberp y) (= x (1- y)))))))
(define-test |nsublis test=eql key=other 1a|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))))))
(define-test |nsublis test=eql key=other 1b|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql))))
(define-test |nsublis test=eql key=other 1c|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql))))
(define-test |nsublis test=eql key=other 2a|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (1 . a))
tree
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsublis test=eql key=other 2b|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (1 . a))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql)))
(assert-eq tree tree2)))
(define-test |nsublis test=eql key=other 2c|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (1 . a))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(assert-eq tree tree2)))
(define-test |nsublis test=eql key=other 3a|
(assert-equal 'a
(nsublis '((10 . xx) (1 . a))
0
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |nsublis test=eq key=other 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((xx . y) (bb . a))
tree
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x))))))
(define-test |nsublis test=eq key=other 2|
(let ((tree (copy-tree '(((b . c) . (f . b)) . ((b . d) . (e . b)))))
(tree2))
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(setf tree2 (nsublis '((xx . y) (bb . a))
tree
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(assert-eq tree tree2)))
(define-test |nsublis test=eq key=other 3|
(assert-equal 'a
(nsublis '((xx . y) (bb . a))
'b
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(define-test |nsublis test=other key=other 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x))))))
(define-test |nsublis test=other key=other 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (0 . a))
tree
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsublis test=other key=other 3|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
0
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |nsublis test-not=any key=identity 2|
(let ((tree (copy-tree '(((1 . 5) . (2 . 1)) . ((1 . 3) . (4 . 1)))))
(tree2))
(assert-equal '(((a . 5) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (0 . a))
tree
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y))))))))
(assert-eq tree tree2)))
(define-test |nsublis test-not=any key=identity 3|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
1
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y))))))))
(define-test |nsublis test-not=any key=identity 4|
(assert-equal 123
(nsublis '((10 . xx) (0 . a))
123
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y))))))))
(define-test |nsublis test-not=any key=other 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (0 . a))
tree
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y)))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsublis test-not=any key=other 3|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
0
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y)))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |nsublis test-not=any key=other 4|
(assert-equal 123
(nsublis '((10 . xx) (0 . a))
123
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y)))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |nsublis test=other test-not=other|
(assert-error 'error
(nsublis 0 '((1 . 2)) :test #'= :test-not #'=)))
(define-test |nsublis test=nil key=identity 1|
(assert-error 'error
(sublis '((10 . xx) (0 . a))
(copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0))))
:test nil)))
(define-test |nsublis test-not=nil key=identity 1|
(assert-error 'error
(nsublis '((10 . xx) (0 . a))
(copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0))))
:test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the pairlis function
(define-test |pairlis 1|
(assert-equal '()
(pairlis '() '())))
(define-test |pairlis 2|
(let ((tail '((a b) (c d))))
(assert-eq tail
(cddr (pairlis '(1 2) '(2 3) tail)))))
(define-test |pairlis 3|
(assert-equal '((c . d) (a . b) (e f))
(pairlis '(a c) '(b d) '((e f)))))
(define-test |pairlis error 1|
(assert-error 'type-error
(pairlis '(a . b) '(c d) '((e f)))))
(define-test |pairlis error 2|
(assert-error 'type-error
(pairlis '(c d) '(a . b) '((e f)))))
(define-test |pairlis error 3|
(assert-error 'error
(pairlis '(a b) '(c d e))))
(define-test |pairlis error 4|
(assert-error 'error
(pairlis '(c d e) '(a b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the copy-alist function
(define-test |copy-alist 1|
(assert-equal '()
(copy-alist '())))
(define-test |copy-alist 2|
(assert-equal '((a) (b))
(copy-alist '((a) (b)))))
(define-test |copy-alist 3|
(assert-false (let ((alist '((a) (b))))
(eq (car alist)
(car (copy-alist alist))))))
(define-test |copy-alist 4|
(assert-equal '((a b) c (d e))
(copy-alist '((a b) c (d e)))))
(define-test |copy-alist 5|
(assert-equal '((a b) nil (d e))
(copy-alist '((a b) nil (d e)))))
(define-test |copy-alist error 2|
(assert-error 'type-error
(copy-alist '((a) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the tailp function
(define-test tailp.1
(assert-false (tailp 123 '())))
(define-test tailp.2
(assert-false (tailp 123 '(123))))
(define-test tailp.3
(assert-true (tailp 123 123)))
(define-test tailp.4
(assert-true (tailp 123 '(a . 123))))
(define-test tailp.5
(let ((tail '(a b)))
(assert-true (tailp tail (list* 1 2 tail)))))
(define-test tailp.6
(let ((tail '(a b)))
(assert-false (tailp tail (list* 1 2 (copy-list tail))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the ldiff function
(define-test ldiff.1
(let ((list '(a b c . d)))
(assert-equal nil (ldiff list list))))
(define-test ldiff.2
(let ((list '(a b c . d)))
(assert-equal '(a) (ldiff list (cdr list)))))
(define-test ldiff.3
(let ((list '(a b c . d)))
(assert-equal '(a b c) (ldiff list 'd))))
(define-test ldiff.4
(let ((list '(a b c . d)))
(assert-equal '(a b c . d) (ldiff list (cons 'c 'd)))))
(define-test ldiff.5
(let ((list '(a b c . d)))
(assert-equal '(a b c . d) (ldiff list 234))))
(define-test ldiff.6
(let ((list '(a b c . d)))
(assert-equal '(a b c . d) (ldiff list nil))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the union function
(define-test |union test=eql key=identity 1a|
(assert-equal '()
(union '() '())))
(define-test |union test=eql key=identity 1b|
(assert-equal '()
(union '() '() :test #'eql)))
(define-test |union test=eql key=identity 1c|
(assert-equal '()
(union '() '() :test 'eql)))
(define-test |union test=eql key=identity 2a|
(assert-equal '()
(set-difference (union '(1 2 3) '(3 4 5))
'(1 2 3 4 5))))
(define-test |union test=eql key=identity 2b|
(assert-equal '()
(set-difference (union '(1 2 3) '(3 4 5) :test #'eql)
'(1 2 3 4 5))))
(define-test |union test=eql key=identity 2|
(assert-equal '()
(set-difference (union '(1 2 3) '(3 4 5) :test 'eql)
'(1 2 3 4 5))))
(define-test |union test=eql key=identity 3a|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (union (append l1 l2) (append l2 l3))
(append l1 l2 l3)))))
(define-test |union test=eql key=identity 3b|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:test #'eql)
(append l1 l2 l3)
:test #'eql))))
(define-test |union test=eql key=identity 3c|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:test 'eql)
(append l1 l2 l3)
:test 'eql))))
(define-test |union test=eql key=identity dotted-list 1|
(assert-error 'type-error
(union '(1 2 . 3) '(2 3 4))))
(define-test |union test=eql key=identity dotted-list 2|
(assert-error 'type-error
(union '(1 2 3) '(2 3 . 4))))
(define-test |union test=eql key=nil 2a|
(assert-equal '()
(set-difference (union '(1 2 3) '(3 4 5) :key nil)
'(1 2 3 4 5))))
(define-test |union test=eq key=identity 1|
(assert-equal '()
(union '() '() :test #'eq)))
(define-test |union test=eq key=identity 2|
(assert-equal '()
(set-difference (union '(abc def) '(abc ghi)
:test #'eq)
'(abc def ghi)
:test #'eq)))
(define-test |union test=eq key=identity 3|
(let ((l1 (loop for code from 30 below 40 collect (string (code-char code))))
(l2 (loop for code from 40 below 100 collect (string (code-char code))))
(l3 (loop for code from 100 below 110 collect (string (code-char code)))))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:test #'eq)
(append l1 l2 l3)
:test #'eq))))
(define-test |union test=eq key=identity dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'eq)))
(define-test |union test=eq key=identity dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'eq)))
(define-test |union test=equal key=identity 1|
(assert-equal '()
(union '() '() :test #'equal)))
(define-test |union test=equal key=identity 2|
(assert-equal '()
(set-difference (union '("abc" "def") '("abc" "ghi")
:test #'equal)
'("abc" "def" "ghi")
:test #'equal)))
(define-test |union test=equal key=identity 3|
(let ((l1 (loop for code from 30 below 100 collect (string (code-char code))))
(l2 (loop for code from 40 below 110 collect (string (code-char code))))
(l3 (loop for code from 30 below 110 collect (string (code-char code)))))
(assert-equal '()
(set-difference (union l1 l2 :test #'equal)
l3
:test #'equal))))
(define-test |union test=equal key=identity dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'equal)))
(define-test |union test=equal key=identity dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'equal)))
(define-test |union test=equalp key=identity 1|
(assert-equal '()
(union '() '() :test #'equalp)))
(define-test |union test=equalp key=identity 3|
(let ((l1 (loop for i from 30 below 100
collect (make-array 1 :initial-element i)))
(l2 (loop for i from 40 below 110
collect (make-array 1 :initial-element i)))
(l3 (loop for i from 30 below 110
collect (make-array 1 :initial-element i))))
(assert-equal '()
(set-difference (union l1 l2 :test #'equalp)
l3
:test #'equalp))))
(define-test |union test=equalp key=identity dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'equalp)))
(define-test |union test=equalp key=identity dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'equalp)))
(define-test |union test=other key=identity 1|
(assert-equal '()
(union '() '() :test #'<)))
(define-test |union test=other key=identity dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'(lambda (x y) (eq x y)))))
(define-test |union test=other key=identity dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'(lambda (x y) (eq x y)))))
(define-test |union test=eql key=other 1a|
(assert-equal 1
(length (union '(1) '(3) :key #'oddp))))
(define-test |union test=eql key=other 1b|
(assert-equal 1
(length (union '(1) '(3) :key #'oddp :test #'eql))))
(define-test |union test=eql key=other 1c|
(assert-equal 1
(length (union '(1) '(3) :key #'oddp :test 'eql))))
(define-test |union test=eql key=other 2a|
(assert-equal 2
(length (union '(4 1) '(3) :key #'oddp))))
(define-test |union test=eql key=other 2b|
(assert-equal 2
(length (union '(4 1) '(3) :key #'oddp :test #'eql))))
(define-test |union test=eql key=other 2c|
(assert-equal 2
(length (union '(4 1) '(3) :key #'oddp :test 'eql))))
(define-test |union test=eql key=other 3|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:key #'car)
(append l1 l2 l3)
:key #'car))))
(define-test |union test=eql key=other 4|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:test #'eql
:key #'car)
(append l1 l2 l3)
:test #'eql
:key #'car))))
(define-test |union test=eql key=other 5|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:test 'eql
:key #'car)
(append l1 l2 l3)
:test 'eql
:key #'car))))
(define-test |union test=eql key=other dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :key #'identity)))
(define-test |union test=eql key=other dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :key #'identity)))
(define-test |union test=eq key=other 1|
(assert-equal '()
(set-difference
(union '((a) (b) (c))
'((b) (c) (d))
:key #'car
:test #'eq)
'((a) (b) (c) (d))
:key #'car
:test #'eq)))
(define-test |union test=eq key=other 3|
(let ((l1 (loop for code from 30 below 40 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 100 collect (list (string (code-char code)))))
(l3 (loop for code from 100 below 110 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:key #'car
:test #'eq)
(append l1 l2 l3)
:test #'eq
:key #'car))))
(define-test |union test=eq key=other dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'eq :key #'identity)))
(define-test |union test=eq key=other dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'eq :key #'identity)))
(define-test |union test=equal key=other 1|
(assert-equal '()
(union '() '() :test #'equal :key #'car)))
(define-test |union test=equal key=other 2|
(assert-equal '()
(set-difference (union '(("abc") ("def")) '(("abc") ("ghi"))
:key #'car
:test #'equal)
'(("abc") ("def") ("ghi"))
:key #'car
:test #'equal)))
(define-test |union test=equal key=other 3|
(let ((l1 (loop for code from 30 below 100 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 110 collect (list (string (code-char code)))))
(l3 (loop for code from 30 below 110 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (union l1 l2 :test #'equal :key #'car)
l3
:test #'equal :key #'car))))
(define-test |union test=equal key=other dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'equal :key #'identity)))
(define-test |union test=equal key=other dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'equal :key #'identity)))
(define-test |union test=equalp key=other 1|
(assert-equal '()
(union '() '() :test #'equalp :key #'car)))
(define-test |union test=equalp key=other 2|
(assert-equal '()
(set-difference (union '((#(1)) (#(2))) '((#(1)) (#(3)))
:key #'car
:test #'equalp)
'((#(1)) (#(2)) (#(3)))
:key #'car
:test #'equalp)))
(define-test |union test=equalp key=other 3|
(let ((l1 (loop for i from 30 below 100
collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 40 below 110
collect (list (make-array 1 :initial-element i))))
(l3 (loop for i from 30 below 110
collect (list (make-array 1 :initial-element i)))))
(assert-equal '()
(set-difference (union l1 l2 :test #'equalp :key #'car)
l3
:test #'equalp :key #'car))))
(define-test |union test=equalp key=other dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'equalp :key #'identity)))
(define-test |union test=equalp key=other dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'equalp :key #'identity)))
(define-test |union test=other key=other 1|
(assert-equal '()
(set-difference
(union '(1 3 5 7)
'(2 4 10 3)
:key (lambda (x) (mod x 5))
:test #'=)
'(0 1 2 3 4) :key (lambda (x) (mod x 5)))))
(define-test |union test=other key=other dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test (lambda (x y) (eq x y)) :key #'identity)))
(define-test |union test=other key=other dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test (lambda (x y) (eq x y)) :key #'identity)))
(define-test |union test-not=other key=identity 1|
(assert-equal '()
(set-difference
(union '(1 2 3 4)
'(3 4 5 6)
:test-not #'/=)
'(1 2 3 4 5 6))))
(define-test |union test-not=other key=other 1|
(assert-equal '()
(set-difference
(union '(1 3 5 7)
'(2 4 10 3)
:key (lambda (x) (mod x 5))
:test-not #'/=)
'(0 1 2 3 4) :key (lambda (x) (mod x 5)))))
(define-test |union test=other test-not=other 1|
(assert-error 'error
(union '(1 2 3) '(2 3 4) :test #'eql :test-not #'eql)))
(define-test |union test=nil key=identity 2a|
(assert-error 'error
(set-difference (union '(1 2 3) '(3 4 5) :test nil)
'(1 2 3 4 5))))
(define-test |union test-not=nil key=identity 2a|
(assert-error 'error
(set-difference (union '(1 2 3) '(3 4 5) :test-not nil)
'(1 2 3 4 5))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nunion function
(define-test |nunion test=eql key=identity 1a|
(assert-equal '()
(nunion '() '())))
(define-test |nunion test=eql key=identity 1b|
(assert-equal '()
(nunion '() '() :test #'eql)))
(define-test |nunion test=eql key=identity 1c|
(assert-equal '()
(nunion '() '() :test 'eql)))
(define-test |nunion test=eql key=identity 2a|
(assert-equal '()
(set-difference (nunion (copy-list '(1 2 3))
(copy-list '(3 4 5)))
'(1 2 3 4 5))))
(define-test |nunion test=eql key=identity 2b|
(assert-equal '()
(set-difference (nunion (copy-list '(1 2 3))
(copy-list '(3 4 5))
:test #'eql)
'(1 2 3 4 5))))
(define-test |nunion test=eql key=identity 2|
(assert-equal '()
(set-difference (nunion (copy-list '(1 2 3))
(copy-list '(3 4 5))
:test 'eql)
'(1 2 3 4 5))))
(define-test |nunion test=eql key=identity 3a|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3)))
(append l1 l2 l3)))))
(define-test |nunion test=eql key=identity 3b|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eql)
(append l1 l2 l3)
:test #'eql))))
(define-test |nunion test=eql key=identity 3c|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test 'eql)
(append l1 l2 l3)
:test 'eql))))
(define-test |nunion test=eql key=nil 1|
(assert-equal '()
(set-difference (nunion (copy-list '(1 2 3))
(copy-list '(3 4 5))
:key nil)
'(1 2 3 4 5))))
(define-test |nunion test=eq key=identity 1|
(assert-equal '()
(nunion '() '() :test #'eq)))
(define-test |nunion test=eq key=identity 2|
(assert-equal '()
(set-difference (nunion '(abc def) '(abc ghi)
:test #'eq)
'(abc def ghi)
:test #'eq)))
(define-test |nunion test=eq key=identity 3|
(let ((l1 (loop for code from 30 below 40 collect (string (code-char code))))
(l2 (loop for code from 40 below 100 collect (string (code-char code))))
(l3 (loop for code from 100 below 110 collect (string (code-char code)))))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eq)
(append l1 l2 l3)
:test #'eq))))
(define-test |nunion test=equal key=identity 1|
(assert-equal '()
(nunion '() '() :test #'equal)))
(define-test |nunion test=equal key=identity 2|
(assert-equal '()
(set-difference (nunion (copy-list '("abc" "def"))
(copy-list '("abc" "ghi"))
:test #'equal)
'("abc" "def" "ghi")
:test #'equal)))
(define-test |nunion test=equal key=identity 3|
(let ((l1 (loop for code from 30 below 100 collect (string (code-char code))))
(l2 (loop for code from 40 below 110 collect (string (code-char code))))
(l3 (loop for code from 30 below 110 collect (string (code-char code)))))
(assert-equal '()
(set-difference (nunion (copy-list l1)
(copy-list l2)
:test #'equal)
l3
:test #'equal))))
(define-test |nunion test=equalp key=identity 1|
(assert-equal '()
(nunion '() '() :test #'equalp)))
(define-test |nunion test=equalp key=identity 3|
(let ((l1 (loop for i from 30 below 100
collect (make-array 1 :initial-element i)))
(l2 (loop for i from 40 below 110
collect (make-array 1 :initial-element i)))
(l3 (loop for i from 30 below 110
collect (make-array 1 :initial-element i))))
(assert-equal '()
(set-difference (nunion (copy-list l1)
(copy-list l2)
:test #'equalp)
l3
:test #'equalp))))
(define-test |nunion test=other key=identity 1|
(assert-equal '()
(nunion '() '() :test #'<)))
(define-test |nunion test=eql key=other 1a|
(assert-equal 1
(length (nunion (copy-list '(1))
(copy-list '(3))
:key #'oddp))))
(define-test |nunion test=eql key=other 1b|
(assert-equal 1
(length (nunion (copy-list '(1))
(copy-list '(3))
:key #'oddp
:test #'eql))))
(define-test |nunion test=eql key=other 1c|
(assert-equal 1
(length (nunion (copy-list '(1))
(copy-list '(3))
:key #'oddp
:test 'eql))))
(define-test |nunion test=eql key=other 2a|
(assert-equal 2
(length (nunion (copy-list '(4 1))
(copy-list '(3))
:key #'oddp))))
(define-test |nunion test=eql key=other 2b|
(assert-equal 2
(length (nunion (copy-list '(4 1))
(copy-list '(3))
:key #'oddp
:test #'eql))))
(define-test |nunion test=eql key=other 2c|
(assert-equal 2
(length (nunion (copy-list '(4 1))
(copy-list '(3))
:key #'oddp
:test 'eql))))
(define-test |nunion test=eql key=other 3|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key #'car)
(append l1 l2 l3)
:key #'car))))
(define-test |nunion test=eql key=other 4|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eql
:key #'car)
(append l1 l2 l3)
:test #'eql
:key #'car))))
(define-test |nunion test=eql key=other 5|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test 'eql
:key #'car)
(append l1 l2 l3)
:test 'eql
:key #'car))))
(define-test |nunion test=eq key=other 1|
(assert-equal '()
(set-difference
(nunion (copy-list '((a) (b) (c)))
(copy-list '((b) (c) (d)))
:key #'car
:test #'eq)
'((a) (b) (c) (d))
:key #'car
:test #'eq)))
(define-test |nunion test=eq key=other 3|
(let ((l1 (loop for code from 30 below 40 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 100 collect (list (string (code-char code)))))
(l3 (loop for code from 100 below 110 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key #'car
:test #'eq)
(append l1 l2 l3)
:test #'eq
:key #'car))))
(define-test |nunion test=equal key=other 1|
(assert-equal '()
(nunion '() '() :test #'equal :key #'car)))
(define-test |nunion test=equal key=other 2|
(assert-equal '()
(set-difference (nunion (copy-list '(("abc") ("def")))
(copy-list '(("abc") ("ghi")))
:key #'car
:test #'equal)
'(("abc") ("def") ("ghi"))
:key #'car
:test #'equal)))
(define-test |nunion test=equal key=other 3|
(let ((l1 (loop for code from 30 below 100 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 110 collect (list (string (code-char code)))))
(l3 (loop for code from 30 below 110 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (nunion (copy-list l1)
(copy-list l2)
:test #'equal
:key #'car)
l3
:test #'equal :key #'car))))
(define-test |nunion test=equalp key=other 1|
(assert-equal '()
(nunion '() '() :test #'equalp :key #'car)))
(define-test |nunion test=equalp key=other 2|
(assert-equal '()
(set-difference (nunion (copy-list '((#(1)) (#(2))))
(copy-list '((#(1)) (#(3))))
:key #'car
:test #'equalp)
'((#(1)) (#(2)) (#(3)))
:key #'car
:test #'equalp)))
(define-test |nunion test=equalp key=other 3|
(let ((l1 (loop for i from 30 below 100
collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 40 below 110
collect (list (make-array 1 :initial-element i))))
(l3 (loop for i from 30 below 110
collect (list (make-array 1 :initial-element i)))))
(assert-equal '()
(set-difference (nunion (copy-list l1)
(copy-list l2)
:test #'equalp
:key #'car)
l3
:test #'equalp :key #'car))))
(define-test |nunion test=other key=other 1|
(assert-equal '()
(set-difference
(nunion (copy-list '(1 3 5 7))
(copy-list '(2 4 10 3))
:key (lambda (x) (mod x 5))
:test #'=)
'(0 1 2 3 4) :key (lambda (x) (mod x 5)))))
(define-test |nunion test-not=other key=identity 1|
(assert-equal '()
(set-difference
(nunion (copy-list '(1 2 3 4))
(copy-list '(3 4 5 6))
:test-not #'/=)
'(1 2 3 4 5 6))))
(define-test |nunion test-not=other key=other 1|
(assert-equal '()
(set-difference
(nunion (copy-list '(1 3 5 7))
(copy-list '(2 4 10 3))
:key (lambda (x) (mod x 5))
:test-not #'/=)
'(0 1 2 3 4) :key (lambda (x) (mod x 5)))))
(define-test |nunion test=other test-not=other 1|
(assert-error 'error
(nunion (copy-list '(1 2 3))
(copy-list '(2 3 4))
:test #'eql
:test-not #'eql)))
(define-test |nunion test=nil key=identity 1|
(assert-error 'error
(set-difference (nunion (copy-list '(1 2 3))
(copy-list '(3 4 5))
:test nil)
'(1 2 3 4 5))))
(define-test |nunion test-not=nil key=identity 1|
(assert-error 'error
(set-difference (nunion (copy-list '(1 2 3))
(copy-list '(3 4 5))
:test-not nil)
'(1 2 3 4 5))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the intersection function
(define-test |intersection test=eql key=identity 1a|
(assert-equal '()
(intersection '() '())))
(define-test |intersection test=eql key=identity 1b|
(assert-equal '()
(intersection '() '() :test #'eql)))
(define-test |intersection test=eql key=identity 1c|
(assert-equal '()
(intersection '() '() :test 'eql)))
(define-test |intersection test=eql key=identity 2a|
(assert-equal '()
(set-difference (intersection (copy-list '(1 2 3 4))
(copy-list '(2 3 4 5)))
'(2 3 4))))
(define-test |intersection test=eql key=identity 2b|
(assert-equal '()
(set-difference (intersection (copy-list '(1 2 3 4))
(copy-list '(2 3 4 5))
:test #'eql)
'(2 3 4))))
(define-test |intersection test=eql key=identity 2|
(assert-equal '()
(set-difference (intersection (copy-list '(1 2 3 4))
(copy-list '(2 3 4 5))
:test 'eql)
'(2 3 4))))
(define-test |intersection test=eql key=identity 3a|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3)))
l2))))
(define-test |intersection test=eql key=identity 3b|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eql)
l2
:test #'eql))))
(define-test |intersection test=eql key=identity 3c|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test 'eql)
l2
:test 'eql))))
(define-test |intersection test=eql key=nil 1|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key nil)
l2))))
(define-test |intersection test=eq key=identity 1|
(assert-equal '()
(intersection '() '() :test #'eq)))
(define-test |intersection test=eq key=identity 2|
(assert-equal '()
(set-difference (intersection '(abc def) '(abc ghi)
:test #'eq)
'(abc)
:test #'eq)))
(define-test |intersection test=eq key=identity 3|
(let ((l1 (loop for code from 30 below 40 collect (string (code-char code))))
(l2 (loop for code from 40 below 100 collect (string (code-char code))))
(l3 (loop for code from 100 below 110 collect (string (code-char code)))))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eq)
l2
:test #'eq))))
(define-test |intersection test=equal key=identity 1|
(assert-equal '()
(intersection '() '() :test #'equal)))
(define-test |intersection test=equal key=identity 2|
(assert-equal '()
(set-difference (intersection (copy-list '("abc" "def"))
(copy-list '("abc" "ghi"))
:test #'equal)
'("abc")
:test #'equal)))
(define-test |intersection test=equal key=identity 3|
(let ((l1 (loop for code from 30 below 100 collect (string (code-char code))))
(l2 (loop for code from 40 below 110 collect (string (code-char code))))
(l3 (loop for code from 40 below 100 collect (string (code-char code)))))
(assert-equal '()
(set-difference (intersection (copy-list l1)
(copy-list l2)
:test #'equal)
l3
:test #'equal))))
(define-test |intersection test=equalp key=identity 1|
(assert-equal '()
(intersection '() '() :test #'equalp)))
(define-test |intersection test=equalp key=identity 3|
(let ((l1 (loop for i from 30 below 100
collect (make-array 1 :initial-element i)))
(l2 (loop for i from 40 below 110
collect (make-array 1 :initial-element i)))
(l3 (loop for i from 40 below 100
collect (make-array 1 :initial-element i))))
(assert-equal '()
(set-difference (intersection (copy-list l1)
(copy-list l2)
:test #'equalp)
l3
:test #'equalp))))
(define-test |intersection test=other key=identity 1|
(assert-equal '()
(intersection '() '() :test #'<)))
(define-test |intersection test=eql key=other 1a|
(assert-equal 1
(length (intersection (copy-list '(1))
(copy-list '(3))
:key #'oddp))))
(define-test |intersection test=eql key=other 1b|
(assert-equal 1
(length (intersection (copy-list '(1))
(copy-list '(3))
:key #'oddp
:test #'eql))))
(define-test |intersection test=eql key=other 1c|
(assert-equal 1
(length (intersection (copy-list '(1))
(copy-list '(3))
:key #'oddp
:test 'eql))))
(define-test |intersection test=eql key=other 2a|
(assert-equal 1
(length (intersection (copy-list '(4 1))
(copy-list '(3))
:key #'oddp))))
(define-test |intersection test=eql key=other 2b|
(assert-equal 1
(length (intersection (copy-list '(4 1))
(copy-list '(3))
:key #'oddp
:test #'eql))))
(define-test |intersection test=eql key=other 2c|
(assert-equal 1
(length (intersection (copy-list '(4 1))
(copy-list '(3))
:key #'oddp
:test 'eql))))
(define-test |intersection test=eql key=other 3|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key #'car)
l2
:key #'car))))
(define-test |intersection test=eql key=other 4|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eql
:key #'car)
l2
:test #'eql
:key #'car))))
(define-test |intersection test=eql key=other 5|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test 'eql
:key #'car)
l2
:test 'eql
:key #'car))))
(define-test |intersection test=eq key=other 1|
(assert-equal '()
(set-difference
(intersection (copy-list '((a) (b) (c)))
(copy-list '((b) (c) (d)))
:key #'car
:test #'eq)
'((b) (c))
:key #'car
:test #'eq)))
(define-test |intersection test=eq key=other 3|
(let ((l1 (loop for code from 30 below 40 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 100 collect (list (string (code-char code)))))
(l3 (loop for code from 100 below 110 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key #'car
:test #'eq)
l2
:test #'eq
:key #'car))))
(define-test |intersection test=equal key=other 1|
(assert-equal '()
(intersection '()
'()
:test #'equal
:key #'car)))
(define-test |intersection test=equal key=other 2|
(assert-equal '()
(set-difference (intersection (copy-list '(("abc") ("def")))
(copy-list '(("abc") ("ghi")))
:key #'car
:test #'equal)
'(("abc"))
:key #'car
:test #'equal)))
(define-test |intersection test=equal key=other 3|
(let ((l1 (loop for code from 30 below 100 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 110 collect (list (string (code-char code)))))
(l3 (loop for code from 40 below 100 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (intersection (copy-list l1)
(copy-list l2)
:test #'equal
:key #'car)
l3
:test #'equal :key #'car))))
(define-test |intersection test=equalp key=other 1|
(assert-equal '()
(intersection '() '() :test #'equalp :key #'car)))
(define-test |intersection test=equalp key=other 2|
(assert-equal '()
(set-difference (intersection (copy-list '((#(1)) (#(2))))
(copy-list '((#(1)) (#(3))))
:key #'car
:test #'equalp)
'((#(1)))
:key #'car
:test #'equalp)))
(define-test |intersection test=equalp key=other 3|
(let ((l1 (loop for i from 30 below 100
collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 40 below 110
collect (list (make-array 1 :initial-element i))))
(l3 (loop for i from 40 below 100
collect (list (make-array 1 :initial-element i)))))
(assert-equal '()
(set-difference (intersection (copy-list l1)
(copy-list l2)
:test #'equalp
:key #'car)
l3
:test #'equalp :key #'car))))
(define-test |intersection test=other key=other 1|
(assert-equal '()
(set-difference
(intersection (copy-list '(1 3 5 7))
(copy-list '(2 4 10 3))
:key (lambda (x) (mod x 5))
:test #'=)
'(3 5 7) :key (lambda (x) (mod x 5)))))
(define-test |intersection test-not=other key=identity 1|
(assert-equal '()
(set-difference
(intersection (copy-list '(1 2 3 4))
(copy-list '(3 4 5 6))
:test-not #'/=)
'(3 4))))
(define-test |intersection test-not=other key=other 1|
(assert-equal '()
(set-difference
(intersection (copy-list '(1 3 5 7))
(copy-list '(2 4 10 3))
:key (lambda (x) (mod x 5))
:test-not #'/=)
'(3 5 7) :key (lambda (x) (mod x 5)))))
(define-test |intersection test=other test-not=other 1|
(assert-error 'error
(intersection (copy-list '(1 2 3))
(copy-list '(2 3 4))
:test #'eql
:test-not #'eql)))
(define-test |intersection test=nil key=identity 1|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-error 'error
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test nil)
l2))))
(define-test |intersection test-not=nil key=identity 1|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-error 'error
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test-not nil)
l2))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nintersection function
(define-test |nintersection test=eql key=identity 1a|
(assert-equal '()
(nintersection '() '())))
(define-test |nintersection test=eql key=identity 1b|
(assert-equal '()
(nintersection '() '() :test #'eql)))
(define-test |nintersection test=eql key=identity 1c|
(assert-equal '()
(nintersection '() '() :test 'eql)))
(define-test |nintersection test=eql key=identity 2a|
(assert-equal '()
(set-difference (nintersection (copy-list '(1 2 3 4))
(copy-list '(2 3 4 5)))
'(2 3 4))))
(define-test |nintersection test=eql key=identity 2b|
(assert-equal '()
(set-difference (nintersection (copy-list '(1 2 3 4))
(copy-list '(2 3 4 5))
:test #'eql)
'(2 3 4))))
(define-test |nintersection test=eql key=identity 2|
(assert-equal '()
(set-difference (nintersection (copy-list '(1 2 3 4))
(copy-list '(2 3 4 5))
:test 'eql)
'(2 3 4))))
(define-test |nintersection test=eql key=identity 3a|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3)))
l2))))
(define-test |nintersection test=eql key=identity 3b|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eql)
l2
:test #'eql))))
(define-test |nintersection test=eql key=identity 3c|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test 'eql)
l2
:test 'eql))))
(define-test |nintersection test=eql key=nil 1|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key nil)
l2))))
(define-test |nintersection test=eq key=identity 1|
(assert-equal '()
(nintersection '() '() :test #'eq)))
(define-test |nintersection test=eq key=identity 2|
(assert-equal '()
(set-difference (nintersection '(abc def) '(abc ghi)
:test #'eq)
'(abc)
:test #'eq)))
(define-test |nintersection test=eq key=identity 3|
(let ((l1 (loop for code from 30 below 40 collect (string (code-char code))))
(l2 (loop for code from 40 below 100 collect (string (code-char code))))
(l3 (loop for code from 100 below 110 collect (string (code-char code)))))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eq)
l2
:test #'eq))))
(define-test |nintersection test=equal key=identity 1|
(assert-equal '()
(nintersection '() '() :test #'equal)))
(define-test |nintersection test=equal key=identity 2|
(assert-equal '()
(set-difference (nintersection (copy-list '("abc" "def"))
(copy-list '("abc" "ghi"))
:test #'equal)
'("abc")
:test #'equal)))
(define-test |nintersection test=equal key=identity 3|
(let ((l1 (loop for code from 30 below 100 collect (string (code-char code))))
(l2 (loop for code from 40 below 110 collect (string (code-char code))))
(l3 (loop for code from 40 below 100 collect (string (code-char code)))))
(assert-equal '()
(set-difference (nintersection (copy-list l1)
(copy-list l2)
:test #'equal)
l3
:test #'equal))))
(define-test |nintersection test=equalp key=identity 1|
(assert-equal '()
(nintersection '() '() :test #'equalp)))
(define-test |nintersection test=equalp key=identity 3|
(let ((l1 (loop for i from 30 below 100
collect (make-array 1 :initial-element i)))
(l2 (loop for i from 40 below 110
collect (make-array 1 :initial-element i)))
(l3 (loop for i from 40 below 100
collect (make-array 1 :initial-element i))))
(assert-equal '()
(set-difference (nintersection (copy-list l1)
(copy-list l2)
:test #'equalp)
l3
:test #'equalp))))
(define-test |nintersection test=other key=identity 1|
(assert-equal '()
(nintersection '() '() :test #'<)))
(define-test |nintersection test=eql key=other 1a|
(assert-equal 1
(length (nintersection (copy-list '(1))
(copy-list '(3))
:key #'oddp))))
(define-test |nintersection test=eql key=other 1b|
(assert-equal 1
(length (nintersection (copy-list '(1))
(copy-list '(3))
:key #'oddp
:test #'eql))))
(define-test |nintersection test=eql key=other 1c|
(assert-equal 1
(length (nintersection (copy-list '(1))
(copy-list '(3))
:key #'oddp
:test 'eql))))
(define-test |nintersection test=eql key=other 2a|
(assert-equal 1
(length (nintersection (copy-list '(4 1))
(copy-list '(3))
:key #'oddp))))
(define-test |nintersection test=eql key=other 2b|
(assert-equal 1
(length (nintersection (copy-list '(4 1))
(copy-list '(3))
:key #'oddp
:test #'eql))))
(define-test |nintersection test=eql key=other 2c|
(assert-equal 1
(length (nintersection (copy-list '(4 1))
(copy-list '(3))
:key #'oddp
:test 'eql))))
(define-test |nintersection test=eql key=other 3|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key #'car)
l2
:key #'car))))
(define-test |nintersection test=eql key=other 4|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eql
:key #'car)
l2
:test #'eql
:key #'car))))
(define-test |nintersection test=eql key=other 5|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test 'eql
:key #'car)
l2
:test 'eql
:key #'car))))
(define-test |nintersection test=eq key=other 1|
(assert-equal '()
(set-difference
(nintersection (copy-list '((a) (b) (c)))
(copy-list '((b) (c) (d)))
:key #'car
:test #'eq)
'((b) (c))
:key #'car
:test #'eq)))
(define-test |nintersection test=eq key=other 3|
(let ((l1 (loop for code from 30 below 40 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 100 collect (list (string (code-char code)))))
(l3 (loop for code from 100 below 110 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key #'car
:test #'eq)
l2
:test #'eq
:key #'car))))
(define-test |nintersection test=equal key=other 1|
(assert-equal '()
(nintersection '()
'()
:test #'equal
:key #'car)))
(define-test |nintersection test=equal key=other 2|
(assert-equal '()
(set-difference (nintersection (copy-list '(("abc") ("def")))
(copy-list '(("abc") ("ghi")))
:key #'car
:test #'equal)
'(("abc"))
:key #'car
:test #'equal)))
(define-test |nintersection test=equal key=other 3|
(let ((l1 (loop for code from 30 below 100 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 110 collect (list (string (code-char code)))))
(l3 (loop for code from 40 below 100 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (nintersection (copy-list l1)
(copy-list l2)
:test #'equal
:key #'car)
l3
:test #'equal :key #'car))))
(define-test |nintersection test=equalp key=other 1|
(assert-equal '()
(nintersection '() '() :test #'equalp :key #'car)))
(define-test |nintersection test=equalp key=other 2|
(assert-equal '()
(set-difference (nintersection (copy-list '((#(1)) (#(2))))
(copy-list '((#(1)) (#(3))))
:key #'car
:test #'equalp)
'((#(1)))
:key #'car
:test #'equalp)))
(define-test |nintersection test=equalp key=other 3|
(let ((l1 (loop for i from 30 below 100
collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 40 below 110
collect (list (make-array 1 :initial-element i))))
(l3 (loop for i from 40 below 100
collect (list (make-array 1 :initial-element i)))))
(assert-equal '()
(set-difference (nintersection (copy-list l1)
(copy-list l2)
:test #'equalp
:key #'car)
l3
:test #'equalp :key #'car))))
(define-test |nintersection test=other key=other 1|
(assert-equal '()
(set-difference
(nintersection (copy-list '(1 3 5 7))
(copy-list '(2 4 10 3))
:key (lambda (x) (mod x 5))
:test #'=)
'(3 5 7) :key (lambda (x) (mod x 5)))))
(define-test |nintersection test-not=other key=identity 1|
(assert-equal '()
(set-difference
(nintersection (copy-list '(1 2 3 4))
(copy-list '(3 4 5 6))
:test-not #'/=)
'(3 4))))
(define-test |nintersection test-not=other key=other 1|
(assert-equal '()
(set-difference
(nintersection (copy-list '(1 3 5 7))
(copy-list '(2 4 10 3))
:key (lambda (x) (mod x 5))
:test-not #'/=)
'(3 5 7) :key (lambda (x) (mod x 5)))))
(define-test |nintersection test=other test-not=other 1|
(assert-error 'error
(nintersection (copy-list '(1 2 3))
(copy-list '(2 3 4))
:test #'eql
:test-not #'eql)))
(define-test |nintersection test=nil key=identity 1|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-error 'error
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test nil)
l2))))
(define-test |nintersection test-not=nil key=identity 1|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-error 'error
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test-not nil)
l2))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the set-difference function
(define-test |set-difference test=eql key=identity 1a|
(assert-equal '()
(set-difference '() '())))
(define-test |set-difference test=eql key=identity 1b|
(assert-equal '()
(set-difference '()
'()
:test #'eql)))
(define-test |set-difference test=eql key=identity 1c|
(assert-equal '()
(set-difference '()
'()
:test 'eql)))
(define-test |set-difference test=eql key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)))))
(define-test |set-difference test=eql key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:test #'eql))))
(define-test |set-difference test=eql key=identity 2c|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:test 'eql))))
(define-test |set-difference test=eql key=identity 3a|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 200 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)))))
(define-test |set-difference test=eql key=identity 3b|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 200 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:test #'eql))))
(define-test |set-difference test=eql key=identity 3c|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 200 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:test 'eql))))
(define-test |set-difference test=eql key=nil 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:key nil))))
(define-test |set-difference test=eq key=identity 1|
(assert-equal '()
(set-difference '()
'()
:test #'eq)))
(define-test |set-difference test=eq key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal 1
(length (set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))
(assert-eq (car l1)
(car (set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))))
(define-test |set-difference test=eq key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal 1
(length (set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'eq)))
(assert-eq (car l1)
(car (set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'eq)))))
(define-test |set-difference test=eq key=identity 3|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal 1
(length (set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))
(assert-eq (car l1)
(car (set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))))
(define-test |set-difference test=equal key=identity 1|
(assert-equal '()
(set-difference '()
'()
:test #'equal)))
(define-test |set-difference test=equal key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equal))))
(define-test |set-difference test=equal key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'equal))))
(define-test |set-difference test=equal key=identity 3|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equal))))
(define-test |set-difference test=equalp key=identity 1|
(assert-equal '()
(set-difference '()
'()
:test #'equalp)))
(define-test |set-difference test=equalp key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 20 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equalp))))
(define-test |set-difference test=equalp key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 20 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'equalp))))
(define-test |set-difference test=equalp key=identity 3a|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 200 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equalp))))
(define-test |set-difference test=equalp key=identity 3b|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 200 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equalp))))
(define-test |set-difference test=other key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 1 below 20 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:test #'>))))
(define-test |set-difference test-not=other key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 1 below 20 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:test-not #'<=))))
(define-test |set-difference test=eql key=other 1a|
(assert-equal '()
(set-difference '()
'()
:key #'car)))
(define-test |set-difference test=eql key=other 1b|
(assert-equal '()
(set-difference '()
'()
:key #'car
:test #'eql)))
(define-test |set-difference test=eql key=other 1c|
(assert-equal '()
(set-difference '()
'()
:key #'car
:test 'eql)))
(define-test |set-difference test=eql key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car))))
(define-test |set-difference test=eql key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car
:test #'eql))))
(define-test |set-difference test=eql key=other 2c|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car
:test 'eql))))
(define-test |set-difference test=eql key=other 3a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car))))
(define-test |set-difference test=eql key=other 3b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car
:test #'eql))))
(define-test |set-difference test=eql key=other 3c|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car
:test 'eql))))
(define-test |set-difference test=eq key=other 1|
(assert-equal '()
(set-difference '()
'()
:key #'car
:test #'eq)))
(define-test |set-difference test=eq key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal 1
(length (set-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))
(assert-eq (car l1)
(car (set-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))))
(define-test |set-difference test=eq key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal 1
(length (set-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test 'eq)))
(assert-eq (car l1)
(car (set-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test 'eq)))))
(define-test |set-difference test=eq key=other 3|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 200 collect (list (list i)))))
(assert-equal 1
(length (set-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))
(assert-eq (car l1)
(car (set-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))))
(define-test |set-difference test=equal key=other 1|
(assert-equal '()
(set-difference '()
'()
:key #'car
:test #'equal)))
(define-test |set-difference test=equal key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal '(((1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equal))))
(define-test |set-difference test=equal key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal '(((1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test 'equal))))
(define-test |set-difference test=equal key=other 3|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 200 collect (list (list i)))))
(assert-equal '(((1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equal))))
(define-test |set-difference test=equalp key=other 1|
(assert-equal '()
(set-difference '()
'()
:key #'car
:test #'equalp)))
(define-test |set-difference test=equalp key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 20 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equalp))))
(define-test |set-difference test=equalp key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 20 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test 'equalp))))
(define-test |set-difference test=equalp key=other 3a|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 200 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equalp))))
(define-test |set-difference test=equalp key=other 3b|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 200 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test 'equalp))))
(define-test |set-difference test=other key=other 1|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 1 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car
:test #'>))))
(define-test |set-difference test-not=other key=other 1|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 1 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car
:test-not #'<=))))
(define-test |set-difference test=other test-not=other 1|
(assert-error 'error
(set-difference '(1 2 3) '(2 3 4)
:test #'eql
:test-not #'eql)))
(define-test |set-difference test=nil key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-error 'error
(set-difference (copy-list l1)
(copy-list l2)
:test nil))))
(define-test |set-difference test-not=nil key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-error 'error
(set-difference (copy-list l1)
(copy-list l2)
:test-not nil))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nset-difference function
(define-test |nset-difference test=eql key=identity 1a|
(assert-equal '()
(nset-difference '() '())))
(define-test |nset-difference test=eql key=identity 1b|
(assert-equal '()
(nset-difference '()
'()
:test #'eql)))
(define-test |nset-difference test=eql key=identity 1c|
(assert-equal '()
(nset-difference '()
'()
:test 'eql)))
(define-test |nset-difference test=eql key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)))))
(define-test |nset-difference test=eql key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:test #'eql))))
(define-test |nset-difference test=eql key=identity 2c|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:test 'eql))))
(define-test |nset-difference test=eql key=identity 3a|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 200 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)))))
(define-test |nset-difference test=eql key=identity 3b|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 200 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:test #'eql))))
(define-test |nset-difference test=eql key=identity 3c|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 200 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:test 'eql))))
(define-test |nset-difference test=eql key=nil 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:key nil))))
(define-test |nset-difference test=eq key=identity 1|
(assert-equal '()
(nset-difference '()
'()
:test #'eq)))
(define-test |nset-difference test=eq key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal 1
(length (nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))
(assert-eq (car l1)
(car (nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))))
(define-test |nset-difference test=eq key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal 1
(length (nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'eq)))
(assert-eq (car l1)
(car (nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'eq)))))
(define-test |nset-difference test=eq key=identity 3|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal 1
(length (nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))
(assert-eq (car l1)
(car (nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))))
(define-test |nset-difference test=equal key=identity 1|
(assert-equal '()
(nset-difference '()
'()
:test #'equal)))
(define-test |nset-difference test=equal key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equal))))
(define-test |nset-difference test=equal key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'equal))))
(define-test |nset-difference test=equal key=identity 3|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equal))))
(define-test |nset-difference test=equalp key=identity 1|
(assert-equal '()
(nset-difference '()
'()
:test #'equalp)))
(define-test |nset-difference test=equalp key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 20 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equalp))))
(define-test |nset-difference test=equalp key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 20 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'equalp))))
(define-test |nset-difference test=equalp key=identity 3a|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 200 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equalp))))
(define-test |nset-difference test=equalp key=identity 3b|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 200 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equalp))))
(define-test |nset-difference test=other key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 1 below 20 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:test #'>))))
(define-test |nset-difference test-not=other key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 1 below 20 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:test-not #'<=))))
(define-test |nset-difference test=eql key=other 1a|
(assert-equal '()
(nset-difference '()
'()
:key #'car)))
(define-test |nset-difference test=eql key=other 1b|
(assert-equal '()
(nset-difference '()
'()
:key #'car
:test #'eql)))
(define-test |nset-difference test=eql key=other 1c|
(assert-equal '()
(nset-difference '()
'()
:key #'car
:test 'eql)))
(define-test |nset-difference test=eql key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car))))
(define-test |nset-difference test=eql key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car
:test #'eql))))
(define-test |nset-difference test=eql key=other 2c|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car
:test 'eql))))
(define-test |nset-difference test=eql key=other 3a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car))))
(define-test |nset-difference test=eql key=other 3b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car
:test #'eql))))
(define-test |nset-difference test=eql key=other 3c|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car
:test 'eql))))
(define-test |nset-difference test=eq key=other 1|
(assert-equal '()
(nset-difference '()
'()
:key #'car
:test #'eq)))
(define-test |nset-difference test=eq key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal 1
(length (nset-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))
(assert-eq (car l1)
(car (nset-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))))
(define-test |nset-difference test=eq key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal 1
(length (nset-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test 'eq)))
(assert-eq (car l1)
(car (nset-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test 'eq)))))
(define-test |nset-difference test=eq key=other 3|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal 1
(length (nset-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))
(assert-eq (car l1)
(car (nset-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))))
(define-test |nset-difference test=equal key=other 1|
(assert-equal '()
(nset-difference '()
'()
:key #'car
:test #'equal)))
(define-test |nset-difference test=equal key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal '(((1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equal))))
(define-test |nset-difference test=equal key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal '(((1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test 'equal))))
(define-test |nset-difference test=equal key=other 3|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 200 collect (list (list i)))))
(assert-equal '(((1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equal))))
(define-test |nset-difference test=equalp key=other 1|
(assert-equal '()
(nset-difference '()
'()
:key #'car
:test #'equalp)))
(define-test |nset-difference test=equalp key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 20 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equalp))))
(define-test |nset-difference test=equalp key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 20 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test 'equalp))))
(define-test |nset-difference test=equalp key=other 3a|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 200 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equalp))))
(define-test |nset-difference test=equalp key=other 3b|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 200 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test 'equalp))))
(define-test |nset-difference test=other key=other 1|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 1 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car
:test #'>))))
(define-test |nset-difference test-not=other key=other 1|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 1 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car
:test-not #'<=))))
(define-test |nset-difference test=other test-not=other 1|
(assert-error 'error
(nset-difference '(1 2 3) '(2 3 4)
:test #'eql
:test-not #'eql)))
(define-test |nset-difference test=nil key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-error 'error
(nset-difference (copy-list l1)
(copy-list l2)
:test nil))))
(define-test |nset-difference test-not=nil key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-error 'error
(nset-difference (copy-list l1)
(copy-list l2)
:test-not nil))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the adjoin function
(define-test |adjoin test=eql key=identity 1a|
(assert-equal '(1)
(adjoin 1 '())))
(define-test |adjoin test=eql key=identity 1b|
(assert-equal '(1)
(adjoin 1 '() :test #'eql)))
(define-test |adjoin test=eql key=identity 1c|
(assert-equal '(1)
(adjoin 1 '() :test 'eql)))
(define-test |adjoin test=eql key=identity 2a|
(assert-equal '(1 2)
(adjoin 1 '(2))))
(define-test |adjoin test=eql key=identity 2b|
(assert-equal '(1 2)
(adjoin 1 '(2) :test #'eql)))
(define-test |adjoin test=eql key=identity 2c|
(assert-equal '(1 2)
(adjoin 1 '(2) :test 'eql)))
(define-test |adjoin test=eql key=identity 3a|
(assert-equal '(2 1)
(adjoin 1 '(2 1))))
(define-test |adjoin test=eql key=identity 3b|
(assert-equal '(2 1)
(adjoin 1 '(2 1) :test #'eql)))
(define-test |adjoin test=eql key=identity 3c|
(assert-equal '(2 1)
(adjoin 1 '(2 1) :test 'eql)))
(define-test |adjoin test=eql key=nil 3b|
(assert-equal '(2 1)
(adjoin 1 '(2 1) :key nil)))
(define-test |adjoin test=eq key=identity 1a|
(assert-equal '(a)
(adjoin 'a '() :test #'eq)))
(define-test |adjoin test=eq key=identity 1b|
(assert-equal '(a)
(adjoin 'a '() :test 'eq)))
(define-test |adjoin test=eq key=identity 2a|
(assert-equal '(a b)
(adjoin 'a '(b) :test #'eq)))
(define-test |adjoin test=eq key=identity 2b|
(assert-equal '(a b)
(adjoin 'a '(b) :test 'eq)))
(define-test |adjoin test=eq key=identity 3a|
(assert-equal '(b a)
(adjoin 'a '(b a) :test #'eq)))
(define-test |adjoin test=eq key=identity 3b|
(assert-equal '(b a)
(adjoin 'a '(b a) :test 'eq)))
(define-test |adjoin test=other key=identity 1|
(assert-equal '(1 2)
(adjoin 1 '(2) :test #'=)))
(define-test |adjoin test=other key=identity 2|
(assert-equal '(2 1)
(adjoin 1 '(2 1) :test #'=)))
(define-test |adjoin test-not=other key=identity 1|
(assert-equal '(1 2)
(adjoin 1 '(2) :test-not #'/=)))
(define-test |adjoin test-not=other key=identity 2|
(assert-equal '(2 1)
(adjoin 1 '(2 1) :test-not #'/=)))
(define-test |adjoin test=eql key=other 1a|
(assert-equal '((1))
(adjoin '(1) '() :key #'car)))
(define-test |adjoin test=eql key=other 1b|
(assert-equal '((1))
(adjoin '(1) '() :key #'car :test #'eql)))
(define-test |adjoin test=eql key=other 1c|
(assert-equal '((1))
(adjoin '(1) '() :key #'car :test 'eql)))
(define-test |adjoin test=eql key=other 2a|
(assert-equal '((1) (2))
(adjoin '(1) '((2)) :key #'car)))
(define-test |adjoin test=eql key=other 2b|
(assert-equal '((1) (2))
(adjoin '(1) '((2)) :key #'car :test #'eql)))
(define-test |adjoin test=eql key=other 2c|
(assert-equal '((1) (2))
(adjoin '(1) '((2)) :key #'car :test 'eql)))
(define-test |adjoin test=eql key=other 3a|
(assert-equal '((2) (1))
(adjoin '(1) '((2) (1)) :key #'car)))
(define-test |adjoin test=eql key=other 3b|
(assert-equal '((2) (1))
(adjoin '(1) '((2) (1)) :key #'car :test #'eql)))
(define-test |adjoin test=eql key=other 3c|
(assert-equal '((2) (1))
(adjoin '(1) '((2) (1)) :key #'car :test 'eql)))
(define-test |adjoin test=eq key=other 1a|
(assert-equal '((a))
(adjoin '(a) '() :key #'car :test #'eq)))
(define-test |adjoin test=eq key=other 1b|
(assert-equal '((a))
(adjoin '(a) '() :key #'car :test 'eq)))
(define-test |adjoin test=eq key=other 2a|
(assert-equal '((a) (b))
(adjoin '(a) '((b)) :key #'car :test #'eq)))
(define-test |adjoin test=eq key=other 2b|
(assert-equal '((a) (b))
(adjoin '(a) '((b)) :key #'car :test 'eq)))
(define-test |adjoin test=eq key=other 3a|
(assert-equal '((b) (a))
(adjoin '(a) '((b) (a)) :key #'car :test #'eq)))
(define-test |adjoin test=eq key=other 3b|
(assert-equal '((b) (a))
(adjoin '(a) '((b) (a)) :key #'car :test 'eq)))
(define-test |adjoin test=other key=other 1|
(assert-equal '((1) (2))
(adjoin '(1) '((2)) :key #'car :test #'=)))
(define-test |adjoin test=other key=other 2|
(assert-equal '((2) (1))
(adjoin '(1) '((2) (1)) :key #'car :test #'=)))
(define-test |adjoin test-not=other key=other 1|
(assert-equal '((1) (2))
(adjoin '(1) '((2)) :key #'car :test-not #'/=)))
(define-test |adjoin test-not=other key=other 2|
(assert-equal '((2) (1))
(adjoin '(1) '((2) (1)) :key #'car :test-not #'/=)))
(define-test |adjoin test=other test-not=other 1|
(assert-error 'error (adjoin 1 '() :test #'eql :test-not #'eql)))
(define-test |adjoin test=nil key=identity 3b|
(assert-error 'error
(adjoin 1 '(2 1) :test nil)))
(define-test |adjoin test-not=nil key=identity 3b|
(assert-error 'error
(adjoin 1 '(2 1) :test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the set-exclusiv-or function
(define-test |set-exclusive-or test=eql key=identity 1|
(assert-equal '()
(set-exclusive-or '() '())))
(define-test |set-exclusive-or test=eql key=identity 2a|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))))
#'<))))
(define-test |set-exclusive-or test=eql key=identity 2b|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test #'eql))
#'<))))
(define-test |set-exclusive-or test=eql key=identity 2c|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test 'eql))
#'<))))
(define-test |set-exclusive-or test=eql key=identity 3a|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))))
#'<))))
(define-test |set-exclusive-or test=eql key=identity 3b|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test #'eql))
#'<))))
(define-test |set-exclusive-or test=eql key=identity 3c|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test 'eql))
#'<))))
(define-test |set-exclusive-or test=eql key=nil 1|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:key nil))
#'<))))
(define-test |set-exclusive-or test=eq key=identity 2a|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:test #'eq))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eq key=identity 2b|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:test 'eq))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eq key=identity 3a|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:test #'eq))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eq key=identity 3b|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:test 'eq))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equal key=identity 2a|
(let ((l1 (loop for i from 2 to 10 collect (list i)))
(l2 (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test #'equal))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equal key=identity 2b|
(let ((l1 (loop for i from 2 to 10 collect (list i)))
(l2 (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test 'equal))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equal key=identity 3a|
(let ((l1 (loop for i from 2 to 50 collect (list i)))
(l2 (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test #'equal))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equal key=identity 3b|
(let ((l1 (loop for i from 2 to 50 collect (list i)))
(l2 (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test 'equal))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=identity 2a|
(let ((l1 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test #'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=identity 2b|
(let ((l1 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test 'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=identity 3a|
(let ((l1 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test #'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=identity 3b|
(let ((l1 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test 'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=other key=identity 1|
(assert-equal '()
(set-exclusive-or '() '() :test #'=)))
(define-test |set-exclusive-or test=other key=identity 2|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test '=))
#'<))))
(define-test |set-exclusive-or test=other key=identity 3|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test '=))
#'<))))
(define-test |set-exclusive-or test-not=other key=identity 2|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test-not '/=))
#'<))))
(define-test |set-exclusive-or test-not=other key=identity 3|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test-not '/=))
#'<))))
(define-test |set-exclusive-or test=eql key=other 1|
(assert-equal '()
(set-exclusive-or '() '() :key #'car)))
(define-test |set-exclusive-or test=eql key=other 2a|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eql key=other 2b|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test #'eql))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eql key=other 2c|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test 'eql))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eql key=other 3a|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eql key=other 3b|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test #'eql))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eql key=other 3c|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test 'eql))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eq key=other 2a|
(let ((l (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l)
(append l (list (list (list 1))))
:key #'car
:test #'eq))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=eq key=other 2b|
(let ((l (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l)
(append l (list (list (list 1))))
:key #'car
:test 'eq))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=eq key=other 3a|
(let ((l (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l)
(append l (list (list (list 1))))
:key #'car
:test #'eq))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=eq key=other 3b|
(let ((l (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l)
(append l (list (list (list 1))))
:key #'car
:test 'eq))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=equal key=other 2a|
(let ((l1 (loop for i from 2 to 10 collect (list (list i))))
(l2 (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l1)
(append l2 (list (list (list 1))))
:key #'car
:test #'equal))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=equal key=other 2b|
(let ((l1 (loop for i from 2 to 10 collect (list (list i))))
(l2 (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l1)
(append l2 (list (list (list 1))))
:key #'car
:test 'equal))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=equal key=other 3a|
(let ((l1 (loop for i from 2 to 50 collect (list (list i))))
(l2 (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l1)
(append l2 (list (list (list 1))))
:key #'car
:test #'equal))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=equal key=other 3b|
(let ((l1 (loop for i from 2 to 50 collect (list (list i))))
(l2 (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l1)
(append l2 (list (list (list 1))))
:key #'car
:test 'equal))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=equalp key=other 2a|
(let ((l1 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:key #'car
:test #'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=other 2b|
(let ((l1 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:key #'car
:test 'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=other 3a|
(let ((l1 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:key #'car
:test #'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=other 3b|
(let ((l1 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:key #'car
:test 'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=other key=other 1|
(assert-equal '()
(set-exclusive-or '() '() :test #'= :key #'car)))
(define-test |set-exclusive-or test=other key=other 2|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test '=))
#'<
:key #'car))))
(define-test |set-exclusive-or test=other key=other 3|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test '=))
#'<
:key #'car))))
(define-test |set-exclusive-or test-not=other key=other 2|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test-not '/=))
#'<
:key #'car))))
(define-test |set-exclusive-or test-not=other key=other 3|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test-not '/=))
#'<
:key #'car))))
(define-test |set-exclusive-or test=other test-not=other 1|
(assert-error 'error
(set-exclusive-or '() '() :test #'eql :test-not #'eql)))
(define-test |set-exclusive-or test=nil key=identity 1|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-error
'error
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test nil))
#'<))))
(define-test |set-exclusive-or test-not=nil key=identity 1|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-error
'error
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test-not nil))
#'<))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nset-exclusiv-or function
(define-test |nset-exclusive-or test=eql key=identity 1|
(assert-equal '()
(nset-exclusive-or '() '())))
(define-test |nset-exclusive-or test=eql key=identity 2a|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))))
#'<))))
(define-test |nset-exclusive-or test=eql key=identity 2b|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test #'eql))
#'<))))
(define-test |nset-exclusive-or test=eql key=identity 2c|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test 'eql))
#'<))))
(define-test |nset-exclusive-or test=eql key=identity 3a|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))))
#'<))))
(define-test |nset-exclusive-or test=eql key=identity 3b|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test #'eql))
#'<))))
(define-test |nset-exclusive-or test=eql key=identity 3c|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test 'eql))
#'<))))
(define-test |nset-exclusive-or test=eql key=nil 3b|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:key nil))
#'<))))
(define-test |nset-exclusive-or test=eq key=identity 2a|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:test #'eq))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eq key=identity 2b|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:test 'eq))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eq key=identity 3a|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:test #'eq))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eq key=identity 3b|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:test 'eq))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equal key=identity 2a|
(let ((l1 (loop for i from 2 to 10 collect (list i)))
(l2 (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test #'equal))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equal key=identity 2b|
(let ((l1 (loop for i from 2 to 10 collect (list i)))
(l2 (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test 'equal))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equal key=identity 3a|
(let ((l1 (loop for i from 2 to 50 collect (list i)))
(l2 (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test #'equal))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equal key=identity 3b|
(let ((l1 (loop for i from 2 to 50 collect (list i)))
(l2 (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test 'equal))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=identity 2a|
(let ((l1 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test #'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=identity 2b|
(let ((l1 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test 'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=identity 3a|
(let ((l1 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test #'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=identity 3b|
(let ((l1 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test 'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=other key=identity 1|
(assert-equal '()
(nset-exclusive-or '() '() :test #'=)))
(define-test |nset-exclusive-or test=other key=identity 2|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test '=))
#'<))))
(define-test |nset-exclusive-or test=other key=identity 3|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test '=))
#'<))))
(define-test |nset-exclusive-or test-not=other key=identity 2|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test-not '/=))
#'<))))
(define-test |nset-exclusive-or test-not=other key=identity 3|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test-not '/=))
#'<))))
(define-test |nset-exclusive-or test=eql key=other 1|
(assert-equal '()
(nset-exclusive-or '() '() :key #'car)))
(define-test |nset-exclusive-or test=eql key=other 2a|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eql key=other 2b|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test #'eql))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eql key=other 2c|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test 'eql))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eql key=other 3a|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eql key=other 3b|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test #'eql))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eql key=other 3c|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test 'eql))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eq key=other 2a|
(let ((l (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l))
(copy-list (append l (list (list (list 1)))))
:key #'car
:test #'eq))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=eq key=other 2b|
(let ((l (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l))
(copy-list (append l (list (list (list 1)))))
:key #'car
:test 'eq))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=eq key=other 3a|
(let ((l (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l))
(copy-list (append l (list (list (list 1)))))
:key #'car
:test #'eq))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=eq key=other 3b|
(let ((l (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l))
(copy-list (append l (list (list (list 1)))))
:key #'car
:test 'eq))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=equal key=other 2a|
(let ((l1 (loop for i from 2 to 10 collect (list (list i))))
(l2 (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l1))
(copy-list (append l2 (list (list (list 1)))))
:key #'car
:test #'equal))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=equal key=other 2b|
(let ((l1 (loop for i from 2 to 10 collect (list (list i))))
(l2 (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l1))
(copy-list (append l2 (list (list (list 1)))))
:key #'car
:test 'equal))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=equal key=other 3a|
(let ((l1 (loop for i from 2 to 50 collect (list (list i))))
(l2 (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l1))
(copy-list (append l2 (list (list (list 1)))))
:key #'car
:test #'equal))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=equal key=other 3b|
(let ((l1 (loop for i from 2 to 50 collect (list (list i))))
(l2 (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l1))
(copy-list (append l2 (list (list (list 1)))))
:key #'car
:test 'equal))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=equalp key=other 2a|
(let ((l1 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:key #'car
:test #'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=other 2b|
(let ((l1 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:key #'car
:test 'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=other 3a|
(let ((l1 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:key #'car
:test #'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=other 3b|
(let ((l1 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:key #'car
:test 'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=other key=other 1|
(assert-equal '()
(nset-exclusive-or '() '() :test #'= :key #'car)))
(define-test |nset-exclusive-or test=other key=other 2|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test '=))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=other key=other 3|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test '=))
#'<
:key #'car))))
(define-test |nset-exclusive-or test-not=other key=other 2|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test-not '/=))
#'<
:key #'car))))
(define-test |nset-exclusive-or test-not=other key=other 3|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test-not '/=))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=other test-not=other 1|
(assert-error 'error
(nset-exclusive-or '() '() :test #'eql :test-not #'eql)))
(define-test |nset-exclusive-or test=nil key=identity 3b|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-error
'error
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test nil))
#'<))))
(define-test |nset-exclusive-or test-not=nil key=identity 3b|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-error
'error
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test-not nil))
#'<))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the subsetp function
(define-test |subsetp test=eql key=identity 1a|
(assert-true (subsetp '()
'())))
(define-test |subsetp test=eql key=identity 1b|
(assert-true (subsetp '()
'()
:test #'eql)))
(define-test |subsetp test=eql key=identity 1c|
(assert-true (subsetp '()
'()
:test 'eql)))
(define-test |subsetp test=eql key=identity 2a|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-true (subsetp l1
l2))))
(define-test |subsetp test=eql key=identity 2b|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-true (subsetp l1
l2
:test #'eql))))
(define-test |subsetp test=eql key=identity 2c|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-true (subsetp l1
l2
:test 'eql))))
(define-test |subsetp test=eql key=identity 3a|
(let ((l1 (loop for i from 1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-true (subsetp l1
l2))))
(define-test |subsetp test=eql key=identity 3b|
(let ((l1 (loop for i from 1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-true (subsetp l1
l2
:test #'eql))))
(define-test |subsetp test=eql key=identity 3c|
(let ((l1 (loop for i from 1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-true (subsetp l1
l2
:test 'eql))))
(define-test |subsetp test=eql key=identity 4a|
(let ((l1 (loop for i from -1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-false (subsetp l1
l2))))
(define-test |subsetp test=eql key=identity 4b|
(let ((l1 (loop for i from -1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-false (subsetp l1
l2
:test #'eql))))
(define-test |subsetp test=eql key=identity 4c|
(let ((l1 (loop for i from -1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-false (subsetp l1
l2
:test 'eql))))
(define-test |subsetp test=eql key=identity 5a|
(let ((l1 (loop for i from -1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-false (subsetp l1
l2))))
(define-test |subsetp test=eql key=identity 5b|
(let ((l1 (loop for i from -1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-false (subsetp l1
l2
:test #'eql))))
(define-test |subsetp test=eql key=identity 5c|
(let ((l1 (loop for i from -1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-false (subsetp l1
l2
:test 'eql))))
(define-test |subsetp test=eql key=nil 1|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-true (subsetp l1
l2
:key nil))))
(define-test |subsetp test=eq key=identity 2a|
(let ((l (loop repeat 10 collect (make-array 1 :initial-element 1))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:test #'eq))))
(define-test |subsetp test=eq key=identity 2b|
(let ((l (loop repeat 10 collect (make-array 1 :initial-element 1))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:test 'eq))))
(define-test |subsetp test=eq key=identity 3a|
(let ((l (loop repeat 50 collect (make-array 1 :initial-element 1))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:test #'eq))))
(define-test |subsetp test=eq key=identity 3b|
(let ((l (loop repeat 50 collect (make-array 1 :initial-element 1))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:test 'eq))))
(define-test |subsetp test=eq key=identity 4a|
(let ((l (loop repeat 10 collect (make-array 1 :initial-element 1))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:test #'eq))))
(define-test |subsetp test=eq key=identity 4b|
(let ((l (loop repeat 10 collect (make-array 1 :initial-element 1))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:test 'eq))))
(define-test |subsetp test=eq key=identity 5a|
(let ((l (loop repeat 50 collect (make-array 1 :initial-element 1))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:test #'eq))))
(define-test |subsetp test=eq key=identity 5b|
(let ((l (loop repeat 50 collect (make-array 1 :initial-element 1))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:test 'eq))))
(define-test |subsetp test=equal key=identity 2a|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:test #'equal))))
(define-test |subsetp test=equal key=identity 2b|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:test 'equal))))
(define-test |subsetp test=equal key=identity 3a|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:test #'equal))))
(define-test |subsetp test=equal key=identity 3b|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:test 'equal))))
(define-test |subsetp test=equal key=identity 4a|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:test #'equal))))
(define-test |subsetp test=equal key=identity 4b|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:test 'equal))))
(define-test |subsetp test=equal key=identity 5a|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:test #'equal))))
(define-test |subsetp test=equal key=identity 5b|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:test 'equal))))
(define-test |subsetp test=equalp key=identity 2a|
(let ((l1 (loop for i from 1 to 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 10 to 0 collect (make-array 1 :initial-element i))))
(assert-true (subsetp l1
l2
:test #'equalp))))
(define-test |subsetp test=equalp key=identity 2b|
(let ((l1 (loop for i from 1 to 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 10 to 0 collect (make-array 1 :initial-element i))))
(assert-true (subsetp l1
l2
:test 'equalp))))
(define-test |subsetp test=equalp key=identity 3a|
(let ((l1 (loop for i from 1 to 50 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 50 to 0 collect (make-array 1 :initial-element i))))
(assert-true (subsetp l1
l2
:test #'equalp))))
(define-test |subsetp test=equalp key=identity 3b|
(let ((l1 (loop for i from 1 to 50 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 50 to 0 collect (make-array 1 :initial-element i))))
(assert-true (subsetp l1
l2
:test 'equalp))))
(define-test |subsetp test=equalp key=identity 4a|
(let ((l1 (loop for i from -1 to 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 10 to 0 collect (make-array 1 :initial-element i))))
(assert-false (subsetp l1
l2
:test #'equalp))))
(define-test |subsetp test=equalp key=identity 4b|
(let ((l1 (loop for i from -1 to 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 10 to 0 collect (make-array 1 :initial-element i))))
(assert-false (subsetp l1
l2
:test 'equalp))))
(define-test |subsetp test=equalp key=identity 5a|
(let ((l1 (loop for i from -1 to 50 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 50 to 0 collect (make-array 1 :initial-element i))))
(assert-false (subsetp l1
l2
:test #'equalp))))
(define-test |subsetp test=equalp key=identity 5b|
(let ((l1 (loop for i from -1 to 50 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 50 to 0 collect (make-array 1 :initial-element i))))
(assert-false (subsetp l1
l2
:test 'equalp))))
(define-test |subsetp test=other key=identity 2b|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-true (subsetp l1
l2
:test #'=))))
(define-test |subsetp test=other key=identity 3b|
(let ((l1 (loop for i from 1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-true (subsetp l1
l2
:test #'=))))
(define-test |subsetp test=other key=identity 4b|
(let ((l1 (loop for i from -1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-false (subsetp l1
l2
:test #'=))))
(define-test |subsetp test=other key=identity 5b|
(let ((l1 (loop for i from -1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-false (subsetp l1
l2
:test #'=))))
(define-test |subsetp test-not=other key=identity 2b|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-true (subsetp l1
l2
:test-not #'/=))))
(define-test |subsetp test-not=other key=identity 3b|
(let ((l1 (loop for i from 1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-true (subsetp l1
l2
:test-not #'/=))))
(define-test |subsetp test-not=other key=identity 4b|
(let ((l1 (loop for i from -1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-false (subsetp l1
l2
:test-not #'/=))))
(define-test |subsetp test-not=other key=identity 5b|
(let ((l1 (loop for i from -1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-false (subsetp l1
l2
:test-not #'/=))))
(define-test |subsetp test=eql key=other 1a|
(assert-true (subsetp '()
'()
:key #'car)))
(define-test |subsetp test=eql key=other 1b|
(assert-true (subsetp '()
'()
:key #'car
:test #'eql)))
(define-test |subsetp test=eql key=other 1c|
(assert-true (subsetp '()
'()
:key #'car
:test 'eql)))
(define-test |subsetp test=eql key=other 2a|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car))))
(define-test |subsetp test=eql key=other 2b|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test #'eql))))
(define-test |subsetp test=eql key=other 2c|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test 'eql))))
(define-test |subsetp test=eql key=other 3a|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car))))
(define-test |subsetp test=eql key=other 3b|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test #'eql))))
(define-test |subsetp test=eql key=other 3c|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test 'eql))))
(define-test |subsetp test=eql key=other 4a|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car))))
(define-test |subsetp test=eql key=other 4b|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test #'eql))))
(define-test |subsetp test=eql key=other 4c|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test 'eql))))
(define-test |subsetp test=eql key=other 5a|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car))))
(define-test |subsetp test=eql key=other 5b|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test #'eql))))
(define-test |subsetp test=eql key=other 5c|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test 'eql))))
(define-test |subsetp test=eq key=other 2a|
(let ((l (loop repeat 10 collect (list (make-array 1 :initial-element 1)))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:key #'car
:test #'eq))))
(define-test |subsetp test=eq key=other 2b|
(let ((l (loop repeat 10 collect (list (make-array 1 :initial-element 1)))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:key #'car
:test 'eq))))
(define-test |subsetp test=eq key=other 3a|
(let ((l (loop repeat 50 collect (list (make-array 1 :initial-element 1)))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:key #'car
:test #'eq))))
(define-test |subsetp test=eq key=other 3b|
(let ((l (loop repeat 50 collect (list (make-array 1 :initial-element 1)))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:key #'car
:test 'eq))))
(define-test |subsetp test=eq key=other 4a|
(let ((l (loop repeat 10 collect (list (make-array 1 :initial-element 1)))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:key #'car
:test #'eq))))
(define-test |subsetp test=eq key=other 4b|
(let ((l (loop repeat 10 collect (list (make-array 1 :initial-element 1)))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:key #'car
:test 'eq))))
(define-test |subsetp test=eq key=other 5a|
(let ((l (loop repeat 50 collect (list (make-array 1 :initial-element 1)))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:key #'car
:test #'eq))))
(define-test |subsetp test=eq key=other 5b|
(let ((l (loop repeat 50 collect (list (make-array 1 :initial-element 1)))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:key #'car
:test 'eq))))
(define-test |subsetp test=equal key=other 2a|
(let ((l1 (loop for i from 1 to 10 collect (list (list i))))
(l2 (loop for i downfrom 10 to 0 collect (list (list i)))))
(assert-true (subsetp l1
l2
:key #'car
:test #'equal))))
(define-test |subsetp test=equal key=other 2b|
(let ((l1 (loop for i from 1 to 10 collect (list (list i))))
(l2 (loop for i downfrom 10 to 0 collect (list (list i)))))
(assert-true (subsetp l1
l2
:key #'car
:test 'equal))))
(define-test |subsetp test=equal key=other 3a|
(let ((l1 (loop for i from 1 to 50 collect (list (list i))))
(l2 (loop for i downfrom 50 to 0 collect (list (list i)))))
(assert-true (subsetp l1
l2
:key #'car
:test #'equal))))
(define-test |subsetp test=equal key=other 3b|
(let ((l1 (loop for i from 1 to 50 collect (list (list i))))
(l2 (loop for i downfrom 50 to 0 collect (list (list i)))))
(assert-true (subsetp l1
l2
:key #'car
:test 'equal))))
(define-test |subsetp test=equal key=other 4a|
(let ((l1 (loop for i from -1 to 10 collect (list (list i))))
(l2 (loop for i downfrom 10 to 0 collect (list (list i)))))
(assert-false (subsetp l1
l2
:key #'car
:test #'equal))))
(define-test |subsetp test=equal key=other 4b|
(let ((l1 (loop for i from -1 to 10 collect (list (list i))))
(l2 (loop for i downfrom 10 to 0 collect (list (list i)))))
(assert-false (subsetp l1
l2
:key #'car
:test 'equal))))
(define-test |subsetp test=equal key=other 5a|
(let ((l1 (loop for i from -1 to 50 collect (list (list i))))
(l2 (loop for i downfrom 50 to 0 collect (list (list i)))))
(assert-false (subsetp l1
l2
:key #'car
:test #'equal))))
(define-test |subsetp test=equal key=other 5b|
(let ((l1 (loop for i from -1 to 50 collect (list (list i))))
(l2 (loop for i downfrom 50 to 0 collect (list (list i)))))
(assert-false (subsetp l1
l2
:key #'car
:test 'equal))))
(define-test |subsetp test=equalp key=other 2a|
(let ((l1 (loop for i from 1 to 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 10 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-true (subsetp l1
l2
:key #'car
:test #'equalp))))
(define-test |subsetp test=equalp key=other 2b|
(let ((l1 (loop for i from 1 to 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 10 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-true (subsetp l1
l2
:key #'car
:test 'equalp))))
(define-test |subsetp test=equalp key=other 3a|
(let ((l1 (loop for i from 1 to 50 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 50 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-true (subsetp l1
l2
:key #'car
:test #'equalp))))
(define-test |subsetp test=equalp key=other 3b|
(let ((l1 (loop for i from 1 to 50 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 50 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-true (subsetp l1
l2
:key #'car
:test 'equalp))))
(define-test |subsetp test=equalp key=other 4a|
(let ((l1 (loop for i from -1 to 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 10 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-false (subsetp l1
l2
:key #'car
:test #'equalp))))
(define-test |subsetp test=equalp key=other 4b|
(let ((l1 (loop for i from -1 to 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 10 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-false (subsetp l1
l2
:key #'car
:test 'equalp))))
(define-test |subsetp test=equalp key=other 5a|
(let ((l1 (loop for i from -1 to 50 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 50 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-false (subsetp l1
l2
:key #'car
:test #'equalp))))
(define-test |subsetp test=equalp key=other 5b|
(let ((l1 (loop for i from -1 to 50 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 50 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-false (subsetp l1
l2
:key #'car
:test 'equalp))))
(define-test |subsetp test=other key=other 2b|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test #'=))))
(define-test |subsetp test=other key=other 3b|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test #'=))))
(define-test |subsetp test=other key=other 4b|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test #'=))))
(define-test |subsetp test=other key=other 5b|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test #'=))))
(define-test |subsetp test-not=other key=other 2b|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test-not #'/=))))
(define-test |subsetp test-not=other key=other 3b|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test-not #'/=))))
(define-test |subsetp test-not=other key=other 4b|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test-not #'/=))))
(define-test |subsetp test-not=other key=other 5b|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test-not #'/=))))
(define-test |subsetp test=other test-not=other 1|
(assert-error 'error
(subsetp '() '() :test #'eql :test-not #'eql)))
(define-test |subsetp test=nil key=identity 1|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-error 'error
(subsetp l1
l2
:test nil))))
(define-test |subsetp test-not=nil key=identity 1|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-error 'error
(subsetp l1
l2
:test-not nil))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the pushnew macro
(define-test |pushnew test=eql key=identity 1a|
(let ((list '()))
(assert-equal '(1)
(pushnew 1 list))
(assert-equal '(1)
list)))
(define-test |pushnew test=eql key=identity 1b|
(let ((list '()))
(assert-equal '(1)
(pushnew 1 list :test #'eql))
(assert-equal '(1)
list)))
(define-test |pushnew test=eql key=identity 1c|
(let ((list '()))
(assert-equal '(1)
(pushnew 1 list :test 'eql))
(assert-equal '(1)
list)))
(define-test |pushnew test=eql key=identity 2a|
(let ((list '(1)))
(assert-equal '(1)
(pushnew 1 list))
(assert-equal '(1)
list)))
(define-test |pushnew test=eql key=identity 2b|
(let ((list '(1)))
(assert-equal '(1)
(pushnew 1 list :test #'eql))
(assert-equal '(1)
list)))
(define-test |pushnew test=eql key=identity 2c|
(let ((list '(1)))
(assert-equal '(1)
(pushnew 1 list :test 'eql))
(assert-equal '(1)
list)))
(define-test |pushnew test=eql key=identity 3a|
(let ((list '(2)))
(assert-equal '(1 2)
(pushnew 1 list))
(assert-equal '(1 2)
list)))
(define-test |pushnew test=eql key=identity 3b|
(let ((list '(2)))
(assert-equal '(1 2)
(pushnew 1 list :test #'eql))
(assert-equal '(1 2)
list)))
(define-test |pushnew test=eql key=identity 3c|
(let ((list '(2)))
(assert-equal '(1 2)
(pushnew 1 list :test 'eql))
(assert-equal '(1 2)
list)))
(define-test |pushnew test=eql key=identity 4a|
(let ((list '(2 1)))
(assert-equal '(2 1)
(pushnew 1 list))
(assert-equal '(2 1)
list)))
(define-test |pushnew test=eql key=identity 4b|
(let ((list '(2 1)))
(assert-equal '(2 1)
(pushnew 1 list :test #'eql))
(assert-equal '(2 1)
list)))
(define-test |pushnew test=eql key=identity 4c|
(let ((list '(2 1)))
(assert-equal '(2 1)
(pushnew 1 list :test 'eql))
(assert-equal '(2 1)
list)))
(define-test |pushnew test=eql key=nil 3b|
(let ((list '(2)))
(assert-equal '(1 2)
(pushnew 1 list :key nil))
(assert-equal '(1 2)
list)))
(define-test |pushnew test=eq key=identity 1b|
(let ((list '()))
(assert-equal '(a)
(pushnew 'a list :test #'eq))
(assert-equal '(a)
list)))
(define-test |pushnew test=eq key=identity 1c|
(let ((list '()))
(assert-equal '(a)
(pushnew 'a list :test 'eq))
(assert-equal '(a)
list)))
(define-test |pushnew test=eq key=identity 2b|
(let ((list '(a)))
(assert-equal '(a)
(pushnew 'a list :test #'eq))
(assert-equal '(a)
list)))
(define-test |pushnew test=eq key=identity 2c|
(let ((list '(a)))
(assert-equal '(a)
(pushnew 'a list :test 'eq))
(assert-equal '(a)
list)))
(define-test |pushnew test=eq key=identity 3b|
(let ((list '(b)))
(assert-equal '(a b)
(pushnew 'a list :test #'eq))
(assert-equal '(a b)
list)))
(define-test |pushnew test=eq key=identity 3c|
(let ((list '(b)))
(assert-equal '(a b)
(pushnew 'a list :test 'eq))
(assert-equal '(a b)
list)))
(define-test |pushnew test=eq key=identity 4b|
(let ((list '(b a)))
(assert-equal '(b a)
(pushnew 'a list :test #'eq))
(assert-equal '(b a)
list)))
(define-test |pushnew test=eq key=identity 4c|
(let ((list '(b a)))
(assert-equal '(b a)
(pushnew 'a list :test 'eq))
(assert-equal '(b a)
list)))
(define-test |pushnew test=eql key=other 1|
(let ((list '()))
(assert-equal '((1))
(pushnew '(1) list :key #'car))
(assert-equal '((1))
list)))
(define-test |pushnew test=eql key=other 2|
(let ((list '((1))))
(assert-equal '((1))
(pushnew '(1) list :key #'car))
(assert-equal '((1))
list)))
(define-test |pushnew test=eql key=other 3|
(let ((list '((2))))
(assert-equal '((1) (2))
(pushnew '(1) list :key #'car))
(assert-equal '((1) (2))
list)))
(define-test |pushnew test=eql key=other 4|
(let ((list '((2) (1))))
(assert-equal '((2) (1))
(pushnew '(1) list :key #'car))
(assert-equal '((2) (1))
list)))
(define-test |pushnew test=eq key=other 1|
(let ((list '()))
(assert-equal '((a))
(pushnew '(a) list :test #'eq :key #'car))
(assert-equal '((a))
list)))
(define-test |pushnew test=eq key=other 2|
(let ((list '((a))))
(assert-equal '((a))
(pushnew '(a) list :test #'eq :key #'car))
(assert-equal '((a))
list)))
(define-test |pushnew test=eq key=other 3|
(let ((list '((b))))
(assert-equal '((a) (b))
(pushnew '(a) list :test #'eq :key #'car))
(assert-equal '((a) (b))
list)))
(define-test |pushnew test=eq key=other 4|
(let ((list '((b) (a))))
(assert-equal '((b) (a))
(pushnew '(a) list :test #'eq :key #'car))
(assert-equal '((b) (a))
list)))
(define-test |pushnew test=other key=identity 1b|
(let ((list '()))
(assert-equal '(1)
(pushnew 1 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(1)
list)))
(define-test |pushnew test=other key=identity 2b|
(let ((list '(1)))
(assert-equal '(1 1)
(pushnew 1 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(1 1)
list)))
(define-test |pushnew test=other key=identity 3b|
(let ((list '(2)))
(assert-equal '(1 2)
(pushnew 1 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(1 2)
list)))
(define-test |pushnew test=other key=identity 4b|
(let ((list '(2 1)))
(assert-equal '(1 2 1)
(pushnew 1 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(1 2 1)
list)))
(define-test |pushnew test=other key=identity 5b|
(let ((list '(1)))
(assert-equal '(1)
(pushnew 2 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(1)
list)))
(define-test |pushnew test=other key=identity 6b|
(let ((list '(2)))
(assert-equal '(2 2)
(pushnew 2 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(2 2)
list)))
(define-test |pushnew test=other key=identity 7b|
(let ((list '(2 1)))
(assert-equal '(2 1)
(pushnew 2 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(2 1)
list)))
(define-test |pushnew test=other key=other 3b|
(let ((list '((2))))
(assert-equal '((1) (2))
(pushnew '(1) list
:test (lambda (x y) (= (1- x) y))
:key #'car))
(assert-equal '((1) (2))
list)))
(define-test |pushnew test=other key=other 4b|
(let ((list '((2) (1))))
(assert-equal '((1) (2) (1))
(pushnew '(1) list
:test (lambda (x y) (= (1- x) y))
:key #'car))
(assert-equal '((1) (2) (1))
list)))
(define-test |pushnew test=other key=other 5b|
(let ((list '((1))))
(assert-equal '((1))
(pushnew '(2) list
:test (lambda (x y) (= (1- x) y))
:key #'car))
(assert-equal '((1))
list)))
(define-test |pushnew test=other key=other 6b|
(let ((list '((2))))
(assert-equal '((2) (2))
(pushnew '(2) list
:test (lambda (x y) (= (1- x) y))
:key #'car))
(assert-equal '((2) (2))
list)))
(define-test |pushnew test=other key=other 7b|
(let ((list '((2) (1))))
(assert-equal '((2) (1))
(pushnew '(2) list
:test (lambda (x y) (= (1- x) y))
:key #'car))
(assert-equal '((2) (1))
list)))
(define-test |pushnew test-not=other key=identity 1b|
(let ((list '()))
(assert-equal '(1)
(pushnew 1 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(1)
list)))
(define-test |pushnew test-not=other key=identity 2b|
(let ((list '(1)))
(assert-equal '(1 1)
(pushnew 1 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(1 1)
list)))
(define-test |pushnew test-not=other key=identity 3b|
(let ((list '(2)))
(assert-equal '(1 2)
(pushnew 1 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(1 2)
list)))
(define-test |pushnew test-not=other key=identity 4b|
(let ((list '(2 1)))
(assert-equal '(1 2 1)
(pushnew 1 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(1 2 1)
list)))
(define-test |pushnew test-not=other key=identity 5b|
(let ((list '(1)))
(assert-equal '(1)
(pushnew 2 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(1)
list)))
(define-test |pushnew test-not=other key=identity 6b|
(let ((list '(2)))
(assert-equal '(2 2)
(pushnew 2 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(2 2)
list)))
(define-test |pushnew test-not=other key=identity 7b|
(let ((list '(2 1)))
(assert-equal '(2 1)
(pushnew 2 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(2 1)
list)))
(define-test |pushnew test-not=other key=other 3b|
(let ((list '((2))))
(assert-equal '((1) (2))
(pushnew '(1) list
:test-not (lambda (x y) (/= (1- x) y))
:key #'car))
(assert-equal '((1) (2))
list)))
(define-test |pushnew test-not=other key=other 4b|
(let ((list '((2) (1))))
(assert-equal '((1) (2) (1))
(pushnew '(1) list
:test-not (lambda (x y) (/= (1- x) y))
:key #'car))
(assert-equal '((1) (2) (1))
list)))
(define-test |pushnew test-not=other key=other 5b|
(let ((list '((1))))
(assert-equal '((1))
(pushnew '(2) list
:test-not (lambda (x y) (/= (1- x) y))
:key #'car))
(assert-equal '((1))
list)))
(define-test |pushnew test-not=other key=other 6b|
(let ((list '((2))))
(assert-equal '((2) (2))
(pushnew '(2) list
:test-not (lambda (x y) (/= (1- x) y))
:key #'car))
(assert-equal '((2) (2))
list)))
(define-test |pushnew test-not=other key=other 7b|
(let ((list '((2) (1))))
(assert-equal '((2) (1))
(pushnew '(2) list
:test-not (lambda (x y) (/= (1- x) y))
:key #'car))
(assert-equal '((2) (1))
list)))
(define-test |pushnew test=other test-not=other 1|
(let ((fun nil)
(warned nil))
(handler-bind ((warning (lambda (condition)
(setf warned t)
(muffle-warning condition))))
(setf fun
(compile nil '(lambda ()
(declare (special list))
(pushnew '2 list
:test #'eql
:test-not #'eql)))))
(assert-true warned)
(assert-error 'error (funcall fun))))
(define-test |pushnew test=nil key=identity 3b|
(let ((list '(2)))
(assert-error 'error
(pushnew 1 list :test nil))))
(define-test |pushnew test-not=nil key=identity 3b|
(let ((list '(2)))
(assert-error 'error
(pushnew 1 list :test-not nil))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the POP macro.
(define-test |pop 1|
(let ((var (list 1)))
(assert-equal 1
(pop var))
(assert-equal '()
var)))
(define-test |pop 2|
(let ((var (list 1 2)))
(assert-equal 1
(pop var))
(assert-equal '(2)
var)))
(define-test |pop 3|
(let ((list (list (list 1))))
(assert-equal 1
(pop (car list)))
(assert-equal '(())
list)))
(define-test |pop 4|
(let ((list (list (list 1 2))))
(assert-equal 1
(pop (car list)))
(assert-equal '((2))
list)))
(define-test |pop error 1|
(let ((list (copy-tree '(1 . 2))))
(assert-equal 1
(pop list))
(assert-error 'type-error
(pop list))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the NSUBST function.
(define-test nsubst.1
(assert-equal '(a (c))
(nsubst 'c '(b) (copy-tree '(a ((b)))) :test-not (complement #'equal))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the GETF function.
(define-test |getf 1|
(assert-equal nil
(getf '() 'a)))
(define-test |getf 2|
(assert-equal 1
(getf '(a 1) 'a)))
(define-test |getf 3|
(assert-equal 1
(getf '(b 2 a 1) 'a)))
(define-test |getf 4|
(assert-equal nil
(getf '(b 2 a 1) 'c)))
(define-test |getf error 1|
(assert-error 'type-error
(getf '(b 2 a) 'c)))
(define-test |getf error 2|
(assert-error 'type-error
(getf 1 'c)))
(define-test |getf error 3|
(assert-error 'type-error
(getf '(b 2 a 3 . f) 'c)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the GET-PROPERTIES function.
(define-test |get-properties 1|
(multiple-value-bind (indicator value tail)
(get-properties '() '(a))
(assert-equal nil indicator)
(assert-equal nil value)
(assert-equal nil tail)))
(define-test |get-properties 2|
(multiple-value-bind (indicator value tail)
(get-properties '(a 1) '(b a))
(assert-equal 'a indicator)
(assert-equal 1 value)
(assert-equal '(a 1) tail)))
(define-test |get-properties 3|
(multiple-value-bind (indicator value tail)
(get-properties '(b 2 a 1) '(c a d))
(assert-equal 'a indicator)
(assert-equal 1 value)
(assert-equal '(a 1) tail)))
(define-test |get-properties 4|
(multiple-value-bind (indicator value tail)
(get-properties '(b 2 a 1) '(c d e))
(assert-equal nil indicator)
(assert-equal nil value)
(assert-equal nil tail)))
(define-test |get-properties 5|
(multiple-value-bind (indicator value tail)
(get-properties '(b 2 a 1 e 10) '(c a d))
(assert-equal 'a indicator)
(assert-equal 1 value)
(assert-equal '(a 1 e 10) tail)))
(define-test |get-properties error 1|
(assert-error 'type-error
(get-properties '(b 2 a) '(c d e))))
(define-test |get-properties error 2|
(assert-error 'type-error
(get-properties '(b 2 a 3 . f) '(c d e))))
(define-test |get-properties error 3|
(assert-error 'type-error
(get-properties 1 '(c d e))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the SETF expander for GETF.
(define-test |(setf getf) 1|
(let ((list (copy-list '(:a 0 :c 1 :e 2 :c 3))))
(assert-equal 4
(setf (getf list :c) 4))
(assert-equal '(:a 0 :c 4 :e 2 :c 3)
list)))
(define-test |(setf getf) 2|
(let ((list (copy-list '(:a 0 :c 1 :e 2 :c 3)))
(thing 0))
(assert-equal 4
(setf (getf list :d (incf thing)) 4))
(assert-equal 4
(getf list :d))
(assert-equal 1 thing)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the REMF macro.
(define-test remf.1
(let ((list (copy-tree '(a 1 b 2 c 3))))
(assert-true (remf list 'c))
(assert-equal '(a 1 b 2)
list)))
| true |
(cl:in-package #:sicl-cons-high-test)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Helper function to defeat the type inferencing of the
;;; compiler so there are no warnings.
;;; This function always returns true when given a proper list.
(defun twisted (list)
(if (null list)
t
(twisted (cdr list))))
(declaim (notinline twisted))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAAR function.
(define-test caar.1
(assert-equal 'a (caar '((a)))))
(define-test caar.error.1
(assert-error 'type-error (caar 'a)))
(define-test caar.error.2
(assert-error 'type-error (caar '(a))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADR function.
(define-test cdar.1
(assert-equal 'b (cdar '((a . b)))))
(define-test cdar.error.1
(assert-error 'type-error (cdar 'a)))
(define-test cdar.error.2
(assert-error 'type-error (cdar '(a . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADR function.
(define-test cadr.1
(assert-equal 'b (cadr '(a b))))
(define-test cadr.error.1
(assert-error 'type-error (cadr 'a)))
(define-test cadr.error.2
(assert-error 'type-error (cadr '(a . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDR function.
(define-test cddr.1
(assert-equal 'c (cddr '(a b . c))))
(define-test cddr.error.1
(assert-error 'type-error (cddr 'a)))
(define-test cddr.error.2
(assert-error 'type-error (cddr '(a . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAAAR function.
(define-test caaar.1
(assert-equal 'a (caaar '(((a))))))
(define-test caaar.error.1
(assert-error 'type-error (caaar 'a)))
(define-test caaar.error.2
(assert-error 'type-error (caaar '(a))))
(define-test caaar.error.3
(assert-error 'type-error (caaar '((a)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDAAR function.
(define-test cdaar.1
(assert-equal 'b (cdaar '(((a . b))))))
(define-test cdaar.error.1
(assert-error 'type-error (cdaar 'a)))
(define-test cdaar.error.2
(assert-error 'type-error (cdaar '(a))))
(define-test cdaar.error.3
(assert-error 'type-error (cdaar '((a . b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADAR function.
(define-test cadar.1
(assert-equal 'b (cadar (cons (cons 'a (cons 'b 'c)) 'd))))
(define-test cadar.error.1
(assert-error 'type-error (cadar 'a)))
(define-test cadar.error.2
(assert-error 'type-error (cadar '(a . b))))
(define-test cadar.error.3
(assert-error 'type-error (cadar '((a . c) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDAR function.
(define-test cddar.1
(assert-equal 'c (cddar (cons (cons 'a (cons 'b 'c)) 'd))))
(define-test cddar.error.1
(assert-error 'type-error (cddar 'a)))
(define-test cddar.error.2
(assert-error 'type-error (cddar '(a . b))))
(define-test cddar.error.3
(assert-error 'type-error (cddar '((a . b) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAADR function.
(define-test caadr.1
(assert-equal 'b (caadr (cons 'a (cons (cons 'b 'c) 'd)))))
(define-test caadr.error.1
(assert-error 'type-error (caadr 'a)))
(define-test caadr.error.2
(assert-error 'type-error (caadr '(a . b))))
(define-test caadr.error.3
(assert-error 'type-error (caadr '(a . (b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADDR function.
(define-test caddr.1
(assert-equal 'c (caddr (cons 'a (cons 'b (cons 'c 'd))))))
(define-test caddr.error.1
(assert-error 'type-error (caddr 'a)))
(define-test caddr.error.2
(assert-error 'type-error (caddr '(a . b))))
(define-test caddr.error.3
(assert-error 'type-error (caddr '(a c . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDADR function.
(define-test cdadr.1
(assert-equal 'c (cdadr (cons 'a (cons (cons 'b 'c) 'd)))))
(define-test cdadr.error.1
(assert-error 'type-error (cdadr 'a)))
(define-test cdadr.error.2
(assert-error 'type-error (cdadr '(a . b))))
(define-test cdadr.error.3
(assert-error 'type-error (cdadr '(a b . c))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDDR function.
(define-test cdddr.1
(assert-equal 'd (cdddr (cons 'a (cons 'b (cons 'c 'd))))))
(define-test cdddr.error.1
(assert-error 'type-error (cdddr 'a)))
(define-test cdddr.error.2
(assert-error 'type-error (cdddr '(a . b))))
(define-test cdddr.error.3
(assert-error 'type-error (cdddr '(a c . b))))
;;; Tree to be used for testing some c*r functions.
(defvar *cons-test-4*
(cons (cons (cons (cons 'a 'b)
(cons 'c 'd))
(cons (cons 'e 'f)
(cons 'g 'h)))
(cons (cons (cons 'i 'j)
(cons 'k 'l))
(cons (cons 'm 'n)
(cons 'o 'p)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAAAAR function.
(define-test caaaar.1
(assert-equal 'a (caaaar *cons-test-4*)))
(define-test caaaar.error.1
(assert-error 'type-error (caaaar 'a)))
(define-test caaaar.error.2
(assert-error 'type-error (caaaar '(a))))
(define-test caaaar.error.3
(assert-error 'type-error (caaaar '((a)))))
(define-test caaaar.error.4
(assert-error 'type-error (caaaar '(((a))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAAADR function.
(define-test caaadr.1
(assert-equal 'i (caaadr *cons-test-4*)))
(define-test caaadr.error.1
(assert-error 'type-error (caaadr 'a)))
(define-test caaadr.error.2
(assert-error 'type-error (caaadr '(a . b))))
(define-test caaadr.error.3
(assert-error 'type-error (caaadr '(a . (b)))))
(define-test caaadr.error.4
(assert-error 'type-error (caaadr '(a . ((b))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAADAR function.
(define-test caadar.1
(assert-equal 'e (caadar *cons-test-4*)))
(define-test caadar.error.1
(assert-error 'type-error (caadar 'a)))
(define-test caadar.error.2
(assert-error 'type-error (caadar '(a . b))))
(define-test caadar.error.3
(assert-error 'type-error (caadar '((a . c) . b))))
(define-test caadar.error.4
(assert-error 'type-error (caadar '((a . (c)) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CAADDR function.
(define-test caaddr.1
(assert-equal 'm (caaddr *cons-test-4*)))
(define-test caaddr.error.1
(assert-error 'type-error (caaddr 'a)))
(define-test caaddr.error.2
(assert-error 'type-error (caaddr '(a . b))))
(define-test caaddr.error.3
(assert-error 'type-error (caaddr '(a c . b))))
(define-test caaddr.error.4
(assert-error 'type-error (caaddr '(a c . (b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADAAR function.
(define-test cadaar.1
(assert-equal 'c (cadaar *cons-test-4*)))
(define-test cadaar.error.1
(assert-error 'type-error (cadaar 'a)))
(define-test cadaar.error.2
(assert-error 'type-error (cadaar '(a))))
(define-test cadaar.error.3
(assert-error 'type-error (cadaar '((a . b)))))
(define-test cadaar.error.4
(assert-error 'type-error (cadaar '((a . (b))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADADR function.
(define-test cadadr.1
(assert-equal 'k (cadadr *cons-test-4*)))
(define-test cadadr.error.1
(assert-error 'type-error (cadadr 'a)))
(define-test cadadr.error.2
(assert-error 'type-error (cadadr '(a . b))))
(define-test cadadr.error.3
(assert-error 'type-error (cadadr '(a b . c))))
(define-test cadadr.error.4
(assert-error 'type-error (cadadr '(a (b . e) . c))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADDAR function.
(define-test caddar.1
(assert-equal 'g (caddar *cons-test-4*)))
(define-test caddar.error.1
(assert-error 'type-error (caddar 'a)))
(define-test caddar.error.2
(assert-error 'type-error (caddar '(a . b))))
(define-test caddar.error.3
(assert-error 'type-error (caddar '((a . b) . b))))
(define-test caddar.error.4
(assert-error 'type-error (caddar '((a b . c) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CADDDR function.
(define-test cadddr.1
(assert-equal 'o (cadddr *cons-test-4*)))
(define-test cadddr.error.1
(assert-error 'type-error (cadddr 'a)))
(define-test cadddr.error.2
(assert-error 'type-error (cadddr '(a . b))))
(define-test cadddr.error.3
(assert-error 'type-error (cadddr '(a c . b))))
(define-test cadddr.error.4
(assert-error 'type-error (cadddr '(a c e . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDAAAR function.
(define-test cdaaar.1
(assert-equal 'b (cdaaar *cons-test-4*)))
(define-test cdaaar.error.1
(assert-error 'type-error (cdaaar 'a)))
(define-test cdaaar.error.2
(assert-error 'type-error (cdaaar '(a))))
(define-test cdaaar.error.3
(assert-error 'type-error (cdaaar '((a)))))
(define-test cdaaar.error.4
(assert-error 'type-error (cdaaar '(((a . b))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDAADR function.
(define-test cdaadr.1
(assert-equal 'j (cdaadr *cons-test-4*)))
(define-test cdaadr.error.1
(assert-error 'type-error (cdaadr 'a)))
(define-test cdaadr.error.2
(assert-error 'type-error (cdaadr '(a . b))))
(define-test cdaadr.error.3
(assert-error 'type-error (cdaadr '(a . (b)))))
(define-test cdaadr.error.4
(assert-error 'type-error (cdaadr '(a . ((b . c))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDADAR function.
(define-test cdadar.1
(assert-equal 'f (cdadar *cons-test-4*)))
(define-test cdadar.error.1
(assert-error 'type-error (cdadar 'a)))
(define-test cdadar.error.2
(assert-error 'type-error (cdadar '(a . b))))
(define-test cdadar.error.3
(assert-error 'type-error (cdadar '((a . c) . b))))
(define-test cdadar.error.4
(assert-error 'type-error (cdadar '((a . (c . d)) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDADDR function.
(define-test cdaddr.1
(assert-equal 'n (cdaddr *cons-test-4*)))
(define-test cdaddr.error.1
(assert-error 'type-error (cdaddr 'a)))
(define-test cdaddr.error.2
(assert-error 'type-error (cdaddr '(a . b))))
(define-test cdaddr.error.3
(assert-error 'type-error (cdaddr '(a c . b))))
(define-test cdaddr.error.4
(assert-error 'type-error (cdaddr '(a c b . d))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDAAR function.
(define-test cddaar.1
(assert-equal 'd (cddaar *cons-test-4*)))
(define-test cddaar.error.1
(assert-error 'type-error (cddaar 'a)))
(define-test cddaar.error.2
(assert-error 'type-error (cddaar '(a))))
(define-test cddaar.error.3
(assert-error 'type-error (cddaar '((a . b)))))
(define-test cddaar.error.4
(assert-error 'type-error (cddaar '((a . (b))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDADR function.
(define-test cddadr.1
(assert-equal 'l (cddadr *cons-test-4*)))
(define-test cddadr.error.1
(assert-error 'type-error (cddadr 'a)))
(define-test cddadr.error.2
(assert-error 'type-error (cddadr '(a . b))))
(define-test cddadr.error.3
(assert-error 'type-error (cddadr '(a b . c))))
(define-test cddadr.error.4
(assert-error 'type-error (cddadr '(a (b . e) . c))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDDAR function.
(define-test cdddar.1
(assert-equal 'h (cdddar *cons-test-4*)))
(define-test cdddar.error.1
(assert-error 'type-error (cdddar 'a)))
(define-test cdddar.error.2
(assert-error 'type-error (cdddar '(a . b))))
(define-test cdddar.error.3
(assert-error 'type-error (cdddar '((a . b) . b))))
(define-test cdddar.error.4
(assert-error 'type-error (cdddar '((a b . c) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the CDDDDR function.
(define-test cddddr.1
(assert-equal 'p (cddddr *cons-test-4*)))
(define-test cddddr.error.1
(assert-error 'type-error (cddddr 'a)))
(define-test cddddr.error.2
(assert-error 'type-error (cddddr '(a . b))))
(define-test cddddr.error.3
(assert-error 'type-error (cddddr '(a c . b))))
(define-test cddddr.error.4
(assert-error 'type-error (cddddr '(a c e . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the FIRST function
(define-test first.1
(assert-equal nil (first nil)))
(define-test first.2
(assert-equal 1 (first '(1))))
(define-test first.3
(assert-equal 1 (first '(1 2))))
(define-test first.error.1
(assert-error 'type-error (first 1)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the SECOND function
(define-test second.1
(assert-equal nil (second nil)))
(define-test second.2
(assert-equal nil (second '(1))))
(define-test second.3
(assert-equal 1 (second '(0 1))))
(define-test second.4
(assert-equal 1 (second '(0 1 2))))
(define-test second.error.1
(assert-error 'type-error (second 1)))
(define-test second.error.2
(assert-error 'type-error (second '(0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the THIRD function.
(define-test third.1
(assert-equal nil (third nil)))
(define-test third.2
(assert-equal nil (third '(1))))
(define-test third.3
(assert-equal nil (third '(1 1))))
(define-test third.4
(assert-equal 1 (third '(0 0 1))))
(define-test third.5
(assert-equal 1 (third '(0 0 1 2))))
(define-test third.error.1
(assert-error 'type-error (third 1)))
(define-test third.error.2
(assert-error 'type-error (third '(0 . 1))))
(define-test third.error.3
(assert-error 'type-error (third '(0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the FOURTH function.
(define-test fourth.1
(assert-equal nil (fourth nil)))
(define-test fourth.2
(assert-equal nil (fourth '(1))))
(define-test fourth.3
(assert-equal nil (fourth '(1 1))))
(define-test fourth.4
(assert-equal nil (fourth '(1 1 1))))
(define-test fourth.5
(assert-equal 1 (fourth '(0 0 0 1))))
(define-test fourth.6
(assert-equal 1 (fourth '(0 0 0 1 2))))
(define-test fourth.error.1
(assert-error 'type-error (fourth 1)))
(define-test fourth.error.2
(assert-error 'type-error (fourth '(0 . 1))))
(define-test fourth.error.3
(assert-error 'type-error (fourth '(0 0 . 1))))
(define-test fourth.error.4
(assert-error 'type-error (fourth '(0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the FIFTH function.
(define-test fifth.1
(assert-equal nil (fifth nil)))
(define-test fifth.2
(assert-equal nil (fifth '(1))))
(define-test fifth.3
(assert-equal nil (fifth '(1 1))))
(define-test fifth.4
(assert-equal nil (fifth '(1 1 1))))
(define-test fifth.5
(assert-equal nil (fifth '(1 1 1 1))))
(define-test fifth.6
(assert-equal 1 (fifth '(0 0 0 0 1))))
(define-test fifth.7
(assert-equal 1 (fifth '(0 0 0 0 1 2))))
(define-test fifth.error.1
(assert-error 'type-error (fifth 1)))
(define-test fifth.error.2
(assert-error 'type-error (fifth '(0 . 1))))
(define-test fifth.error.3
(assert-error 'type-error (fifth '(0 0 . 1))))
(define-test fifth.error.4
(assert-error 'type-error (fifth '(0 0 0 . 1))))
(define-test fifth.error.5
(assert-error 'type-error (fifth '(0 0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the SIXTH function.
(define-test sixth.1
(assert-equal nil (sixth nil)))
(define-test sixth.2
(assert-equal nil (sixth '(1))))
(define-test sixth.3
(assert-equal nil (sixth '(1 1))))
(define-test sixth.4
(assert-equal nil (sixth '(1 1 1))))
(define-test sixth.5
(assert-equal nil (sixth '(1 1 1 1))))
(define-test sixth.6
(assert-equal nil (sixth '(1 1 1 1 1))))
(define-test sixth.7
(assert-equal 1 (sixth '(0 0 0 0 0 1))))
(define-test sixth.8
(assert-equal 1 (sixth '(0 0 0 0 0 1 2))))
(define-test sixth.error.1
(assert-error 'type-error (sixth 1)))
(define-test sixth.error.2
(assert-error 'type-error (sixth '(0 . 1))))
(define-test sixth.error.3
(assert-error 'type-error (sixth '(0 0 . 1))))
(define-test sixth.error.4
(assert-error 'type-error (sixth '(0 0 0 . 1))))
(define-test sixth.error.5
(assert-error 'type-error (sixth '(0 0 0 0 . 1))))
(define-test sixth.error.6
(assert-error 'type-error (sixth '(0 0 0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the SEVENTH function.
(define-test seventh.1
(assert-equal nil (seventh nil)))
(define-test seventh.2
(assert-equal nil (seventh '(1))))
(define-test seventh.3
(assert-equal nil (seventh '(1 1))))
(define-test seventh.4
(assert-equal nil (seventh '(1 1 1))))
(define-test seventh.5
(assert-equal nil (seventh '(1 1 1 1))))
(define-test seventh.6
(assert-equal nil (seventh '(1 1 1 1 1))))
(define-test seventh.7
(assert-equal nil (seventh '(1 1 1 1 1 1))))
(define-test seventh.8
(assert-equal 1 (seventh '(0 0 0 0 0 0 1))))
(define-test seventh.9
(assert-equal 1 (seventh '(0 0 0 0 0 0 1 2))))
(define-test seventh.error.1
(assert-error 'type-error (seventh 1)))
(define-test seventh.error.2
(assert-error 'type-error (seventh '(0 . 1))))
(define-test seventh.error.3
(assert-error 'type-error (seventh '(0 0 . 1))))
(define-test seventh.error.4
(assert-error 'type-error (seventh '(0 0 0 . 1))))
(define-test seventh.error.5
(assert-error 'type-error (seventh '(0 0 0 0 . 1))))
(define-test seventh.error.6
(assert-error 'type-error (seventh '(0 0 0 0 0 . 1))))
(define-test seventh.error.7
(assert-error 'type-error (seventh '(0 0 0 0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the EIGHTH function.
(define-test eighth.1
(assert-equal nil (eighth nil)))
(define-test eighth.2
(assert-equal nil (eighth '(1))))
(define-test eighth.3
(assert-equal nil (eighth '(1 1))))
(define-test eighth.4
(assert-equal nil (eighth '(1 1 1))))
(define-test eighth.5
(assert-equal nil (eighth '(1 1 1 1))))
(define-test eighth.6
(assert-equal nil (eighth '(1 1 1 1 1))))
(define-test eighth.7
(assert-equal nil (eighth '(1 1 1 1 1 1))))
(define-test eighth.8
(assert-equal nil (eighth '(1 1 1 1 1 1 1))))
(define-test eighth.9
(assert-equal 1 (eighth '(0 0 0 0 0 0 0 1))))
(define-test eighth.10
(assert-equal 1 (eighth '(0 0 0 0 0 0 0 1 2))))
(define-test eighth.error.1
(assert-error 'type-error (eighth 1)))
(define-test eighth.error.2
(assert-error 'type-error (eighth '(0 . 1))))
(define-test eighth.error.3
(assert-error 'type-error (eighth '(0 0 . 1))))
(define-test eighth.error.4
(assert-error 'type-error (eighth '(0 0 0 . 1))))
(define-test eighth.error.5
(assert-error 'type-error (eighth '(0 0 0 0 . 1))))
(define-test eighth.error.6
(assert-error 'type-error (eighth '(0 0 0 0 0 . 1))))
(define-test eighth.error.7
(assert-error 'type-error (eighth '(0 0 0 0 0 0 . 1))))
(define-test eighth.error.8
(assert-error 'type-error (eighth '(0 0 0 0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the NINTH function.
(define-test ninth.1
(assert-equal nil (ninth nil)))
(define-test ninth.2
(assert-equal nil (ninth '(1))))
(define-test ninth.3
(assert-equal nil (ninth '(1 1))))
(define-test ninth.4
(assert-equal nil (ninth '(1 1 1))))
(define-test ninth.5
(assert-equal nil (ninth '(1 1 1 1))))
(define-test ninth.6
(assert-equal nil (ninth '(1 1 1 1 1))))
(define-test ninth.7
(assert-equal nil (ninth '(1 1 1 1 1 1))))
(define-test ninth.8
(assert-equal nil (ninth '(1 1 1 1 1 1 1))))
(define-test ninth.9
(assert-equal nil (ninth '(1 1 1 1 1 1 1 1))))
(define-test ninth.10
(assert-equal 1 (ninth '(0 0 0 0 0 0 0 0 1))))
(define-test ninth.11
(assert-equal 1 (ninth '(0 0 0 0 0 0 0 0 1 2))))
(define-test ninth.error.1
(assert-error 'type-error (ninth 1)))
(define-test ninth.error.2
(assert-error 'type-error (ninth '(0 . 1))))
(define-test ninth.error.3
(assert-error 'type-error (ninth '(0 0 . 1))))
(define-test ninth.error.4
(assert-error 'type-error (ninth '(0 0 0 . 1))))
(define-test ninth.error.5
(assert-error 'type-error (ninth '(0 0 0 0 . 1))))
(define-test ninth.error.6
(assert-error 'type-error (ninth '(0 0 0 0 0 . 1))))
(define-test ninth.error.7
(assert-error 'type-error (ninth '(0 0 0 0 0 0 . 1))))
(define-test ninth.error.8
(assert-error 'type-error (ninth '(0 0 0 0 0 0 . 1))))
(define-test ninth.error.9
(assert-error 'type-error (ninth '(0 0 0 0 0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the TENTH function.
(define-test tenth.1
(assert-equal nil (tenth nil)))
(define-test tenth.2
(assert-equal nil (tenth '(1))))
(define-test tenth.3
(assert-equal nil (tenth '(1 1))))
(define-test tenth.4
(assert-equal nil (tenth '(1 1 1))))
(define-test tenth.5
(assert-equal nil (tenth '(1 1 1 1))))
(define-test tenth.6
(assert-equal nil (tenth '(1 1 1 1 1))))
(define-test tenth.7
(assert-equal nil (tenth '(1 1 1 1 1 1))))
(define-test tenth.8
(assert-equal nil (tenth '(1 1 1 1 1 1 1))))
(define-test tenth.9
(assert-equal nil (tenth '(1 1 1 1 1 1 1 1))))
(define-test tenth.10
(assert-equal nil (tenth '(1 1 1 1 1 1 1 1 1))))
(define-test tenth.11
(assert-equal 1 (tenth '(0 0 0 0 0 0 0 0 0 1))))
(define-test tenth.12
(assert-equal 1 (tenth '(0 0 0 0 0 0 0 0 0 1 2))))
(define-test tenth.error.1
(assert-error 'type-error (tenth 1)))
(define-test tenth.error.2
(assert-error 'type-error (tenth '(0 . 1))))
(define-test tenth.error.3
(assert-error 'type-error (tenth '(0 0 . 1))))
(define-test tenth.error.4
(assert-error 'type-error (tenth '(0 0 0 . 1))))
(define-test tenth.error.5
(assert-error 'type-error (tenth '(0 0 0 0 . 1))))
(define-test tenth.error.6
(assert-error 'type-error (tenth '(0 0 0 0 0 . 1))))
(define-test tenth.error.7
(assert-error 'type-error (tenth '(0 0 0 0 0 0 . 1))))
(define-test tenth.error.8
(assert-error 'type-error (tenth '(0 0 0 0 0 0 . 1))))
(define-test tenth.error.9
(assert-error 'type-error (tenth '(0 0 0 0 0 0 0 . 1))))
(define-test tenth.error.10
(assert-error 'type-error (tenth '(0 0 0 0 0 0 0 0 . 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAAR) function and SETF expander.
(define-test |setf caar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caar list) 1))
(assert-equal '((1 . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caar error 1|
(let ((list '()))
(assert-error 'type-error
(setf (caar list) 1))))
(define-test |setf caar error 2|
(let ((list 0))
(assert-error 'type-error
(setf (caar list) 1))))
(define-test |setf caar error 3|
(let ((list (copy-tree '(0 0))))
(assert-error 'type-error
(setf (caar list) 1))))
(define-test |setf caar error 4|
(let ((list (copy-tree '(() 0))))
(assert-error 'type-error
(setf (caar list) 1))))
(define-test |setf caar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caar) (list 1 list)))
(assert-equal '((1 . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caar apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf caar) (list 1 list)))))
(define-test |setf caar apply error 2|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caar) (list 1 list)))))
(define-test |setf caar apply error 3|
(let ((list (copy-tree '(0 0))))
(assert-error 'type-error
(apply #'(setf caar) (list 1 list)))))
(define-test |setf caar apply error 4|
(let ((list (copy-tree '(() 0))))
(assert-error 'type-error
(apply #'(setf caar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADR) function and SETF expander.
(define-test |setf cadr 1|
(let ((list (copy-tree '(0 0))))
(assert-equal 1 (setf (cadr list) 1))
(assert-equal '(0 1) list)))
(define-test |setf cadr error 1|
(let ((list '()))
(assert-error 'type-error
(setf (cadr list) 1))))
(define-test |setf cadr error 2|
(let ((list 0))
(assert-error 'type-error
(setf (cadr list) 1))))
(define-test |setf cadr error 3|
(let ((list (copy-tree '(0))))
(assert-error 'type-error
(setf (cadr list) 1))))
(define-test |setf cadr error 4|
(let ((list (copy-tree '(0 . 0))))
(assert-error 'type-error
(setf (cadr list) 1))))
(define-test |setf cadr apply 1|
(let ((list (copy-tree '(0 0))))
(assert-equal 1 (apply #'(setf cadr) (list 1 list)))
(assert-equal '(0 1) list)))
(define-test |setf cadr apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf cadr) (list 1 list)))))
(define-test |setf cadr apply error 2|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cadr) (list 1 list)))))
(define-test |setf cadr apply error 3|
(let ((list (copy-tree '(0))))
(assert-error 'type-error
(apply #'(setf cadr) (list 1 list)))))
(define-test |setf cadr apply error 4|
(let ((list (copy-tree '(0 . 0))))
(assert-error 'type-error
(apply #'(setf cadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDAR) function and SETF expander.
(define-test |setf cdar 1|
(let ((list (copy-tree '((0) 0))))
(assert-equal 1 (setf (cdar list) 1))
(assert-equal '((0 . 1) 0) list)))
(define-test |setf cdar error 1|
(let ((list '()))
(assert-error 'type-error
(setf (cdar list) 1))))
(define-test |setf cdar error 2|
(let ((list 0))
(assert-error 'type-error
(setf (cdar list) 1))))
(define-test |setf cdar error 3|
(let ((list (copy-tree '(0))))
(assert-error 'type-error
(setf (cdar list) 1))))
(define-test |setf cdar error 4|
(let ((list (copy-tree '(()))))
(assert-error 'type-error
(setf (cdar list) 1))))
(define-test |setf cdar apply 1|
(let ((list (copy-tree '((0) 0))))
(assert-equal 1 (apply #'(setf cdar) (list 1 list)))
(assert-equal '((0 . 1) 0) list)))
(define-test |setf cdar apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf cdar) (list 1 list)))))
(define-test |setf cdar apply error 2|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdar) (list 1 list)))))
(define-test |setf cdar apply error 3|
(let ((list (copy-tree '(0))))
(assert-error 'type-error
(apply #'(setf cdar) (list 1 list)))))
(define-test |setf cdar apply error 4|
(let ((list (copy-tree '(()))))
(assert-error 'type-error
(apply #'(setf cdar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDR) function and SETF expander.
(define-test |setf cddr 1|
(let ((list (copy-tree '(0 0))))
(assert-equal 1 (setf (cddr list) 1))
(assert-equal '(0 0 . 1) list)))
(define-test |setf cddr error 1|
(let ((list '()))
(assert-error 'type-error
(setf (cddr list) 1))))
(define-test |setf cddr error 2|
(let ((list 0))
(assert-error 'type-error
(setf (cddr list) 1))))
(define-test |setf cddr error 3|
(let ((list (copy-tree '(0))))
(assert-error 'type-error
(setf (cddr list) 1))))
(define-test |setf cddr error 4|
(let ((list (copy-tree '(0 . 1))))
(assert-error 'type-error
(setf (cddr list) 1))))
(define-test |setf cddr apply 1|
(let ((list (copy-tree '(0 0))))
(assert-equal 1 (apply #'(setf cddr) (list 1 list)))
(assert-equal '(0 0 . 1) list)))
(define-test |setf cddr apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf cddr) (list 1 list)))))
(define-test |setf cddr apply error 2|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cddr) (list 1 list)))))
(define-test |setf cddr apply error 3|
(let ((list (copy-tree '(0))))
(assert-error 'type-error
(apply #'(setf cddr) (list 1 list)))))
(define-test |setf cddr apply error 4|
(let ((list (copy-tree '(0 . 1))))
(assert-error 'type-error
(apply #'(setf cddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAAAR) function and SETF expander.
(define-test |setf caaar 1|
(let ((list (copy-tree '(((0 0) 0) 0))))
(assert-equal 1 (setf (caaar list) 1))
(assert-equal '(((1 0) 0) 0) list)))
(define-test |setf caaar error 1|
(let ((list '()))
(assert-error 'type-error
(setf (caaar list) 1))))
(define-test |setf caaar error 2|
(let ((list 0))
(assert-error 'type-error
(setf (caaar list) 1))))
(define-test |setf caaar error 3|
(let ((list (copy-tree '(0 0))))
(assert-error 'type-error
(setf (caaar list) 1))))
(define-test |setf caaar error 4|
(let ((list (copy-tree '((0 0) 0))))
(assert-error 'type-error
(setf (caaar list) 1))))
(define-test |setf caaar error 5|
(let ((list (copy-tree '((() 0) 0))))
(assert-error 'type-error
(setf (caaar list) 1))))
(define-test |setf caaar apply 1|
(let ((list (copy-tree '(((0 0) 0) 0))))
(assert-equal 1 (apply #'(setf caaar) (list 1 list)))
(assert-equal '(((1 0) 0) 0) list)))
(define-test |setf caaar apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf caaar) (list 1 list)))))
(define-test |setf caaar apply error 2|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caaar) (list 1 list)))))
(define-test |setf caaar apply error 3|
(let ((list (copy-tree '(0 0))))
(assert-error 'type-error
(apply #'(setf caaar) (list 1 list)))))
(define-test |setf caaar apply error 4|
(let ((list (copy-tree '((0 0) 0))))
(assert-error 'type-error
(apply #'(setf caaar) (list 1 list)))))
(define-test |setf caaar apply error 5|
(let ((list (copy-tree '((() 0) 0))))
(assert-error 'type-error
(apply #'(setf caaar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAADR) function and SETF expander.
(define-test |setf caadr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caadr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
((1 . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caadr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caadr list) 1))))
(define-test |setf caadr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
0 ))))
(assert-error 'type-error
(setf (caadr list) 1))))
(define-test |setf caadr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(0 . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (caadr list) 1))))
(define-test |setf caadr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caadr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
((1 . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caadr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caadr) (list 1 list)))))
(define-test |setf caadr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
0 ))))
(assert-error 'type-error
(apply #'(setf caadr) (list 1 list)))))
(define-test |setf caadr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(0 . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf caadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADAR) function and SETF expander.
(define-test |setf cadar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cadar list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . (1 . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cadar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cadar list) 1))))
(define-test |setf cadar error 2|
(let ((list (copy-tree '(0 .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cadar list) 1))))
(define-test |setf cadar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . 0) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cadar list) 1))))
(define-test |setf cadar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cadar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . (1 . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cadar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cadar) (list 1 list)))))
(define-test |setf cadar apply error 2|
(let ((list (copy-tree '(0 .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cadar) (list 1 list)))))
(define-test |setf cadar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . 0) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cadar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADDR) function and SETF expander.
(define-test |setf caddr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caddr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . (1 . (0 . 0))))
list)))
(define-test |setf caddr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caddr list) 1))))
(define-test |setf caddr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
0 ))))
(assert-error 'type-error
(setf (caddr list) 1))))
(define-test |setf caddr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . 0 )))))
(assert-error 'type-error
(setf (caddr list) 1))))
(define-test |setf caddr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caddr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . (1 . (0 . 0))))
list)))
(define-test |setf caddr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caddr) (list 1 list)))))
(define-test |setf caddr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
0 ))))
(assert-error 'type-error
(apply #'(setf caddr) (list 1 list)))))
(define-test |setf caddr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . 0 )))))
(assert-error 'type-error
(apply #'(setf caddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDAAR) function and SETF expander.
(define-test |setf cdaar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdaar list) 1))
(assert-equal '((((0 . 0) . 1) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdaar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdaar list) 1))))
(define-test |setf cdaar error 2|
(let ((list (copy-tree '(0 .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cdaar list) 1))))
(define-test |setf cdaar error 3|
(let ((list (copy-tree '((0 . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cdaar list) 1))))
(define-test |setf cdaar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdaar) (list 1 list)))
(assert-equal '((((0 . 0) . 1) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdaar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdaar) (list 1 list)))))
(define-test |setf cdaar apply error 2|
(let ((list (copy-tree '(0 .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cdaar) (list 1 list)))))
(define-test |setf cdaar apply error 3|
(let ((list (copy-tree '((0 . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cdaar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDADR) function and SETF expander.
(define-test |setf cdadr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdadr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . 1) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdadr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdadr list) 1))))
(define-test |setf cdadr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
0 ))))
(assert-error 'type-error
(setf (cdadr list) 1))))
(define-test |setf cdadr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(0 . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cdadr list) 1))))
(define-test |setf cdadr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdadr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . 1) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdadr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdadr) (list 1 list)))))
(define-test |setf cdadr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
0 ))))
(assert-error 'type-error
(apply #'(setf cdadr) (list 1 list)))))
(define-test |setf cdadr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(0 . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cdadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDAR) function and SETF expander.
(define-test |setf cddar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cddar list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . 1)) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cddar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cddar list) 1))))
(define-test |setf cddar error 2|
(let ((list (copy-tree '(0 .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cddar list) 1))))
(define-test |setf cddar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . 0) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(setf (cddar list) 1))))
(define-test |setf cddar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cddar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . 1)) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cddar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cddar) (list 1 list)))))
(define-test |setf cddar apply error 2|
(let ((list (copy-tree '(0 .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cddar) (list 1 list)))))
(define-test |setf cddar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . 0) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-error 'type-error
(apply #'(setf cddar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDDR) function and SETF expander.
(define-test |setf cdddr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdddr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . 1)))
list)))
(define-test |setf cdddr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdddr list) 1))))
(define-test |setf cdddr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cdddr list) 1))))
(define-test |setf cdddr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(setf (cdddr list) 1))))
(define-test |setf cdddr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdddr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . 1)))
list)))
(define-test |setf cdddr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdddr) (list 1 list)))))
(define-test |setf cdddr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cdddr) (list 1 list)))))
(define-test |setf cdddr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(apply #'(setf cdddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAAAAR) function and SETF expander.
(define-test |setf caaaar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caaaar list) 1))
(assert-equal '((((1 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caaaar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caaaar list) 1))))
(define-test |setf caaaar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (caaaar list) 1))))
(define-test |setf caaaar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(setf (caaaar list) 1))))
(define-test |setf caaaar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caaar list) 0)
(assert-error 'type-error
(setf (caaaar list) 1))))
(define-test |setf caaaar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caaaar) (list 1 list)))
(assert-equal '((((1 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caaaar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caaaar) (list 1 list)))))
(define-test |setf caaaar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf caaaar) (list 1 list)))))
(define-test |setf caaaar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(apply #'(setf caaaar) (list 1 list)))))
(define-test |setf caaaar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caaar list) 0)
(assert-error 'type-error
(apply #'(setf caaaar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAAADR) function and SETF expander.
(define-test |setf caaadr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caaadr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((1 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caaadr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caaadr list) 1))))
(define-test |setf caaadr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (caaadr list) 1))))
(define-test |setf caaadr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(setf (caaadr list) 1))))
(define-test |setf caaadr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caadr list) 0)
(assert-error 'type-error
(setf (caaadr list) 1))))
(define-test |setf caaadr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caaadr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((1 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caaadr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caaadr) (list 1 list)))))
(define-test |setf caaadr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf caaadr) (list 1 list)))))
(define-test |setf caaadr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(apply #'(setf caaadr) (list 1 list)))))
(define-test |setf caaadr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caadr list) 0)
(assert-error 'type-error
(apply #'(setf caaadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAADAR) function and SETF expander.
(define-test |setf caadar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caadar list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((1 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caadar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caadar list) 1))))
(define-test |setf caadar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (caadar list) 1))))
(define-test |setf caadar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(setf (caadar list) 1))))
(define-test |setf caadar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadar list) 0)
(assert-error 'type-error
(setf (caadar list) 1))))
(define-test |setf caadar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caadar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((1 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caadar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caadar) (list 1 list)))))
(define-test |setf caadar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf caadar) (list 1 list)))))
(define-test |setf caadar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(apply #'(setf caadar) (list 1 list)))))
(define-test |setf caadar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadar list) 0)
(assert-error 'type-error
(apply #'(setf caadar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CAADDR) function and SETF expander.
(define-test |setf caaddr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caaddr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((1 . 0) . (0 . 0))))
list)))
(define-test |setf caaddr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caaddr list) 1))))
(define-test |setf caaddr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (caaddr list) 1))))
(define-test |setf caaddr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(setf (caaddr list) 1))))
(define-test |setf caaddr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caddr list) 0)
(assert-error 'type-error
(setf (caaddr list) 1))))
(define-test |setf caaddr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caaddr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((1 . 0) . (0 . 0))))
list)))
(define-test |setf caaddr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caaddr) (list 1 list)))))
(define-test |setf caaddr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf caaddr) (list 1 list)))))
(define-test |setf caaddr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(apply #'(setf caaddr) (list 1 list)))))
(define-test |setf caaddr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caddr list) 0)
(assert-error 'type-error
(apply #'(setf caaddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADAAR) function and SETF expander.
(define-test |setf cadaar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cadaar list) 1))
(assert-equal '((((0 . 0) . (1 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cadaar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cadaar list) 1))))
(define-test |setf cadaar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (cadaar list) 1))))
(define-test |setf cadaar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(setf (cadaar list) 1))))
(define-test |setf cadaar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdaar list) 0)
(assert-error 'type-error
(setf (cadaar list) 1))))
(define-test |setf cadaar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cadaar) (list 1 list)))
(assert-equal '((((0 . 0) . (1 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cadaar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cadaar) (list 1 list)))))
(define-test |setf cadaar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf cadaar) (list 1 list)))))
(define-test |setf cadaar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(apply #'(setf cadaar) (list 1 list)))))
(define-test |setf cadaar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdaar list) 0)
(assert-error 'type-error
(apply #'(setf cadaar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADADR) function and SETF expander.
(define-test |setf cadadr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cadadr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (1 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cadadr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cadadr list) 1))))
(define-test |setf cadadr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cadadr list) 1))))
(define-test |setf cadadr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(setf (cadadr list) 1))))
(define-test |setf cadadr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdadr list) 0)
(assert-error 'type-error
(setf (cadadr list) 1))))
(define-test |setf cadadr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cadadr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (1 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cadadr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cadadr) (list 1 list)))))
(define-test |setf cadadr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cadadr) (list 1 list)))))
(define-test |setf cadadr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(apply #'(setf cadadr) (list 1 list)))))
(define-test |setf cadadr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdadr list) 0)
(assert-error 'type-error
(apply #'(setf cadadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADDAR) function and SETF expander.
(define-test |setf caddar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (caddar list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (1 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caddar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (caddar list) 1))))
(define-test |setf caddar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (caddar list) 1))))
(define-test |setf caddar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(setf (caddar list) 1))))
(define-test |setf caddar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddar list) 0)
(assert-error 'type-error
(setf (caddar list) 1))))
(define-test |setf caddar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf caddar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (1 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf caddar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf caddar) (list 1 list)))))
(define-test |setf caddar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf caddar) (list 1 list)))))
(define-test |setf caddar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(apply #'(setf caddar) (list 1 list)))))
(define-test |setf caddar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddar list) 0)
(assert-error 'type-error
(apply #'(setf caddar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CADDDR) function and SETF expander.
(define-test |setf cadddr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cadddr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (1 . 0))))
list)))
(define-test |setf cadddr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cadddr list) 1))))
(define-test |setf cadddr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cadddr list) 1))))
(define-test |setf cadddr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(setf (cadddr list) 1))))
(define-test |setf cadddr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdddr list) 0)
(assert-error 'type-error
(setf (cadddr list) 1))))
(define-test |setf cadddr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cadddr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (1 . 0))))
list)))
(define-test |setf cadddr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cadddr) (list 1 list)))))
(define-test |setf cadddr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cadddr) (list 1 list)))))
(define-test |setf cadddr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(apply #'(setf cadddr) (list 1 list)))))
(define-test |setf cadddr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdddr list) 0)
(assert-error 'type-error
(apply #'(setf cadddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDAAAR) function and SETF expander.
(define-test |setf cdaaar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdaaar list) 1))
(assert-equal '((((0 . 1) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdaaar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdaaar list) 1))))
(define-test |setf cdaaar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (cdaaar list) 1))))
(define-test |setf cdaaar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(setf (cdaaar list) 1))))
(define-test |setf cdaaar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caaar list) 0)
(assert-error 'type-error
(setf (cdaaar list) 1))))
(define-test |setf cdaaar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdaaar) (list 1 list)))
(assert-equal '((((0 . 1) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdaaar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdaaar) (list 1 list)))))
(define-test |setf cdaaar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf cdaaar) (list 1 list)))))
(define-test |setf cdaaar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(apply #'(setf cdaaar) (list 1 list)))))
(define-test |setf cdaaar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caaar list) 0)
(assert-error 'type-error
(apply #'(setf cdaaar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDAADR) function and SETF expander.
(define-test |setf cdaadr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdaadr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 1) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdaadr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdaadr list) 1))))
(define-test |setf cdaadr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cdaadr list) 1))))
(define-test |setf cdaadr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(setf (cdaadr list) 1))))
(define-test |setf cdaadr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caadr list) 0)
(assert-error 'type-error
(setf (cdaadr list) 1))))
(define-test |setf cdaadr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdaadr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 1) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdaadr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdaadr) (list 1 list)))))
(define-test |setf cdaadr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cdaadr) (list 1 list)))))
(define-test |setf cdaadr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(apply #'(setf cdaadr) (list 1 list)))))
(define-test |setf cdaadr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caadr list) 0)
(assert-error 'type-error
(apply #'(setf cdaadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDADAR) function and SETF expander.
(define-test |setf cdadar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdadar list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 1) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdadar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdadar list) 1))))
(define-test |setf cdadar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (cdadar list) 1))))
(define-test |setf cdadar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(setf (cdadar list) 1))))
(define-test |setf cdadar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadar list) 0)
(assert-error 'type-error
(setf (cdadar list) 1))))
(define-test |setf cdadar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdadar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 1) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdadar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdadar) (list 1 list)))))
(define-test |setf cdadar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf cdadar) (list 1 list)))))
(define-test |setf cdadar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(apply #'(setf cdadar) (list 1 list)))))
(define-test |setf cdadar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadar list) 0)
(assert-error 'type-error
(apply #'(setf cdadar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDADDR) function and SETF expander.
(define-test |setf cdaddr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdaddr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 1) . (0 . 0))))
list)))
(define-test |setf cdaddr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdaddr list) 1))))
(define-test |setf cdaddr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cdaddr list) 1))))
(define-test |setf cdaddr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(setf (cdaddr list) 1))))
(define-test |setf cdaddr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caddr list) 0)
(assert-error 'type-error
(setf (cdaddr list) 1))))
(define-test |setf cdaddr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdaddr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 1) . (0 . 0))))
list)))
(define-test |setf cdaddr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdaddr) (list 1 list)))))
(define-test |setf cdaddr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cdaddr) (list 1 list)))))
(define-test |setf cdaddr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(apply #'(setf cdaddr) (list 1 list)))))
(define-test |setf cdaddr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caddr list) 0)
(assert-error 'type-error
(apply #'(setf cdaddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDAAR) function and SETF expander.
(define-test |setf cddaar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cddaar list) 1))
(assert-equal '((((0 . 0) . (0 . 1)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cddaar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cddaar list) 1))))
(define-test |setf cddaar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (cddaar list) 1))))
(define-test |setf cddaar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(setf (cddaar list) 1))))
(define-test |setf cddaar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdaar list) 0)
(assert-error 'type-error
(setf (cddaar list) 1))))
(define-test |setf cddaar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cddaar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 1)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cddaar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cddaar) (list 1 list)))))
(define-test |setf cddaar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf cddaar) (list 1 list)))))
(define-test |setf cddaar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (caar list) 0)
(assert-error 'type-error
(apply #'(setf cddaar) (list 1 list)))))
(define-test |setf cddaar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdaar list) 0)
(assert-error 'type-error
(apply #'(setf cddaar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDADR) function and SETF expander.
(define-test |setf cddadr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cddadr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 1)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cddadr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cddadr list) 1))))
(define-test |setf cddadr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cddadr list) 1))))
(define-test |setf cddadr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(setf (cddadr list) 1))))
(define-test |setf cddadr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdadr list) 0)
(assert-error 'type-error
(setf (cddadr list) 1))))
(define-test |setf cddadr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cddadr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 1)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cddadr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cddadr) (list 1 list)))))
(define-test |setf cddadr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cddadr) (list 1 list)))))
(define-test |setf cddadr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cadr list) 0)
(assert-error 'type-error
(apply #'(setf cddadr) (list 1 list)))))
(define-test |setf cddadr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdadr list) 0)
(assert-error 'type-error
(apply #'(setf cddadr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDDAR) function and SETF expander.
(define-test |setf cdddar 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cdddar list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 1))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdddar error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cdddar list) 1))))
(define-test |setf cdddar error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(setf (cdddar list) 1))))
(define-test |setf cdddar error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(setf (cdddar list) 1))))
(define-test |setf cdddar error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddar list) 0)
(assert-error 'type-error
(setf (cdddar list) 1))))
(define-test |setf cdddar apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cdddar) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 1))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))))
list)))
(define-test |setf cdddar apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cdddar) (list 1 list)))))
(define-test |setf cdddar apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (car list) 0)
(assert-error 'type-error
(apply #'(setf cdddar) (list 1 list)))))
(define-test |setf cdddar apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdar list) 0)
(assert-error 'type-error
(apply #'(setf cdddar) (list 1 list)))))
(define-test |setf cdddar apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddar list) 0)
(assert-error 'type-error
(apply #'(setf cdddar) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF CDDDDR) function and SETF expander.
(define-test |setf cddddr 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (setf (cddddr list) 1))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 1))))
list)))
(define-test |setf cddddr error 1|
(let ((list 0))
(assert-error 'type-error
(setf (cddddr list) 1))))
(define-test |setf cddddr error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(setf (cddddr list) 1))))
(define-test |setf cddddr error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(setf (cddddr list) 1))))
(define-test |setf cddddr error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdddr list) 0)
(assert-error 'type-error
(setf (cddddr list) 1))))
(define-test |setf cddddr apply 1|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(assert-equal 1 (apply #'(setf cddddr) (list 1 list)))
(assert-equal '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 1))))
list)))
(define-test |setf cddddr apply error 1|
(let ((list 0))
(assert-error 'type-error
(apply #'(setf cddddr) (list 1 list)))))
(define-test |setf cddddr apply error 2|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdr list) 0)
(assert-error 'type-error
(apply #'(setf cddddr) (list 1 list)))))
(define-test |setf cddddr apply error 3|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cddr list) 0)
(assert-error 'type-error
(apply #'(setf cddddr) (list 1 list)))))
(define-test |setf cddddr apply error 4|
(let ((list (copy-tree '((((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0))) .
(((0 . 0) . (0 . 0)) . ((0 . 0) . (0 . 0)))))))
(setf (cdddr list) 0)
(assert-error 'type-error
(apply #'(setf cddddr) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF FIRST) function and SETF expander.
(define-test |setf first 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (first list) 1))
(assert-equal '(1 0 0 0 0 0 0 0 0 0) list)))
(define-test |setf first error 1|
(let ((list '()))
(assert-error 'type-error
(setf (first list) 1))))
(define-test |setf first 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (first list) 1))
(assert-equal '(1 0 0 0 0 0 0 0 0 0) list)))
(define-test |setf first error 1|
(let ((list '()))
(assert-error 'type-error
(setf (first list) 1))))
(define-test |setf first apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf first) (list 1 list)))
(assert-equal '(1 0 0 0 0 0 0 0 0 0) list)))
(define-test |setf first apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf first) (list 1 list)))))
(define-test |setf first apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf first) (list 1 list)))
(assert-equal '(1 0 0 0 0 0 0 0 0 0) list)))
(define-test |setf first apply error 1|
(let ((list '()))
(assert-error 'type-error
(apply #'(setf first) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF SECOND) function and SETF expander.
(define-test |setf second 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (second list) 1))
(assert-equal '(0 1 0 0 0 0 0 0 0 0) list)))
(define-test |setf second error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 0 list)) 1)
(assert-error 'type-error
(setf (second list) 1))))
(define-test |setf second 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (second list) 1))
(assert-equal '(0 1 0 0 0 0 0 0 0 0) list)))
(define-test |setf second error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 0 list)) 1)
(assert-error 'type-error
(setf (second list) 1))))
(define-test |setf second apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf second) (list 1 list)))
(assert-equal '(0 1 0 0 0 0 0 0 0 0) list)))
(define-test |setf second apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 0 list)) 1)
(assert-error 'type-error
(apply #'(setf second) (list 1 list)))))
(define-test |setf second apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf second) (list 1 list)))
(assert-equal '(0 1 0 0 0 0 0 0 0 0) list)))
(define-test |setf second apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 0 list)) 1)
(assert-error 'type-error
(apply #'(setf second) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF THIRD) function and SETF expander.
(define-test |setf third 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (third list) 1))
(assert-equal '(0 0 1 0 0 0 0 0 0 0) list)))
(define-test |setf third error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 1 list)) 1)
(assert-error 'type-error
(setf (third list) 1))))
(define-test |setf third 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (third list) 1))
(assert-equal '(0 0 1 0 0 0 0 0 0 0) list)))
(define-test |setf third error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 1 list)) 1)
(assert-error 'type-error
(setf (third list) 1))))
(define-test |setf third apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf third) (list 1 list)))
(assert-equal '(0 0 1 0 0 0 0 0 0 0) list)))
(define-test |setf third apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 1 list)) 1)
(assert-error 'type-error
(apply #'(setf third) (list 1 list)))))
(define-test |setf third apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf third) (list 1 list)))
(assert-equal '(0 0 1 0 0 0 0 0 0 0) list)))
(define-test |setf third apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 1 list)) 1)
(assert-error 'type-error
(apply #'(setf third) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF FOURTH) function and SETF expander.
(define-test |setf fourth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (fourth list) 1))
(assert-equal '(0 0 0 1 0 0 0 0 0 0) list)))
(define-test |setf fourth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 2 list)) 1)
(assert-error 'type-error
(setf (fourth list) 1))))
(define-test |setf fourth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (fourth list) 1))
(assert-equal '(0 0 0 1 0 0 0 0 0 0) list)))
(define-test |setf fourth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 2 list)) 1)
(assert-error 'type-error
(setf (fourth list) 1))))
(define-test |setf fourth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf fourth) (list 1 list)))
(assert-equal '(0 0 0 1 0 0 0 0 0 0) list)))
(define-test |setf fourth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 2 list)) 1)
(assert-error 'type-error
(apply #'(setf fourth) (list 1 list)))))
(define-test |setf fourth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf fourth) (list 1 list)))
(assert-equal '(0 0 0 1 0 0 0 0 0 0) list)))
(define-test |setf fourth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 2 list)) 1)
(assert-error 'type-error
(apply #'(setf fourth) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF FIFTH) function and SETF expander.
(define-test |setf fifth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (fifth list) 1))
(assert-equal '(0 0 0 0 1 0 0 0 0 0) list)))
(define-test |setf fifth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 3 list)) 1)
(assert-error 'type-error
(setf (fifth list) 1))))
(define-test |setf fifth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (fifth list) 1))
(assert-equal '(0 0 0 0 1 0 0 0 0 0) list)))
(define-test |setf fifth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 3 list)) 1)
(assert-error 'type-error
(setf (fifth list) 1))))
(define-test |setf fifth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf fifth) (list 1 list)))
(assert-equal '(0 0 0 0 1 0 0 0 0 0) list)))
(define-test |setf fifth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 3 list)) 1)
(assert-error 'type-error
(apply #'(setf fifth) (list 1 list)))))
(define-test |setf fifth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf fifth) (list 1 list)))
(assert-equal '(0 0 0 0 1 0 0 0 0 0) list)))
(define-test |setf fifth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 3 list)) 1)
(assert-error 'type-error
(apply #'(setf fifth) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF SIXTH) function and SETF expander.
(define-test |setf sixth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (sixth list) 1))
(assert-equal '(0 0 0 0 0 1 0 0 0 0) list)))
(define-test |setf sixth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 4 list)) 1)
(assert-error 'type-error
(setf (sixth list) 1))))
(define-test |setf sixth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (sixth list) 1))
(assert-equal '(0 0 0 0 0 1 0 0 0 0) list)))
(define-test |setf sixth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 4 list)) 1)
(assert-error 'type-error
(setf (sixth list) 1))))
(define-test |setf sixth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf sixth) (list 1 list)))
(assert-equal '(0 0 0 0 0 1 0 0 0 0) list)))
(define-test |setf sixth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 4 list)) 1)
(assert-error 'type-error
(apply #'(setf sixth) (list 1 list)))))
(define-test |setf sixth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf sixth) (list 1 list)))
(assert-equal '(0 0 0 0 0 1 0 0 0 0) list)))
(define-test |setf sixth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 4 list)) 1)
(assert-error 'type-error
(apply #'(setf sixth) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF SEVENTH) function and SETF expander.
(define-test |setf seventh 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (seventh list) 1))
(assert-equal '(0 0 0 0 0 0 1 0 0 0) list)))
(define-test |setf seventh error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 5 list)) 1)
(assert-error 'type-error
(setf (seventh list) 1))))
(define-test |setf seventh 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (seventh list) 1))
(assert-equal '(0 0 0 0 0 0 1 0 0 0) list)))
(define-test |setf seventh error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 5 list)) 1)
(assert-error 'type-error
(setf (seventh list) 1))))
(define-test |setf seventh apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf seventh) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 1 0 0 0) list)))
(define-test |setf seventh apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 5 list)) 1)
(assert-error 'type-error
(apply #'(setf seventh) (list 1 list)))))
(define-test |setf seventh apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf seventh) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 1 0 0 0) list)))
(define-test |setf seventh apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 5 list)) 1)
(assert-error 'type-error
(apply #'(setf seventh) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF EIGHTH) function and SETF expander.
(define-test |setf eighth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (eighth list) 1))
(assert-equal '(0 0 0 0 0 0 0 1 0 0) list)))
(define-test |setf eighth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 6 list)) 1)
(assert-error 'type-error
(setf (eighth list) 1))))
(define-test |setf eighth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (eighth list) 1))
(assert-equal '(0 0 0 0 0 0 0 1 0 0) list)))
(define-test |setf eighth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 6 list)) 1)
(assert-error 'type-error
(setf (eighth list) 1))))
(define-test |setf eighth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf eighth) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 0 1 0 0) list)))
(define-test |setf eighth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 6 list)) 1)
(assert-error 'type-error
(apply #'(setf eighth) (list 1 list)))))
(define-test |setf eighth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf eighth) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 0 1 0 0) list)))
(define-test |setf eighth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 6 list)) 1)
(assert-error 'type-error
(apply #'(setf eighth) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF NINTH) function and SETF expander.
(define-test |setf ninth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (ninth list) 1))
(assert-equal '(0 0 0 0 0 0 0 0 1 0) list)))
(define-test |setf ninth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 7 list)) 1)
(assert-error 'type-error
(setf (ninth list) 1))))
(define-test |setf ninth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (ninth list) 1))
(assert-equal '(0 0 0 0 0 0 0 0 1 0) list)))
(define-test |setf ninth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 7 list)) 1)
(assert-error 'type-error
(setf (ninth list) 1))))
(define-test |setf ninth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf ninth) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 0 0 1 0) list)))
(define-test |setf ninth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 7 list)) 1)
(assert-error 'type-error
(apply #'(setf ninth) (list 1 list)))))
(define-test |setf ninth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf ninth) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 0 0 1 0) list)))
(define-test |setf ninth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 7 list)) 1)
(assert-error 'type-error
(apply #'(setf ninth) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF TENTH) function and SETF expander.
(define-test |setf tenth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (tenth list) 1))
(assert-equal '(0 0 0 0 0 0 0 0 0 1) list)))
(define-test |setf tenth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 8 list)) 1)
(assert-error 'type-error
(setf (tenth list) 1))))
(define-test |setf tenth 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (setf (tenth list) 1))
(assert-equal '(0 0 0 0 0 0 0 0 0 1) list)))
(define-test |setf tenth error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 8 list)) 1)
(assert-error 'type-error
(setf (tenth list) 1))))
(define-test |setf tenth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf tenth) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 0 0 0 1) list)))
(define-test |setf tenth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 8 list)) 1)
(assert-error 'type-error
(apply #'(setf tenth) (list 1 list)))))
(define-test |setf tenth apply 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(assert-equal 1 (apply #'(setf tenth) (list 1 list)))
(assert-equal '(0 0 0 0 0 0 0 0 0 1) list)))
(define-test |setf tenth apply error 1|
(let ((list (copy-tree '(0 0 0 0 0 0 0 0 0 0))))
(setf (cdr (nthcdr 8 list)) 1)
(assert-error 'type-error
(apply #'(setf tenth) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the REST function.
(define-test rest.1
(assert-equal '() (rest '())))
(define-test rest.2
(assert-equal '() (rest '(0))))
(define-test rest.3
(assert-equal '(1) (rest '(0 1))))
(define-test rest.error.1
(assert-error 'type-error
(rest 1)))
(define-test rest.apply.1
(assert-equal '(1) (apply (second (list 'a #'rest)) '((0 1)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the SETF expander and SETF function for REST.
(define-test |setf-rest 1|
(let ((list (copy-list '(0))))
(assert-equal 1 (setf (rest list) 1))
(assert-equal '(0 . 1) list)))
(define-test |setf-rest error 1|
(let ((list 1))
(assert-error 'type-error
(setf (rest list) 1))))
(define-test |setf-rest apply 1|
(let ((list (copy-list '(0))))
(assert-equal 1 (apply #'(setf rest) (list 1 list)))
(assert-equal '(0 . 1) list)))
(define-test |setf-rest apply error 1|
(let ((list 1))
(assert-error 'type-error
(apply #'(setf rest) (list 1 list)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the LIST function.
(define-test list.1
(assert-equal '() (list)))
(define-test list.2
(assert-equal '(1) (list 1)))
(define-test list.3
(assert-equal '(1 2) (list 1 2)))
(define-test list.4
(assert-equal '(1 2 3) (list 1 2 3)))
(define-test list.5
(assert-equal '((a) (b) 1 2) (list '(a) '(b) 1 2)))
(define-test list.apply.1a
(assert-equal '() (apply (cadr (list 1 #'list)) '())))
(define-test list.apply.2a
(assert-equal '(1) (apply (cadr (list 1 #'list)) (list 1))))
(define-test list.apply.3a
(assert-equal '(1 2) (apply (cadr (list 1 #'list)) (list 1 2))))
(define-test list.apply.4a
(assert-equal '(1 2 3) (apply (cadr (list 1 #'list)) (list 1 2 3))))
(define-test list.apply.5a
(assert-equal '((a) (b) 1 2)
(apply (cadr (list 1 #'list)) (list '(a) '(b) 1 2))))
(define-test list.apply.1b
(assert-equal '() (apply (cadr (list 1 'list)) '())))
(define-test list.apply.2b
(assert-equal '(1) (apply (cadr (list 1 'list)) (list 1))))
(define-test list.apply.3b
(assert-equal '(1 2) (apply (cadr (list 1 'list)) (list 1 2))))
(define-test list.apply.4b
(assert-equal '(1 2 3) (apply (cadr (list 1 'list)) (list 1 2 3))))
(define-test list.apply.5b
(assert-equal '((a) (b) 1 2)
(apply (cadr (list 1 'list)) (list '(a) '(b) 1 2))))
(define-test list.order.1
(let ((i 0))
(assert-equal '(1 2 3) (list (incf i) (incf i) (incf i)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the LIST* function.
(define-test list*.1
(assert-equal '(1 2 3) (list* 1 '(2 3))))
(define-test list*.2
(assert-equal '(1 2 3) (list* 1 2 '(3))))
(define-test list*.3
(assert-equal '(1 2 3) (list* 1 2 3 '())))
(define-test list*.4
(assert-equal 'a (list* 'a)))
(define-test list*.5
(assert-equal '(1 2 . 3) (list* 1 2 3)))
(define-test list*.apply.1
(assert-equal '(1 2 3)
(apply (cadr (list 1 #'list*)) (list 1 '(2 3)))))
(define-test list*.apply.2
(assert-equal '(1 2 3)
(apply (cadr (list 1 #'list*)) (list 1 2 '(3)))))
(define-test list*.apply.3
(assert-equal '(1 2 3)
(apply (cadr (list 1 #'list*)) (list 1 2 3 '()))))
(define-test list*.apply.4
(assert-equal 'a
(apply (cadr (list 1 #'list*)) (list 'a))))
(define-test list*.apply.5
(assert-equal '(1 2 . 3)
(apply (cadr (list 1 #'list*)) (list 1 2 3))))
(define-test list*.error.1
(assert-error 'error
(list*)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the LAST function.
(define-test |last 1|
(assert-equal '() (last '())))
(define-test |last 2|
(assert-equal '(1) (last '(1))))
(define-test |last 3|
(assert-equal '(2) (last '(1 2))))
(define-test |last 4|
(assert-equal '(1 . 2) (last '(1 . 2))))
(define-test |last 5|
(assert-equal '(2 3) (last '(1 2 3) 2)))
(define-test |last 6|
(assert-equal '(1 2 . 3) (last '(1 2 . 3) 2)))
(define-test |last 7|
(assert-equal '(2 3 . 4) (last '(1 2 3 . 4) 2)))
(define-test |last 8|
(assert-equal '(1 2 3) (last '(1 2 3) 3)))
(define-test |last 9|
(assert-equal '(1 2 3) (last '(1 2 3) 4)))
(define-test |last error 1|
(assert-error 'type-error
(last 1)))
(define-test |last error 2|
(assert-error 'type-error
(last '(1) 'a)))
(define-test |last apply error 1|
(assert-error 'type-error
(apply #'last (list 1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the COPY-LIST function.
(define-test copy-list.1
(assert-equal '() (copy-list '())))
(define-test copy-list.2
(assert-equal '(1) (copy-list '(1))))
(define-test copy-list.3
(let ((thing '(a b)))
(assert-equal thing (car (copy-list (list thing 1 2))))))
(define-test copy-list.4
(assert-equal '(1 . 2) (copy-list '(1 . 2))))
(define-test copy-list.error
(assert-error 'type-error (copy-list 1)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the LIST-LENGTH function.
(define-test |list-length proper-list 1|
(assert-equal 0
(list-length '())))
(define-test |list-length proper-list 2|
(assert-equal 1
(list-length '(0))))
(define-test |list-length proper-list 3|
(assert-equal 2
(list-length '(0 0))))
(define-test |list-length proper-list 4|
(assert-equal 3
(list-length '(0 0 0))))
(define-test |list-length proper-list 5|
(assert-equal 4
(list-length '(0 0 0 0))))
(define-test |list-length proper-list 6|
(assert-equal 5
(list-length '(0 0 0 0 0))))
(define-test |list-length circular-list 1|
(assert-equal nil
(list-length '#1=(0 . #1#))))
(define-test |list-length circular-list 2|
(assert-equal nil
(list-length '#1=(0 0 . #1#))))
(define-test |list-length circular-list 3|
(assert-equal nil
(list-length '#1=(0 0 0 . #1#))))
(define-test |list-length circular-list 4|
(assert-equal nil
(list-length '#1=(0 0 0 0 . #1#))))
(define-test |list-length dotted-list 1|
(assert-error 'type-error
(list-length '(0 . 0))))
(define-test |list-length dotted-list 2|
(assert-error 'type-error
(list-length '(0 0 . 0))))
(define-test |list-length dotted-list 3|
(assert-error 'type-error
(list-length '(0 0 0 . 0))))
(define-test |list-length dotted-list 4|
(assert-error 'type-error
(list-length '(0 0 0 0 . 0))))
(define-test |list-length not-a-list 1|
(assert-error 'type-error
(list-length 0)))
(define-test |list-length not-a-list 2|
(assert-error 'type-error
(list-length 'a)))
(define-test |list-length not-a-list 3|
(assert-error 'type-error
(list-length #(a))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the MAKE-LIST function.
(define-test make-list.1
(assert-equal '() (make-list 0)))
(define-test make-list.2
(assert-equal 1 (length (make-list 1))))
(define-test make-list.3
(assert-equal '(3 3) (make-list 2 :initial-element 3)))
(define-test make-list.error.1
(assert-error 'type-error (make-list 'a)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the NTHCDR function.
(define-test |nthcdr 1|
(assert-equal '()
(nthcdr 0 '())))
(define-test |nthcdr 2|
(assert-equal '()
(nthcdr 1 '())))
(define-test |nthcdr 3|
(assert-equal '(0 0)
(nthcdr 1 '(0 0 0))))
(define-test |nthcdr error 1|
(assert-error 'type-error
(nthcdr 'a '(0 0))))
(define-test |nthcdr error 2|
(assert-error 'type-error
(nthcdr '-1 '(0 0))))
(define-test |nthcdr error 3|
(assert-error 'type-error
(nthcdr 2 '(0 . 0))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the NTH function.
(define-test |nth 1|
(assert-equal '()
(nth 0 '())))
(define-test |nth 2|
(assert-equal '()
(nth 1 '())))
(define-test |nth 3|
(assert-equal 1
(nth 0 '(1 2))))
(define-test |nth 4|
(assert-equal 2
(nth 1 '(1 2))))
(define-test |nth 5|
(assert-equal '()
(nth 3 '(1 2))))
(define-test |nth error 1|
(assert-error 'type-error
(nth 3 '(1 2 . 0))))
(define-test |nth error 2|
(assert-error 'type-error
(nth -1 '(1))))
(define-test |nth error 2|
(assert-error 'type-error
(nth 'a '(1))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the (SETF NTH) function and SETF expander.
(define-test |setf-nth 1|
(let ((list (copy-list '(0 0 0))))
(assert-equal 1
(setf (nth 0 list) 1))
(assert-equal '(1 0 0)
list)))
(define-test |setf-nth 1|
(let ((list (copy-list '(0 0 0))))
(assert-equal 1
(setf (nth 2 list) 1))
(assert-equal '(0 0 1)
list)))
(define-test |setf-nth error 1|
(assert-error 'error
(setf (nth 0 '()) 1)))
(define-test |setf-nth error 2|
(assert-error 'error
(setf (nth 1 (copy-list '(0))) 1)))
(define-test |setf-nth error 3|
(assert-error 'error
(setf (nth 2 (copy-list '(0))) 1)))
(define-test |setf-nth error 4|
(assert-error 'error
(setf (nth -1 (copy-list '(0))) 1)))
(define-test |setf-nth error 5|
(assert-error 'error
(setf (nth 'a (copy-list '(0))) 1)))
(define-test |setf-nth apply 1|
(let ((list (copy-list '(0 0 0))))
(assert-equal 1
(apply #'(setf nth) (list 1 0 list)))
(assert-equal '(1 0 0)
list)))
(define-test |setf-nth apply 1|
(let ((list (copy-list '(0 0 0))))
(assert-equal 1
(apply #'(setf nth) (list 1 2 list)))
(assert-equal '(0 0 1)
list)))
(define-test |setf-nth apply error 1|
(assert-error 'error
(apply #'(setf nth) (list 1 0 '()))))
(define-test |setf-nth apply error 2|
(assert-error 'error
(apply #'(setf nth) (list 1 1 (copy-list '(0))))))
(define-test |setf-nth apply error 3|
(assert-error 'error
(apply #'(setf nth) (list 1 2 (copy-list '(0))))))
(define-test |setf-nth apply error 4|
(assert-error 'error
(apply #'(setf nth) (list 1 -1 (copy-list '(0))))))
(define-test |setf-nth apply error 5|
(assert-error 'error
(apply #'(setf nth) (list 1 'a (copy-list '(0))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the copy-tree function
(define-test copy-tree.1
(assert-equal 'x (copy-tree 'x)))
(define-test copy-tree.2
(assert-equal '(a . b) (copy-tree '(a . b))))
(define-test copy-tree.3
(let ((tree '(((((a b . c) d (e (f g)) . h))) (i j (k)))))
(assert-equal tree (copy-tree tree))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the tree-equal function
(define-test |tree-equal test=eql 1a|
(assert-true (tree-equal nil nil)))
(define-test |tree-equal test=eql 1b|
(assert-true (tree-equal nil nil :test #'eql)))
(define-test |tree-equal test=eql 1c|
(assert-true (tree-equal nil nil :test 'eql)))
(define-test |tree-equal test=eql 2a|
(assert-true (tree-equal 1 1)))
(define-test |tree-equal test=eql 2b|
(assert-true (tree-equal 1 1 :test #'eql)))
(define-test |tree-equal test=eql 2c|
(assert-true (tree-equal 1 1 :test 'eql)))
(define-test |tree-equal test=eql 3a|
(assert-true (tree-equal '(1) '(1))))
(define-test |tree-equal test=eql 3b|
(assert-true (tree-equal '(1) '(1) :test #'eql)))
(define-test |tree-equal test=eql 3c|
(assert-true (tree-equal '(1) '(1) :test 'eql)))
(define-test |tree-equal test=eql 4a|
(assert-true (tree-equal '(1 . 2) '(1 . 2))))
(define-test |tree-equal test=eql 4b|
(assert-true (tree-equal '(1 . 2) '(1 . 2) :test #'eql)))
(define-test |tree-equal test=eql 4c|
(assert-true (tree-equal '(1 . 2) '(1 . 2) :test 'eql)))
(define-test |tree-equal test=eql 5a|
(assert-false (tree-equal 1 2)))
(define-test |tree-equal test=eql 5b|
(assert-false (tree-equal 1 2 :test #'eql)))
(define-test |tree-equal test=eql 5c|
(assert-false (tree-equal 1 2 :test 'eql)))
(define-test |tree-equal test=eql 6a|
(assert-false (tree-equal '(1) '(2))))
(define-test |tree-equal test=eql 6b|
(assert-false (tree-equal '(1) '(2) :test #'eql)))
(define-test |tree-equal test=eql 6c|
(assert-false (tree-equal '(1) '(2) :test 'eql)))
(define-test |tree-equal test=eql 7a|
(assert-false (tree-equal '(1) '((1)))))
(define-test |tree-equal test=eql 7b|
(assert-false (tree-equal '(1) '((1)) :test #'eql)))
(define-test |tree-equal test=eql 7c|
(assert-false (tree-equal '(1) '((1)) :test 'eql)))
(define-test |tree-equal test=eql 8a|
(assert-false (tree-equal '((1)) '(1))))
(define-test |tree-equal test=eql 8b|
(assert-false (tree-equal '((1)) '(1) :test #'eql)))
(define-test |tree-equal test=eql 8c|
(assert-false (tree-equal '((1)) '(1) :test 'eql)))
(define-test |tree-equal test=eq 1a|
(assert-true (tree-equal 'a 'a :test #'eq)))
(define-test |tree-equal test=eq 1b|
(assert-true (tree-equal 'a 'a :test 'eq)))
(define-test |tree-equal test=eq 2a|
(assert-false (tree-equal 'a 'b :test #'eq)))
(define-test |tree-equal test=eq 2b|
(assert-false (tree-equal 'a 'b :test 'eq)))
(define-test |tree-equal test=eq 3a|
(assert-true (tree-equal '(a) '(a) :test #'eq)))
(define-test |tree-equal test=eq 3b|
(assert-true (tree-equal '(a) '(a) :test 'eq)))
(define-test |tree-equal test=eq 4a|
(assert-false (tree-equal '(a) '((a)) :test #'eq)))
(define-test |tree-equal test=eq 4b|
(assert-false (tree-equal '(a) '((a)) :test 'eq)))
(define-test |tree-equal test=eq 5a|
(assert-false (tree-equal '((a)) '(a) :test #'eq)))
(define-test |tree-equal test=eq 5b|
(assert-false (tree-equal '((a)) '(a) :test 'eq)))
(define-test |tree-equal test-not=eql 1a|
(assert-false (tree-equal '(1) '(2) :test-not #'eql)))
(define-test |tree-equal test-not=eql 1b|
(assert-false (tree-equal '(1) '(2) :test-not 'eql)))
(define-test |tree-equal test-not=eql 2a|
(assert-false (tree-equal '(1) '((1)) :test-not #'eql)))
(define-test |tree-equal test-not=eql 2b|
(assert-false (tree-equal '(1) '((1)) :test-not 'eql)))
(define-test |tree-equal test-not=eql 3a|
(assert-false (tree-equal '((1)) '(1) :test-not #'eql)))
(define-test |tree-equal test-not=eql 3b|
(assert-false (tree-equal '((1)) '(1) :test-not 'eql)))
(define-test |tree-equal test-not=eq 1a|
(assert-true (tree-equal 'a 'b :test-not #'eq)))
(define-test |tree-equal test-not=eq 1b|
(assert-true (tree-equal 'a 'b :test-not 'eq)))
(define-test |tree-equal test-not=eq 2a|
(assert-false (tree-equal 'a 'a :test-not #'eq)))
(define-test |tree-equal test-not=eq 2b|
(assert-false (tree-equal 'a 'a :test-not 'eq)))
(define-test |tree-equal test-not=eq 3a|
(assert-false (tree-equal '(a) '(a) :test-not #'eq)))
(define-test |tree-equal test-not=eq 3b|
(assert-false (tree-equal '(a) '(a) :test-not 'eq)))
(define-test |tree-equal test-not=eq 4a|
(assert-false (tree-equal '(a) '((a)) :test-not #'eq)))
(define-test |tree-equal test-not=eq 4b|
(assert-false (tree-equal '(a) '((a)) :test-not 'eq)))
(define-test |tree-equal test-not=eq 5a|
(assert-false (tree-equal '((a)) '(a) :test-not #'eq)))
(define-test |tree-equal test-not=eq 5b|
(assert-false (tree-equal '((a)) '(a) :test-not 'eq)))
(define-test |tree-equal test-not=eq 6a|
(assert-false (tree-equal '(a) '(b) :test-not #'eq)))
(define-test |tree-equal test-not=eq 6b|
(assert-false (tree-equal '(a) '(b) :test-not 'eq)))
(define-test |tree-equal test=other 1|
(assert-true (tree-equal '(1) '(2)
:test (lambda (x y)
(or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1)))))))
(define-test |tree-equal test=other 2|
(assert-false (tree-equal '(1) '(3)
:test (lambda (x y)
(or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1)))))))
(define-test |tree-equal test=other 3|
(assert-false (tree-equal '(1) '((3))
:test (lambda (x y)
(or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1)))))))
(define-test |tree-equal test=other 4|
(assert-false (tree-equal '((1)) '(3)
:test (lambda (x y)
(or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1)))))))
(define-test |tree-equal test-not=other 1|
(assert-true (tree-equal '(1) '(2)
:test-not (lambda (x y)
(not (or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))))))
(define-test |tree-equal test-not=other 2|
(assert-false (tree-equal '(1) '(3)
:test-not (lambda (x y)
(not (or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))))))
(define-test |tree-equal test-not=other 3|
(assert-false (tree-equal '(1) '((3))
:test-not (lambda (x y)
(not (or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))))))
(define-test |tree-equal test-not=other 4|
(assert-false (tree-equal '((1)) '(3)
:test-not (lambda (x y)
(not (or (eql x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))))))
(define-test |tree-equal test=other test-not=other 1|
(assert-error 'error
(tree-equal '() '() :test #'eql :test-not #'eql)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the endp function
(define-test endp.1
(assert-true (endp '())))
(define-test endp.2
(assert-false (endp '(1 . 2))))
(define-test endp.3
(assert-error 'type-error (endp 1)))
(define-test endp.4
(assert-error 'type-error (endp #\a)))
(define-test endp.5
(assert-error 'type-error (endp "a")))
(define-test endp.6
(assert-error 'type-error (endp 'a)))
(define-test endp.7
(assert-error 'type-error (endp 1.0)))
(define-test endp.8
(assert-error 'type-error (endp #(a))))
(define-test endp.9
(assert-error 'type-error (endp *standard-input*)))
(define-test endp.10
(assert-error 'type-error (endp *package*)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the mapcar function
(define-test |mapcar 1|
(assert-equal '() (mapcar #'1+ '())))
(define-test |mapcar 2|
(assert-equal '(1) (mapcar #'1+ '(0))))
(define-test |mapcar 3|
(assert-equal '(-1 -2 -3) (mapcar #'- '(1 2 3))))
(define-test |mapcar 4|
(assert-equal '(2 4 6) (mapcar #'+ '(1 2 3) '(1 2 3))))
(define-test |mapcar 5|
(assert-equal '(3 6 9) (mapcar #'+ '(1 2 3) '(1 2 3) '(1 2 3))))
(define-test |mapcar 6|
(assert-equal '(2 4) (mapcar #'+ '(1 2 3 4 5) '(1 2))))
(define-test |mapcar 7|
(assert-equal '(2 4) (mapcar #'+ '(1 2) '(1 2 3 4 5))))
(define-test |mapcar error 1|
(assert-error 'type-error (mapcar #'1+ (if (twisted '(a b c)) 1 '(a b c)))))
(define-test |mapcar error 2|
(assert-error 'type-error (mapcar #'1+ (if (twisted '(a b c)) #(1 2 3) '(a b c)))))
(define-test |mapcar error 3|
(assert-error 'type-error (mapcar #'1+ '(1 2 . 3))))
(define-test |mapcar error 4|
(assert-error 'type-error (mapcar #'1+ (if (twisted '(a b c)) "1" '(a b c)))))
(define-test |mapcar error 5|
(assert-error 'error (mapcar #'1+)))
(define-test |mapcar error 6|
(assert-error 'type-error
(mapcar #'list '(a b c) '(d e . f))))
(define-test |mapcar order 1|
(let ((i 0)
(funs (vector #'1+ #'1-))
(lists '((1 2) (3 4) (5 6))))
(assert-equal '(4 5) (mapcar (aref funs (incf i)) (nth (incf i) lists)))))
(define-test |mapcar apply error 1|
(assert-error 'error
(apply (cadr (list 'a #'mapcar)) #'car '())))
(define-test |mapcar apply error 2|
(assert-error 'type-error
(apply (cadr (list 'a #'mapcar)) #'list '((a b c) (d e . f)))))
(define-test |mapcar apply 1|
(assert-equal '(a b c)
(apply (cadr (list 'a #'mapcar)) #'car '(((a) (b) (c))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the mapc function
(define-test mapc.1
(assert-equal '() (mapc #'1+ '())))
(define-test mapc.2
(let ((i 0))
(assert-equal '(1 2 3 6)
(append (mapc (lambda (x) (incf i x)) '(1 2 3))
(list i)))))
(define-test mapc.3
(let ((i 0))
(assert-equal '(1 2 3 12)
(append (mapc (lambda (x y) (incf i (+ x y)))
'(1 2 3)
'(1 2 3))
(list i)))))
(define-test mapc.apply.1
(let ((i 0))
(assert-equal '(1 2 3 12)
(append (apply (cadr (list 'a #'mapc))
(list (lambda (x y) (incf i (+ x y)))
'(1 2 3)
'(1 2 3)))
(list i)))))
(define-test mapc.error.1
(assert-error 'type-error (mapc #'1+ (if (twisted '(a b c)) 1 '(1 2 3)))))
(define-test mapc.error.2
(assert-error 'type-error (mapc #'1+ (if (twisted '(a b c)) #(1 2 3) '(1 2 3)))))
(define-test mapc.error.3
(assert-error 'type-error (mapc #'1+ '(1 2 . 3))))
(define-test mapc.error.4
(assert-error 'type-error (mapc #'1+ (if (twisted '(a b c)) "1" '(1 2 3)))))
(define-test mapc.error.5
(assert-error 'error (mapc #'1+)))
(define-test mapc.apply.error.1
(assert-error 'type-error
(apply #'mapc (list #'list '(1 2) '(3 . 4)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the maplist function
(define-test maplist.1
(assert-equal '() (maplist #'car '())))
(define-test maplist.2
(assert-equal '(1 2 3) (maplist #'car '(1 2 3))))
(define-test maplist.apply.1
(assert-equal '(1 2 3)
(apply (cadr (list 'a #'maplist))
(list #'car '(1 2 3)))))
(define-test maplist.error.1
(assert-error 'type-error (maplist #'car (if (twisted '(a b c)) 1 '(a b c)))))
(define-test maplist.error.2
(assert-error 'type-error (maplist #'car (if (twisted '(a b c)) #(1 2 3) '(a b c)))))
(define-test maplist.error.3
(assert-error 'type-error (maplist #'car '(1 2 . 3))))
(define-test maplist.error.4
(assert-error 'type-error (maplist #'car (if (twisted '(a b c)) "1" '(a b c)))))
(define-test maplist.error.5
(assert-error 'error (maplist #'car)))
(define-test maplist.apply.error.1
(assert-error 'type-error
(apply #'maplist (list #'list '(1 2) '(3 . 4)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the mapl function
(define-test mapl.1
(assert-equal '() (mapl #'car '())))
(define-test mapl.2
(assert-equal '(1) (mapl #'car '(1))))
(define-test mapl.3
(let ((i 0))
(assert-equal 6
(progn (mapl (lambda (sublist) (incf i (car sublist)))
'(1 2 3))
i))))
(define-test mapl.apply.1
(let ((i 0))
(assert-equal 6
(progn (apply (cadr (list 'a #'mapl))
(list (lambda (sublist) (incf i (car sublist)))
'(1 2 3)))
i))))
(define-test mapl.error.1
(assert-error 'type-error (mapl #'car (if (twisted '(a b c)) 1 '(a b c)))))
(define-test mapl.error.2
(assert-error 'type-error (mapl #'car (if (twisted '(a b c)) #(1 2 3) '(a b c)))))
(define-test mapl.error.3
(assert-error 'type-error (mapl #'car '(1 2 . 3))))
(define-test mapl.error.4
(assert-error 'type-error (mapl #'car (if (twisted '(a b c)) "1" '(a b c)))))
(define-test mapl.error.5
(assert-error 'error (mapl #'car)))
(define-test mapl.apply.error.1
(assert-error 'type-error
(apply #'mapl (list #'list '(1 2) '(3 . 4)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the mapcan function
(define-test mapcan.1
(assert-equal '(a b c)
(mapcan #'list '(a b c))))
(define-test mapcan.2
(assert-equal '(a d b e c f)
(mapcan #'list '(a b c) '(d e f))))
(define-test mapcan.3
(assert-equal '(a b c . f)
(mapcan #'cons '(a b c) '(d e f))))
(define-test mapcan.4
(let ((a (list 'a))
(b (list 'b))
(c (list 'c)))
(assert-eq c
(cddr (mapcan #'identity (list a b c))))))
(define-test mapcan.5
(assert-equal '()
(mapcan #'identity '())))
(define-test mapcan.apply.1
(let ((a (list 'a))
(b (list 'b))
(c (list 'c)))
(assert-eq c
(cddr (apply (cadr (list 'a #'mapcan))
(list #'identity (list a b c)))))))
(define-test mapcan.error.1
(assert-error 'type-error
(mapcan #'car (if (twisted '(a b c)) 1 '((a) (b) (c))))))
(define-test mapcan.error.2
(assert-error 'type-error
(mapcan #'car (if (twisted '(a b c)) #(1 2 3) '((a) (b) (c))))))
(define-test mapcan.error.3
(assert-error 'type-error (mapcan #'car '(1 2 . 3))))
(define-test mapcan.error.4
(assert-error 'type-error
(mapcan #'car (if (twisted '(a b c)) "1" '((a) (b) (c))))))
(define-test mapcan.error.5
(assert-error 'error (mapcan #'car)))
(define-test mapcan.apply.error.1
(assert-error 'type-error
(apply #'mapcan (list #'list '(1 2) '(3 . 4)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the mapcon function
(define-test |macon 1|
(assert-equal nil
(mapcon #'identity '())))
(define-test |mapcon 2|
(assert-equal '(1 2 2)
(mapcon #'copy-list '(1 2))))
(define-test |mapcon 3|
(assert-equal '((1 2) (3 4) (2) (4))
(mapcon #'list '(1 2) '(3 4))))
(define-test |mapcon apply 1|
(assert-equal '((1 2) (3 4) (2) (4))
(apply #'mapcon #'list '(1 2) '(3 4) '())))
(define-test |mapcon error 1|
(assert-error 'type-error
(mapcon #'copy-list '(1 . 2))))
(define-test |mapcon error 2|
(assert-error 'type-error
(mapcon #'car (if (twisted '(a b c)) "1" '((a) (b) (c))))))
(define-test |mapcon error 3|
(assert-error 'error
(mapcon #'car)))
(define-test |mapcon apply error 1|
(assert-error 'type-error
(apply #'mapcon (list #'list '(1 2) '(3 . 4)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the append function
(define-test |append 1|
(assert-equal nil (append)))
(define-test |append 2|
(assert-equal 'x (append 'x)))
(define-test |append 4|
(assert-equal
'(a b c d e f g . h)
(append (list 'a) (list 'b) (list 'c)
(list 'd) (list 'e) (list 'f)
(list 'g) 'h)))
(define-test |append 5|
(assert-equal 'a (append nil nil nil nil nil nil nil nil 'a)))
;;; Test suggested by PI:NAME:<NAME>END_PI
(define-test |append 7|
(let ((x (list 'a 'b 'c 'd)))
(assert-false (eq (append x nil) x))))
;;; Order of evaluation tests
(define-test |append order 1|
(assert-equal
'((a b c d e f g h i) 3 1 2 3)
(let ((i 0) x y z)
(list
(append (progn (setf x (incf i)) (copy-list '(a b c)))
(progn (setf y (incf i)) (copy-list '(d e f)))
(progn (setf z (incf i)) (copy-list '(g h i))))
i x y z))))
(define-test |append order 2|
(assert-equal '(1 1) (let ((i 0)) (append (list (incf i)) (list i)))))
;;; Error tests
(define-test |append error 1|
(assert-error 'type-error (append '(a . b) '(z))))
(define-test |append error 2|
(assert-error 'type-error (append '(x y z) '(a . b) '(z))))
;;; This test verifies that append preserves the structure of
;;; the last list.
(define-test |append sharing 1|
(let ((list1 '(1 2))
(list2 '(3 4)))
(assert-eq (cddr (append list1 list2)) list2)))
(define-test |append apply 1|
(let ((list1 '(1 2))
(list2 '(3 4)))
(assert-equal '(1 2 3 4)
(apply (cadr (list 'a #'append)) (list list1 list2)))
(assert-equal '(1 2 3 4)
(apply (cadr (list 'a 'append)) (list list1 list2)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nconc function
(define-test |nconc 1|
(assert-eq '() (nconc)))
(define-test |nconc 2|
(let ((list (copy-tree '(a b c))))
(assert-eq list (nconc list))))
(define-test |nconc 3|
(let ((list (copy-tree '(a b c))))
(assert-eq list (nconc '() list))))
(define-test |nconc 4|
(let ((list1 (copy-tree '(a b c)))
(list2 (copy-tree '(d e f))))
(assert-eq list1 (nconc list1 list2))
(assert-eq list2 (cdddr list1))))
(define-test |nconc 5|
(assert-equal '(a z)
(nconc (copy-tree '(a . b))
(copy-tree '(z)))))
(define-test |nconc 6|
(assert-equal '(x y z a z)
(nconc (copy-tree '(x y z))
(copy-tree '(a . b))
(copy-tree '(z)))))
(define-test |nconc order 1|
(assert-equal
'((a b c d e f g h i) 3 1 2 3)
(let ((i 0) x y z)
(list
(nconc (progn (setf x (incf i)) (copy-list '(a b c)))
(progn (setf y (incf i)) (copy-list '(d e f)))
(progn (setf z (incf i)) (copy-list '(g h i))))
i x y z))))
(define-test |nconc apply 1|
(let ((list1 '(1 2))
(list2 '(3 4)))
(assert-equal '(1 2 3 4)
(apply (cadr (list 'a #'nconc))
(copy-tree (list list1 list2))))
(assert-equal '(1 2 3 4)
(apply (cadr (list 'a 'nconc))
(copy-tree (list list1 list2))))))
(define-test |nconc error 1|
(assert-error 'type-error
(nconc (copy-tree '(a b c)) 'd (copy-tree '(e f)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the revappend function
(define-test revappend.1
(assert-equal '()
(revappend '() '())))
(define-test revappend.2
(assert-equal '(a)
(revappend '(a) '())))
(define-test revappend.3
(assert-equal '(b a)
(revappend '(a b) '())))
(define-test revappend.4
(assert-equal '(b a c)
(revappend '(a b) '(c))))
(define-test revappend.5
(assert-equal '(b a . c)
(revappend '(a b) 'c)))
(define-test revappend.6
(assert-equal 'c
(revappend '() 'c)))
(define-test revappend.7
(let ((l '(x)))
(assert-equal l
(cdr (revappend '(a) l)))))
(define-test revappend.error.1
(assert-error 'type-error
(revappend 'a '())))
(define-test revappend.error.2
(assert-error 'type-error
(revappend '(a . b) '())))
(define-test revappend.error.3
(assert-error 'type-error
(revappend 1 '())))
(define-test revappend.error.4
(assert-error 'type-error
(revappend #(a b) '())))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nreconc function
(define-test nreconc.1
(assert-equal '()
(nreconc '() '())))
(define-test nreconc.2
(assert-equal '(a)
(nreconc (copy-list '(a)) '())))
(define-test nreconc.3
(assert-equal '(b a)
(nreconc (copy-list '(a b)) '())))
(define-test nreconc.4
(assert-equal '(b a c)
(nreconc (copy-list '(a b)) '(c))))
(define-test nreconc.5
(assert-equal '(b a . c)
(nreconc (copy-list '(a b)) 'c)))
(define-test nreconc.6
(assert-equal 'c
(nreconc '() 'c)))
(define-test nreconc.7
(let ((l '(x)))
(assert-equal l
(cdr (nreconc (copy-list '(a)) l)))))
(define-test nreconc.error.1
(assert-error 'type-error
(nreconc 'a '())))
(define-test nreconc.error.2
(assert-error 'type-error
(nreconc (copy-tree '(a . b)) '())))
(define-test nreconc.error.3
(assert-error 'type-error
(nreconc 1 '())))
(define-test nreconc.error.4
(assert-error 'type-error
(nreconc #(a b) '())))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the butlast function
(define-test butlast.1
(assert-equal '() (butlast '())))
(define-test butlast.2
(assert-equal '() (butlast '(0))))
(define-test butlast.3
(assert-equal '(0) (butlast '(0 1))))
(define-test butlast.4
(assert-equal '() (butlast '(0 . 1))))
(define-test butlast.5
(assert-equal '(0) (butlast '(0 1 . 2))))
(define-test butlast.6
(assert-equal '() (butlast '() 0)))
(define-test butlast.7
(assert-equal '() (butlast '() 1)))
(define-test butlast.8
(assert-equal '() (butlast '() 2)))
(define-test butlast.9
(assert-equal '(0) (butlast '(0) 0)))
(define-test butlast.10
(assert-equal '(0 1) (butlast '(0 1) 0)))
(define-test butlast.11
(assert-equal '(0) (butlast '(0 . 1) 0)))
(define-test butlast.12
(assert-equal '(0) (butlast '(0 1 2) 2)))
(define-test butlast.13
(assert-equal '() (butlast '(0 1 2) 3)))
(define-test butlast.13
(assert-equal '() (butlast '(0 1 2) 4)))
(define-test butlast.error.1
(assert-error 'type-error
(butlast '(0 1 2) (if (twisted '(1 2 3)) -1 1))))
(define-test butlast.error.2
(assert-error 'type-error
(butlast '(0 1 2) (if (twisted '(1 2 3)) 'a 1))))
(define-test butlast.error.3
(assert-error 'type-error
(butlast '#1=(0 . #1#))))
(define-test butlast.error.4
(assert-error 'type-error
(butlast 1)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nbutlast function
(define-test |nbutlast n=1 1a|
(assert-equal '()
(nbutlast '())))
(define-test |nbutlast n=1 1b|
(assert-equal '()
(nbutlast '() 1)))
(define-test |nbutlast n=1 2a|
(let ((list (copy-list '(1))))
(assert-equal '()
(nbutlast list))))
(define-test |nbutlast n=1 2b|
(let ((list (copy-list '(1))))
(assert-equal '()
(nbutlast list 1))))
(define-test |nbutlast n=1 3a|
(let ((list (copy-list '(1 2))))
(assert-equal '(1)
(nbutlast list))
(assert-equal '(1)
list)))
(define-test |nbutlast n=1 3b|
(let ((list (copy-list '(1 2))))
(assert-equal '(1)
(nbutlast list 1))
(assert-equal '(1)
list)))
(define-test |nbutlast n=1 4a|
(let ((list (copy-list '(1 . 2))))
(assert-equal '()
(nbutlast list))))
(define-test |nbutlast n=1 4b|
(let ((list (copy-list '(1 . 2))))
(assert-equal '()
(nbutlast list 1))))
(define-test |nbutlast n=1 5a|
(let ((list (copy-list '(1 2 . 3))))
(assert-equal '(1)
(nbutlast list))
(assert-equal '(1)
list)))
(define-test |nbutlast n=1 5b|
(let ((list (copy-list '(1 2 . 3))))
(assert-equal '(1)
(nbutlast list 1))
(assert-equal '(1)
list)))
(define-test |nbutlast n=1 6a|
(let ((list (copy-list '(1 2 3 . 4))))
(assert-equal '(1 2)
(nbutlast list))
(assert-equal '(1 2)
list)))
(define-test |nbutlast n=1 6b|
(let ((list (copy-list '(1 2 3 . 4))))
(assert-equal '(1 2)
(nbutlast list 1))
(assert-equal '(1 2)
list)))
(define-test |nbutlast n=1 7a|
(let ((list (copy-list '(1 2 3 4))))
(assert-equal '(1 2 3)
(nbutlast list))
(assert-equal '(1 2 3)
list)))
(define-test |nbutlast n=1 7b|
(let ((list (copy-list '(1 2 3 4))))
(assert-equal '(1 2 3)
(nbutlast list 1))
(assert-equal '(1 2 3)
list)))
(define-test |nbutlast n=other 1|
(assert-equal '()
(nbutlast '() 2)))
(define-test |nbutlast n=other 2|
(let ((list (copy-list '(1))))
(assert-equal '()
(nbutlast list 2))))
(define-test |nbutlast n=other 3|
(let ((list (copy-list '(1 2))))
(assert-equal '()
(nbutlast list 2))))
(define-test |nbutlast n=other 4|
(let ((list (copy-list '(1 2 3))))
(assert-equal '(1)
(nbutlast list 2))
(assert-equal '(1)
list)))
(define-test |nbutlast n=other 5|
(let ((list (copy-list '(1 2 . 3))))
(assert-equal '()
(nbutlast list 2))))
(define-test |nbutlast n=other 6|
(let ((list (copy-list '(1 2 3 . 4))))
(assert-equal '(1)
(nbutlast list 2))
(assert-equal '(1)
list)))
(define-test |nbutlast error 1|
(assert-error 'type-error
(nbutlast 1)))
(define-test |nbutlast error 2|
(assert-error 'type-error
(nbutlast '() 'a)))
(define-test |nbutlast error 3|
(let ((list (copy-list '(0))))
(setf (cdr list) list)
(assert-error 'type-error
(nbutlast list 1))))
(define-test |nbutlast error 4|
(let ((list (copy-list '(0))))
(setf (cdr list) list)
(assert-error 'type-error
(nbutlast list 2))))
(define-test |nbutlast error 5|
(let ((list (copy-list '(0))))
(setf (cdr list) list)
(assert-error 'type-error
(nbutlast list 3))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the subst function
(define-test |subst test=eql key=identity 1a|
(assert-equal '()
(subst 'a 0 '())))
(define-test |subst test=eql key=identity 1b|
(assert-equal '()
(subst 'a 0 '() :test #'eql)))
(define-test |subst test=eql key=identity 1c|
(assert-equal '()
(subst 'a 0 '() :test 'eql)))
(define-test |subst test=eql key=identity 2a|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 0 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0))))))
(define-test |subst test=eql key=identity 2b|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 0 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test #'eql)))
(define-test |subst test=eql key=identity 2c|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 0 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test 'eql)))
(define-test |subst test=eql key=nil 1|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a
0
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key nil)))
(define-test |subst test=eq key=identity 1|
(assert-equal '()
(subst 'a 'b '()
:test #'eq)))
(define-test |subst test=eq key=identity 2|
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(subst 'a 'b '(((b . c) . (f . b)) . ((b . d) . (e . b)))
:test #'eq)))
(define-test |subst test=other key=identity 1|
(assert-equal '()
(subst 'a 0 '()
:test (lambda (x y) (and (numberp y) (= x (1- y)))))))
(define-test |subst test=other key=identity 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 0 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test (lambda (x y) (and (numberp y) (= x y))))))
(define-test |subst test=eql key=other 1a|
(assert-equal '()
(subst 'a 0 '()
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst test=eql key=other 1b|
(assert-equal '()
(subst 'a 0 '()
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql)))
(define-test |subst test=eql key=other 1c|
(assert-equal '()
(subst 'a 0 '()
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(define-test |subst test=eql key=other 2a|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 1 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst test=eql key=other 2b|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 1 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql)))
(define-test |subst test=eql key=other 2c|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 1 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(define-test |subst test=eq key=other 1|
(assert-equal '()
(subst 'a 'bb '()
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(define-test |subst test=eq key=other 2|
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(subst 'a 'bb '(((b . c) . (f . b)) . ((b . d) . (e . b)))
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(define-test |subst test=other key=other 1|
(assert-equal '()
(subst 'a 0 '()
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst test=other key=other 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 0 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst test-not=any key=other 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst 'a 0 '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y)))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst test=other test-not=other|
(assert-error 'error
(subst 0 1 2 :test #'= :test-not #'=)))
;;; old one left over. Is it still needed?
(define-test subst.1
(assert-equal '(a (c))
(subst 'c '(b) '(a ((b))) :test-not (complement #'equal))))
(define-test |subst test=nil key=identity 1|
(assert-error 'error
(subst 'a
0
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test nil)))
(define-test |subst test-not=nil key=identity 1|
(assert-error 'error
(subst 'a
0
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the subst-if function
(define-test |subst-if key=identity 1|
(assert-equal '()
(subst-if 'a
(lambda (y) (and (numberp y) (zerop (1- y))))
'())))
(define-test |subst-if key=identity 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst-if 'a
(lambda (y) (and (numberp y) (zerop y)))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0))))))
(define-test |subst-if key=other 1|
(assert-equal '()
(subst-if 'a
(lambda (y) (and (numberp y) (zerop (1- y))))
'()
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst-if key=other 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst-if 'a
(lambda (y) (and (numberp y) (zerop (1- y))))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the subst-if-not function
(define-test |subst-if-not key=identity 1|
(assert-equal '()
(subst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop (1- y)))))
'())))
(define-test |subst-if-not key=identity 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop y))))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0))))))
(define-test |subst-if-not key=other 1|
(assert-equal '()
(subst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop (1- y)))))
'()
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |subst-if-not key=other 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(subst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop (1- y)))))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nsubst function
(define-test |nsubst test=eql key=identity 1a|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree))))
(define-test |nsubst test=eql key=identity 1b|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree :test #'eql))))
(define-test |nsubst test=eql key=identity 1c|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree :test 'eql))))
(define-test |nsubst test=eql key=identity 2a|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree)))
(assert-eq tree tree2)))
(define-test |nsubst test=eql key=identity 2b|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree :test #'eql)))
(assert-eq tree tree2)))
(define-test |nsubst test=eql key=identity 2c|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree :test 'eql)))
(assert-eq tree tree2)))
(define-test |nsubst test=eql key=identity 3a|
(assert-equal 2
(nsubst 2 1 1)))
(define-test |nsubst test=eql key=identity 3b|
(assert-equal 2
(nsubst 2 1 1 :test #'eql)))
(define-test |nsubst test=eql key=identity 3c|
(assert-equal 2
(nsubst 2 1 1 :test 'eql)))
(define-test |nsubst test=eql key=nil 1|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree :key nil)))
(assert-eq tree tree2)))
(define-test |nsubst test=eq key=identity 1a|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 'b tree :test #'eq))))
(define-test |nsubst test=eq key=identity 1b|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 'b tree :test 'eq))))
(define-test |nsubst test=eq key=identity 2a|
(let ((tree (copy-tree '(((b . c) . (f . b)) . ((b . d) . (e . b)))))
(tree2))
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(setf tree2 (nsubst 'a 'b tree :test #'eq)))
(assert-eq tree tree2)))
(define-test |nsubst test=eq key=identity 2a|
(let ((tree (copy-tree '(((b . c) . (f . b)) . ((b . d) . (e . b)))))
(tree2))
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(setf tree2 (nsubst 'a 'b tree :test 'eq)))
(assert-eq tree tree2)))
(define-test |nsubst test=eq key=identity 3a|
(assert-equal 'b
(nsubst 'b 'a 'a :test #'eq)))
(define-test |nsubst test=eq key=identity 3b|
(assert-equal 'b
(nsubst 'b 'a 'a :test 'eq)))
(define-test |nsubst test=other key=identity 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree
:test (lambda (x y) (and (numberp y) (= x (1- y))))))))
(define-test |nsubst test=other key=identity 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree
:test (lambda (x y) (and (numberp y) (= x y))))))
(assert-eq tree tree2)))
(define-test |nsubst test=other key=identity 3|
(assert-equal 2
(nsubst 2 1 0 :test (lambda (x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))))
(define-test |nsubst test=eql key=other 1a|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree
:key (lambda (x) (if (numberp x) (1+ x) x))))))
(define-test |nsubst test=eql key=other 1b|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql))))
(define-test |nsubst test=eql key=other 1c|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql))))
(define-test |nsubst test=eql key=other 2a|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 1 tree
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsubst test=eql key=other 2b|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 1 tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql)))
(assert-eq tree tree2)))
(define-test |nsubst test=eql key=other 2c|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 1 tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(assert-eq tree tree2)))
(define-test |nsubst test=eql key=other 3a|
(assert-equal 2
(nsubst 2 1 0 :key #'1+)))
(define-test |nsubst test=eql key=other 3b|
(assert-equal 2
(nsubst 2 1 0 :key #'1+ :test #'eql)))
(define-test |nsubst test=eql key=other 3c|
(assert-equal 2
(nsubst 2 1 0 :key #'1+ :test 'eql)))
(define-test |nsubst test=eq key=other 1a|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 'bb tree
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x))))))
(define-test |nsubst test=eq key=other 1b|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 'bb tree
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x))))))
(define-test |nsubst test=eq key=other 2a|
(let ((tree (copy-tree '(((b . c) . (f . b)) . ((b . d) . (e . b)))))
(tree2))
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(setf tree2 (nsubst 'a 'bb tree
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(assert-eq tree tree2)))
(define-test |nsubst test=eq key=other 2b|
(let ((tree (copy-tree '(((b . c) . (f . b)) . ((b . d) . (e . b)))))
(tree2))
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(setf tree2 (nsubst 'a 'bb tree
:test 'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(assert-eq tree tree2)))
(define-test |nsubst test=eq key=other 3a|
(assert-equal 'b
(nsubst 'b 'a 'c
:test #'eq
:key (lambda (x) (if (eq x 'c) 'a x)))))
(define-test |nsubst test=eq key=other 3b|
(assert-equal 'b
(nsubst 'b 'a 'c
:test 'eq
:key (lambda (x) (if (eq x 'c) 'a x)))))
(define-test |nsubst test=other key=other 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x))))))
(define-test |nsubst test=other key=other 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsubst test=other key=other 3|
(assert-equal 2
(nsubst 2 1 -1
:test (lambda (x y)
(and (numberp x)
(numberp y)
(<= (abs (- x y)) 1)))
:key #'1+)))
(define-test |nsubst test-not=other key=identity 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst 'a 0 tree
:test-not (lambda (x y)
(not (and (numberp y) (= x (1- y)))))))))
(define-test |nsubst test-not=other key=identity 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree
:test-not (lambda (x y)
(not (and (numberp y) (= x y)))))))
(assert-eq tree tree2)))
(define-test |nsubst test-not=other key=identity 3|
(assert-equal 2
(nsubst 2 1 0
:test-not (lambda (x y)
(not (and (numberp x)
(numberp y)
(<= (abs (- x y)) 1)))))))
(define-test |nsubst test-not=any key=other 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst 'a 0 tree
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y)))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsubst test-not=other key=other 3|
(assert-equal 2
(nsubst 2 1 -1
:test-not (lambda (x y)
(not (and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))
:key #'1+)))
(define-test |nsubst test-not=other key=other 4|
(assert-equal -1
(nsubst 2 1 -1
:test-not (lambda (x y)
(not (and (numberp x)
(numberp y)
(<= (abs (- x y)) 1))))
:key #'1-)))
(define-test |nsubst test=other test-not=other|
(assert-error 'error
(nsubst 0 1 2 :test #'= :test-not #'=)))
(define-test |nsubst test=nil key=identity 1|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-error 'error
(setf tree2 (nsubst 'a 0 tree :test nil)))))
(define-test |nsubst test-not=nil key=identity 1|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-error 'error
(setf tree2 (nsubst 'a 0 tree :test-not nil)))))
;;; old one left over. Is it still needed?
(define-test nsubst.1
(let ((tree (copy-tree '(a ((b))))))
(assert-equal '(a (c))
(nsubst 'c '(b) tree :test-not (complement #'equal)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nsubst-if function
(define-test |nsubst-if key=identity 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst-if 'a
(lambda (y) (and (numberp y) (zerop (1- y))))
tree))))
(define-test |nsubst-if key=identity 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst-if 'a
(lambda (y) (and (numberp y) (zerop y)))
tree)))
(assert-eq tree tree2)))
(define-test |nsubst-if key=identity 3|
(assert-equal 2
(nsubst-if 2 #'zerop 0)))
(define-test |nsubst-if key=identity 4|
(assert-equal 1
(nsubst-if 2 #'zerop 1)))
(define-test |nsubst-if key=other 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst-if 'a
(lambda (y) (and (numberp y) (zerop (1- y))))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))))))
(define-test |nsubst-if key=other 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst-if 'a
(lambda (y) (and (numberp y) (zerop (1- y))))
tree
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsubst-if key=other 3|
(assert-equal 2
(nsubst-if 2 #'zerop 1 :key #'1-)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nsubst-if-not function
(define-test |nsubst-if-not key=identity 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop (1- y)))))
tree))))
(define-test |nsubst-if-not key=identity 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop y))))
tree)))
(assert-eq tree tree2)))
(define-test |nsubst-if-not key=identity 3|
(assert-equal 2
(nsubst-if-not 2 #'zerop 1)))
(define-test |nsubst-if-not key=other 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsubst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop (1- y)))))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))))))
(define-test |nsubst-if-not key=other 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsubst-if-not 'a
(lambda (y) (not (and (numberp y) (zerop (1- y)))))
tree
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsubst-if-not key=other 3|
(assert-equal 2
(nsubst-if-not 2 #'zerop 0 :key #'1+)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the null function
(define-test null.1
(assert-equal t
(null '())))
(define-test null.2
(assert-equal nil
(null 1)))
(define-test null.3
(assert-equal nil
(null #\a)))
(define-test null.4
(assert-equal nil
(null #())))
(define-test null.5
(assert-equal nil
(null "")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the acons function
(define-test acons.1
(assert-equal '((a . b))
(acons 'a 'b '())))
(define-test acons.2
(assert-equal '((a . b) c)
(acons 'a 'b '(c))))
(define-test acons.3
(assert-equal '((a . b) . c)
(acons 'a 'b 'c)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the member function
(define-test |member test=eql key=identity 1|
(assert-equal nil
(member 234 '())))
(define-test |member test=eql key=identity 2a|
(assert-equal '(123 b c)
(member 123 '(a b 123 b c))))
(define-test |member test=eql key=identity 2b|
(assert-equal '(123 b c)
(member 123 '(a b 123 b c) :test #'eql)))
(define-test |member test=eql key=identity 2c|
(assert-equal '(123 b c)
(member 123 '(a b 123 b c) :test 'eql)))
(define-test |member test=eql key=identity 3|
(assert-equal nil
(member 123 '(a b c d e))))
(define-test |member test=eql key=other 1|
(assert-equal '(123 b c)
(member 124 '(a b 123 b c)
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |member test=eql key=other 2|
(assert-equal '(123 b c)
(member 124 '(a b 123 b c)
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(define-test |member test=eql key=nil 1|
(assert-equal '(123 b c)
(member 123 '(a b 123 b c) :key nil)))
(define-test |member test=eq key=identity 1|
(assert-equal '(d e)
(member 'd '(a b c d e)
:test #'eq)))
(define-test |member test=eq key=identity 2|
(assert-equal nil
(member 'f '(a b c d e)
:test #'eq)))
(define-test |member test=eq key=other 1|
(assert-equal '((d) (e))
(member 'd '((a) (b) (c) (d) (e))
:key #'car
:test #'eq)))
(define-test |member test=eq key=other 2|
(assert-equal nil
(member 'f '((a) (b) (c) (d) (e))
:key #'car
:test #'eq)))
(define-test |member test-not=eql key=identity 1|
(assert-equal '(3 4 5 2)
(member 2 '(2 2 2 3 4 5 2)
:test-not #'eql)))
(define-test |member test-not=eql key=identity 2|
(assert-equal nil
(member 2 '(2 2 2)
:test-not #'eql)))
(define-test |member test-not=eql key=other 1|
(assert-equal '(3 4 5 2)
(member 3 '(2 2 2 3 4 5 2)
:key #'1+
:test-not #'eql)))
(define-test |member test-not=eql key=other 2|
(assert-equal nil
(member 3 '(2 2 2)
:key #'1+
:test-not #'eql)))
(define-test |member test-not=eq key=identity 1|
(assert-equal '(3 4 5 a)
(member 'a '(a a a 3 4 5 a)
:test-not #'eq)))
(define-test |member test-not=eq key=identity 2|
(assert-equal nil
(member 'a '(a a a)
:test-not #'eq)))
(define-test |member test-not=eq key=other 1|
(assert-equal '((3) 4 5 a)
(member 'a '((a) (a) (a) (3) 4 5 a)
:key #'car
:test-not #'eq)))
(define-test |member test-not=eq key=other 2|
(assert-equal nil
(member 'a '((a) (a) (a))
:key #'car
:test-not #'eq)))
(define-test |member test=other key=identity 1|
(assert-equal '((123) b c)
(member '(123) '(a b (123) b c)
:test #'equal)))
(define-test |member test=other key=other 1|
(assert-equal '(3 4 5)
(member 5 '(1 2 3 4 5)
:key #'1+
:test (lambda (x y) (= x (1+ y))))))
(define-test |member test=other key=other 2|
(assert-equal nil
(member 10 '(1 2 3 4 5)
:key #'1+
:test (lambda (x y) (= x (1+ y))))))
(define-test |member test-not=other key=other 1|
(assert-equal '(3 4 5)
(member 4 '(1 2 3 4 5)
:key #'1+
:test-not (lambda (x y) (not (zerop (mod y x)))))))
(define-test |member test-not=other key=other 2|
(assert-equal nil
(member 10 '(1 2 3 4 5)
:key #'1+
:test-not (lambda (x y) (not (zerop (mod y x)))))))
(define-test |member error 1|
(assert-error 'type-error
(member 123 '(a b . 123))))
(define-test |member error 2|
(assert-error 'error
(member 123 '(1 2 3)
:test #'eql
:test-not #'eq)))
(define-test |member test=nil key=identity 1|
(assert-error 'error
(member 123 '(a b 123 b c) :test nil)))
(define-test |member test-not=nil key=identity 1|
(assert-error 'error
(member 123 '(a b 123 b c) :test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the member-if function
(define-test |member-if key=identity 1|
(assert-equal nil
(member-if #'oddp '(2 4 6))))
(define-test |member-if key=identity 2|
(assert-equal '(3 4)
(member-if #'oddp '(2 6 3 4))))
(define-test |member-if key=other 1|
(assert-equal '(3 4)
(member-if #'evenp '(2 6 3 4)
:key #'1+)))
(define-test |member-if key=other 2|
(assert-equal nil
(member-if #'evenp '(2 6 4)
:key #'1+)))
(define-test |member-if error 1|
(assert-error 'type-error
(member-if #'oddp '(2 4 6 . 7))))
(define-test |member-if key=other error 1|
(assert-error 'type-error
(member-if #'oddp '(2 4 6 . 7) :key #'identity)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the member-if-not function
(define-test |member-if-not key=identity 1|
(assert-equal nil
(member-if-not #'evenp '(2 4 6))))
(define-test |member-if-not key=identity 2|
(assert-equal '(3 4)
(member-if-not #'evenp '(2 6 3 4))))
(define-test |member-if-not key=other 1|
(assert-equal nil
(member-if-not #'oddp '(2 4 6)
:key #'1+)))
(define-test |member-if-not key=other 2|
(assert-equal '(3 4)
(member-if-not #'oddp '(2 6 3 4)
:key #'1+)))
(define-test |member-if-not error 1|
(assert-error 'type-error
(member-if-not #'evenp '(2 4 6 . 7))))
(define-test |member-if-not key=other error 1|
(assert-error 'type-error
(member-if-not #'evenp '(2 4 6 . 7) :key #'identity)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the assoc function
(define-test |assoc test=eql key=identity 1a|
(assert-equal '(a . b)
(assoc 'a '((b) nil (a . b) (a . c)))))
(define-test |assoc test=eql key=identity 1b|
(assert-equal '(a . b)
(assoc 'a '((b) nil (a . b) (a . c))
:test #'eql)))
(define-test |assoc test=eql key=identity 1c|
(assert-equal '(a . b)
(assoc 'a '((b) nil (a . b) (a . c))
:test 'eql)))
(define-test |assoc test=eql key=identity 2a|
(assert-equal nil
(assoc 'c '((b) nil (a . b) (a . c)))))
(define-test |assoc test=eql key=identity 2b|
(assert-equal nil
(assoc 'c '((b) nil (a . b) (a . c))
:test #'eql)))
(define-test |assoc test=eql key=identity 2c|
(assert-equal nil
(assoc 'c '((b) nil (a . b) (a . c))
:test 'eql)))
(define-test |assoc test=eql key=identity 3a|
(assert-equal '(nil . c)
(assoc 'nil '((b) nil (a . b) (nil . c)))))
(define-test |assoc test=eql key=identity 3b|
(assert-equal '(nil . c)
(assoc 'nil '((b) nil (a . b) (nil . c))
:test #'eql)))
(define-test |assoc test=eql key=identity 3c|
(assert-equal '(nil . c)
(assoc 'nil '((b) nil (a . b) (nil . c))
:test 'eql)))
(define-test |assoc test=eql key=identity 4a|
(assert-equal '(123 . b)
(assoc 123 '((b) nil (123 . b) (nil . c)))))
(define-test |assoc test=eql key=identity 4b|
(assert-equal '(123 . b)
(assoc 123 '((b) nil (123 . b) (nil . c))
:test #'eql)))
(define-test |assoc test=eql key=identity 4c|
(assert-equal '(123 . b)
(assoc 123 '((b) nil (123 . b) (nil . c))
:test 'eql)))
(define-test |assoc test=eql key=identity 5a|
(assert-equal '(#\a . b)
(assoc #\a '((b) nil (#\a . b) (nil . c)))))
(define-test |assoc test=eql key=identity 5b|
(assert-equal '(#\a . b)
(assoc #\a '((b) nil (#\a . b) (nil . c))
:test #'eql)))
(define-test |assoc test=eql key=identity 5c|
(assert-equal '(#\a . b)
(assoc #\a '((b) nil (#\a . b) (nil . c))
:test 'eql)))
(define-test |assoc test=eql key=nil 1|
(assert-equal '(nil . c)
(assoc 'nil '((b) nil (a . b) (nil . c))
:key nil)))
(define-test |assoc test=eq key=identity 1a|
(assert-equal '(a . b)
(assoc 'a '((b) nil (a . b) (a . c))
:test #'eq)))
(define-test |assoc test=eq key=identity 1b|
(assert-equal '(a . b)
(assoc 'a '((b) nil (a . b) (a . c))
:test 'eq)))
(define-test |assoc test=eq key=identity 2a|
(assert-equal nil
(assoc 'c '((b) nil (a . b) (a . c))
:test #'eq)))
(define-test |assoc test=eq key=identity 2b|
(assert-equal nil
(assoc 'c '((b) nil (a . b) (a . c))
:test 'eq)))
(define-test |assoc test=eq key=identity 3a|
(assert-equal '(nil . c)
(assoc 'nil '((b) nil (a . b) (nil . c))
:test #'eq)))
(define-test |assoc test=eq key=identity 3b|
(assert-equal '(nil . c)
(assoc 'nil '((b) nil (a . b) (nil . c))
:test 'eq)))
(define-test |assoc test=other key=identity 1|
(assert-equal '((a b) c)
(assoc '(a b) '((a . b) nil ((a b) c) (d e))
:test #'equal)))
(define-test |assoc test-not=other key=identity 1|
(assert-equal '((a b) c)
(assoc '(a b) '((a . b) nil ((a b) c) (d e))
:test-not (complement #'equal))))
(define-test |assoc test=eql key=other 1a|
(assert-equal '((a b) c)
(assoc 'a '(((b a) . b) nil ((a b) c) ((d) e))
:key #'car)))
(define-test |assoc test=eql key=other 1b|
(assert-equal '((a b) c)
(assoc 'a '(((b a) . b) nil ((a b) c) ((d) e))
:test #'eql
:key #'car)))
(define-test |assoc test=eql key=other 1c|
(assert-equal '((a b) c)
(assoc 'a '(((b a) . b) nil ((a b) c) ((d) e))
:test 'eql
:key #'car)))
(define-test |assoc test=eq key=other 1|
(assert-equal '((a b) c)
(assoc 'a '(((b a) . b) nil ((a b) c) ((d) e))
:test #'eq
:key #'car)))
(define-test |assoc test=other key=other 1|
(assert-equal '((a b) c)
(assoc 'a '(((b a) . b) nil ((a b) c) ((d) e))
:test (lambda (x y) (eq x y))
:key #'car)))
(define-test |assoc test-not=eql key=identity 1a|
(assert-equal '(345 b)
(assoc '234 '((234 a) (345 b) (234 c))
:test-not #'eql)))
(define-test |assoc test-not=eql key=identity 1b|
(assert-equal '(345 b)
(assoc '234 '((234 a) (345 b) (234 c))
:test-not 'eql)))
(define-test |assoc test-not=eql key=identity 2|
(assert-equal nil
(assoc '234 '((234 a) (234 b) (234 c))
:test-not #'eql)))
(define-test |assoc test-not=eql key=identity 3|
(assert-equal '(345 b)
(assoc '234 '((234 a) nil (345 b) (234 c))
:test-not #'eql)))
(define-test |assoc test-not=eq key=identity 1a|
(assert-equal '(y b)
(assoc 'x '((x a) (y b) (x c))
:test-not #'eq)))
(define-test |assoc test-not=eq key=identity 1b|
(assert-equal '(y b)
(assoc 'x '((x a) (y b) (x c))
:test-not 'eq)))
(define-test |assoc test-not=eq key=identity 2|
(assert-equal nil
(assoc 'x '((x a) (x b) (x c))
:test-not #'eq)))
(define-test |assoc test-not=eq key=identity 3|
(assert-equal '(y b)
(assoc 'x '((x a) nil (y b) (x c))
:test-not #'eq)))
(define-test assoc.error.1
(assert-error 'type-error
(assoc 'a '((b . c) nil d (a b)))))
(define-test |assoc test-not=eql key=other 1a|
(assert-equal '(345 b)
(assoc '235 '((234 a) (345 b) (234 c))
:test-not #'eql
:key #'1+)))
(define-test |assoc test-not=eql key=other 1b|
(assert-equal '(345 b)
(assoc '235 '((234 a) (345 b) (234 c))
:test-not 'eql
:key #'1+)))
(define-test |assoc test-not=eql key=other 2|
(assert-equal nil
(assoc '235 '((234 a) (234 b) (234 c))
:test-not #'eql
:key #'1+)))
(define-test |assoc test-not=eql key=other 3|
(assert-equal '(345 b)
(assoc '235 '((234 a) nil (345 b) (234 c))
:test-not #'eql
:key #'1+)))
(define-test |assoc test-not=eq key=other 1a|
(assert-equal '((y) b)
(assoc 'x '(((x) a) ((y) b) ((x) c))
:test-not #'eq
:key #'car)))
(define-test |assoc test-not=eq key=other 1b|
(assert-equal '((y) b)
(assoc 'x '(((x) a) ((y) b) ((x) c))
:test-not 'eq
:key #'car)))
(define-test |assoc test-not=eq key=other 2|
(assert-equal nil
(assoc 'x '(((x) a) ((x) b) ((x) c))
:test-not #'eq
:key #'car)))
(define-test |assoc test-not=eq key=other 3|
(assert-equal '((y) b)
(assoc 'x '(((x) a) nil ((y) b) ((x) c))
:test-not #'eq
:key #'car)))
(define-test |assoc test-not=other key=other 1a|
(assert-equal '(345 b)
(assoc '234 '((234 a) (345 b) (234 c))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |assoc test-not=other key=other 1b|
(assert-equal '(345 b)
(assoc '234 '((234 a) (345 b) (234 c))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |assoc test-not=other key=other 2|
(assert-equal nil
(assoc '234 '((234 a) (234 b) (234 c))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |assoc test-not=other key=other 3|
(assert-equal '(345 b)
(assoc '234 '((234 a) nil (345 b) (234 c))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |assoc error 1|
(assert-error 'type-error
(assoc 'a '((b . c) nil d (a b)))))
(define-test |assoc error 2|
(assert-error 'error
(assoc 'a '((b . c) nil d (a b))
:test #'eq
:test-not #'eq)))
(define-test |assoc test=nil key=identity 1|
(assert-error 'error
(assoc 'nil '((b) nil (a . b) (nil . c))
:test nil)))
(define-test |assoc test-not=nil key=identity 1|
(assert-error 'error
(assoc 'nil '((b) nil (a . b) (nil . c))
:test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the assoc-if function
(define-test |assoc-if key=identity 1|
(assert-equal '(a . b)
(assoc-if (lambda (x) (eq x 'a))
'((b) nil (a . b) (a . c)))))
(define-test |assoc-if key=identity 2|
(assert-equal nil
(assoc-if (lambda (x) (eq x 'c))
'((b) nil (a . b) (a . c)))))
(define-test |assoc-if key=identity 3|
(assert-equal '(nil . c)
(assoc-if #'null
'((b) nil (a . b) (nil . c)))))
(define-test |assoc-if key=identity 4|
(assert-equal '(123 . b)
(assoc-if (lambda (x) (eql x 123))
'((b) nil (123 . b) (nil . c)))))
(define-test |assoc-if key=identity 5|
(assert-equal '(#\a . b)
(assoc-if (lambda (x) (eql x #\a))
'((b) nil (#\a . b) (nil . c)))))
(define-test |assoc-if key=other 1|
(assert-equal '((a b) c)
(assoc-if (lambda (x) (eq x 'a))
'(((b a) . b) nil ((a b) c) ((d) e))
:key #'car)))
(define-test |assoc-if error 1|
(assert-error 'type-error
(assoc-if (lambda (x) (eq x 'a))
'((b . c) nil d (a b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the assoc-if-not function
(define-test |assoc-if-not key=identity 1|
(assert-equal '(a . b)
(assoc-if-not (complement (lambda (x) (eq x 'a)))
'((b) nil (a . b) (a . c)))))
(define-test |assoc-if-not key=identity 2|
(assert-equal nil
(assoc-if-not (complement (lambda (x) (eq x 'c)))
'((b) nil (a . b) (a . c)))))
(define-test |assoc-if-not key=identity 3|
(assert-equal '(nil . c)
(assoc-if-not (complement #'null)
'((b) nil (a . b) (nil . c)))))
(define-test |assoc-if-not key=identity 4|
(assert-equal '(123 . b)
(assoc-if-not (complement (lambda (x) (eql x 123)))
'((b) nil (123 . b) (nil . c)))))
(define-test |assoc-if-not key=identity 5|
(assert-equal '(#\a . b)
(assoc-if-not (complement (lambda (x) (eql x #\a)))
'((b) nil (#\a . b) (nil . c)))))
(define-test |assoc-if-not key=other 6|
(assert-equal '((a b) c)
(assoc-if-not (complement (lambda (x) (eq x 'a)))
'(((b a) . b) nil ((a b) c) ((d) e))
:key #'car)))
(define-test |assoc-if-not error 1|
(assert-error 'type-error
(assoc-if-not (complement (lambda (x) (eq x 'a)))
'((b . c) nil d (a b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the rassoc function
(define-test |rassoc test=eql key=identity 1a|
(assert-equal '(b . a)
(rassoc 'a '((b) nil (b . a) (c . a)))))
(define-test |rassoc test=eql key=identity 1b|
(assert-equal '(b . a)
(rassoc 'a '((b) nil (b . a) (c . a))
:test #'eql)))
(define-test |rassoc test=eql key=identity 1c|
(assert-equal '(b . a)
(rassoc 'a '((b) nil (b . a) (c . a))
:test 'eql)))
(define-test |rassoc test=eql key=identity 2a|
(assert-equal nil
(rassoc 'c '((b) nil (b . a) (c . a)))))
(define-test |rassoc test=eql key=identity 2b|
(assert-equal nil
(rassoc 'c '((b) nil (b . a) (c . a))
:test #'eql)))
(define-test |rassoc test=eql key=identity 2c|
(assert-equal nil
(rassoc 'c '((b) nil (b . a) (c . a))
:test 'eql)))
(define-test |rassoc test=eql key=identity 3a|
(assert-equal '(c . nil)
(rassoc 'nil '((b . x) nil (b . a) (c . nil)))))
(define-test |rassoc test=eql key=identity 3b|
(assert-equal '(c . nil)
(rassoc 'nil '((x . b) nil (b . a) (c . nil))
:test #'eql)))
(define-test |rassoc test=eql key=identity 3c|
(assert-equal '(c . nil)
(rassoc 'nil '((b . x) nil (b . a) (c . nil))
:test 'eql)))
(define-test |rassoc test=eql key=identity 4a|
(assert-equal '(b . 123)
(rassoc 123 '((b . x) nil (b . 123) (c . nil)))))
(define-test |rassoc test=eql key=identity 4b|
(assert-equal '(b . 123)
(rassoc 123 '((b . x) nil (b . 123) (c . nil))
:test #'eql)))
(define-test |rassoc test=eql key=identity 4c|
(assert-equal '(b . 123)
(rassoc 123 '((b . x) nil (b . 123) (c . nil))
:test 'eql)))
(define-test |rassoc test=eql key=identity 5a|
(assert-equal '(b . #\a)
(rassoc #\a '((b . x) nil (b . #\a) (c . nil)))))
(define-test |rassoc test=eql key=identity 5b|
(assert-equal '(b . #\a)
(rassoc #\a '((b . x) nil (b . #\a) (c . nil))
:test #'eql)))
(define-test |rassoc test=eql key=identity 5c|
(assert-equal '(b . #\a)
(rassoc #\a '((b . x) nil (b . #\a) (c . nil))
:test 'eql)))
(define-test |rassoc test=eql key=nil 1|
(assert-equal '(b . 123)
(rassoc 123 '((b . x) nil (b . 123) (c . nil))
:key nil)))
(define-test |rassoc test=eq key=identity 1a|
(assert-equal '(b . a)
(rassoc 'a '((b . x) nil (b . a) (c . a))
:test #'eq)))
(define-test |rassoc test=eq key=identity 1b|
(assert-equal '(b . a)
(rassoc 'a '((b . x) nil (b . a) (c . a))
:test 'eq)))
(define-test |rassoc test=eq key=identity 2a|
(assert-equal nil
(rassoc 'c '((b . x) nil (b . a) (c . a))
:test #'eq)))
(define-test |rassoc test=eq key=identity 2b|
(assert-equal nil
(rassoc 'c '((b . x) nil (b . a) (c . a))
:test 'eq)))
(define-test |rassoc test=eq key=identity 3a|
(assert-equal '(c . nil)
(rassoc 'nil '((b . x) nil (b . a) (c . nil))
:test #'eq)))
(define-test |rassoc test=eq key=identity 3b|
(assert-equal '(c . nil)
(rassoc 'nil '((b . x) nil (b . a) (c . nil))
:test 'eq)))
(define-test |rassoc test=other key=identity 1|
(assert-equal '(c . (a b))
(rassoc '(a b) '((b . a) nil (c . (a b)) (e . d))
:test #'equal)))
(define-test |rassoc test-not=other key=identity 1|
(assert-equal '(c . (a b))
(rassoc '(a b) '((b . a) nil (c . (a b)) (e . d))
:test-not (complement #'equal))))
(define-test |rassoc test=eql key=other 1a|
(assert-equal '(c . (a b))
(rassoc 'a '((b . (b a)) nil (c . (a b)) (e . (d)))
:key #'car)))
(define-test |rassoc test=eql key=other 1b|
(assert-equal '(c . (a b))
(rassoc 'a '((b . (b a)) nil (c . (a b)) (e . (d)))
:test #'eql
:key #'car)))
(define-test |rassoc test=eql key=other 1c|
(assert-equal '(c . (a b))
(rassoc 'a '((b . (b a)) nil (c . (a b)) (e . (d)))
:test 'eql
:key #'car)))
(define-test |rassoc test=eq key=other 1|
(assert-equal '(c . (a b))
(rassoc 'a '((b . (b a)) nil (c . (a b)) (e . (d)))
:test #'eq
:key #'car)))
(define-test |rassoc test=other key=other 1|
(assert-equal '(c . (a b))
(rassoc 'a '((b . (b a)) nil (c . (a b)) (e . (d)))
:test (lambda (x y) (eq x y))
:key #'car)))
(define-test |rassoc test-not=eql key=identity 1a|
(assert-equal '(b . 345)
(rassoc '234 '((a . 234) (b . 345) (c . 234))
:test-not #'eql)))
(define-test |rassoc test-not=eql key=identity 1b|
(assert-equal '(b . 345)
(rassoc '234 '((a . 234) (b . 345) (c . 234))
:test-not 'eql)))
(define-test |rassoc test-not=eql key=identity 2|
(assert-equal nil
(rassoc '234 '((a . 234) (b . 234) (c . 234))
:test-not #'eql)))
(define-test |rassoc test-not=eql key=identity 3|
(assert-equal '(b . 345)
(rassoc '234 '((a . 234) nil (b . 345) (c . 234))
:test-not #'eql)))
(define-test |rassoc test-not=eq key=identity 1a|
(assert-equal '(b . y)
(rassoc 'x '((a . x) (b . y) (c . x))
:test-not #'eq)))
(define-test |rassoc test-not=eq key=identity 1b|
(assert-equal '(b . y)
(rassoc 'x '((a . x) (b . y) (c . x))
:test-not 'eq)))
(define-test |rassoc test-not=eq key=identity 2|
(assert-equal nil
(rassoc 'x '((a . x) (b . x) (c . x))
:test-not #'eq)))
(define-test |rassoc test-not=eq key=identity 3|
(assert-equal '(b . y)
(rassoc 'x '((a . x) nil (b . y) (c . x))
:test-not #'eq)))
(define-test rassoc.error.1
(assert-error 'type-error
(rassoc 'a '((b . c) nil d (a b)))))
(define-test |rassoc test-not=eql key=other 1a|
(assert-equal '(b . 345)
(rassoc '235 '((a . 234) (b . 345) (c . 234))
:test-not #'eql
:key #'1+)))
(define-test |rassoc test-not=eql key=other 1b|
(assert-equal '(b . 345)
(rassoc '235 '((a . 234) (b . 345) (c . 234))
:test-not 'eql
:key #'1+)))
(define-test |rassoc test-not=eql key=other 2|
(assert-equal nil
(rassoc '235 '((a . 234) (b . 234) (c . 234))
:test-not #'eql
:key #'1+)))
(define-test |rassoc test-not=eql key=other 3|
(assert-equal '(b . 345)
(rassoc '235 '((a . 234) nil (b . 345) (c . 234))
:test-not #'eql
:key #'1+)))
(define-test |rassoc test-not=eq key=other 1a|
(assert-equal '(b . (y))
(rassoc 'x '((a . (x)) (b . (y)) (c . (x)))
:test-not #'eq
:key #'car)))
(define-test |rassoc test-not=eq key=other 1b|
(assert-equal '(b . (y))
(rassoc 'x '((a . (x)) (b . (y)) (c . (x)))
:test-not 'eq
:key #'car)))
(define-test |rassoc test-not=eq key=other 2|
(assert-equal nil
(rassoc 'x '((a . (x)) (b . (x)) (c . (x)))
:test-not #'eq
:key #'car)))
(define-test |rassoc test-not=eq key=other 3|
(assert-equal '(b . (y))
(rassoc 'x '((a . (x)) nil (b . (y)) (c . (x)))
:test-not #'eq
:key #'car)))
(define-test |rassoc test-not=other key=other 1a|
(assert-equal '(b . 345)
(rassoc '234 '((a . 234) (b . 345) (c . 234))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |rassoc test-not=other key=other 1b|
(assert-equal '(b . 345)
(rassoc '234 '((a . 234) (b . 345) (c . 234))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |rassoc test-not=other key=other 2|
(assert-equal nil
(rassoc '234 '((a . 234) (b . 234) (c . 234))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |rassoc test-not=other key=other 3|
(assert-equal '(b . 345)
(rassoc '234 '((a . 234) nil (b . 345) (c . 234))
:test-not (lambda (x y) (eql (1+ x) y))
:key #'1+)))
(define-test |rassoc error 1|
(assert-error 'type-error
(rassoc 'a '((b . c) nil d (a b)))))
(define-test |rassoc error 2|
(assert-error 'error
(rassoc 'a '((b . c) nil d (a b))
:test #'eq
:test-not #'eq)))
(define-test |rassoc test=nil key=identity 1|
(assert-error 'error
(rassoc 123 '((b . x) nil (b . 123) (c . nil))
:test nil)))
(define-test |rassoc test-not=nil key=identity 1|
(assert-error 'error
(rassoc 123 '((b . x) nil (b . 123) (c . nil))
:test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the rassoc-if function
(define-test rassoc-if.1
(assert-equal '(a . b)
(rassoc-if (lambda (x) (eq x 'b))
'((b) nil (a . b) (a . c)))))
(define-test rassoc-if.2
(assert-equal nil
(rassoc-if (lambda (x) (eq x 'd))
'((b) nil (a . b) (a . c)))))
(define-test rassoc-if.3
(assert-equal '(b)
(rassoc-if #'null
'((b) nil (a . b) (nil . c)))))
(define-test rassoc-if.4
(assert-equal '(b . 123)
(rassoc-if (lambda (x) (eql x 123))
'((b) nil (b . 123) (nil . c)))))
(define-test rassoc-if.5
(assert-equal '(b . #\a)
(rassoc-if (lambda (x) (eql x #\a))
'((b) nil (b . #\a) (nil . c)))))
(define-test rassoc-if.6
(assert-equal '((a b) c)
(rassoc-if (lambda (x) (eq x 'c))
'(((b a) b) ((a b) . (c)) ((d) . e))
:key #'car)))
(define-test rassoc-if.7
(assert-equal '((a b) c)
(rassoc-if (lambda (x) (eq x 'c))
'(((b a) b) nil ((a b) . (c)) ((d) . e))
:key #'car)))
(define-test rassoc-if.error.1
(assert-error 'type-error
(rassoc-if (lambda (x) (eq x 'a))
'((b . c) nil d (a b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the rassoc-if-not function
(define-test rassoc-if-not.1
(assert-equal '(a . b)
(rassoc-if-not (complement (lambda (x) (eq x 'b)))
'((b) nil (a . b) (a . c)))))
(define-test rassoc-if-not.2
(assert-equal nil
(rassoc-if-not (complement (lambda (x) (eq x 'd)))
'((b) nil (a . b) (a . c)))))
(define-test rassoc-if-not.3
(assert-equal '(b)
(rassoc-if-not (complement #'null)
'((b) nil (a . b) (nil . c)))))
(define-test rassoc-if-not.4
(assert-equal '(b . 123)
(rassoc-if-not (complement (lambda (x) (eql x 123)))
'((b) nil (b . 123) (nil . c)))))
(define-test rassoc-if-not.5
(assert-equal '(b . #\a)
(rassoc-if-not (complement (lambda (x) (eql x #\a)))
'((b) nil (b . #\a) (nil . c)))))
(define-test rassoc-if-not.6
(assert-equal '((a b) c)
(rassoc-if-not (complement (lambda (x) (eq x 'c)))
'(((b a) b) nil ((a b) c) ((d) e))
:key #'car)))
(define-test rassoc-if-not.error.1
(assert-error 'type-error
(rassoc-if-not (complement (lambda (x) (eq x 'a)))
'((b . c) nil d (a b)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the sublis function
(define-test |sublis test=eql key=identity 1a|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'())))
(define-test |sublis test=eql key=identity 1b|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:test #'eql)))
(define-test |sublis test=eql key=identity 1c|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:test 'eql)))
(define-test |sublis test=eql key=identity 2a|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0))))))
(define-test |sublis test=eql key=identity 2b|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test #'eql)))
(define-test |sublis test=eql key=identity 2c|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test 'eql)))
(define-test |sublis test=eql key=nil 1|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key nil)))
(define-test |sublis test=eq key=identity 1|
(assert-equal '()
(sublis '((xx . y) (b . a)) '()
:test #'eq)))
(define-test |sublis test=eq key=identity 2|
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(sublis '((xx . y) (b . a))
'(((b . c) . (f . b)) . ((b . d) . (e . b)))
:test #'eq)))
(define-test |sublis test=other key=identity 1|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:test (lambda (x y) (and (numberp y) (= x (1- y)))))))
(define-test |sublis test=other key=identity 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test (lambda (x y) (and (numberp y) (= x y))))))
(define-test |sublis test=eql key=other 1a|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |sublis test=eql key=other 1b|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql)))
(define-test |sublis test=eql key=other 1c|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(define-test |sublis test=eql key=other 2a|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (1 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |sublis test=eql key=other 2b|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (1 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql)))
(define-test |sublis test=eql key=other 2c|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (1 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(define-test |sublis test=eq key=other 1|
(assert-equal '()
(sublis '((xx . y) (bb . a))
'()
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(define-test |sublis test=eq key=other 2|
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(sublis '((xx . y) (bb . a))
'(((b . c) . (f . b)) . ((b . d) . (e . b)))
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(define-test |sublis test=other key=other 1|
(assert-equal '()
(sublis '((10 . xx) (0 . a))
'()
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |sublis test=other key=other 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |sublis test-not=any key=identity 2|
(assert-equal '(((a . 5) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((1 . 5) . (2 . 1)) . ((1 . 3) . (4 . 1)))
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y))))))))
(define-test |sublis test-not=any key=other 2|
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y)))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |sublis test=other test-not=other 1|
(assert-error 'error
(sublis 0 '((1 . 2)) :test #'= :test-not #'=)))
(define-test |sublis test=nil key=identity 1|
(assert-error 'error
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test nil)))
(define-test |sublis test-not=nil key=identity 1|
(assert-error 'error
(sublis '((10 . xx) (0 . a))
'(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))
:test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nsublis function
(define-test |nsublis test=eql key=identity 1a|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree))))
(define-test |nsublis test=eql key=identity 1b|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:test #'eql))))
(define-test |nsublis test=eql key=identity 1c|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:test 'eql))))
(define-test |nsublis test=eql key=identity 2a|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis
'((10 . xx) (0 . a))
tree)))
(assert-eq tree tree2)))
(define-test |nsublis test=eql key=identity 2b|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis
'((10 . xx) (0 . a))
tree
:test #'eql)))
(assert-eq tree tree2)))
(define-test |nsublis test=eql key=identity 2c|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (0 . a))
tree
:test 'eql)))
(assert-eq tree tree2)))
(define-test |nsublis test=eql key=identity 3a|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
0)))
(define-test |nsublis test=eql key=identity 3b|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
0
:test #'eql)))
(define-test |nsublis test=eql key=identity 3c|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
0
:test 'eql)))
(define-test |nsublis test=eql key=nil 1|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis
'((10 . xx) (0 . a))
tree
:key nil)))
(assert-eq tree tree2)))
(define-test |nsublis test=eq key=identity 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis
'((xx . y) (b . a))
tree
:test #'eq))))
(define-test |nsublis test=eq key=identity 2|
(let ((tree (copy-tree '(((b . c) . (f . b)) . ((b . d) . (e . b)))))
(tree2))
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(setf tree2 (nsublis
'((xx . y) (b . a))
tree
:test #'eq)))
(assert-eq tree tree2)))
(define-test |nsublis test=eq key=identity 3a|
(assert-equal 'a
(nsublis '((10 . xx) (c . a))
'c
:test #'eq)))
(define-test |nsublis test=eq key=identity 3b|
(assert-equal 'a
(nsublis '((10 . xx) (c . a))
'c
:test 'eq)))
(define-test |nsublis test=other key=identity 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:test (lambda (x y) (and (numberp y) (= x (1- y))))))))
(define-test |nsublis test=other key=identity 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (0 . a))
tree
:test (lambda (x y) (and (numberp y) (= x y))))))
(assert-eq tree tree2)))
(define-test |nsublis test=other key=identity 3|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
1
:test (lambda (x y) (and (numberp y) (= x (1- y)))))))
(define-test |nsublis test=eql key=other 1a|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))))))
(define-test |nsublis test=eql key=other 1b|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql))))
(define-test |nsublis test=eql key=other 1c|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql))))
(define-test |nsublis test=eql key=other 2a|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (1 . a))
tree
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsublis test=eql key=other 2b|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (1 . a))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test #'eql)))
(assert-eq tree tree2)))
(define-test |nsublis test=eql key=other 2c|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (1 . a))
tree
:key (lambda (x) (if (numberp x) (1+ x) x))
:test 'eql)))
(assert-eq tree tree2)))
(define-test |nsublis test=eql key=other 3a|
(assert-equal 'a
(nsublis '((10 . xx) (1 . a))
0
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |nsublis test=eq key=other 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((xx . y) (bb . a))
tree
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x))))))
(define-test |nsublis test=eq key=other 2|
(let ((tree (copy-tree '(((b . c) . (f . b)) . ((b . d) . (e . b)))))
(tree2))
(assert-equal '(((a . c) . (f . a)) . ((a . d) . (e . a)))
(setf tree2 (nsublis '((xx . y) (bb . a))
tree
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(assert-eq tree tree2)))
(define-test |nsublis test=eq key=other 3|
(assert-equal 'a
(nsublis '((xx . y) (bb . a))
'b
:test #'eq
:key (lambda (x) (if (eq x 'b) 'bb x)))))
(define-test |nsublis test=other key=other 1|
(let ((tree (copy-tree '())))
(assert-equal '()
(nsublis '((10 . xx) (0 . a))
tree
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x))))))
(define-test |nsublis test=other key=other 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (0 . a))
tree
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsublis test=other key=other 3|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
0
:test (lambda (x y) (and (numberp y) (= x (1- y))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |nsublis test-not=any key=identity 2|
(let ((tree (copy-tree '(((1 . 5) . (2 . 1)) . ((1 . 3) . (4 . 1)))))
(tree2))
(assert-equal '(((a . 5) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (0 . a))
tree
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y))))))))
(assert-eq tree tree2)))
(define-test |nsublis test-not=any key=identity 3|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
1
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y))))))))
(define-test |nsublis test-not=any key=identity 4|
(assert-equal 123
(nsublis '((10 . xx) (0 . a))
123
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y))))))))
(define-test |nsublis test-not=any key=other 2|
(let ((tree (copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0)))))
(tree2))
(assert-equal '(((a . 1) . (2 . a)) . ((a . 3) . (4 . a)))
(setf tree2 (nsublis '((10 . xx) (0 . a))
tree
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y)))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(assert-eq tree tree2)))
(define-test |nsublis test-not=any key=other 3|
(assert-equal 'a
(nsublis '((10 . xx) (0 . a))
0
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y)))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |nsublis test-not=any key=other 4|
(assert-equal 123
(nsublis '((10 . xx) (0 . a))
123
:test-not (lambda (x y) (not (and (numberp y) (= x (1- y)))))
:key (lambda (x) (if (numberp x) (1+ x) x)))))
(define-test |nsublis test=other test-not=other|
(assert-error 'error
(nsublis 0 '((1 . 2)) :test #'= :test-not #'=)))
(define-test |nsublis test=nil key=identity 1|
(assert-error 'error
(sublis '((10 . xx) (0 . a))
(copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0))))
:test nil)))
(define-test |nsublis test-not=nil key=identity 1|
(assert-error 'error
(nsublis '((10 . xx) (0 . a))
(copy-tree '(((0 . 1) . (2 . 0)) . ((0 . 3) . (4 . 0))))
:test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the pairlis function
(define-test |pairlis 1|
(assert-equal '()
(pairlis '() '())))
(define-test |pairlis 2|
(let ((tail '((a b) (c d))))
(assert-eq tail
(cddr (pairlis '(1 2) '(2 3) tail)))))
(define-test |pairlis 3|
(assert-equal '((c . d) (a . b) (e f))
(pairlis '(a c) '(b d) '((e f)))))
(define-test |pairlis error 1|
(assert-error 'type-error
(pairlis '(a . b) '(c d) '((e f)))))
(define-test |pairlis error 2|
(assert-error 'type-error
(pairlis '(c d) '(a . b) '((e f)))))
(define-test |pairlis error 3|
(assert-error 'error
(pairlis '(a b) '(c d e))))
(define-test |pairlis error 4|
(assert-error 'error
(pairlis '(c d e) '(a b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the copy-alist function
(define-test |copy-alist 1|
(assert-equal '()
(copy-alist '())))
(define-test |copy-alist 2|
(assert-equal '((a) (b))
(copy-alist '((a) (b)))))
(define-test |copy-alist 3|
(assert-false (let ((alist '((a) (b))))
(eq (car alist)
(car (copy-alist alist))))))
(define-test |copy-alist 4|
(assert-equal '((a b) c (d e))
(copy-alist '((a b) c (d e)))))
(define-test |copy-alist 5|
(assert-equal '((a b) nil (d e))
(copy-alist '((a b) nil (d e)))))
(define-test |copy-alist error 2|
(assert-error 'type-error
(copy-alist '((a) . b))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the tailp function
(define-test tailp.1
(assert-false (tailp 123 '())))
(define-test tailp.2
(assert-false (tailp 123 '(123))))
(define-test tailp.3
(assert-true (tailp 123 123)))
(define-test tailp.4
(assert-true (tailp 123 '(a . 123))))
(define-test tailp.5
(let ((tail '(a b)))
(assert-true (tailp tail (list* 1 2 tail)))))
(define-test tailp.6
(let ((tail '(a b)))
(assert-false (tailp tail (list* 1 2 (copy-list tail))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the ldiff function
(define-test ldiff.1
(let ((list '(a b c . d)))
(assert-equal nil (ldiff list list))))
(define-test ldiff.2
(let ((list '(a b c . d)))
(assert-equal '(a) (ldiff list (cdr list)))))
(define-test ldiff.3
(let ((list '(a b c . d)))
(assert-equal '(a b c) (ldiff list 'd))))
(define-test ldiff.4
(let ((list '(a b c . d)))
(assert-equal '(a b c . d) (ldiff list (cons 'c 'd)))))
(define-test ldiff.5
(let ((list '(a b c . d)))
(assert-equal '(a b c . d) (ldiff list 234))))
(define-test ldiff.6
(let ((list '(a b c . d)))
(assert-equal '(a b c . d) (ldiff list nil))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the union function
(define-test |union test=eql key=identity 1a|
(assert-equal '()
(union '() '())))
(define-test |union test=eql key=identity 1b|
(assert-equal '()
(union '() '() :test #'eql)))
(define-test |union test=eql key=identity 1c|
(assert-equal '()
(union '() '() :test 'eql)))
(define-test |union test=eql key=identity 2a|
(assert-equal '()
(set-difference (union '(1 2 3) '(3 4 5))
'(1 2 3 4 5))))
(define-test |union test=eql key=identity 2b|
(assert-equal '()
(set-difference (union '(1 2 3) '(3 4 5) :test #'eql)
'(1 2 3 4 5))))
(define-test |union test=eql key=identity 2|
(assert-equal '()
(set-difference (union '(1 2 3) '(3 4 5) :test 'eql)
'(1 2 3 4 5))))
(define-test |union test=eql key=identity 3a|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (union (append l1 l2) (append l2 l3))
(append l1 l2 l3)))))
(define-test |union test=eql key=identity 3b|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:test #'eql)
(append l1 l2 l3)
:test #'eql))))
(define-test |union test=eql key=identity 3c|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:test 'eql)
(append l1 l2 l3)
:test 'eql))))
(define-test |union test=eql key=identity dotted-list 1|
(assert-error 'type-error
(union '(1 2 . 3) '(2 3 4))))
(define-test |union test=eql key=identity dotted-list 2|
(assert-error 'type-error
(union '(1 2 3) '(2 3 . 4))))
(define-test |union test=eql key=nil 2a|
(assert-equal '()
(set-difference (union '(1 2 3) '(3 4 5) :key nil)
'(1 2 3 4 5))))
(define-test |union test=eq key=identity 1|
(assert-equal '()
(union '() '() :test #'eq)))
(define-test |union test=eq key=identity 2|
(assert-equal '()
(set-difference (union '(abc def) '(abc ghi)
:test #'eq)
'(abc def ghi)
:test #'eq)))
(define-test |union test=eq key=identity 3|
(let ((l1 (loop for code from 30 below 40 collect (string (code-char code))))
(l2 (loop for code from 40 below 100 collect (string (code-char code))))
(l3 (loop for code from 100 below 110 collect (string (code-char code)))))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:test #'eq)
(append l1 l2 l3)
:test #'eq))))
(define-test |union test=eq key=identity dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'eq)))
(define-test |union test=eq key=identity dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'eq)))
(define-test |union test=equal key=identity 1|
(assert-equal '()
(union '() '() :test #'equal)))
(define-test |union test=equal key=identity 2|
(assert-equal '()
(set-difference (union '("abc" "def") '("abc" "ghi")
:test #'equal)
'("abc" "def" "ghi")
:test #'equal)))
(define-test |union test=equal key=identity 3|
(let ((l1 (loop for code from 30 below 100 collect (string (code-char code))))
(l2 (loop for code from 40 below 110 collect (string (code-char code))))
(l3 (loop for code from 30 below 110 collect (string (code-char code)))))
(assert-equal '()
(set-difference (union l1 l2 :test #'equal)
l3
:test #'equal))))
(define-test |union test=equal key=identity dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'equal)))
(define-test |union test=equal key=identity dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'equal)))
(define-test |union test=equalp key=identity 1|
(assert-equal '()
(union '() '() :test #'equalp)))
(define-test |union test=equalp key=identity 3|
(let ((l1 (loop for i from 30 below 100
collect (make-array 1 :initial-element i)))
(l2 (loop for i from 40 below 110
collect (make-array 1 :initial-element i)))
(l3 (loop for i from 30 below 110
collect (make-array 1 :initial-element i))))
(assert-equal '()
(set-difference (union l1 l2 :test #'equalp)
l3
:test #'equalp))))
(define-test |union test=equalp key=identity dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'equalp)))
(define-test |union test=equalp key=identity dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'equalp)))
(define-test |union test=other key=identity 1|
(assert-equal '()
(union '() '() :test #'<)))
(define-test |union test=other key=identity dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'(lambda (x y) (eq x y)))))
(define-test |union test=other key=identity dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'(lambda (x y) (eq x y)))))
(define-test |union test=eql key=other 1a|
(assert-equal 1
(length (union '(1) '(3) :key #'oddp))))
(define-test |union test=eql key=other 1b|
(assert-equal 1
(length (union '(1) '(3) :key #'oddp :test #'eql))))
(define-test |union test=eql key=other 1c|
(assert-equal 1
(length (union '(1) '(3) :key #'oddp :test 'eql))))
(define-test |union test=eql key=other 2a|
(assert-equal 2
(length (union '(4 1) '(3) :key #'oddp))))
(define-test |union test=eql key=other 2b|
(assert-equal 2
(length (union '(4 1) '(3) :key #'oddp :test #'eql))))
(define-test |union test=eql key=other 2c|
(assert-equal 2
(length (union '(4 1) '(3) :key #'oddp :test 'eql))))
(define-test |union test=eql key=other 3|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:key #'car)
(append l1 l2 l3)
:key #'car))))
(define-test |union test=eql key=other 4|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:test #'eql
:key #'car)
(append l1 l2 l3)
:test #'eql
:key #'car))))
(define-test |union test=eql key=other 5|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:test 'eql
:key #'car)
(append l1 l2 l3)
:test 'eql
:key #'car))))
(define-test |union test=eql key=other dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :key #'identity)))
(define-test |union test=eql key=other dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :key #'identity)))
(define-test |union test=eq key=other 1|
(assert-equal '()
(set-difference
(union '((a) (b) (c))
'((b) (c) (d))
:key #'car
:test #'eq)
'((a) (b) (c) (d))
:key #'car
:test #'eq)))
(define-test |union test=eq key=other 3|
(let ((l1 (loop for code from 30 below 40 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 100 collect (list (string (code-char code)))))
(l3 (loop for code from 100 below 110 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (union (append l1 l2)
(append l2 l3)
:key #'car
:test #'eq)
(append l1 l2 l3)
:test #'eq
:key #'car))))
(define-test |union test=eq key=other dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'eq :key #'identity)))
(define-test |union test=eq key=other dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'eq :key #'identity)))
(define-test |union test=equal key=other 1|
(assert-equal '()
(union '() '() :test #'equal :key #'car)))
(define-test |union test=equal key=other 2|
(assert-equal '()
(set-difference (union '(("abc") ("def")) '(("abc") ("ghi"))
:key #'car
:test #'equal)
'(("abc") ("def") ("ghi"))
:key #'car
:test #'equal)))
(define-test |union test=equal key=other 3|
(let ((l1 (loop for code from 30 below 100 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 110 collect (list (string (code-char code)))))
(l3 (loop for code from 30 below 110 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (union l1 l2 :test #'equal :key #'car)
l3
:test #'equal :key #'car))))
(define-test |union test=equal key=other dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'equal :key #'identity)))
(define-test |union test=equal key=other dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'equal :key #'identity)))
(define-test |union test=equalp key=other 1|
(assert-equal '()
(union '() '() :test #'equalp :key #'car)))
(define-test |union test=equalp key=other 2|
(assert-equal '()
(set-difference (union '((#(1)) (#(2))) '((#(1)) (#(3)))
:key #'car
:test #'equalp)
'((#(1)) (#(2)) (#(3)))
:key #'car
:test #'equalp)))
(define-test |union test=equalp key=other 3|
(let ((l1 (loop for i from 30 below 100
collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 40 below 110
collect (list (make-array 1 :initial-element i))))
(l3 (loop for i from 30 below 110
collect (list (make-array 1 :initial-element i)))))
(assert-equal '()
(set-difference (union l1 l2 :test #'equalp :key #'car)
l3
:test #'equalp :key #'car))))
(define-test |union test=equalp key=other dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test #'equalp :key #'identity)))
(define-test |union test=equalp key=other dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test #'equalp :key #'identity)))
(define-test |union test=other key=other 1|
(assert-equal '()
(set-difference
(union '(1 3 5 7)
'(2 4 10 3)
:key (lambda (x) (mod x 5))
:test #'=)
'(0 1 2 3 4) :key (lambda (x) (mod x 5)))))
(define-test |union test=other key=other dotted-list 1|
(assert-error 'type-error
(union '(a b . c) '(b c d) :test (lambda (x y) (eq x y)) :key #'identity)))
(define-test |union test=other key=other dotted-list 2|
(assert-error 'type-error
(union '(a b c) '(b c . d) :test (lambda (x y) (eq x y)) :key #'identity)))
(define-test |union test-not=other key=identity 1|
(assert-equal '()
(set-difference
(union '(1 2 3 4)
'(3 4 5 6)
:test-not #'/=)
'(1 2 3 4 5 6))))
(define-test |union test-not=other key=other 1|
(assert-equal '()
(set-difference
(union '(1 3 5 7)
'(2 4 10 3)
:key (lambda (x) (mod x 5))
:test-not #'/=)
'(0 1 2 3 4) :key (lambda (x) (mod x 5)))))
(define-test |union test=other test-not=other 1|
(assert-error 'error
(union '(1 2 3) '(2 3 4) :test #'eql :test-not #'eql)))
(define-test |union test=nil key=identity 2a|
(assert-error 'error
(set-difference (union '(1 2 3) '(3 4 5) :test nil)
'(1 2 3 4 5))))
(define-test |union test-not=nil key=identity 2a|
(assert-error 'error
(set-difference (union '(1 2 3) '(3 4 5) :test-not nil)
'(1 2 3 4 5))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nunion function
(define-test |nunion test=eql key=identity 1a|
(assert-equal '()
(nunion '() '())))
(define-test |nunion test=eql key=identity 1b|
(assert-equal '()
(nunion '() '() :test #'eql)))
(define-test |nunion test=eql key=identity 1c|
(assert-equal '()
(nunion '() '() :test 'eql)))
(define-test |nunion test=eql key=identity 2a|
(assert-equal '()
(set-difference (nunion (copy-list '(1 2 3))
(copy-list '(3 4 5)))
'(1 2 3 4 5))))
(define-test |nunion test=eql key=identity 2b|
(assert-equal '()
(set-difference (nunion (copy-list '(1 2 3))
(copy-list '(3 4 5))
:test #'eql)
'(1 2 3 4 5))))
(define-test |nunion test=eql key=identity 2|
(assert-equal '()
(set-difference (nunion (copy-list '(1 2 3))
(copy-list '(3 4 5))
:test 'eql)
'(1 2 3 4 5))))
(define-test |nunion test=eql key=identity 3a|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3)))
(append l1 l2 l3)))))
(define-test |nunion test=eql key=identity 3b|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eql)
(append l1 l2 l3)
:test #'eql))))
(define-test |nunion test=eql key=identity 3c|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test 'eql)
(append l1 l2 l3)
:test 'eql))))
(define-test |nunion test=eql key=nil 1|
(assert-equal '()
(set-difference (nunion (copy-list '(1 2 3))
(copy-list '(3 4 5))
:key nil)
'(1 2 3 4 5))))
(define-test |nunion test=eq key=identity 1|
(assert-equal '()
(nunion '() '() :test #'eq)))
(define-test |nunion test=eq key=identity 2|
(assert-equal '()
(set-difference (nunion '(abc def) '(abc ghi)
:test #'eq)
'(abc def ghi)
:test #'eq)))
(define-test |nunion test=eq key=identity 3|
(let ((l1 (loop for code from 30 below 40 collect (string (code-char code))))
(l2 (loop for code from 40 below 100 collect (string (code-char code))))
(l3 (loop for code from 100 below 110 collect (string (code-char code)))))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eq)
(append l1 l2 l3)
:test #'eq))))
(define-test |nunion test=equal key=identity 1|
(assert-equal '()
(nunion '() '() :test #'equal)))
(define-test |nunion test=equal key=identity 2|
(assert-equal '()
(set-difference (nunion (copy-list '("abc" "def"))
(copy-list '("abc" "ghi"))
:test #'equal)
'("abc" "def" "ghi")
:test #'equal)))
(define-test |nunion test=equal key=identity 3|
(let ((l1 (loop for code from 30 below 100 collect (string (code-char code))))
(l2 (loop for code from 40 below 110 collect (string (code-char code))))
(l3 (loop for code from 30 below 110 collect (string (code-char code)))))
(assert-equal '()
(set-difference (nunion (copy-list l1)
(copy-list l2)
:test #'equal)
l3
:test #'equal))))
(define-test |nunion test=equalp key=identity 1|
(assert-equal '()
(nunion '() '() :test #'equalp)))
(define-test |nunion test=equalp key=identity 3|
(let ((l1 (loop for i from 30 below 100
collect (make-array 1 :initial-element i)))
(l2 (loop for i from 40 below 110
collect (make-array 1 :initial-element i)))
(l3 (loop for i from 30 below 110
collect (make-array 1 :initial-element i))))
(assert-equal '()
(set-difference (nunion (copy-list l1)
(copy-list l2)
:test #'equalp)
l3
:test #'equalp))))
(define-test |nunion test=other key=identity 1|
(assert-equal '()
(nunion '() '() :test #'<)))
(define-test |nunion test=eql key=other 1a|
(assert-equal 1
(length (nunion (copy-list '(1))
(copy-list '(3))
:key #'oddp))))
(define-test |nunion test=eql key=other 1b|
(assert-equal 1
(length (nunion (copy-list '(1))
(copy-list '(3))
:key #'oddp
:test #'eql))))
(define-test |nunion test=eql key=other 1c|
(assert-equal 1
(length (nunion (copy-list '(1))
(copy-list '(3))
:key #'oddp
:test 'eql))))
(define-test |nunion test=eql key=other 2a|
(assert-equal 2
(length (nunion (copy-list '(4 1))
(copy-list '(3))
:key #'oddp))))
(define-test |nunion test=eql key=other 2b|
(assert-equal 2
(length (nunion (copy-list '(4 1))
(copy-list '(3))
:key #'oddp
:test #'eql))))
(define-test |nunion test=eql key=other 2c|
(assert-equal 2
(length (nunion (copy-list '(4 1))
(copy-list '(3))
:key #'oddp
:test 'eql))))
(define-test |nunion test=eql key=other 3|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key #'car)
(append l1 l2 l3)
:key #'car))))
(define-test |nunion test=eql key=other 4|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eql
:key #'car)
(append l1 l2 l3)
:test #'eql
:key #'car))))
(define-test |nunion test=eql key=other 5|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test 'eql
:key #'car)
(append l1 l2 l3)
:test 'eql
:key #'car))))
(define-test |nunion test=eq key=other 1|
(assert-equal '()
(set-difference
(nunion (copy-list '((a) (b) (c)))
(copy-list '((b) (c) (d)))
:key #'car
:test #'eq)
'((a) (b) (c) (d))
:key #'car
:test #'eq)))
(define-test |nunion test=eq key=other 3|
(let ((l1 (loop for code from 30 below 40 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 100 collect (list (string (code-char code)))))
(l3 (loop for code from 100 below 110 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (nunion (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key #'car
:test #'eq)
(append l1 l2 l3)
:test #'eq
:key #'car))))
(define-test |nunion test=equal key=other 1|
(assert-equal '()
(nunion '() '() :test #'equal :key #'car)))
(define-test |nunion test=equal key=other 2|
(assert-equal '()
(set-difference (nunion (copy-list '(("abc") ("def")))
(copy-list '(("abc") ("ghi")))
:key #'car
:test #'equal)
'(("abc") ("def") ("ghi"))
:key #'car
:test #'equal)))
(define-test |nunion test=equal key=other 3|
(let ((l1 (loop for code from 30 below 100 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 110 collect (list (string (code-char code)))))
(l3 (loop for code from 30 below 110 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (nunion (copy-list l1)
(copy-list l2)
:test #'equal
:key #'car)
l3
:test #'equal :key #'car))))
(define-test |nunion test=equalp key=other 1|
(assert-equal '()
(nunion '() '() :test #'equalp :key #'car)))
(define-test |nunion test=equalp key=other 2|
(assert-equal '()
(set-difference (nunion (copy-list '((#(1)) (#(2))))
(copy-list '((#(1)) (#(3))))
:key #'car
:test #'equalp)
'((#(1)) (#(2)) (#(3)))
:key #'car
:test #'equalp)))
(define-test |nunion test=equalp key=other 3|
(let ((l1 (loop for i from 30 below 100
collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 40 below 110
collect (list (make-array 1 :initial-element i))))
(l3 (loop for i from 30 below 110
collect (list (make-array 1 :initial-element i)))))
(assert-equal '()
(set-difference (nunion (copy-list l1)
(copy-list l2)
:test #'equalp
:key #'car)
l3
:test #'equalp :key #'car))))
(define-test |nunion test=other key=other 1|
(assert-equal '()
(set-difference
(nunion (copy-list '(1 3 5 7))
(copy-list '(2 4 10 3))
:key (lambda (x) (mod x 5))
:test #'=)
'(0 1 2 3 4) :key (lambda (x) (mod x 5)))))
(define-test |nunion test-not=other key=identity 1|
(assert-equal '()
(set-difference
(nunion (copy-list '(1 2 3 4))
(copy-list '(3 4 5 6))
:test-not #'/=)
'(1 2 3 4 5 6))))
(define-test |nunion test-not=other key=other 1|
(assert-equal '()
(set-difference
(nunion (copy-list '(1 3 5 7))
(copy-list '(2 4 10 3))
:key (lambda (x) (mod x 5))
:test-not #'/=)
'(0 1 2 3 4) :key (lambda (x) (mod x 5)))))
(define-test |nunion test=other test-not=other 1|
(assert-error 'error
(nunion (copy-list '(1 2 3))
(copy-list '(2 3 4))
:test #'eql
:test-not #'eql)))
(define-test |nunion test=nil key=identity 1|
(assert-error 'error
(set-difference (nunion (copy-list '(1 2 3))
(copy-list '(3 4 5))
:test nil)
'(1 2 3 4 5))))
(define-test |nunion test-not=nil key=identity 1|
(assert-error 'error
(set-difference (nunion (copy-list '(1 2 3))
(copy-list '(3 4 5))
:test-not nil)
'(1 2 3 4 5))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the intersection function
(define-test |intersection test=eql key=identity 1a|
(assert-equal '()
(intersection '() '())))
(define-test |intersection test=eql key=identity 1b|
(assert-equal '()
(intersection '() '() :test #'eql)))
(define-test |intersection test=eql key=identity 1c|
(assert-equal '()
(intersection '() '() :test 'eql)))
(define-test |intersection test=eql key=identity 2a|
(assert-equal '()
(set-difference (intersection (copy-list '(1 2 3 4))
(copy-list '(2 3 4 5)))
'(2 3 4))))
(define-test |intersection test=eql key=identity 2b|
(assert-equal '()
(set-difference (intersection (copy-list '(1 2 3 4))
(copy-list '(2 3 4 5))
:test #'eql)
'(2 3 4))))
(define-test |intersection test=eql key=identity 2|
(assert-equal '()
(set-difference (intersection (copy-list '(1 2 3 4))
(copy-list '(2 3 4 5))
:test 'eql)
'(2 3 4))))
(define-test |intersection test=eql key=identity 3a|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3)))
l2))))
(define-test |intersection test=eql key=identity 3b|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eql)
l2
:test #'eql))))
(define-test |intersection test=eql key=identity 3c|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test 'eql)
l2
:test 'eql))))
(define-test |intersection test=eql key=nil 1|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key nil)
l2))))
(define-test |intersection test=eq key=identity 1|
(assert-equal '()
(intersection '() '() :test #'eq)))
(define-test |intersection test=eq key=identity 2|
(assert-equal '()
(set-difference (intersection '(abc def) '(abc ghi)
:test #'eq)
'(abc)
:test #'eq)))
(define-test |intersection test=eq key=identity 3|
(let ((l1 (loop for code from 30 below 40 collect (string (code-char code))))
(l2 (loop for code from 40 below 100 collect (string (code-char code))))
(l3 (loop for code from 100 below 110 collect (string (code-char code)))))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eq)
l2
:test #'eq))))
(define-test |intersection test=equal key=identity 1|
(assert-equal '()
(intersection '() '() :test #'equal)))
(define-test |intersection test=equal key=identity 2|
(assert-equal '()
(set-difference (intersection (copy-list '("abc" "def"))
(copy-list '("abc" "ghi"))
:test #'equal)
'("abc")
:test #'equal)))
(define-test |intersection test=equal key=identity 3|
(let ((l1 (loop for code from 30 below 100 collect (string (code-char code))))
(l2 (loop for code from 40 below 110 collect (string (code-char code))))
(l3 (loop for code from 40 below 100 collect (string (code-char code)))))
(assert-equal '()
(set-difference (intersection (copy-list l1)
(copy-list l2)
:test #'equal)
l3
:test #'equal))))
(define-test |intersection test=equalp key=identity 1|
(assert-equal '()
(intersection '() '() :test #'equalp)))
(define-test |intersection test=equalp key=identity 3|
(let ((l1 (loop for i from 30 below 100
collect (make-array 1 :initial-element i)))
(l2 (loop for i from 40 below 110
collect (make-array 1 :initial-element i)))
(l3 (loop for i from 40 below 100
collect (make-array 1 :initial-element i))))
(assert-equal '()
(set-difference (intersection (copy-list l1)
(copy-list l2)
:test #'equalp)
l3
:test #'equalp))))
(define-test |intersection test=other key=identity 1|
(assert-equal '()
(intersection '() '() :test #'<)))
(define-test |intersection test=eql key=other 1a|
(assert-equal 1
(length (intersection (copy-list '(1))
(copy-list '(3))
:key #'oddp))))
(define-test |intersection test=eql key=other 1b|
(assert-equal 1
(length (intersection (copy-list '(1))
(copy-list '(3))
:key #'oddp
:test #'eql))))
(define-test |intersection test=eql key=other 1c|
(assert-equal 1
(length (intersection (copy-list '(1))
(copy-list '(3))
:key #'oddp
:test 'eql))))
(define-test |intersection test=eql key=other 2a|
(assert-equal 1
(length (intersection (copy-list '(4 1))
(copy-list '(3))
:key #'oddp))))
(define-test |intersection test=eql key=other 2b|
(assert-equal 1
(length (intersection (copy-list '(4 1))
(copy-list '(3))
:key #'oddp
:test #'eql))))
(define-test |intersection test=eql key=other 2c|
(assert-equal 1
(length (intersection (copy-list '(4 1))
(copy-list '(3))
:key #'oddp
:test 'eql))))
(define-test |intersection test=eql key=other 3|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key #'car)
l2
:key #'car))))
(define-test |intersection test=eql key=other 4|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eql
:key #'car)
l2
:test #'eql
:key #'car))))
(define-test |intersection test=eql key=other 5|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test 'eql
:key #'car)
l2
:test 'eql
:key #'car))))
(define-test |intersection test=eq key=other 1|
(assert-equal '()
(set-difference
(intersection (copy-list '((a) (b) (c)))
(copy-list '((b) (c) (d)))
:key #'car
:test #'eq)
'((b) (c))
:key #'car
:test #'eq)))
(define-test |intersection test=eq key=other 3|
(let ((l1 (loop for code from 30 below 40 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 100 collect (list (string (code-char code)))))
(l3 (loop for code from 100 below 110 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key #'car
:test #'eq)
l2
:test #'eq
:key #'car))))
(define-test |intersection test=equal key=other 1|
(assert-equal '()
(intersection '()
'()
:test #'equal
:key #'car)))
(define-test |intersection test=equal key=other 2|
(assert-equal '()
(set-difference (intersection (copy-list '(("abc") ("def")))
(copy-list '(("abc") ("ghi")))
:key #'car
:test #'equal)
'(("abc"))
:key #'car
:test #'equal)))
(define-test |intersection test=equal key=other 3|
(let ((l1 (loop for code from 30 below 100 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 110 collect (list (string (code-char code)))))
(l3 (loop for code from 40 below 100 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (intersection (copy-list l1)
(copy-list l2)
:test #'equal
:key #'car)
l3
:test #'equal :key #'car))))
(define-test |intersection test=equalp key=other 1|
(assert-equal '()
(intersection '() '() :test #'equalp :key #'car)))
(define-test |intersection test=equalp key=other 2|
(assert-equal '()
(set-difference (intersection (copy-list '((#(1)) (#(2))))
(copy-list '((#(1)) (#(3))))
:key #'car
:test #'equalp)
'((#(1)))
:key #'car
:test #'equalp)))
(define-test |intersection test=equalp key=other 3|
(let ((l1 (loop for i from 30 below 100
collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 40 below 110
collect (list (make-array 1 :initial-element i))))
(l3 (loop for i from 40 below 100
collect (list (make-array 1 :initial-element i)))))
(assert-equal '()
(set-difference (intersection (copy-list l1)
(copy-list l2)
:test #'equalp
:key #'car)
l3
:test #'equalp :key #'car))))
(define-test |intersection test=other key=other 1|
(assert-equal '()
(set-difference
(intersection (copy-list '(1 3 5 7))
(copy-list '(2 4 10 3))
:key (lambda (x) (mod x 5))
:test #'=)
'(3 5 7) :key (lambda (x) (mod x 5)))))
(define-test |intersection test-not=other key=identity 1|
(assert-equal '()
(set-difference
(intersection (copy-list '(1 2 3 4))
(copy-list '(3 4 5 6))
:test-not #'/=)
'(3 4))))
(define-test |intersection test-not=other key=other 1|
(assert-equal '()
(set-difference
(intersection (copy-list '(1 3 5 7))
(copy-list '(2 4 10 3))
:key (lambda (x) (mod x 5))
:test-not #'/=)
'(3 5 7) :key (lambda (x) (mod x 5)))))
(define-test |intersection test=other test-not=other 1|
(assert-error 'error
(intersection (copy-list '(1 2 3))
(copy-list '(2 3 4))
:test #'eql
:test-not #'eql)))
(define-test |intersection test=nil key=identity 1|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-error 'error
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test nil)
l2))))
(define-test |intersection test-not=nil key=identity 1|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-error 'error
(set-difference (intersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test-not nil)
l2))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nintersection function
(define-test |nintersection test=eql key=identity 1a|
(assert-equal '()
(nintersection '() '())))
(define-test |nintersection test=eql key=identity 1b|
(assert-equal '()
(nintersection '() '() :test #'eql)))
(define-test |nintersection test=eql key=identity 1c|
(assert-equal '()
(nintersection '() '() :test 'eql)))
(define-test |nintersection test=eql key=identity 2a|
(assert-equal '()
(set-difference (nintersection (copy-list '(1 2 3 4))
(copy-list '(2 3 4 5)))
'(2 3 4))))
(define-test |nintersection test=eql key=identity 2b|
(assert-equal '()
(set-difference (nintersection (copy-list '(1 2 3 4))
(copy-list '(2 3 4 5))
:test #'eql)
'(2 3 4))))
(define-test |nintersection test=eql key=identity 2|
(assert-equal '()
(set-difference (nintersection (copy-list '(1 2 3 4))
(copy-list '(2 3 4 5))
:test 'eql)
'(2 3 4))))
(define-test |nintersection test=eql key=identity 3a|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3)))
l2))))
(define-test |nintersection test=eql key=identity 3b|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eql)
l2
:test #'eql))))
(define-test |nintersection test=eql key=identity 3c|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test 'eql)
l2
:test 'eql))))
(define-test |nintersection test=eql key=nil 1|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key nil)
l2))))
(define-test |nintersection test=eq key=identity 1|
(assert-equal '()
(nintersection '() '() :test #'eq)))
(define-test |nintersection test=eq key=identity 2|
(assert-equal '()
(set-difference (nintersection '(abc def) '(abc ghi)
:test #'eq)
'(abc)
:test #'eq)))
(define-test |nintersection test=eq key=identity 3|
(let ((l1 (loop for code from 30 below 40 collect (string (code-char code))))
(l2 (loop for code from 40 below 100 collect (string (code-char code))))
(l3 (loop for code from 100 below 110 collect (string (code-char code)))))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eq)
l2
:test #'eq))))
(define-test |nintersection test=equal key=identity 1|
(assert-equal '()
(nintersection '() '() :test #'equal)))
(define-test |nintersection test=equal key=identity 2|
(assert-equal '()
(set-difference (nintersection (copy-list '("abc" "def"))
(copy-list '("abc" "ghi"))
:test #'equal)
'("abc")
:test #'equal)))
(define-test |nintersection test=equal key=identity 3|
(let ((l1 (loop for code from 30 below 100 collect (string (code-char code))))
(l2 (loop for code from 40 below 110 collect (string (code-char code))))
(l3 (loop for code from 40 below 100 collect (string (code-char code)))))
(assert-equal '()
(set-difference (nintersection (copy-list l1)
(copy-list l2)
:test #'equal)
l3
:test #'equal))))
(define-test |nintersection test=equalp key=identity 1|
(assert-equal '()
(nintersection '() '() :test #'equalp)))
(define-test |nintersection test=equalp key=identity 3|
(let ((l1 (loop for i from 30 below 100
collect (make-array 1 :initial-element i)))
(l2 (loop for i from 40 below 110
collect (make-array 1 :initial-element i)))
(l3 (loop for i from 40 below 100
collect (make-array 1 :initial-element i))))
(assert-equal '()
(set-difference (nintersection (copy-list l1)
(copy-list l2)
:test #'equalp)
l3
:test #'equalp))))
(define-test |nintersection test=other key=identity 1|
(assert-equal '()
(nintersection '() '() :test #'<)))
(define-test |nintersection test=eql key=other 1a|
(assert-equal 1
(length (nintersection (copy-list '(1))
(copy-list '(3))
:key #'oddp))))
(define-test |nintersection test=eql key=other 1b|
(assert-equal 1
(length (nintersection (copy-list '(1))
(copy-list '(3))
:key #'oddp
:test #'eql))))
(define-test |nintersection test=eql key=other 1c|
(assert-equal 1
(length (nintersection (copy-list '(1))
(copy-list '(3))
:key #'oddp
:test 'eql))))
(define-test |nintersection test=eql key=other 2a|
(assert-equal 1
(length (nintersection (copy-list '(4 1))
(copy-list '(3))
:key #'oddp))))
(define-test |nintersection test=eql key=other 2b|
(assert-equal 1
(length (nintersection (copy-list '(4 1))
(copy-list '(3))
:key #'oddp
:test #'eql))))
(define-test |nintersection test=eql key=other 2c|
(assert-equal 1
(length (nintersection (copy-list '(4 1))
(copy-list '(3))
:key #'oddp
:test 'eql))))
(define-test |nintersection test=eql key=other 3|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key #'car)
l2
:key #'car))))
(define-test |nintersection test=eql key=other 4|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test #'eql
:key #'car)
l2
:test #'eql
:key #'car))))
(define-test |nintersection test=eql key=other 5|
(let ((l1 (loop for i from 30 below 40 collect (list i)))
(l2 (loop for i from 40 below 100 collect (list i)))
(l3 (loop for i from 100 below 110 collect (list i))))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test 'eql
:key #'car)
l2
:test 'eql
:key #'car))))
(define-test |nintersection test=eq key=other 1|
(assert-equal '()
(set-difference
(nintersection (copy-list '((a) (b) (c)))
(copy-list '((b) (c) (d)))
:key #'car
:test #'eq)
'((b) (c))
:key #'car
:test #'eq)))
(define-test |nintersection test=eq key=other 3|
(let ((l1 (loop for code from 30 below 40 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 100 collect (list (string (code-char code)))))
(l3 (loop for code from 100 below 110 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:key #'car
:test #'eq)
l2
:test #'eq
:key #'car))))
(define-test |nintersection test=equal key=other 1|
(assert-equal '()
(nintersection '()
'()
:test #'equal
:key #'car)))
(define-test |nintersection test=equal key=other 2|
(assert-equal '()
(set-difference (nintersection (copy-list '(("abc") ("def")))
(copy-list '(("abc") ("ghi")))
:key #'car
:test #'equal)
'(("abc"))
:key #'car
:test #'equal)))
(define-test |nintersection test=equal key=other 3|
(let ((l1 (loop for code from 30 below 100 collect (list (string (code-char code)))))
(l2 (loop for code from 40 below 110 collect (list (string (code-char code)))))
(l3 (loop for code from 40 below 100 collect (list (string (code-char code))))))
(assert-equal '()
(set-difference (nintersection (copy-list l1)
(copy-list l2)
:test #'equal
:key #'car)
l3
:test #'equal :key #'car))))
(define-test |nintersection test=equalp key=other 1|
(assert-equal '()
(nintersection '() '() :test #'equalp :key #'car)))
(define-test |nintersection test=equalp key=other 2|
(assert-equal '()
(set-difference (nintersection (copy-list '((#(1)) (#(2))))
(copy-list '((#(1)) (#(3))))
:key #'car
:test #'equalp)
'((#(1)))
:key #'car
:test #'equalp)))
(define-test |nintersection test=equalp key=other 3|
(let ((l1 (loop for i from 30 below 100
collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 40 below 110
collect (list (make-array 1 :initial-element i))))
(l3 (loop for i from 40 below 100
collect (list (make-array 1 :initial-element i)))))
(assert-equal '()
(set-difference (nintersection (copy-list l1)
(copy-list l2)
:test #'equalp
:key #'car)
l3
:test #'equalp :key #'car))))
(define-test |nintersection test=other key=other 1|
(assert-equal '()
(set-difference
(nintersection (copy-list '(1 3 5 7))
(copy-list '(2 4 10 3))
:key (lambda (x) (mod x 5))
:test #'=)
'(3 5 7) :key (lambda (x) (mod x 5)))))
(define-test |nintersection test-not=other key=identity 1|
(assert-equal '()
(set-difference
(nintersection (copy-list '(1 2 3 4))
(copy-list '(3 4 5 6))
:test-not #'/=)
'(3 4))))
(define-test |nintersection test-not=other key=other 1|
(assert-equal '()
(set-difference
(nintersection (copy-list '(1 3 5 7))
(copy-list '(2 4 10 3))
:key (lambda (x) (mod x 5))
:test-not #'/=)
'(3 5 7) :key (lambda (x) (mod x 5)))))
(define-test |nintersection test=other test-not=other 1|
(assert-error 'error
(nintersection (copy-list '(1 2 3))
(copy-list '(2 3 4))
:test #'eql
:test-not #'eql)))
(define-test |nintersection test=nil key=identity 1|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-error 'error
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test nil)
l2))))
(define-test |nintersection test-not=nil key=identity 1|
(let ((l1 (loop for i from 30 below 40 collect i))
(l2 (loop for i from 40 below 100 collect i))
(l3 (loop for i from 100 below 110 collect i)))
(assert-error 'error
(set-difference (nintersection (copy-list (append l1 l2))
(copy-list (append l2 l3))
:test-not nil)
l2))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the set-difference function
(define-test |set-difference test=eql key=identity 1a|
(assert-equal '()
(set-difference '() '())))
(define-test |set-difference test=eql key=identity 1b|
(assert-equal '()
(set-difference '()
'()
:test #'eql)))
(define-test |set-difference test=eql key=identity 1c|
(assert-equal '()
(set-difference '()
'()
:test 'eql)))
(define-test |set-difference test=eql key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)))))
(define-test |set-difference test=eql key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:test #'eql))))
(define-test |set-difference test=eql key=identity 2c|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:test 'eql))))
(define-test |set-difference test=eql key=identity 3a|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 200 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)))))
(define-test |set-difference test=eql key=identity 3b|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 200 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:test #'eql))))
(define-test |set-difference test=eql key=identity 3c|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 200 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:test 'eql))))
(define-test |set-difference test=eql key=nil 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:key nil))))
(define-test |set-difference test=eq key=identity 1|
(assert-equal '()
(set-difference '()
'()
:test #'eq)))
(define-test |set-difference test=eq key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal 1
(length (set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))
(assert-eq (car l1)
(car (set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))))
(define-test |set-difference test=eq key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal 1
(length (set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'eq)))
(assert-eq (car l1)
(car (set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'eq)))))
(define-test |set-difference test=eq key=identity 3|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal 1
(length (set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))
(assert-eq (car l1)
(car (set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))))
(define-test |set-difference test=equal key=identity 1|
(assert-equal '()
(set-difference '()
'()
:test #'equal)))
(define-test |set-difference test=equal key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equal))))
(define-test |set-difference test=equal key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'equal))))
(define-test |set-difference test=equal key=identity 3|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equal))))
(define-test |set-difference test=equalp key=identity 1|
(assert-equal '()
(set-difference '()
'()
:test #'equalp)))
(define-test |set-difference test=equalp key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 20 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equalp))))
(define-test |set-difference test=equalp key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 20 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'equalp))))
(define-test |set-difference test=equalp key=identity 3a|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 200 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equalp))))
(define-test |set-difference test=equalp key=identity 3b|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 200 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equalp))))
(define-test |set-difference test=other key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 1 below 20 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:test #'>))))
(define-test |set-difference test-not=other key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 1 below 20 collect i)))
(assert-equal '(1)
(set-difference (copy-list l1)
(copy-list l2)
:test-not #'<=))))
(define-test |set-difference test=eql key=other 1a|
(assert-equal '()
(set-difference '()
'()
:key #'car)))
(define-test |set-difference test=eql key=other 1b|
(assert-equal '()
(set-difference '()
'()
:key #'car
:test #'eql)))
(define-test |set-difference test=eql key=other 1c|
(assert-equal '()
(set-difference '()
'()
:key #'car
:test 'eql)))
(define-test |set-difference test=eql key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car))))
(define-test |set-difference test=eql key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car
:test #'eql))))
(define-test |set-difference test=eql key=other 2c|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car
:test 'eql))))
(define-test |set-difference test=eql key=other 3a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car))))
(define-test |set-difference test=eql key=other 3b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car
:test #'eql))))
(define-test |set-difference test=eql key=other 3c|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car
:test 'eql))))
(define-test |set-difference test=eq key=other 1|
(assert-equal '()
(set-difference '()
'()
:key #'car
:test #'eq)))
(define-test |set-difference test=eq key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal 1
(length (set-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))
(assert-eq (car l1)
(car (set-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))))
(define-test |set-difference test=eq key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal 1
(length (set-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test 'eq)))
(assert-eq (car l1)
(car (set-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test 'eq)))))
(define-test |set-difference test=eq key=other 3|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 200 collect (list (list i)))))
(assert-equal 1
(length (set-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))
(assert-eq (car l1)
(car (set-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))))
(define-test |set-difference test=equal key=other 1|
(assert-equal '()
(set-difference '()
'()
:key #'car
:test #'equal)))
(define-test |set-difference test=equal key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal '(((1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equal))))
(define-test |set-difference test=equal key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal '(((1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test 'equal))))
(define-test |set-difference test=equal key=other 3|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 200 collect (list (list i)))))
(assert-equal '(((1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equal))))
(define-test |set-difference test=equalp key=other 1|
(assert-equal '()
(set-difference '()
'()
:key #'car
:test #'equalp)))
(define-test |set-difference test=equalp key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 20 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equalp))))
(define-test |set-difference test=equalp key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 20 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test 'equalp))))
(define-test |set-difference test=equalp key=other 3a|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 200 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equalp))))
(define-test |set-difference test=equalp key=other 3b|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 200 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(set-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test 'equalp))))
(define-test |set-difference test=other key=other 1|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 1 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car
:test #'>))))
(define-test |set-difference test-not=other key=other 1|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 1 below 20 collect (list i))))
(assert-equal '((1))
(set-difference (copy-list l1)
(copy-list l2)
:key #'car
:test-not #'<=))))
(define-test |set-difference test=other test-not=other 1|
(assert-error 'error
(set-difference '(1 2 3) '(2 3 4)
:test #'eql
:test-not #'eql)))
(define-test |set-difference test=nil key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-error 'error
(set-difference (copy-list l1)
(copy-list l2)
:test nil))))
(define-test |set-difference test-not=nil key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-error 'error
(set-difference (copy-list l1)
(copy-list l2)
:test-not nil))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nset-difference function
(define-test |nset-difference test=eql key=identity 1a|
(assert-equal '()
(nset-difference '() '())))
(define-test |nset-difference test=eql key=identity 1b|
(assert-equal '()
(nset-difference '()
'()
:test #'eql)))
(define-test |nset-difference test=eql key=identity 1c|
(assert-equal '()
(nset-difference '()
'()
:test 'eql)))
(define-test |nset-difference test=eql key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)))))
(define-test |nset-difference test=eql key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:test #'eql))))
(define-test |nset-difference test=eql key=identity 2c|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:test 'eql))))
(define-test |nset-difference test=eql key=identity 3a|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 200 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)))))
(define-test |nset-difference test=eql key=identity 3b|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 200 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:test #'eql))))
(define-test |nset-difference test=eql key=identity 3c|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 200 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:test 'eql))))
(define-test |nset-difference test=eql key=nil 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:key nil))))
(define-test |nset-difference test=eq key=identity 1|
(assert-equal '()
(nset-difference '()
'()
:test #'eq)))
(define-test |nset-difference test=eq key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal 1
(length (nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))
(assert-eq (car l1)
(car (nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))))
(define-test |nset-difference test=eq key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal 1
(length (nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'eq)))
(assert-eq (car l1)
(car (nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'eq)))))
(define-test |nset-difference test=eq key=identity 3|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal 1
(length (nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))
(assert-eq (car l1)
(car (nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'eq)))))
(define-test |nset-difference test=equal key=identity 1|
(assert-equal '()
(nset-difference '()
'()
:test #'equal)))
(define-test |nset-difference test=equal key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equal))))
(define-test |nset-difference test=equal key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'equal))))
(define-test |nset-difference test=equal key=identity 3|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equal))))
(define-test |nset-difference test=equalp key=identity 1|
(assert-equal '()
(nset-difference '()
'()
:test #'equalp)))
(define-test |nset-difference test=equalp key=identity 2a|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 20 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equalp))))
(define-test |nset-difference test=equalp key=identity 2b|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 20 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test 'equalp))))
(define-test |nset-difference test=equalp key=identity 3a|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 200 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equalp))))
(define-test |nset-difference test=equalp key=identity 3b|
(let ((l1 (loop for i from 1 below 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i from 2 below 200 collect (make-array 1 :initial-element i))))
(assert-equalp '(#(1))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:test #'equalp))))
(define-test |nset-difference test=other key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 1 below 20 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:test #'>))))
(define-test |nset-difference test-not=other key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 1 below 20 collect i)))
(assert-equal '(1)
(nset-difference (copy-list l1)
(copy-list l2)
:test-not #'<=))))
(define-test |nset-difference test=eql key=other 1a|
(assert-equal '()
(nset-difference '()
'()
:key #'car)))
(define-test |nset-difference test=eql key=other 1b|
(assert-equal '()
(nset-difference '()
'()
:key #'car
:test #'eql)))
(define-test |nset-difference test=eql key=other 1c|
(assert-equal '()
(nset-difference '()
'()
:key #'car
:test 'eql)))
(define-test |nset-difference test=eql key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car))))
(define-test |nset-difference test=eql key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car
:test #'eql))))
(define-test |nset-difference test=eql key=other 2c|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car
:test 'eql))))
(define-test |nset-difference test=eql key=other 3a|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car))))
(define-test |nset-difference test=eql key=other 3b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car
:test #'eql))))
(define-test |nset-difference test=eql key=other 3c|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car
:test 'eql))))
(define-test |nset-difference test=eq key=other 1|
(assert-equal '()
(nset-difference '()
'()
:key #'car
:test #'eq)))
(define-test |nset-difference test=eq key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal 1
(length (nset-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))
(assert-eq (car l1)
(car (nset-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))))
(define-test |nset-difference test=eq key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 20 collect (list i))))
(assert-equal 1
(length (nset-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test 'eq)))
(assert-eq (car l1)
(car (nset-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test 'eq)))))
(define-test |nset-difference test=eq key=other 3|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 2 below 200 collect (list i))))
(assert-equal 1
(length (nset-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))
(assert-eq (car l1)
(car (nset-difference (copy-list l1)
(copy-list (append (mapcar #'copy-list (cdr l1))
l2))
:key #'car
:test #'eq)))))
(define-test |nset-difference test=equal key=other 1|
(assert-equal '()
(nset-difference '()
'()
:key #'car
:test #'equal)))
(define-test |nset-difference test=equal key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal '(((1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equal))))
(define-test |nset-difference test=equal key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 20 collect (list (list i)))))
(assert-equal '(((1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test 'equal))))
(define-test |nset-difference test=equal key=other 3|
(let ((l1 (loop for i from 1 below 10 collect (list (list i))))
(l2 (loop for i from 2 below 200 collect (list (list i)))))
(assert-equal '(((1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equal))))
(define-test |nset-difference test=equalp key=other 1|
(assert-equal '()
(nset-difference '()
'()
:key #'car
:test #'equalp)))
(define-test |nset-difference test=equalp key=other 2a|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 20 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equalp))))
(define-test |nset-difference test=equalp key=other 2b|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 20 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test 'equalp))))
(define-test |nset-difference test=equalp key=other 3a|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 200 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test #'equalp))))
(define-test |nset-difference test=equalp key=other 3b|
(let ((l1 (loop for i from 1 below 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i from 2 below 200 collect (list (make-array 1 :initial-element i)))))
(assert-equalp '((#(1)))
(nset-difference (copy-list l1)
(copy-list (append (cdr l1) l2))
:key #'car
:test 'equalp))))
(define-test |nset-difference test=other key=other 1|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 1 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car
:test #'>))))
(define-test |nset-difference test-not=other key=other 1|
(let ((l1 (loop for i from 1 below 10 collect (list i)))
(l2 (loop for i from 1 below 20 collect (list i))))
(assert-equal '((1))
(nset-difference (copy-list l1)
(copy-list l2)
:key #'car
:test-not #'<=))))
(define-test |nset-difference test=other test-not=other 1|
(assert-error 'error
(nset-difference '(1 2 3) '(2 3 4)
:test #'eql
:test-not #'eql)))
(define-test |nset-difference test=nil key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-error 'error
(nset-difference (copy-list l1)
(copy-list l2)
:test nil))))
(define-test |nset-difference test-not=nil key=identity 1|
(let ((l1 (loop for i from 1 below 10 collect i))
(l2 (loop for i from 2 below 20 collect i)))
(assert-error 'error
(nset-difference (copy-list l1)
(copy-list l2)
:test-not nil))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the adjoin function
(define-test |adjoin test=eql key=identity 1a|
(assert-equal '(1)
(adjoin 1 '())))
(define-test |adjoin test=eql key=identity 1b|
(assert-equal '(1)
(adjoin 1 '() :test #'eql)))
(define-test |adjoin test=eql key=identity 1c|
(assert-equal '(1)
(adjoin 1 '() :test 'eql)))
(define-test |adjoin test=eql key=identity 2a|
(assert-equal '(1 2)
(adjoin 1 '(2))))
(define-test |adjoin test=eql key=identity 2b|
(assert-equal '(1 2)
(adjoin 1 '(2) :test #'eql)))
(define-test |adjoin test=eql key=identity 2c|
(assert-equal '(1 2)
(adjoin 1 '(2) :test 'eql)))
(define-test |adjoin test=eql key=identity 3a|
(assert-equal '(2 1)
(adjoin 1 '(2 1))))
(define-test |adjoin test=eql key=identity 3b|
(assert-equal '(2 1)
(adjoin 1 '(2 1) :test #'eql)))
(define-test |adjoin test=eql key=identity 3c|
(assert-equal '(2 1)
(adjoin 1 '(2 1) :test 'eql)))
(define-test |adjoin test=eql key=nil 3b|
(assert-equal '(2 1)
(adjoin 1 '(2 1) :key nil)))
(define-test |adjoin test=eq key=identity 1a|
(assert-equal '(a)
(adjoin 'a '() :test #'eq)))
(define-test |adjoin test=eq key=identity 1b|
(assert-equal '(a)
(adjoin 'a '() :test 'eq)))
(define-test |adjoin test=eq key=identity 2a|
(assert-equal '(a b)
(adjoin 'a '(b) :test #'eq)))
(define-test |adjoin test=eq key=identity 2b|
(assert-equal '(a b)
(adjoin 'a '(b) :test 'eq)))
(define-test |adjoin test=eq key=identity 3a|
(assert-equal '(b a)
(adjoin 'a '(b a) :test #'eq)))
(define-test |adjoin test=eq key=identity 3b|
(assert-equal '(b a)
(adjoin 'a '(b a) :test 'eq)))
(define-test |adjoin test=other key=identity 1|
(assert-equal '(1 2)
(adjoin 1 '(2) :test #'=)))
(define-test |adjoin test=other key=identity 2|
(assert-equal '(2 1)
(adjoin 1 '(2 1) :test #'=)))
(define-test |adjoin test-not=other key=identity 1|
(assert-equal '(1 2)
(adjoin 1 '(2) :test-not #'/=)))
(define-test |adjoin test-not=other key=identity 2|
(assert-equal '(2 1)
(adjoin 1 '(2 1) :test-not #'/=)))
(define-test |adjoin test=eql key=other 1a|
(assert-equal '((1))
(adjoin '(1) '() :key #'car)))
(define-test |adjoin test=eql key=other 1b|
(assert-equal '((1))
(adjoin '(1) '() :key #'car :test #'eql)))
(define-test |adjoin test=eql key=other 1c|
(assert-equal '((1))
(adjoin '(1) '() :key #'car :test 'eql)))
(define-test |adjoin test=eql key=other 2a|
(assert-equal '((1) (2))
(adjoin '(1) '((2)) :key #'car)))
(define-test |adjoin test=eql key=other 2b|
(assert-equal '((1) (2))
(adjoin '(1) '((2)) :key #'car :test #'eql)))
(define-test |adjoin test=eql key=other 2c|
(assert-equal '((1) (2))
(adjoin '(1) '((2)) :key #'car :test 'eql)))
(define-test |adjoin test=eql key=other 3a|
(assert-equal '((2) (1))
(adjoin '(1) '((2) (1)) :key #'car)))
(define-test |adjoin test=eql key=other 3b|
(assert-equal '((2) (1))
(adjoin '(1) '((2) (1)) :key #'car :test #'eql)))
(define-test |adjoin test=eql key=other 3c|
(assert-equal '((2) (1))
(adjoin '(1) '((2) (1)) :key #'car :test 'eql)))
(define-test |adjoin test=eq key=other 1a|
(assert-equal '((a))
(adjoin '(a) '() :key #'car :test #'eq)))
(define-test |adjoin test=eq key=other 1b|
(assert-equal '((a))
(adjoin '(a) '() :key #'car :test 'eq)))
(define-test |adjoin test=eq key=other 2a|
(assert-equal '((a) (b))
(adjoin '(a) '((b)) :key #'car :test #'eq)))
(define-test |adjoin test=eq key=other 2b|
(assert-equal '((a) (b))
(adjoin '(a) '((b)) :key #'car :test 'eq)))
(define-test |adjoin test=eq key=other 3a|
(assert-equal '((b) (a))
(adjoin '(a) '((b) (a)) :key #'car :test #'eq)))
(define-test |adjoin test=eq key=other 3b|
(assert-equal '((b) (a))
(adjoin '(a) '((b) (a)) :key #'car :test 'eq)))
(define-test |adjoin test=other key=other 1|
(assert-equal '((1) (2))
(adjoin '(1) '((2)) :key #'car :test #'=)))
(define-test |adjoin test=other key=other 2|
(assert-equal '((2) (1))
(adjoin '(1) '((2) (1)) :key #'car :test #'=)))
(define-test |adjoin test-not=other key=other 1|
(assert-equal '((1) (2))
(adjoin '(1) '((2)) :key #'car :test-not #'/=)))
(define-test |adjoin test-not=other key=other 2|
(assert-equal '((2) (1))
(adjoin '(1) '((2) (1)) :key #'car :test-not #'/=)))
(define-test |adjoin test=other test-not=other 1|
(assert-error 'error (adjoin 1 '() :test #'eql :test-not #'eql)))
(define-test |adjoin test=nil key=identity 3b|
(assert-error 'error
(adjoin 1 '(2 1) :test nil)))
(define-test |adjoin test-not=nil key=identity 3b|
(assert-error 'error
(adjoin 1 '(2 1) :test-not nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the set-exclusiv-or function
(define-test |set-exclusive-or test=eql key=identity 1|
(assert-equal '()
(set-exclusive-or '() '())))
(define-test |set-exclusive-or test=eql key=identity 2a|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))))
#'<))))
(define-test |set-exclusive-or test=eql key=identity 2b|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test #'eql))
#'<))))
(define-test |set-exclusive-or test=eql key=identity 2c|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test 'eql))
#'<))))
(define-test |set-exclusive-or test=eql key=identity 3a|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))))
#'<))))
(define-test |set-exclusive-or test=eql key=identity 3b|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test #'eql))
#'<))))
(define-test |set-exclusive-or test=eql key=identity 3c|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test 'eql))
#'<))))
(define-test |set-exclusive-or test=eql key=nil 1|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:key nil))
#'<))))
(define-test |set-exclusive-or test=eq key=identity 2a|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:test #'eq))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eq key=identity 2b|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:test 'eq))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eq key=identity 3a|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:test #'eq))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eq key=identity 3b|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:test 'eq))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equal key=identity 2a|
(let ((l1 (loop for i from 2 to 10 collect (list i)))
(l2 (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test #'equal))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equal key=identity 2b|
(let ((l1 (loop for i from 2 to 10 collect (list i)))
(l2 (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test 'equal))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equal key=identity 3a|
(let ((l1 (loop for i from 2 to 50 collect (list i)))
(l2 (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test #'equal))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equal key=identity 3b|
(let ((l1 (loop for i from 2 to 50 collect (list i)))
(l2 (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test 'equal))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=identity 2a|
(let ((l1 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test #'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=identity 2b|
(let ((l1 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test 'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=identity 3a|
(let ((l1 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test #'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=identity 3b|
(let ((l1 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:test 'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=other key=identity 1|
(assert-equal '()
(set-exclusive-or '() '() :test #'=)))
(define-test |set-exclusive-or test=other key=identity 2|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test '=))
#'<))))
(define-test |set-exclusive-or test=other key=identity 3|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test '=))
#'<))))
(define-test |set-exclusive-or test-not=other key=identity 2|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test-not '/=))
#'<))))
(define-test |set-exclusive-or test-not=other key=identity 3|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test-not '/=))
#'<))))
(define-test |set-exclusive-or test=eql key=other 1|
(assert-equal '()
(set-exclusive-or '() '() :key #'car)))
(define-test |set-exclusive-or test=eql key=other 2a|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eql key=other 2b|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test #'eql))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eql key=other 2c|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test 'eql))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eql key=other 3a|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eql key=other 3b|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test #'eql))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eql key=other 3c|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test 'eql))
#'<
:key #'car))))
(define-test |set-exclusive-or test=eq key=other 2a|
(let ((l (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l)
(append l (list (list (list 1))))
:key #'car
:test #'eq))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=eq key=other 2b|
(let ((l (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l)
(append l (list (list (list 1))))
:key #'car
:test 'eq))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=eq key=other 3a|
(let ((l (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l)
(append l (list (list (list 1))))
:key #'car
:test #'eq))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=eq key=other 3b|
(let ((l (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l)
(append l (list (list (list 1))))
:key #'car
:test 'eq))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=equal key=other 2a|
(let ((l1 (loop for i from 2 to 10 collect (list (list i))))
(l2 (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l1)
(append l2 (list (list (list 1))))
:key #'car
:test #'equal))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=equal key=other 2b|
(let ((l1 (loop for i from 2 to 10 collect (list (list i))))
(l2 (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l1)
(append l2 (list (list (list 1))))
:key #'car
:test 'equal))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=equal key=other 3a|
(let ((l1 (loop for i from 2 to 50 collect (list (list i))))
(l2 (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l1)
(append l2 (list (list (list 1))))
:key #'car
:test #'equal))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=equal key=other 3b|
(let ((l1 (loop for i from 2 to 50 collect (list (list i))))
(l2 (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (set-exclusive-or (cons '((0)) l1)
(append l2 (list (list (list 1))))
:key #'car
:test 'equal))
#'<
:key #'caar))))
(define-test |set-exclusive-or test=equalp key=other 2a|
(let ((l1 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:key #'car
:test #'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=other 2b|
(let ((l1 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:key #'car
:test 'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=other 3a|
(let ((l1 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:key #'car
:test #'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=equalp key=other 3b|
(let ((l1 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l1)
(append l2 (list (list 1)))
:key #'car
:test 'equalp))
#'<
:key #'car))))
(define-test |set-exclusive-or test=other key=other 1|
(assert-equal '()
(set-exclusive-or '() '() :test #'= :key #'car)))
(define-test |set-exclusive-or test=other key=other 2|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test '=))
#'<
:key #'car))))
(define-test |set-exclusive-or test=other key=other 3|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test '=))
#'<
:key #'car))))
(define-test |set-exclusive-or test-not=other key=other 2|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test-not '/=))
#'<
:key #'car))))
(define-test |set-exclusive-or test-not=other key=other 3|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (set-exclusive-or (cons '(0) l)
(append l (list (list 1)))
:key #'car
:test-not '/=))
#'<
:key #'car))))
(define-test |set-exclusive-or test=other test-not=other 1|
(assert-error 'error
(set-exclusive-or '() '() :test #'eql :test-not #'eql)))
(define-test |set-exclusive-or test=nil key=identity 1|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-error
'error
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test nil))
#'<))))
(define-test |set-exclusive-or test-not=nil key=identity 1|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-error
'error
(sort (copy-list (set-exclusive-or (cons 0 l)
(append l (list 1))
:test-not nil))
#'<))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the nset-exclusiv-or function
(define-test |nset-exclusive-or test=eql key=identity 1|
(assert-equal '()
(nset-exclusive-or '() '())))
(define-test |nset-exclusive-or test=eql key=identity 2a|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))))
#'<))))
(define-test |nset-exclusive-or test=eql key=identity 2b|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test #'eql))
#'<))))
(define-test |nset-exclusive-or test=eql key=identity 2c|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test 'eql))
#'<))))
(define-test |nset-exclusive-or test=eql key=identity 3a|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))))
#'<))))
(define-test |nset-exclusive-or test=eql key=identity 3b|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test #'eql))
#'<))))
(define-test |nset-exclusive-or test=eql key=identity 3c|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test 'eql))
#'<))))
(define-test |nset-exclusive-or test=eql key=nil 3b|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:key nil))
#'<))))
(define-test |nset-exclusive-or test=eq key=identity 2a|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:test #'eq))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eq key=identity 2b|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:test 'eq))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eq key=identity 3a|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:test #'eq))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eq key=identity 3b|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:test 'eq))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equal key=identity 2a|
(let ((l1 (loop for i from 2 to 10 collect (list i)))
(l2 (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test #'equal))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equal key=identity 2b|
(let ((l1 (loop for i from 2 to 10 collect (list i)))
(l2 (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test 'equal))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equal key=identity 3a|
(let ((l1 (loop for i from 2 to 50 collect (list i)))
(l2 (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test #'equal))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equal key=identity 3b|
(let ((l1 (loop for i from 2 to 50 collect (list i)))
(l2 (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test 'equal))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=identity 2a|
(let ((l1 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test #'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=identity 2b|
(let ((l1 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 10 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test 'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=identity 3a|
(let ((l1 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test #'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=identity 3b|
(let ((l1 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1)))
(l2 (loop for i from 2 to 50 collect (make-array 1 :initial-element 1))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:test 'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=other key=identity 1|
(assert-equal '()
(nset-exclusive-or '() '() :test #'=)))
(define-test |nset-exclusive-or test=other key=identity 2|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test '=))
#'<))))
(define-test |nset-exclusive-or test=other key=identity 3|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test '=))
#'<))))
(define-test |nset-exclusive-or test-not=other key=identity 2|
(let ((l (loop for i from 2 to 10 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test-not '/=))
#'<))))
(define-test |nset-exclusive-or test-not=other key=identity 3|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-equal
'(0 1)
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test-not '/=))
#'<))))
(define-test |nset-exclusive-or test=eql key=other 1|
(assert-equal '()
(nset-exclusive-or '() '() :key #'car)))
(define-test |nset-exclusive-or test=eql key=other 2a|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eql key=other 2b|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test #'eql))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eql key=other 2c|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test 'eql))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eql key=other 3a|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eql key=other 3b|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test #'eql))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eql key=other 3c|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test 'eql))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=eq key=other 2a|
(let ((l (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l))
(copy-list (append l (list (list (list 1)))))
:key #'car
:test #'eq))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=eq key=other 2b|
(let ((l (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l))
(copy-list (append l (list (list (list 1)))))
:key #'car
:test 'eq))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=eq key=other 3a|
(let ((l (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l))
(copy-list (append l (list (list (list 1)))))
:key #'car
:test #'eq))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=eq key=other 3b|
(let ((l (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l))
(copy-list (append l (list (list (list 1)))))
:key #'car
:test 'eq))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=equal key=other 2a|
(let ((l1 (loop for i from 2 to 10 collect (list (list i))))
(l2 (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l1))
(copy-list (append l2 (list (list (list 1)))))
:key #'car
:test #'equal))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=equal key=other 2b|
(let ((l1 (loop for i from 2 to 10 collect (list (list i))))
(l2 (loop for i from 2 to 10 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l1))
(copy-list (append l2 (list (list (list 1)))))
:key #'car
:test 'equal))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=equal key=other 3a|
(let ((l1 (loop for i from 2 to 50 collect (list (list i))))
(l2 (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l1))
(copy-list (append l2 (list (list (list 1)))))
:key #'car
:test #'equal))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=equal key=other 3b|
(let ((l1 (loop for i from 2 to 50 collect (list (list i))))
(l2 (loop for i from 2 to 50 collect (list (list i)))))
(assert-equal
'(((0)) ((1)))
(sort (copy-list (nset-exclusive-or (copy-list (cons '((0)) l1))
(copy-list (append l2 (list (list (list 1)))))
:key #'car
:test 'equal))
#'<
:key #'caar))))
(define-test |nset-exclusive-or test=equalp key=other 2a|
(let ((l1 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:key #'car
:test #'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=other 2b|
(let ((l1 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 10 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:key #'car
:test 'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=other 3a|
(let ((l1 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:key #'car
:test #'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=equalp key=other 3b|
(let ((l1 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1))))
(l2 (loop for i from 2 to 50 collect (list (make-array 1 :initial-element 1)))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l1))
(copy-list (append l2 (list (list 1))))
:key #'car
:test 'equalp))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=other key=other 1|
(assert-equal '()
(nset-exclusive-or '() '() :test #'= :key #'car)))
(define-test |nset-exclusive-or test=other key=other 2|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test '=))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=other key=other 3|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test '=))
#'<
:key #'car))))
(define-test |nset-exclusive-or test-not=other key=other 2|
(let ((l (loop for i from 2 to 10 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test-not '/=))
#'<
:key #'car))))
(define-test |nset-exclusive-or test-not=other key=other 3|
(let ((l (loop for i from 2 to 50 collect (list i))))
(assert-equal
'((0) (1))
(sort (copy-list (nset-exclusive-or (copy-list (cons '(0) l))
(copy-list (append l (list (list 1))))
:key #'car
:test-not '/=))
#'<
:key #'car))))
(define-test |nset-exclusive-or test=other test-not=other 1|
(assert-error 'error
(nset-exclusive-or '() '() :test #'eql :test-not #'eql)))
(define-test |nset-exclusive-or test=nil key=identity 3b|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-error
'error
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test nil))
#'<))))
(define-test |nset-exclusive-or test-not=nil key=identity 3b|
(let ((l (loop for i from 2 to 50 collect i)))
(assert-error
'error
(sort (copy-list (nset-exclusive-or (copy-list (cons 0 l))
(copy-list (append l (list 1)))
:test-not nil))
#'<))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the subsetp function
(define-test |subsetp test=eql key=identity 1a|
(assert-true (subsetp '()
'())))
(define-test |subsetp test=eql key=identity 1b|
(assert-true (subsetp '()
'()
:test #'eql)))
(define-test |subsetp test=eql key=identity 1c|
(assert-true (subsetp '()
'()
:test 'eql)))
(define-test |subsetp test=eql key=identity 2a|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-true (subsetp l1
l2))))
(define-test |subsetp test=eql key=identity 2b|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-true (subsetp l1
l2
:test #'eql))))
(define-test |subsetp test=eql key=identity 2c|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-true (subsetp l1
l2
:test 'eql))))
(define-test |subsetp test=eql key=identity 3a|
(let ((l1 (loop for i from 1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-true (subsetp l1
l2))))
(define-test |subsetp test=eql key=identity 3b|
(let ((l1 (loop for i from 1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-true (subsetp l1
l2
:test #'eql))))
(define-test |subsetp test=eql key=identity 3c|
(let ((l1 (loop for i from 1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-true (subsetp l1
l2
:test 'eql))))
(define-test |subsetp test=eql key=identity 4a|
(let ((l1 (loop for i from -1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-false (subsetp l1
l2))))
(define-test |subsetp test=eql key=identity 4b|
(let ((l1 (loop for i from -1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-false (subsetp l1
l2
:test #'eql))))
(define-test |subsetp test=eql key=identity 4c|
(let ((l1 (loop for i from -1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-false (subsetp l1
l2
:test 'eql))))
(define-test |subsetp test=eql key=identity 5a|
(let ((l1 (loop for i from -1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-false (subsetp l1
l2))))
(define-test |subsetp test=eql key=identity 5b|
(let ((l1 (loop for i from -1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-false (subsetp l1
l2
:test #'eql))))
(define-test |subsetp test=eql key=identity 5c|
(let ((l1 (loop for i from -1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-false (subsetp l1
l2
:test 'eql))))
(define-test |subsetp test=eql key=nil 1|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-true (subsetp l1
l2
:key nil))))
(define-test |subsetp test=eq key=identity 2a|
(let ((l (loop repeat 10 collect (make-array 1 :initial-element 1))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:test #'eq))))
(define-test |subsetp test=eq key=identity 2b|
(let ((l (loop repeat 10 collect (make-array 1 :initial-element 1))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:test 'eq))))
(define-test |subsetp test=eq key=identity 3a|
(let ((l (loop repeat 50 collect (make-array 1 :initial-element 1))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:test #'eq))))
(define-test |subsetp test=eq key=identity 3b|
(let ((l (loop repeat 50 collect (make-array 1 :initial-element 1))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:test 'eq))))
(define-test |subsetp test=eq key=identity 4a|
(let ((l (loop repeat 10 collect (make-array 1 :initial-element 1))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:test #'eq))))
(define-test |subsetp test=eq key=identity 4b|
(let ((l (loop repeat 10 collect (make-array 1 :initial-element 1))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:test 'eq))))
(define-test |subsetp test=eq key=identity 5a|
(let ((l (loop repeat 50 collect (make-array 1 :initial-element 1))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:test #'eq))))
(define-test |subsetp test=eq key=identity 5b|
(let ((l (loop repeat 50 collect (make-array 1 :initial-element 1))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:test 'eq))))
(define-test |subsetp test=equal key=identity 2a|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:test #'equal))))
(define-test |subsetp test=equal key=identity 2b|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:test 'equal))))
(define-test |subsetp test=equal key=identity 3a|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:test #'equal))))
(define-test |subsetp test=equal key=identity 3b|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:test 'equal))))
(define-test |subsetp test=equal key=identity 4a|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:test #'equal))))
(define-test |subsetp test=equal key=identity 4b|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:test 'equal))))
(define-test |subsetp test=equal key=identity 5a|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:test #'equal))))
(define-test |subsetp test=equal key=identity 5b|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:test 'equal))))
(define-test |subsetp test=equalp key=identity 2a|
(let ((l1 (loop for i from 1 to 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 10 to 0 collect (make-array 1 :initial-element i))))
(assert-true (subsetp l1
l2
:test #'equalp))))
(define-test |subsetp test=equalp key=identity 2b|
(let ((l1 (loop for i from 1 to 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 10 to 0 collect (make-array 1 :initial-element i))))
(assert-true (subsetp l1
l2
:test 'equalp))))
(define-test |subsetp test=equalp key=identity 3a|
(let ((l1 (loop for i from 1 to 50 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 50 to 0 collect (make-array 1 :initial-element i))))
(assert-true (subsetp l1
l2
:test #'equalp))))
(define-test |subsetp test=equalp key=identity 3b|
(let ((l1 (loop for i from 1 to 50 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 50 to 0 collect (make-array 1 :initial-element i))))
(assert-true (subsetp l1
l2
:test 'equalp))))
(define-test |subsetp test=equalp key=identity 4a|
(let ((l1 (loop for i from -1 to 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 10 to 0 collect (make-array 1 :initial-element i))))
(assert-false (subsetp l1
l2
:test #'equalp))))
(define-test |subsetp test=equalp key=identity 4b|
(let ((l1 (loop for i from -1 to 10 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 10 to 0 collect (make-array 1 :initial-element i))))
(assert-false (subsetp l1
l2
:test 'equalp))))
(define-test |subsetp test=equalp key=identity 5a|
(let ((l1 (loop for i from -1 to 50 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 50 to 0 collect (make-array 1 :initial-element i))))
(assert-false (subsetp l1
l2
:test #'equalp))))
(define-test |subsetp test=equalp key=identity 5b|
(let ((l1 (loop for i from -1 to 50 collect (make-array 1 :initial-element i)))
(l2 (loop for i downfrom 50 to 0 collect (make-array 1 :initial-element i))))
(assert-false (subsetp l1
l2
:test 'equalp))))
(define-test |subsetp test=other key=identity 2b|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-true (subsetp l1
l2
:test #'=))))
(define-test |subsetp test=other key=identity 3b|
(let ((l1 (loop for i from 1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-true (subsetp l1
l2
:test #'=))))
(define-test |subsetp test=other key=identity 4b|
(let ((l1 (loop for i from -1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-false (subsetp l1
l2
:test #'=))))
(define-test |subsetp test=other key=identity 5b|
(let ((l1 (loop for i from -1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-false (subsetp l1
l2
:test #'=))))
(define-test |subsetp test-not=other key=identity 2b|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-true (subsetp l1
l2
:test-not #'/=))))
(define-test |subsetp test-not=other key=identity 3b|
(let ((l1 (loop for i from 1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-true (subsetp l1
l2
:test-not #'/=))))
(define-test |subsetp test-not=other key=identity 4b|
(let ((l1 (loop for i from -1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-false (subsetp l1
l2
:test-not #'/=))))
(define-test |subsetp test-not=other key=identity 5b|
(let ((l1 (loop for i from -1 to 50 collect i))
(l2 (loop for i downfrom 50 to 0 collect i)))
(assert-false (subsetp l1
l2
:test-not #'/=))))
(define-test |subsetp test=eql key=other 1a|
(assert-true (subsetp '()
'()
:key #'car)))
(define-test |subsetp test=eql key=other 1b|
(assert-true (subsetp '()
'()
:key #'car
:test #'eql)))
(define-test |subsetp test=eql key=other 1c|
(assert-true (subsetp '()
'()
:key #'car
:test 'eql)))
(define-test |subsetp test=eql key=other 2a|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car))))
(define-test |subsetp test=eql key=other 2b|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test #'eql))))
(define-test |subsetp test=eql key=other 2c|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test 'eql))))
(define-test |subsetp test=eql key=other 3a|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car))))
(define-test |subsetp test=eql key=other 3b|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test #'eql))))
(define-test |subsetp test=eql key=other 3c|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test 'eql))))
(define-test |subsetp test=eql key=other 4a|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car))))
(define-test |subsetp test=eql key=other 4b|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test #'eql))))
(define-test |subsetp test=eql key=other 4c|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test 'eql))))
(define-test |subsetp test=eql key=other 5a|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car))))
(define-test |subsetp test=eql key=other 5b|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test #'eql))))
(define-test |subsetp test=eql key=other 5c|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test 'eql))))
(define-test |subsetp test=eq key=other 2a|
(let ((l (loop repeat 10 collect (list (make-array 1 :initial-element 1)))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:key #'car
:test #'eq))))
(define-test |subsetp test=eq key=other 2b|
(let ((l (loop repeat 10 collect (list (make-array 1 :initial-element 1)))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:key #'car
:test 'eq))))
(define-test |subsetp test=eq key=other 3a|
(let ((l (loop repeat 50 collect (list (make-array 1 :initial-element 1)))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:key #'car
:test #'eq))))
(define-test |subsetp test=eq key=other 3b|
(let ((l (loop repeat 50 collect (list (make-array 1 :initial-element 1)))))
(assert-true (subsetp (reverse (cdr (butlast l)))
l
:key #'car
:test 'eq))))
(define-test |subsetp test=eq key=other 4a|
(let ((l (loop repeat 10 collect (list (make-array 1 :initial-element 1)))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:key #'car
:test #'eq))))
(define-test |subsetp test=eq key=other 4b|
(let ((l (loop repeat 10 collect (list (make-array 1 :initial-element 1)))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:key #'car
:test 'eq))))
(define-test |subsetp test=eq key=other 5a|
(let ((l (loop repeat 50 collect (list (make-array 1 :initial-element 1)))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:key #'car
:test #'eq))))
(define-test |subsetp test=eq key=other 5b|
(let ((l (loop repeat 50 collect (list (make-array 1 :initial-element 1)))))
(assert-false (subsetp l
(reverse (cdr (butlast l)))
:key #'car
:test 'eq))))
(define-test |subsetp test=equal key=other 2a|
(let ((l1 (loop for i from 1 to 10 collect (list (list i))))
(l2 (loop for i downfrom 10 to 0 collect (list (list i)))))
(assert-true (subsetp l1
l2
:key #'car
:test #'equal))))
(define-test |subsetp test=equal key=other 2b|
(let ((l1 (loop for i from 1 to 10 collect (list (list i))))
(l2 (loop for i downfrom 10 to 0 collect (list (list i)))))
(assert-true (subsetp l1
l2
:key #'car
:test 'equal))))
(define-test |subsetp test=equal key=other 3a|
(let ((l1 (loop for i from 1 to 50 collect (list (list i))))
(l2 (loop for i downfrom 50 to 0 collect (list (list i)))))
(assert-true (subsetp l1
l2
:key #'car
:test #'equal))))
(define-test |subsetp test=equal key=other 3b|
(let ((l1 (loop for i from 1 to 50 collect (list (list i))))
(l2 (loop for i downfrom 50 to 0 collect (list (list i)))))
(assert-true (subsetp l1
l2
:key #'car
:test 'equal))))
(define-test |subsetp test=equal key=other 4a|
(let ((l1 (loop for i from -1 to 10 collect (list (list i))))
(l2 (loop for i downfrom 10 to 0 collect (list (list i)))))
(assert-false (subsetp l1
l2
:key #'car
:test #'equal))))
(define-test |subsetp test=equal key=other 4b|
(let ((l1 (loop for i from -1 to 10 collect (list (list i))))
(l2 (loop for i downfrom 10 to 0 collect (list (list i)))))
(assert-false (subsetp l1
l2
:key #'car
:test 'equal))))
(define-test |subsetp test=equal key=other 5a|
(let ((l1 (loop for i from -1 to 50 collect (list (list i))))
(l2 (loop for i downfrom 50 to 0 collect (list (list i)))))
(assert-false (subsetp l1
l2
:key #'car
:test #'equal))))
(define-test |subsetp test=equal key=other 5b|
(let ((l1 (loop for i from -1 to 50 collect (list (list i))))
(l2 (loop for i downfrom 50 to 0 collect (list (list i)))))
(assert-false (subsetp l1
l2
:key #'car
:test 'equal))))
(define-test |subsetp test=equalp key=other 2a|
(let ((l1 (loop for i from 1 to 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 10 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-true (subsetp l1
l2
:key #'car
:test #'equalp))))
(define-test |subsetp test=equalp key=other 2b|
(let ((l1 (loop for i from 1 to 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 10 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-true (subsetp l1
l2
:key #'car
:test 'equalp))))
(define-test |subsetp test=equalp key=other 3a|
(let ((l1 (loop for i from 1 to 50 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 50 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-true (subsetp l1
l2
:key #'car
:test #'equalp))))
(define-test |subsetp test=equalp key=other 3b|
(let ((l1 (loop for i from 1 to 50 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 50 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-true (subsetp l1
l2
:key #'car
:test 'equalp))))
(define-test |subsetp test=equalp key=other 4a|
(let ((l1 (loop for i from -1 to 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 10 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-false (subsetp l1
l2
:key #'car
:test #'equalp))))
(define-test |subsetp test=equalp key=other 4b|
(let ((l1 (loop for i from -1 to 10 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 10 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-false (subsetp l1
l2
:key #'car
:test 'equalp))))
(define-test |subsetp test=equalp key=other 5a|
(let ((l1 (loop for i from -1 to 50 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 50 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-false (subsetp l1
l2
:key #'car
:test #'equalp))))
(define-test |subsetp test=equalp key=other 5b|
(let ((l1 (loop for i from -1 to 50 collect (list (make-array 1 :initial-element i))))
(l2 (loop for i downfrom 50 to 0 collect (list (make-array 1 :initial-element i)))))
(assert-false (subsetp l1
l2
:key #'car
:test 'equalp))))
(define-test |subsetp test=other key=other 2b|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test #'=))))
(define-test |subsetp test=other key=other 3b|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test #'=))))
(define-test |subsetp test=other key=other 4b|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test #'=))))
(define-test |subsetp test=other key=other 5b|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test #'=))))
(define-test |subsetp test-not=other key=other 2b|
(let ((l1 (loop for i from 1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test-not #'/=))))
(define-test |subsetp test-not=other key=other 3b|
(let ((l1 (loop for i from 1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-true (subsetp l1
l2
:key #'car
:test-not #'/=))))
(define-test |subsetp test-not=other key=other 4b|
(let ((l1 (loop for i from -1 to 10 collect (list i)))
(l2 (loop for i downfrom 10 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test-not #'/=))))
(define-test |subsetp test-not=other key=other 5b|
(let ((l1 (loop for i from -1 to 50 collect (list i)))
(l2 (loop for i downfrom 50 to 0 collect (list i))))
(assert-false (subsetp l1
l2
:key #'car
:test-not #'/=))))
(define-test |subsetp test=other test-not=other 1|
(assert-error 'error
(subsetp '() '() :test #'eql :test-not #'eql)))
(define-test |subsetp test=nil key=identity 1|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-error 'error
(subsetp l1
l2
:test nil))))
(define-test |subsetp test-not=nil key=identity 1|
(let ((l1 (loop for i from 1 to 10 collect i))
(l2 (loop for i downfrom 10 to 0 collect i)))
(assert-error 'error
(subsetp l1
l2
:test-not nil))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the pushnew macro
(define-test |pushnew test=eql key=identity 1a|
(let ((list '()))
(assert-equal '(1)
(pushnew 1 list))
(assert-equal '(1)
list)))
(define-test |pushnew test=eql key=identity 1b|
(let ((list '()))
(assert-equal '(1)
(pushnew 1 list :test #'eql))
(assert-equal '(1)
list)))
(define-test |pushnew test=eql key=identity 1c|
(let ((list '()))
(assert-equal '(1)
(pushnew 1 list :test 'eql))
(assert-equal '(1)
list)))
(define-test |pushnew test=eql key=identity 2a|
(let ((list '(1)))
(assert-equal '(1)
(pushnew 1 list))
(assert-equal '(1)
list)))
(define-test |pushnew test=eql key=identity 2b|
(let ((list '(1)))
(assert-equal '(1)
(pushnew 1 list :test #'eql))
(assert-equal '(1)
list)))
(define-test |pushnew test=eql key=identity 2c|
(let ((list '(1)))
(assert-equal '(1)
(pushnew 1 list :test 'eql))
(assert-equal '(1)
list)))
(define-test |pushnew test=eql key=identity 3a|
(let ((list '(2)))
(assert-equal '(1 2)
(pushnew 1 list))
(assert-equal '(1 2)
list)))
(define-test |pushnew test=eql key=identity 3b|
(let ((list '(2)))
(assert-equal '(1 2)
(pushnew 1 list :test #'eql))
(assert-equal '(1 2)
list)))
(define-test |pushnew test=eql key=identity 3c|
(let ((list '(2)))
(assert-equal '(1 2)
(pushnew 1 list :test 'eql))
(assert-equal '(1 2)
list)))
(define-test |pushnew test=eql key=identity 4a|
(let ((list '(2 1)))
(assert-equal '(2 1)
(pushnew 1 list))
(assert-equal '(2 1)
list)))
(define-test |pushnew test=eql key=identity 4b|
(let ((list '(2 1)))
(assert-equal '(2 1)
(pushnew 1 list :test #'eql))
(assert-equal '(2 1)
list)))
(define-test |pushnew test=eql key=identity 4c|
(let ((list '(2 1)))
(assert-equal '(2 1)
(pushnew 1 list :test 'eql))
(assert-equal '(2 1)
list)))
(define-test |pushnew test=eql key=nil 3b|
(let ((list '(2)))
(assert-equal '(1 2)
(pushnew 1 list :key nil))
(assert-equal '(1 2)
list)))
(define-test |pushnew test=eq key=identity 1b|
(let ((list '()))
(assert-equal '(a)
(pushnew 'a list :test #'eq))
(assert-equal '(a)
list)))
(define-test |pushnew test=eq key=identity 1c|
(let ((list '()))
(assert-equal '(a)
(pushnew 'a list :test 'eq))
(assert-equal '(a)
list)))
(define-test |pushnew test=eq key=identity 2b|
(let ((list '(a)))
(assert-equal '(a)
(pushnew 'a list :test #'eq))
(assert-equal '(a)
list)))
(define-test |pushnew test=eq key=identity 2c|
(let ((list '(a)))
(assert-equal '(a)
(pushnew 'a list :test 'eq))
(assert-equal '(a)
list)))
(define-test |pushnew test=eq key=identity 3b|
(let ((list '(b)))
(assert-equal '(a b)
(pushnew 'a list :test #'eq))
(assert-equal '(a b)
list)))
(define-test |pushnew test=eq key=identity 3c|
(let ((list '(b)))
(assert-equal '(a b)
(pushnew 'a list :test 'eq))
(assert-equal '(a b)
list)))
(define-test |pushnew test=eq key=identity 4b|
(let ((list '(b a)))
(assert-equal '(b a)
(pushnew 'a list :test #'eq))
(assert-equal '(b a)
list)))
(define-test |pushnew test=eq key=identity 4c|
(let ((list '(b a)))
(assert-equal '(b a)
(pushnew 'a list :test 'eq))
(assert-equal '(b a)
list)))
(define-test |pushnew test=eql key=other 1|
(let ((list '()))
(assert-equal '((1))
(pushnew '(1) list :key #'car))
(assert-equal '((1))
list)))
(define-test |pushnew test=eql key=other 2|
(let ((list '((1))))
(assert-equal '((1))
(pushnew '(1) list :key #'car))
(assert-equal '((1))
list)))
(define-test |pushnew test=eql key=other 3|
(let ((list '((2))))
(assert-equal '((1) (2))
(pushnew '(1) list :key #'car))
(assert-equal '((1) (2))
list)))
(define-test |pushnew test=eql key=other 4|
(let ((list '((2) (1))))
(assert-equal '((2) (1))
(pushnew '(1) list :key #'car))
(assert-equal '((2) (1))
list)))
(define-test |pushnew test=eq key=other 1|
(let ((list '()))
(assert-equal '((a))
(pushnew '(a) list :test #'eq :key #'car))
(assert-equal '((a))
list)))
(define-test |pushnew test=eq key=other 2|
(let ((list '((a))))
(assert-equal '((a))
(pushnew '(a) list :test #'eq :key #'car))
(assert-equal '((a))
list)))
(define-test |pushnew test=eq key=other 3|
(let ((list '((b))))
(assert-equal '((a) (b))
(pushnew '(a) list :test #'eq :key #'car))
(assert-equal '((a) (b))
list)))
(define-test |pushnew test=eq key=other 4|
(let ((list '((b) (a))))
(assert-equal '((b) (a))
(pushnew '(a) list :test #'eq :key #'car))
(assert-equal '((b) (a))
list)))
(define-test |pushnew test=other key=identity 1b|
(let ((list '()))
(assert-equal '(1)
(pushnew 1 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(1)
list)))
(define-test |pushnew test=other key=identity 2b|
(let ((list '(1)))
(assert-equal '(1 1)
(pushnew 1 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(1 1)
list)))
(define-test |pushnew test=other key=identity 3b|
(let ((list '(2)))
(assert-equal '(1 2)
(pushnew 1 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(1 2)
list)))
(define-test |pushnew test=other key=identity 4b|
(let ((list '(2 1)))
(assert-equal '(1 2 1)
(pushnew 1 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(1 2 1)
list)))
(define-test |pushnew test=other key=identity 5b|
(let ((list '(1)))
(assert-equal '(1)
(pushnew 2 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(1)
list)))
(define-test |pushnew test=other key=identity 6b|
(let ((list '(2)))
(assert-equal '(2 2)
(pushnew 2 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(2 2)
list)))
(define-test |pushnew test=other key=identity 7b|
(let ((list '(2 1)))
(assert-equal '(2 1)
(pushnew 2 list
:test (lambda (x y) (= (1- x) y))))
(assert-equal '(2 1)
list)))
(define-test |pushnew test=other key=other 3b|
(let ((list '((2))))
(assert-equal '((1) (2))
(pushnew '(1) list
:test (lambda (x y) (= (1- x) y))
:key #'car))
(assert-equal '((1) (2))
list)))
(define-test |pushnew test=other key=other 4b|
(let ((list '((2) (1))))
(assert-equal '((1) (2) (1))
(pushnew '(1) list
:test (lambda (x y) (= (1- x) y))
:key #'car))
(assert-equal '((1) (2) (1))
list)))
(define-test |pushnew test=other key=other 5b|
(let ((list '((1))))
(assert-equal '((1))
(pushnew '(2) list
:test (lambda (x y) (= (1- x) y))
:key #'car))
(assert-equal '((1))
list)))
(define-test |pushnew test=other key=other 6b|
(let ((list '((2))))
(assert-equal '((2) (2))
(pushnew '(2) list
:test (lambda (x y) (= (1- x) y))
:key #'car))
(assert-equal '((2) (2))
list)))
(define-test |pushnew test=other key=other 7b|
(let ((list '((2) (1))))
(assert-equal '((2) (1))
(pushnew '(2) list
:test (lambda (x y) (= (1- x) y))
:key #'car))
(assert-equal '((2) (1))
list)))
(define-test |pushnew test-not=other key=identity 1b|
(let ((list '()))
(assert-equal '(1)
(pushnew 1 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(1)
list)))
(define-test |pushnew test-not=other key=identity 2b|
(let ((list '(1)))
(assert-equal '(1 1)
(pushnew 1 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(1 1)
list)))
(define-test |pushnew test-not=other key=identity 3b|
(let ((list '(2)))
(assert-equal '(1 2)
(pushnew 1 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(1 2)
list)))
(define-test |pushnew test-not=other key=identity 4b|
(let ((list '(2 1)))
(assert-equal '(1 2 1)
(pushnew 1 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(1 2 1)
list)))
(define-test |pushnew test-not=other key=identity 5b|
(let ((list '(1)))
(assert-equal '(1)
(pushnew 2 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(1)
list)))
(define-test |pushnew test-not=other key=identity 6b|
(let ((list '(2)))
(assert-equal '(2 2)
(pushnew 2 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(2 2)
list)))
(define-test |pushnew test-not=other key=identity 7b|
(let ((list '(2 1)))
(assert-equal '(2 1)
(pushnew 2 list
:test-not (lambda (x y) (/= (1- x) y))))
(assert-equal '(2 1)
list)))
(define-test |pushnew test-not=other key=other 3b|
(let ((list '((2))))
(assert-equal '((1) (2))
(pushnew '(1) list
:test-not (lambda (x y) (/= (1- x) y))
:key #'car))
(assert-equal '((1) (2))
list)))
(define-test |pushnew test-not=other key=other 4b|
(let ((list '((2) (1))))
(assert-equal '((1) (2) (1))
(pushnew '(1) list
:test-not (lambda (x y) (/= (1- x) y))
:key #'car))
(assert-equal '((1) (2) (1))
list)))
(define-test |pushnew test-not=other key=other 5b|
(let ((list '((1))))
(assert-equal '((1))
(pushnew '(2) list
:test-not (lambda (x y) (/= (1- x) y))
:key #'car))
(assert-equal '((1))
list)))
(define-test |pushnew test-not=other key=other 6b|
(let ((list '((2))))
(assert-equal '((2) (2))
(pushnew '(2) list
:test-not (lambda (x y) (/= (1- x) y))
:key #'car))
(assert-equal '((2) (2))
list)))
(define-test |pushnew test-not=other key=other 7b|
(let ((list '((2) (1))))
(assert-equal '((2) (1))
(pushnew '(2) list
:test-not (lambda (x y) (/= (1- x) y))
:key #'car))
(assert-equal '((2) (1))
list)))
(define-test |pushnew test=other test-not=other 1|
(let ((fun nil)
(warned nil))
(handler-bind ((warning (lambda (condition)
(setf warned t)
(muffle-warning condition))))
(setf fun
(compile nil '(lambda ()
(declare (special list))
(pushnew '2 list
:test #'eql
:test-not #'eql)))))
(assert-true warned)
(assert-error 'error (funcall fun))))
(define-test |pushnew test=nil key=identity 3b|
(let ((list '(2)))
(assert-error 'error
(pushnew 1 list :test nil))))
(define-test |pushnew test-not=nil key=identity 3b|
(let ((list '(2)))
(assert-error 'error
(pushnew 1 list :test-not nil))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the POP macro.
(define-test |pop 1|
(let ((var (list 1)))
(assert-equal 1
(pop var))
(assert-equal '()
var)))
(define-test |pop 2|
(let ((var (list 1 2)))
(assert-equal 1
(pop var))
(assert-equal '(2)
var)))
(define-test |pop 3|
(let ((list (list (list 1))))
(assert-equal 1
(pop (car list)))
(assert-equal '(())
list)))
(define-test |pop 4|
(let ((list (list (list 1 2))))
(assert-equal 1
(pop (car list)))
(assert-equal '((2))
list)))
(define-test |pop error 1|
(let ((list (copy-tree '(1 . 2))))
(assert-equal 1
(pop list))
(assert-error 'type-error
(pop list))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the NSUBST function.
(define-test nsubst.1
(assert-equal '(a (c))
(nsubst 'c '(b) (copy-tree '(a ((b)))) :test-not (complement #'equal))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the GETF function.
(define-test |getf 1|
(assert-equal nil
(getf '() 'a)))
(define-test |getf 2|
(assert-equal 1
(getf '(a 1) 'a)))
(define-test |getf 3|
(assert-equal 1
(getf '(b 2 a 1) 'a)))
(define-test |getf 4|
(assert-equal nil
(getf '(b 2 a 1) 'c)))
(define-test |getf error 1|
(assert-error 'type-error
(getf '(b 2 a) 'c)))
(define-test |getf error 2|
(assert-error 'type-error
(getf 1 'c)))
(define-test |getf error 3|
(assert-error 'type-error
(getf '(b 2 a 3 . f) 'c)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the GET-PROPERTIES function.
(define-test |get-properties 1|
(multiple-value-bind (indicator value tail)
(get-properties '() '(a))
(assert-equal nil indicator)
(assert-equal nil value)
(assert-equal nil tail)))
(define-test |get-properties 2|
(multiple-value-bind (indicator value tail)
(get-properties '(a 1) '(b a))
(assert-equal 'a indicator)
(assert-equal 1 value)
(assert-equal '(a 1) tail)))
(define-test |get-properties 3|
(multiple-value-bind (indicator value tail)
(get-properties '(b 2 a 1) '(c a d))
(assert-equal 'a indicator)
(assert-equal 1 value)
(assert-equal '(a 1) tail)))
(define-test |get-properties 4|
(multiple-value-bind (indicator value tail)
(get-properties '(b 2 a 1) '(c d e))
(assert-equal nil indicator)
(assert-equal nil value)
(assert-equal nil tail)))
(define-test |get-properties 5|
(multiple-value-bind (indicator value tail)
(get-properties '(b 2 a 1 e 10) '(c a d))
(assert-equal 'a indicator)
(assert-equal 1 value)
(assert-equal '(a 1 e 10) tail)))
(define-test |get-properties error 1|
(assert-error 'type-error
(get-properties '(b 2 a) '(c d e))))
(define-test |get-properties error 2|
(assert-error 'type-error
(get-properties '(b 2 a 3 . f) '(c d e))))
(define-test |get-properties error 3|
(assert-error 'type-error
(get-properties 1 '(c d e))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the SETF expander for GETF.
(define-test |(setf getf) 1|
(let ((list (copy-list '(:a 0 :c 1 :e 2 :c 3))))
(assert-equal 4
(setf (getf list :c) 4))
(assert-equal '(:a 0 :c 4 :e 2 :c 3)
list)))
(define-test |(setf getf) 2|
(let ((list (copy-list '(:a 0 :c 1 :e 2 :c 3)))
(thing 0))
(assert-equal 4
(setf (getf list :d (incf thing)) 4))
(assert-equal 4
(getf list :d))
(assert-equal 1 thing)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Tests for the REMF macro.
(define-test remf.1
(let ((list (copy-tree '(a 1 b 2 c 3))))
(assert-true (remf list 'c))
(assert-equal '(a 1 b 2)
list)))
|
[
{
"context": "; DEALINGS IN THE SOFTWARE.\n;\n; Original author: Mertcan Temel <[email protected]>\n\n(in-package \"SVL\")\n\n(include-b",
"end": 1281,
"score": 0.999817967414856,
"start": 1268,
"tag": "NAME",
"value": "Mertcan Temel"
},
{
"context": "THE SOFTWARE.\n;\n; Original author: Mertcan Temel <[email protected]>\n\n(in-package \"SVL\")\n\n(include-book \"../svex-eval",
"end": 1298,
"score": 0.9999309182167053,
"start": 1283,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/centaur/svl/svexl/svexl.lisp
|
KestrelInstitute/acl2
| 305 |
; SVL - Listener-based Hierachical Symbolic Vector Hardware Analysis Framework
; Copyright (C) 2019 Centaur Technology
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: Mertcan Temel <[email protected]>
(in-package "SVL")
(include-book "../svex-eval-wog")
(fty::deftypes
svexl-node
:prepwork ((local
(defthm integerp-implies-4vecp
(implies (integerp x)
(4vec-p x))
:hints (("Goal"
:in-theory (e/d (4vec-p) ())))))
(local (defthm car-of-svar-when-consp
(implies (and (sv::svar-p x)
(consp x)
(syntaxp (quotep v)))
(equal (equal (car x) v)
(equal v :var)))
:hints(("Goal" :in-theory (enable sv::svar-p)))))
(local (defthm 4vec-not-svar-p
(implies (sv::svar-p x)
(not (4vec-p x)))
:hints(("Goal" :in-theory (enable 4vec-p sv::svar-p)))))
(local (defthm cons-fnsym-not-svar-p
(implies (not (eq x :var))
(not (sv::svar-p (cons x y))))
:hints(("Goal" :in-theory (enable fnsym-p sv::svar-p)))))
(local (defthm car-of-4vec-fix-integerp
(implies (consp (4vec-fix x))
(integerp (car (4vec-fix x))))
:hints(("Goal" :in-theory (enable 4vec-fix 4vec)))))
(local (defthm car-of-4vec-fix-type
(or (integerp (car (4vec-fix x)))
(not (car (4vec-fix x))))
:hints(("Goal" :in-theory (enable 4vec-fix 4vec)))
:rule-classes ((:type-prescription :typed-term (car (4vec-fix x)))))))
(fty::defflexsum
svexl-node
(:var
:short "A variable, which represents a @(see 4vec)."
:cond (if (atom x)
(or (stringp x)
(and x (symbolp x)))
(eq (car x) :var))
:fields ((name :acc-body x :type sv::svar-p))
:ctor-body name)
(:quote
:short "A ``quoted constant'' @(see 4vec), which represents itself."
:cond (or (atom x)
(integerp (car x)))
:fields ((val :acc-body x
:type 4vec))
:ctor-body val)
(:node
:cond (and (consp x)
(consp (cdr x))
(not (cddr x))
(eq (car x) ':node))
:fields ((node-id :acc-body (cadr x) :type natp))
:ctor-body (hons ':node (hons node-id nil)))
(:call
:short "A function applied to some expressions."
:cond t
:fields ((fn :acc-body (car x)
:type sv::fnsym)
(args :acc-body (cdr x)
:type svexl-nodelist))
:ctor-body (hons fn args)))
(fty::deflist svexl-nodelist
:elt-type svexl-node
:true-listp t))
(fty::defalist svexl-node-array
:key-type natp
:val-type svexl-node
:true-listp t)
(fty::defalist svexl-node-alist
:key-type sv::svar-p
:val-type svexl-node
:true-listp t)
(fty::defprod
svexl
((top-node svexl-node)
(node-array svexl-node-array)))
(fty::defprod
svexllist
((top-nodelist svexl-nodelist)
(node-array svexl-node-array)))
(fty::defprod
svexl-alist
((top-node-alist svexl-node-alist)
(node-array svexl-node-array)))
(define reuse-statsp (x)
:enabled t
(if (atom x)
(eq x nil)
(and (consp (car x))
(natp (cdar x))
(svex-p (caar x))
(reuse-statsp (cdr x)))))
(define nodesdb-p (x)
:enabled t
(reuse-statsp x)
///
(defthm nodesdb-p-implies-reuse-statsp
(implies (nodesdb-p x)
(reuse-statsp x))))
(define reverse-nodesdb-p (x)
:enabled t
(if (atom x)
(eq x nil)
(and (consp (car x))
(natp (caar x))
(svex-p (cdar x))
(reverse-nodesdb-p (cdr x)))))
(define node-env-p (x)
:measure (acl2-count x)
(if (atom x)
(eq x nil)
(and (consp (car x))
(natp (caar x))
(4vec-p (cdar x))
(node-env-p (cdr x)))))
(acl2::defines
svex-to-svexl-get-stats
:prepwork
((local
(in-theory (e/d (sv::svex-kind
sv::svexlist-p
sv::svex-p)
())))
(local
(defthm lemma1
(implies (and (hons-assoc-equal svex acc)
(reuse-statsp acc))
(and (natp (+ 1 (cdr (hons-assoc-equal svex acc))))
(natp (cdr (hons-assoc-equal svex acc))))))))
(define svex-to-svexl-get-stats ((acc reuse-statsp)
(svex svex-p))
:measure (sv::svex-count svex)
:verify-guards nil
:returns (res-acc reuse-statsp :hyp (and (reuse-statsp acc)
(svex-p svex)))
(sv::svex-case
svex
:var acc
:quote acc
:call (b* ((entry (hons-get svex acc)))
(if entry
(hons-acons svex (1+ (cdr entry)) acc)
(svex-to-svexl-get-stats-lst (hons-acons svex 1 acc)
svex.args)))))
(define svex-to-svexl-get-stats-lst ((acc reuse-statsp)
(lst sv::svexlist-p))
:returns (res-acc reuse-statsp :hyp (and (reuse-statsp acc)
(sv::svexlist-p lst)))
:measure (sv::svexlist-count lst)
(if (atom lst)
acc
(b* ((acc (svex-to-svexl-get-stats acc (car lst)))
(acc (svex-to-svexl-get-stats-lst acc (cdr lst))))
acc)))
///
(verify-guards svex-to-svexl-get-stats))
(define should-be-an-svexl-node ((reuse-stats reuse-statsp)
(svex svex-p))
:inline t
(b* ((reuse-stats-entry (hons-get svex reuse-stats)))
(and reuse-stats-entry
(> (cdr reuse-stats-entry) 1))))
(acl2::defines
svex-to-svexl-aux
:flag-defthm-macro defthm-svex-to-svexl-aux
:flag-local nil
:prepwork
((local
(in-theory (e/d (svex-kind
sv::svexlist-p
svexl-node-p
svexl-node-array-p
sv::svex-p)
(natp))))
(local
(defthm lemma1
(implies (and (hons-assoc-equal svex nodesdb)
(reuse-statsp nodesdb))
(natp (cdr (hons-assoc-equal svex nodesdb)))))))
(define svex-to-svexl-aux ((svex svex-p)
(reuse-stats reuse-statsp)
(nodesdb nodesdb-p)
(svexl-node-array svexl-node-array-p)
(cnt natp))
:guard (equal cnt (len svexl-node-array))
:verify-guards nil ;;verified below.
:measure (sv::svex-count svex)
:returns (mv (res-svex svexl-node-p
:hyp (and (svex-p svex)
(nodesdb-p nodesdb)
#|(natp cnt)||#))
(nodesdb-res nodesdb-p
:hyp (and (svex-p svex)
#|(natp cnt)||#
(nodesdb-p nodesdb)))
(svexl-res svexl-node-array-p
:hyp (and (svex-p svex)
(svexl-node-array-p svexl-node-array)
(nodesdb-p nodesdb)
#|(natp cnt)||#))
(cnt-res natp #|:hyp||# #|(natp cnt)||#))
(b* ((cnt (mbe :exec cnt
:logic (len svexl-node-array))))
(sv::svex-case
svex
:quote (mv svex nodesdb svexl-node-array cnt)
:var (mv svex nodesdb svexl-node-array cnt)
:call (b* ((nodesdb-entry (hons-get svex nodesdb))
((when nodesdb-entry)
(mv (make-svexl-node-node :node-id (cdr nodesdb-entry))
nodesdb svexl-node-array cnt))
((mv rest-node nodesdb svexl-node-array cnt)
(svex-to-svexl-aux-lst svex.args reuse-stats nodesdb svexl-node-array cnt))
(cnt (mbe :exec cnt :logic (len svexl-node-array)))
(new-node (make-svexl-node-call
:fn svex.fn
:args rest-node)))
(if (should-be-an-svexl-node reuse-stats svex)
(mv (make-svexl-node-node :node-id cnt)
(hons-acons svex cnt nodesdb)
(hons-acons cnt new-node svexl-node-array)
(1+ cnt))
(mv new-node nodesdb svexl-node-array cnt))))))
(define svex-to-svexl-aux-lst ((lst svexlist-p)
(reuse-stats reuse-statsp)
(nodesdb nodesdb-p)
(svexl-node-array svexl-node-array-p)
(cnt natp))
:measure (sv::svexlist-count lst)
:returns (mv (res-svexlst svexl-nodelist-p
:hyp (and (svexlist-p lst)
(nodesdb-p nodesdb)
(natp cnt)))
(nodesdb-res nodesdb-p
:hyp (and (svexlist-p lst)
(natp cnt)
(nodesdb-p nodesdb)))
(svexl-res svexl-node-array-p
:hyp (and (svexlist-p lst)
(nodesdb-p nodesdb)
(svexl-node-array-p svexl-node-array)
(natp cnt)))
(cnt-res natp :hyp (natp cnt)))
:guard (equal cnt (len svexl-node-array))
(b* ((cnt (mbe :exec cnt
:logic (len svexl-node-array))))
(if (atom lst)
(mv nil nodesdb svexl-node-array cnt)
(b* (((mv new-car-lst nodesdb svexl-node-array cnt)
(svex-to-svexl-aux
(car lst) reuse-stats nodesdb svexl-node-array cnt))
(cnt (mbe :exec cnt
:logic (len svexl-node-array)))
((mv new-cdr-lst nodesdb svexl-node-array cnt)
(svex-to-svexl-aux-lst
(cdr lst) reuse-stats nodesdb svexl-node-array cnt))
(cnt (mbe :exec cnt
:logic (len svexl-node-array))))
(mv (cons new-car-lst
new-cdr-lst)
nodesdb svexl-node-array cnt)))))
///
(local
(defthm lemma2
(implies (natp x)
(rationalp x))))
(defthm-svex-to-svexl-aux
(defthm return-cnt-of-svex-to-svexl-aux
(implies (equal (len svexl-node-array) cnt)
(equal (mv-nth 3 (svex-to-svexl-aux
svex reuse-stats nodesdb svexl-node-array cnt))
(len (mv-nth 2 (svex-to-svexl-aux
svex reuse-stats nodesdb svexl-node-array cnt)))))
:flag svex-to-svexl-aux)
(defthm return-cnt-of-svex-to-svexl-aux-lst
(and
(true-listp (mv-nth 0 (svex-to-svexl-aux-lst
lst reuse-stats nodesdb svexl-node-array cnt)))
(equal (len (mv-nth 0 (svex-to-svexl-aux-lst
lst reuse-stats nodesdb svexl-node-array cnt)))
(len lst))
(implies (equal (len svexl-node-array) cnt)
(equal (mv-nth 3 (svex-to-svexl-aux-lst
lst reuse-stats nodesdb svexl-node-array cnt))
(len (mv-nth 2 (svex-to-svexl-aux-lst
lst reuse-stats nodesdb svexl-node-array cnt))))))
:flag svex-to-svexl-aux-lst))
(verify-guards svex-to-svexl-aux))
(define svex-to-svexl ((svex svex-p))
:returns (svexl svexl-p :hyp (svex-p svex))
(b* ((svex (hons-copy svex))
(reuse-stats (svex-to-svexl-get-stats nil svex))
((mv new-node nodesdb svexl-node-array ?cnt)
(svex-to-svexl-aux svex reuse-stats nil
nil 0))
(- (fast-alist-free nodesdb))
(- (fast-alist-free svexl-node-array))
(- (fast-alist-free reuse-stats))
(svexl (make-svexl
:top-node new-node
:node-array svexl-node-array)))
svexl))
(define svexlist-to-svexllist ((svexlist svexlist-p))
:returns (svexl svexllist-p :hyp (svexlist-p svexlist))
(b* ((svexlist (hons-copy svexlist))
(reuse-stats (svex-to-svexl-get-stats-lst nil svexlist))
((mv new-node-lst nodesdb svexl-node-array ?cnt)
(svex-to-svexl-aux-lst svexlist reuse-stats nil
nil 0))
(- (fast-alist-free nodesdb))
(- (fast-alist-free svexl-node-array))
(- (fast-alist-free reuse-stats))
(svexllist (make-svexllist
:top-nodelist new-node-lst
:node-array svexl-node-array)))
svexllist))
(define svex-alist-to-svexl-alist ((svex-alist sv::svex-alist-p))
:prepwork
((local
(defthm lemma1
(implies (and (sv::svarlist-p svarlist)
(svexl-nodelist-p nodelist)
(equal (len svarlist)
(len nodelist)))
(svexl-node-alist-p (pairlis$ svarlist nodelist)))
:hints (("Goal"
:induct (pairlis$ svarlist nodelist)
:in-theory (e/d (svexl-node-alist-p
svexl-nodelist-p
sv::svarlist-p)
())))))
(local
(defthm lemma2
(implies (SV::SVEX-ALIST-P SVEX-ALIST)
(and (EQUAL (LEN (STRIP-CARS SVEX-ALIST))
(LEN (STRIP-CDRS SVEX-ALIST)))
(SV::SVARLIST-P (STRIP-CARS SVEX-ALIST))
(SVEXLIST-P (STRIP-CDRS SVEX-ALIST))))
:hints (("Goal"
:in-theory (e/d (SV::SVEX-ALIST-P
SVEXLIST-P
SV::SVARLIST-P)
()))))))
:guard-hints (("Goal"
:do-not-induct t
:in-theory (e/d () ())))
:returns (svexl-alist svexl-alist-p :hyp (sv::svex-alist-p svex-alist))
(b* ((keys (strip-cars svex-alist))
(svexlist (strip-cdrs svex-alist))
(svexlist (hons-copy svexlist))
(reuse-stats (svex-to-svexl-get-stats-lst nil svexlist))
((mv new-node-lst nodesdb svexl-node-array ?cnt)
(svex-to-svexl-aux-lst svexlist reuse-stats nil
nil 0))
(top-node-alist (pairlis$ keys new-node-lst))
(- (fast-alist-free nodesdb))
(- (fast-alist-free svexl-node-array))
(- (fast-alist-free reuse-stats))
(svexl-alist (make-svexl-alist
:top-node-alist top-node-alist
:node-array svexl-node-array)))
svexl-alist))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Svexl to Svex functions (convert back)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(acl2::defines
svexl-node-to-svex
:flag-local nil
:flag-defthm-macro defthm-svexl-node-to-svex
:prepwork
((local
(in-theory (e/d ( ;svexl-node-kind
sv::svexlist-p
svexl-node-p
reverse-nodesdb-p
svexl-node-array-p
sv::svex-p)
())))
(local
(defthm lemma1
(implies (and
(hons-assoc-equal x
reverse-nodesdb)
(reverse-nodesdb-p reverse-nodesdb))
(svex-p (cdr (hons-assoc-equal x
reverse-nodesdb))))
:hints (("Goal"
:induct (reverse-nodesdb-p reverse-nodesdb)
:do-not-induct t
:in-theory (e/d () ())))))
(local
(defthm lemma2
(implies (and (equal (svexl-node-kind x) :var)
(svexl-node-p x))
(svex-p x))
:hints (("Goal"
:in-theory (e/d (svexl-node-p svex-p svexl-node-kind) ())))))
(local
(defthm lemma3
(implies (and (equal (svexl-node-kind x) :quote)
(svexl-node-p x))
(svex-p (svexl-node-quote->val x)))
:hints (("Goal"
:in-theory (e/d (svexl-node-p svex-p svexl-node-quote->val 4vec-p svexl-node-kind) ())))))
)
(define svexl-node-to-svex ((x svexl-node-p)
(reverse-nodesdb reverse-nodesdb-p))
:measure (svexl-node-count x)
:verify-guards nil
:returns (res sv::svex-p :hyp (and (svexl-node-p x)
(reverse-nodesdb-p reverse-nodesdb)))
(svexl-node-case
x
:var x
:quote x.val
:node (b* ((node (hons-get x.node-id reverse-nodesdb)))
(if node
(cdr node)
(sv::4vec-x)))
:call (cons
x.fn
(svexl-nodelist-to-svexlist x.args
reverse-nodesdb))))
(define svexl-nodelist-to-svexlist ((lst svexl-nodelist-p)
(reverse-nodesdb reverse-nodesdb-p))
:returns (res sv::svexlist-p :hyp (and (svexl-nodelist-p lst)
(reverse-nodesdb-p reverse-nodesdb)))
:measure (svexl-nodelist-count lst)
(if (atom lst)
nil
(cons (svexl-node-to-svex (car lst) reverse-nodesdb)
(svexl-nodelist-to-svexlist (cdr lst) reverse-nodesdb))))
///
(verify-guards svexl-node-to-svex))
(define svexl-to-svex-aux ((x svexl-node-array-p))
:verify-guards nil
:prepwork
((local
(in-theory (e/d (svexl-node-array-p
node-env-p)
()))))
:returns (reverse-nodesdb reverse-nodesdb-p :hyp (svexl-node-array-p x))
(if (atom x)
nil
(b* ((reverse-nodesdb (svexl-to-svex-aux (cdr x)))
(node-id (caar x))
(node (cdar x))
(res (svexl-node-to-svex node reverse-nodesdb)))
(hons-acons node-id res reverse-nodesdb)))
///
(verify-guards svexl-to-svex-aux))
(define svexl-to-svex ((svexl svexl-p))
:returns (svex svex-p :hyp (svexl-p svexl))
(b* ((node (svexl->top-node svexl))
(node-array (svexl->node-array svexl))
(reverse-nodesdb (svexl-to-svex-aux node-array))
(res (svexl-node-to-svex node reverse-nodesdb))
(- (fast-alist-free reverse-nodesdb)))
res))
(define svexllist-to-svexlist ((svexllist svexllist-p))
:returns (svexlist svexlist-p :hyp (svexllist-p svexllist))
(b* ((top-nodelist (svexllist->top-nodelist svexllist))
(node-array (svexllist->node-array svexllist))
(reverse-nodesdb (svexl-to-svex-aux node-array))
(res (svexl-nodelist-to-svexlist top-nodelist reverse-nodesdb))
(- (fast-alist-free reverse-nodesdb)))
res))
(define svexl-alist-to-svex-alist ((svexl-alist svexl-alist-p))
:returns (svex-alist sv::svex-alist-p :hyp (svexl-alist-p svexl-alist))
:prepwork
((local
(progn
(defthm lemma1
(IMPLIES
(SVEXL-NODE-ALIST-P node-alist)
(SVEXL-NODELIST-P (STRIP-CDRS node-alist)))
:hints (("Goal"
:in-theory (e/d (SVEXL-NODE-ALIST-P SVEXL-NODELIST-P)
()))))
(defthm lemma2
(implies (svexl-node-alist-p alist)
(and (SV::SVARLIST-P (STRIP-CARS alist))
(SVEXL-NODELIST-P (STRIP-CDRS alist))))
:hints (("Goal"
:in-theory (e/d (svexl-node-alist-p) ()))))
(defthm len-of-svexl-nodelist-to-svexlist
(equal (len (svexl-nodelist-to-svexlist lst r))
(len lst))
:hints (("Goal"
:induct (len lst)
:in-theory (e/d (svexl-nodelist-to-svexlist) ()))))
(defthm len-of-strip-cars
(equal (len (strip-cars x))
(len x)))
(defthm len-of-strip-cdrs
(equal (len (strip-cdrs x))
(len x))))))
(b* ((top-node-alist (svexl-alist->top-node-alist svexl-alist))
(node-array (svexl-alist->node-array svexl-alist))
(reverse-nodesdb (svexl-to-svex-aux node-array))
(top-nodelist (strip-cdrs top-node-alist))
(keys (strip-cars top-node-alist))
(res (svexl-nodelist-to-svexlist top-nodelist reverse-nodesdb))
(- (fast-alist-free reverse-nodesdb)))
(pairlis$ keys res)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Eval functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(acl2::defines
svexl-node-eval
:flag-local nil
:flag-defthm-macro defthm-svexl-node-eval
:prepwork
((local
(in-theory (e/d (svexl-node-kind
svex-env-fastlookup-wog
sv::svexlist-p
svexl-node-p
svexl-node-array-p
sv::svex-p)
())))
(local
(defthm lemma1
(implies (and (node-env-p node-env)
(hons-assoc-equal x node-env))
(4vec-p (cdr (hons-assoc-equal x node-env))))
:hints (("goal"
:in-theory (e/d (node-env-p) ()))))))
(define svexl-node-eval ((x svexl-node-p)
(node-env node-env-p)
(env sv::svex-env-p))
:measure (svexl-node-count x)
:verify-guards nil
:returns (res sv::4vec-p :hyp (and (svexl-node-p x)
(node-env-p node-env)
(sv::svex-env-p env)))
(svexl-node-case
x
:var (sv::svex-env-fastlookup x.name env)
:quote x.val
:node (svex-env-fastlookup-wog x.node-id node-env)
:call (sv::svex-apply
x.fn
(svexl-nodelist-eval x.args
node-env
env))))
(define svexl-nodelist-eval ((lst svexl-nodelist-p)
(node-env node-env-p)
(env sv::svex-env-p))
:returns (res sv::4veclist-p :hyp (and (svexl-nodelist-p lst)
(node-env-p node-env)
(sv::svex-env-p env)))
:measure (svexl-nodelist-count lst)
(if (atom lst)
nil
(cons (svexl-node-eval (car lst) node-env env)
(svexl-nodelist-eval (cdr lst) node-env env))))
///
(verify-guards svexl-node-eval))
(define svexl-node-alist-eval ((alist svexl-node-alist-p)
(node-env node-env-p)
(env sv::svex-env-p))
:returns (res sv::svex-env-p :hyp (and (svexl-node-alist-p alist)
(node-env-p node-env)
(sv::svex-env-p env)))
(if (atom alist)
nil
(acons (caar alist)
(svexl-node-eval (cdar alist)
node-env env)
(svexl-node-alist-eval (cdr alist)
node-env
env))))
(define svexl-eval-aux ((x svexl-node-array-p)
(env sv::svex-env-p))
:verify-guards nil
:prepwork
((local
(in-theory (e/d (svexl-node-array-p
node-env-p)
()))))
:returns (res-node-env node-env-p :hyp (and (svexl-node-array-p x)
(sv::svex-env-p env)))
(if (atom x)
nil
(b* ((node-env (svexl-eval-aux (cdr x) env))
(node-id (caar x))
(node (cdar x))
(eval-res (svexl-node-eval node node-env env)))
(hons-acons node-id eval-res node-env)))
///
(verify-guards svexl-eval-aux))
(define svexl-eval ((x svexl-p)
(env sv::svex-env-p))
:returns (res sv::4vec-p :hyp (and (svexl-p x)
(sv::svex-env-p env)))
(b* ((node (svexl->top-node x))
(node-array (svexl->node-array x))
(node-env (svexl-eval-aux node-array env))
(res (svexl-node-eval node node-env env))
(- (fast-alist-free node-env)))
res))
(define svexllist-eval ((x svexllist-p)
(env sv::svex-env-p))
:returns (res sv::4veclist-p :hyp (and (svexllist-p x)
(sv::svex-env-p env)))
(b* ((node-lst (svexllist->top-nodelist x))
(node-array (svexllist->node-array x))
(node-env (svexl-eval-aux node-array env))
(res (svexl-nodelist-eval node-lst node-env env))
(- (fast-alist-free node-env)))
res))
(define svexl-alist-eval ((x svexl-alist-p)
(env sv::svex-env-p))
:returns (res sv::svex-env-p :hyp (and (svexl-alist-p x)
(sv::svex-env-p env)))
(b* ((top-node-alist (svexl-alist->top-node-alist x))
(node-array (svexl-alist->node-array x))
(node-env (svexl-eval-aux node-array env))
(res (svexl-node-alist-eval top-node-alist node-env env))
(- (fast-alist-free node-env)))
res))
;; Example:
#|
(b* ((svex #!SV'(bitor (bitand (bitor a b) (bitor (bitor a b)
(bitor a b)))
(bitor (bitor a b)
(bitor a b))))
(env (make-fast-alist #!SV`((a . 12312321) (b . 331312312))))
(svexl (svex-to-svexl svex)))
`((svex-eval ,(svex-eval svex env))
(svexl-eval ,(svexl-eval svexl env))
(svexl ,svexl)))||#
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Eval functions without guards:
(define svexl-node-kind-wog (x)
:returns kind
:inline t
:guard-hints
(("goal" :in-theory
(disable fty::open-member-equal-on-list-of-tags))
(and stable-under-simplificationp
'(:expand ((svex-p x)))))
:progn t
(cond ((if (atom x)
(or (stringp x) (and x (symbolp x)))
(eq (car x) :var))
:var)
((or (atom x) (integerp (car x)))
:quote)
((and (consp x)
(consp (cdr x))
(not (cddr x))
(eq (car x) ':node))
:node)
(t :call)))
(def-rp-rule$ t nil
svexl-node-kind-is-svexl-node-kind-wog
(equal (svexl-node-kind x)
(svexl-node-kind-wog x))
:hints (("Goal"
:in-theory (e/d (svexl-node-kind-wog
svexl-node-kind) ()))))
(defthmd svexl-node-kind-wog-is-svexl-node-kind
(equal (svexl-node-kind-wog x)
(svexl-node-kind x))
:hints (("Goal"
:in-theory (e/d (svexl-node-kind-wog
svexl-node-kind) ()))))
(acl2::defines
svexl-node-eval-wog
:flag-local nil
:flag-defthm-macro defthm-svexl-node-eval-wog
:prepwork
((local
(in-theory (e/d (svexl-node-kind
sv::svexlist-p
svexl-node-p
svexl-node-array-p
svexl-node-kind-wog-is-svexl-node-kind
sv::svex-p)
()))))
(define svexl-node-eval-wog ((x)
(node-env)
(env))
:measure (acl2-count x)
:verify-guards nil
(b* ((kind (svexl-node-kind-wog x)))
(cond ((eq kind :var)
(svex-env-fastlookup-wog x env))
((eq kind :quote) x)
((eq kind :node)
(svex-env-fastlookup-wog (cadr x) node-env))
(t
(b* ((x.fn (car x))
(x.args (cdr x)))
(svex-apply-wog
x.fn
(svexl-nodelist-eval-wog x.args node-env env)))))))
(define svexl-nodelist-eval-wog ((lst)
(node-env)
(env))
:measure (acl2-count lst)
(if (atom lst)
nil
(cons (svexl-node-eval-wog (car lst) node-env env)
(svexl-nodelist-eval-wog (cdr lst) node-env env))))
///
;; openers:
(def-rp-rule svexl-eval-node-of-var
(implies (eq (svexl-node-kind-wog x) ':var)
(equal (svexl-node-eval-wog x node-env env-wires)
(let ((entry (hons-get x env-wires)))
(if entry (cdr entry)
(sv::4vec-x)))))
:hints (("goal"
:expand (svexl-node-eval-wog x node-env env-wires)
:in-theory (e/d (svex-env-fastlookup-wog) ()))))
(def-rp-rule svexl-eval-node-of-node
(implies (eq (svexl-node-kind-wog x) ':node)
(equal (svexl-node-eval-wog x node-env env-wires)
(let ((entry (hons-get (cadr x) node-env)))
(if entry (cdr entry)
(sv::4vec-x)))))
:hints (("goal"
:expand (svexl-node-eval-wog x node-env env-wires)
:in-theory (e/d (svex-env-fastlookup-wog) ()))))
(def-rp-rule svexl-eval-node-of-quoted
(implies (eq (svexl-node-kind-wog x) ':quote)
(equal (svexl-node-eval-wog x node-env env-wires)
x))
:hints (("goal"
:expand (svexl-node-eval-wog x node-env env-wires)
:in-theory (e/d (svex-env-fastlookup-wog) ()))))
(def-rp-rule svexl-eval-node-of-call
(implies (eq (svexl-node-kind-wog x) ':call)
(equal (svexl-node-eval-wog x node-env env)
(svex-apply-wog
(car x)
(svexl-nodelist-eval-wog (cdr x) node-env env))))
:hints (("goal"
:expand (svexl-node-eval-wog x node-env env)
:in-theory (e/d (svex-env-fastlookup-wog) ()))))
(def-rp-rule svexl-nodelist-eval-wog-of-cons
(equal (svexl-nodelist-eval-wog (cons x rest) node-env env)
(cons (svexl-node-eval-wog x node-env env)
(svexl-nodelist-eval-wog rest node-env env)))
:hints (("Goal"
:expand (svexl-nodelist-eval-wog (cons x rest) node-env env)
:in-theory (e/d () ()))))
(def-rp-rule svexl-nodelist-eval-wog-of-nil
(equal (svexl-nodelist-eval-wog nil node-env env)
nil)
:hints (("Goal"
:expand (svexl-nodelist-eval-wog nil node-env env)
:in-theory (e/d () ()))))
(verify-guards svexl-node-eval-wog))
(define svexl-node-alist-eval-wog ((alist alistp)
(node-env)
(env))
:measure (acl2-count alist)
(if (atom alist)
nil
(acons
(caar alist)
(svexl-node-eval-wog (cdar alist) node-env env)
(svexl-node-alist-eval-wog (cdr alist) node-env env)))
///
(def-rp-rule svexl-node-alist-eval-wog-of-cons
(equal (svexl-node-alist-eval-wog (cons x rest) node-env env)
(acons
(car x)
(svexl-node-eval-wog (cdr x) node-env env)
(svexl-node-alist-eval-wog rest node-env env)))
:hints (("Goal"
:expand (svexl-node-alist-eval-wog (cons x rest) node-env env)
:in-theory (e/d () ()))))
(def-rp-rule svexl-node-alist-eval-wog-of-nil
(equal (svexl-node-alist-eval-wog nil node-env env)
nil)
:hints (("Goal"
:expand (svexl-node-alist-eval-wog nil node-env env)
:in-theory (e/d () ()))))
)
(defthm-svexl-node-eval-wog
(defthm svexl-node-eval-is-svexl-node-eval-wog
(implies (and (svexl-node-p x)
(sv::svex-env-p env))
(equal (svexl-node-eval x node-env env)
(svexl-node-eval-wog x node-env env)))
:flag svexl-node-eval-wog)
(defthm svexl-nodelist-eval-is-svexl-nodelist-eval-wog
(implies (and (svexl-nodelist-p lst)
(sv::svex-env-p env))
(equal (svexl-nodelist-eval lst node-env env)
(svexl-nodelist-eval-wog lst node-env env)))
:flag svexl-nodelist-eval-wog)
:hints (("goal"
:expand ((svexl-node-eval x node-env env))
:in-theory (e/d (svex-call->fn
svexl-nodelist-fix
svexl-node-var->name
svexl-node-quote->val
svexl-node-call->args
svexl-nodelist-p
svexl-node-call->fn
svexl-node-node->node-id
svexl-node-p
svex-kind
svex-env-fastlookup-wog
svex-eval-wog
SVEX-APPLY-IS-SVEX-APPLY-WOG
svex-env-lookup-is-svex-env-fastlookup-wog
svexl-node-kind-wog-is-svexl-node-kind
svexlist-eval-wog
svexl-node-eval
svexl-node-kind
svexl-node-eval-wog
svex-p
sv::svar-p
svex-eval
svex-var->name
sv::svex-quote->val
svex-call->args
svexl-nodelist-eval
svexl-nodelist-eval-wog)
()))))
(rp::add-rp-rule svexl-node-eval-is-svexl-node-eval-wog)
(rp::add-rp-rule svexl-nodelist-eval-is-svexl-nodelist-eval-wog)
(def-rp-rule svexl-node-alist-eval-is-svexl-node-alist-eval-wog
(implies (and (svexl-node-alist-p alist)
(sv::svex-env-p env))
(equal (svexl-node-alist-eval alist node-env env)
(svexl-node-alist-eval-wog alist node-env env)))
:hints (("Goal"
:in-theory (e/d (svexl-node-alist-eval
svexl-node-alist-p
svexl-node-alist-eval-wog)
()))))
(define svexl-eval-aux-wog ((x alistp)
(env))
:prepwork
((local
(in-theory (e/d (svexl-node-array-p
node-env-p)
()))))
(if (atom x)
nil
(b* ((node-env
(svexl-eval-aux-wog (cdr x) env))
(node-id (caar x))
(node (cdar x))
(eval-res (svexl-node-eval-wog node node-env env)))
(hons-acons node-id eval-res node-env)))
///
(def-rp-rule$ t nil
svexl-eval-aux-is-svexl-eval-aux-wog
(implies (and (svexl-node-array-p x)
(sv::svex-env-p env))
(equal (svexl-eval-aux x env)
(svexl-eval-aux-wog x env)))
:hints (("Goal"
:in-theory (e/d (svexl-eval-aux
svexl-eval-aux-wog) ()))))
(rp::defthm-lambda
svexl-eval-aux-wog-cons
(equal (svexl-eval-aux-wog (cons (cons node-id node) rest) env)
(b* ((node-env (svexl-eval-aux-wog rest env))
(eval-res (svexl-node-eval-wog node node-env env)))
(hons-acons node-id eval-res node-env))))
(def-rp-rule
svexl-eval-aux-wog-nil
(equal (svexl-eval-aux-wog nil env)
nil)))
(define svexl-eval-wog ((x)
(env))
:verify-guards nil
(b* ((node (cdar x))
(node-array (cdr (cadr x)))
(node-env (svexl-eval-aux-wog node-array env))
(res (svexl-node-eval-wog node node-env env))
(- (fast-alist-free node-env)))
res)
///
(def-rp-rule$ t nil
svexl-eval-is-svexl-eval-wog
(implies (and (svexl-p x)
(sv::svex-env-p env))
(equal (svexl-eval x env)
(svexl-eval-wog x env)))
:hints (("Goal"
:in-theory (e/d (svexl-eval
svexl->top-node
svexl->node-array
svexl-p
svexl-eval-wog
SVEXL-EVAL-AUX-IS-SVEXL-EVAL-AUX-WOG)
()))))
(defthmd svexl-eval-wog-is-svexl-eval
(implies (and (svexl-p x)
(sv::svex-env-p env))
(equal (svexl-eval-wog x env)
(svexl-eval x env)))
:hints (("Goal"
:in-theory (e/d (svexl-eval-is-svexl-eval-wog)
()))))
(set-ignore-ok t)
(add-rp-rule svexl-eval-wog :beta-reduce t))
(define svexllist-eval-wog ((x)
(env))
:verify-guards nil
(b* ((node-lst (cdr (car x)))
(node-array (cdr (cadr x)))
(node-env (svexl-eval-aux-wog node-array env))
(res (svexl-nodelist-eval-wog node-lst node-env env))
(- (fast-alist-free node-env)))
res)
///
(def-rp-rule$ t nil
svexllist-eval-is-svexllist-eval-wog
(implies (and (svexllist-p x)
(sv::svex-env-p env))
(equal (svexllist-eval x env)
(svexllist-eval-wog x env)))
:hints (("Goal"
:in-theory (e/d (svexllist-eval
SVEXLLIST->TOP-NODELIST
SVEXLLIST->NODE-ARRAY
SVEXLLIST-P
svexllist-eval-wog
SVEXL-EVAL-AUX-IS-SVEXL-EVAL-AUX-WOG)
()))))
(set-ignore-ok t)
(add-rp-rule svexllist-eval-wog :beta-reduce t))
(define svexl-alist-eval-wog ((x)
(env))
:verify-guards nil
(b* ((top-node-alist (cdar x))
(node-array (cdr (cadr x)))
(node-env (svexl-eval-aux-wog node-array env))
(res (svexl-node-alist-eval-wog top-node-alist node-env env))
(- (fast-alist-free node-env)))
res)
///
(def-rp-rule$ t nil
svexl-alist-eval-is-svexl-alist-eval-wog
(implies (and (svexl-alist-p x)
(sv::svex-env-p env))
(equal (svexl-alist-eval x env)
(svexl-alist-eval-wog x env)))
:hints (("Goal"
:in-theory (e/d (svexl-alist-eval
SVEXL-ALIST-P
SVEXL-ALIST->NODE-ARRAY
svexl-alist-eval-wog
SVEXL-ALIST->TOP-NODE-ALIST
svexl-node-alist-eval-is-svexl-node-alist-eval-wog
SVEXL-EVAL-AUX-IS-SVEXL-EVAL-AUX-WOG)
()))))
(set-ignore-ok t)
(add-rp-rule svexl-alist-eval-wog :beta-reduce t))
(memoize 'svexl-alist-p)
(memoize 'svexllist-p)
(memoize 'svexl-p)
(defthm-svexl-node-eval-wog
(defthm svex-p-implies-svexl-node-p
(implies (svex-p x)
(svexl-node-p x))
:flag svexl-node-eval-wog)
(defthm svexlist-p-implies-svexl-nodelist-p
(implies (svexlist-p lst)
(svexl-nodelist-p lst))
:flag svexl-nodelist-eval-wog)
:rule-classes :type-prescription
:hints (("Goal"
:in-theory (e/d (svex-p
svexl-node-kind-wog-is-svexl-node-kind
svexlist-p
svexl-nodelist-p
svexl-node-p
svexl-node-kind
svex-kind) ()))))
|
6442
|
; SVL - Listener-based Hierachical Symbolic Vector Hardware Analysis Framework
; Copyright (C) 2019 Centaur Technology
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: <NAME> <<EMAIL>>
(in-package "SVL")
(include-book "../svex-eval-wog")
(fty::deftypes
svexl-node
:prepwork ((local
(defthm integerp-implies-4vecp
(implies (integerp x)
(4vec-p x))
:hints (("Goal"
:in-theory (e/d (4vec-p) ())))))
(local (defthm car-of-svar-when-consp
(implies (and (sv::svar-p x)
(consp x)
(syntaxp (quotep v)))
(equal (equal (car x) v)
(equal v :var)))
:hints(("Goal" :in-theory (enable sv::svar-p)))))
(local (defthm 4vec-not-svar-p
(implies (sv::svar-p x)
(not (4vec-p x)))
:hints(("Goal" :in-theory (enable 4vec-p sv::svar-p)))))
(local (defthm cons-fnsym-not-svar-p
(implies (not (eq x :var))
(not (sv::svar-p (cons x y))))
:hints(("Goal" :in-theory (enable fnsym-p sv::svar-p)))))
(local (defthm car-of-4vec-fix-integerp
(implies (consp (4vec-fix x))
(integerp (car (4vec-fix x))))
:hints(("Goal" :in-theory (enable 4vec-fix 4vec)))))
(local (defthm car-of-4vec-fix-type
(or (integerp (car (4vec-fix x)))
(not (car (4vec-fix x))))
:hints(("Goal" :in-theory (enable 4vec-fix 4vec)))
:rule-classes ((:type-prescription :typed-term (car (4vec-fix x)))))))
(fty::defflexsum
svexl-node
(:var
:short "A variable, which represents a @(see 4vec)."
:cond (if (atom x)
(or (stringp x)
(and x (symbolp x)))
(eq (car x) :var))
:fields ((name :acc-body x :type sv::svar-p))
:ctor-body name)
(:quote
:short "A ``quoted constant'' @(see 4vec), which represents itself."
:cond (or (atom x)
(integerp (car x)))
:fields ((val :acc-body x
:type 4vec))
:ctor-body val)
(:node
:cond (and (consp x)
(consp (cdr x))
(not (cddr x))
(eq (car x) ':node))
:fields ((node-id :acc-body (cadr x) :type natp))
:ctor-body (hons ':node (hons node-id nil)))
(:call
:short "A function applied to some expressions."
:cond t
:fields ((fn :acc-body (car x)
:type sv::fnsym)
(args :acc-body (cdr x)
:type svexl-nodelist))
:ctor-body (hons fn args)))
(fty::deflist svexl-nodelist
:elt-type svexl-node
:true-listp t))
(fty::defalist svexl-node-array
:key-type natp
:val-type svexl-node
:true-listp t)
(fty::defalist svexl-node-alist
:key-type sv::svar-p
:val-type svexl-node
:true-listp t)
(fty::defprod
svexl
((top-node svexl-node)
(node-array svexl-node-array)))
(fty::defprod
svexllist
((top-nodelist svexl-nodelist)
(node-array svexl-node-array)))
(fty::defprod
svexl-alist
((top-node-alist svexl-node-alist)
(node-array svexl-node-array)))
(define reuse-statsp (x)
:enabled t
(if (atom x)
(eq x nil)
(and (consp (car x))
(natp (cdar x))
(svex-p (caar x))
(reuse-statsp (cdr x)))))
(define nodesdb-p (x)
:enabled t
(reuse-statsp x)
///
(defthm nodesdb-p-implies-reuse-statsp
(implies (nodesdb-p x)
(reuse-statsp x))))
(define reverse-nodesdb-p (x)
:enabled t
(if (atom x)
(eq x nil)
(and (consp (car x))
(natp (caar x))
(svex-p (cdar x))
(reverse-nodesdb-p (cdr x)))))
(define node-env-p (x)
:measure (acl2-count x)
(if (atom x)
(eq x nil)
(and (consp (car x))
(natp (caar x))
(4vec-p (cdar x))
(node-env-p (cdr x)))))
(acl2::defines
svex-to-svexl-get-stats
:prepwork
((local
(in-theory (e/d (sv::svex-kind
sv::svexlist-p
sv::svex-p)
())))
(local
(defthm lemma1
(implies (and (hons-assoc-equal svex acc)
(reuse-statsp acc))
(and (natp (+ 1 (cdr (hons-assoc-equal svex acc))))
(natp (cdr (hons-assoc-equal svex acc))))))))
(define svex-to-svexl-get-stats ((acc reuse-statsp)
(svex svex-p))
:measure (sv::svex-count svex)
:verify-guards nil
:returns (res-acc reuse-statsp :hyp (and (reuse-statsp acc)
(svex-p svex)))
(sv::svex-case
svex
:var acc
:quote acc
:call (b* ((entry (hons-get svex acc)))
(if entry
(hons-acons svex (1+ (cdr entry)) acc)
(svex-to-svexl-get-stats-lst (hons-acons svex 1 acc)
svex.args)))))
(define svex-to-svexl-get-stats-lst ((acc reuse-statsp)
(lst sv::svexlist-p))
:returns (res-acc reuse-statsp :hyp (and (reuse-statsp acc)
(sv::svexlist-p lst)))
:measure (sv::svexlist-count lst)
(if (atom lst)
acc
(b* ((acc (svex-to-svexl-get-stats acc (car lst)))
(acc (svex-to-svexl-get-stats-lst acc (cdr lst))))
acc)))
///
(verify-guards svex-to-svexl-get-stats))
(define should-be-an-svexl-node ((reuse-stats reuse-statsp)
(svex svex-p))
:inline t
(b* ((reuse-stats-entry (hons-get svex reuse-stats)))
(and reuse-stats-entry
(> (cdr reuse-stats-entry) 1))))
(acl2::defines
svex-to-svexl-aux
:flag-defthm-macro defthm-svex-to-svexl-aux
:flag-local nil
:prepwork
((local
(in-theory (e/d (svex-kind
sv::svexlist-p
svexl-node-p
svexl-node-array-p
sv::svex-p)
(natp))))
(local
(defthm lemma1
(implies (and (hons-assoc-equal svex nodesdb)
(reuse-statsp nodesdb))
(natp (cdr (hons-assoc-equal svex nodesdb)))))))
(define svex-to-svexl-aux ((svex svex-p)
(reuse-stats reuse-statsp)
(nodesdb nodesdb-p)
(svexl-node-array svexl-node-array-p)
(cnt natp))
:guard (equal cnt (len svexl-node-array))
:verify-guards nil ;;verified below.
:measure (sv::svex-count svex)
:returns (mv (res-svex svexl-node-p
:hyp (and (svex-p svex)
(nodesdb-p nodesdb)
#|(natp cnt)||#))
(nodesdb-res nodesdb-p
:hyp (and (svex-p svex)
#|(natp cnt)||#
(nodesdb-p nodesdb)))
(svexl-res svexl-node-array-p
:hyp (and (svex-p svex)
(svexl-node-array-p svexl-node-array)
(nodesdb-p nodesdb)
#|(natp cnt)||#))
(cnt-res natp #|:hyp||# #|(natp cnt)||#))
(b* ((cnt (mbe :exec cnt
:logic (len svexl-node-array))))
(sv::svex-case
svex
:quote (mv svex nodesdb svexl-node-array cnt)
:var (mv svex nodesdb svexl-node-array cnt)
:call (b* ((nodesdb-entry (hons-get svex nodesdb))
((when nodesdb-entry)
(mv (make-svexl-node-node :node-id (cdr nodesdb-entry))
nodesdb svexl-node-array cnt))
((mv rest-node nodesdb svexl-node-array cnt)
(svex-to-svexl-aux-lst svex.args reuse-stats nodesdb svexl-node-array cnt))
(cnt (mbe :exec cnt :logic (len svexl-node-array)))
(new-node (make-svexl-node-call
:fn svex.fn
:args rest-node)))
(if (should-be-an-svexl-node reuse-stats svex)
(mv (make-svexl-node-node :node-id cnt)
(hons-acons svex cnt nodesdb)
(hons-acons cnt new-node svexl-node-array)
(1+ cnt))
(mv new-node nodesdb svexl-node-array cnt))))))
(define svex-to-svexl-aux-lst ((lst svexlist-p)
(reuse-stats reuse-statsp)
(nodesdb nodesdb-p)
(svexl-node-array svexl-node-array-p)
(cnt natp))
:measure (sv::svexlist-count lst)
:returns (mv (res-svexlst svexl-nodelist-p
:hyp (and (svexlist-p lst)
(nodesdb-p nodesdb)
(natp cnt)))
(nodesdb-res nodesdb-p
:hyp (and (svexlist-p lst)
(natp cnt)
(nodesdb-p nodesdb)))
(svexl-res svexl-node-array-p
:hyp (and (svexlist-p lst)
(nodesdb-p nodesdb)
(svexl-node-array-p svexl-node-array)
(natp cnt)))
(cnt-res natp :hyp (natp cnt)))
:guard (equal cnt (len svexl-node-array))
(b* ((cnt (mbe :exec cnt
:logic (len svexl-node-array))))
(if (atom lst)
(mv nil nodesdb svexl-node-array cnt)
(b* (((mv new-car-lst nodesdb svexl-node-array cnt)
(svex-to-svexl-aux
(car lst) reuse-stats nodesdb svexl-node-array cnt))
(cnt (mbe :exec cnt
:logic (len svexl-node-array)))
((mv new-cdr-lst nodesdb svexl-node-array cnt)
(svex-to-svexl-aux-lst
(cdr lst) reuse-stats nodesdb svexl-node-array cnt))
(cnt (mbe :exec cnt
:logic (len svexl-node-array))))
(mv (cons new-car-lst
new-cdr-lst)
nodesdb svexl-node-array cnt)))))
///
(local
(defthm lemma2
(implies (natp x)
(rationalp x))))
(defthm-svex-to-svexl-aux
(defthm return-cnt-of-svex-to-svexl-aux
(implies (equal (len svexl-node-array) cnt)
(equal (mv-nth 3 (svex-to-svexl-aux
svex reuse-stats nodesdb svexl-node-array cnt))
(len (mv-nth 2 (svex-to-svexl-aux
svex reuse-stats nodesdb svexl-node-array cnt)))))
:flag svex-to-svexl-aux)
(defthm return-cnt-of-svex-to-svexl-aux-lst
(and
(true-listp (mv-nth 0 (svex-to-svexl-aux-lst
lst reuse-stats nodesdb svexl-node-array cnt)))
(equal (len (mv-nth 0 (svex-to-svexl-aux-lst
lst reuse-stats nodesdb svexl-node-array cnt)))
(len lst))
(implies (equal (len svexl-node-array) cnt)
(equal (mv-nth 3 (svex-to-svexl-aux-lst
lst reuse-stats nodesdb svexl-node-array cnt))
(len (mv-nth 2 (svex-to-svexl-aux-lst
lst reuse-stats nodesdb svexl-node-array cnt))))))
:flag svex-to-svexl-aux-lst))
(verify-guards svex-to-svexl-aux))
(define svex-to-svexl ((svex svex-p))
:returns (svexl svexl-p :hyp (svex-p svex))
(b* ((svex (hons-copy svex))
(reuse-stats (svex-to-svexl-get-stats nil svex))
((mv new-node nodesdb svexl-node-array ?cnt)
(svex-to-svexl-aux svex reuse-stats nil
nil 0))
(- (fast-alist-free nodesdb))
(- (fast-alist-free svexl-node-array))
(- (fast-alist-free reuse-stats))
(svexl (make-svexl
:top-node new-node
:node-array svexl-node-array)))
svexl))
(define svexlist-to-svexllist ((svexlist svexlist-p))
:returns (svexl svexllist-p :hyp (svexlist-p svexlist))
(b* ((svexlist (hons-copy svexlist))
(reuse-stats (svex-to-svexl-get-stats-lst nil svexlist))
((mv new-node-lst nodesdb svexl-node-array ?cnt)
(svex-to-svexl-aux-lst svexlist reuse-stats nil
nil 0))
(- (fast-alist-free nodesdb))
(- (fast-alist-free svexl-node-array))
(- (fast-alist-free reuse-stats))
(svexllist (make-svexllist
:top-nodelist new-node-lst
:node-array svexl-node-array)))
svexllist))
(define svex-alist-to-svexl-alist ((svex-alist sv::svex-alist-p))
:prepwork
((local
(defthm lemma1
(implies (and (sv::svarlist-p svarlist)
(svexl-nodelist-p nodelist)
(equal (len svarlist)
(len nodelist)))
(svexl-node-alist-p (pairlis$ svarlist nodelist)))
:hints (("Goal"
:induct (pairlis$ svarlist nodelist)
:in-theory (e/d (svexl-node-alist-p
svexl-nodelist-p
sv::svarlist-p)
())))))
(local
(defthm lemma2
(implies (SV::SVEX-ALIST-P SVEX-ALIST)
(and (EQUAL (LEN (STRIP-CARS SVEX-ALIST))
(LEN (STRIP-CDRS SVEX-ALIST)))
(SV::SVARLIST-P (STRIP-CARS SVEX-ALIST))
(SVEXLIST-P (STRIP-CDRS SVEX-ALIST))))
:hints (("Goal"
:in-theory (e/d (SV::SVEX-ALIST-P
SVEXLIST-P
SV::SVARLIST-P)
()))))))
:guard-hints (("Goal"
:do-not-induct t
:in-theory (e/d () ())))
:returns (svexl-alist svexl-alist-p :hyp (sv::svex-alist-p svex-alist))
(b* ((keys (strip-cars svex-alist))
(svexlist (strip-cdrs svex-alist))
(svexlist (hons-copy svexlist))
(reuse-stats (svex-to-svexl-get-stats-lst nil svexlist))
((mv new-node-lst nodesdb svexl-node-array ?cnt)
(svex-to-svexl-aux-lst svexlist reuse-stats nil
nil 0))
(top-node-alist (pairlis$ keys new-node-lst))
(- (fast-alist-free nodesdb))
(- (fast-alist-free svexl-node-array))
(- (fast-alist-free reuse-stats))
(svexl-alist (make-svexl-alist
:top-node-alist top-node-alist
:node-array svexl-node-array)))
svexl-alist))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Svexl to Svex functions (convert back)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(acl2::defines
svexl-node-to-svex
:flag-local nil
:flag-defthm-macro defthm-svexl-node-to-svex
:prepwork
((local
(in-theory (e/d ( ;svexl-node-kind
sv::svexlist-p
svexl-node-p
reverse-nodesdb-p
svexl-node-array-p
sv::svex-p)
())))
(local
(defthm lemma1
(implies (and
(hons-assoc-equal x
reverse-nodesdb)
(reverse-nodesdb-p reverse-nodesdb))
(svex-p (cdr (hons-assoc-equal x
reverse-nodesdb))))
:hints (("Goal"
:induct (reverse-nodesdb-p reverse-nodesdb)
:do-not-induct t
:in-theory (e/d () ())))))
(local
(defthm lemma2
(implies (and (equal (svexl-node-kind x) :var)
(svexl-node-p x))
(svex-p x))
:hints (("Goal"
:in-theory (e/d (svexl-node-p svex-p svexl-node-kind) ())))))
(local
(defthm lemma3
(implies (and (equal (svexl-node-kind x) :quote)
(svexl-node-p x))
(svex-p (svexl-node-quote->val x)))
:hints (("Goal"
:in-theory (e/d (svexl-node-p svex-p svexl-node-quote->val 4vec-p svexl-node-kind) ())))))
)
(define svexl-node-to-svex ((x svexl-node-p)
(reverse-nodesdb reverse-nodesdb-p))
:measure (svexl-node-count x)
:verify-guards nil
:returns (res sv::svex-p :hyp (and (svexl-node-p x)
(reverse-nodesdb-p reverse-nodesdb)))
(svexl-node-case
x
:var x
:quote x.val
:node (b* ((node (hons-get x.node-id reverse-nodesdb)))
(if node
(cdr node)
(sv::4vec-x)))
:call (cons
x.fn
(svexl-nodelist-to-svexlist x.args
reverse-nodesdb))))
(define svexl-nodelist-to-svexlist ((lst svexl-nodelist-p)
(reverse-nodesdb reverse-nodesdb-p))
:returns (res sv::svexlist-p :hyp (and (svexl-nodelist-p lst)
(reverse-nodesdb-p reverse-nodesdb)))
:measure (svexl-nodelist-count lst)
(if (atom lst)
nil
(cons (svexl-node-to-svex (car lst) reverse-nodesdb)
(svexl-nodelist-to-svexlist (cdr lst) reverse-nodesdb))))
///
(verify-guards svexl-node-to-svex))
(define svexl-to-svex-aux ((x svexl-node-array-p))
:verify-guards nil
:prepwork
((local
(in-theory (e/d (svexl-node-array-p
node-env-p)
()))))
:returns (reverse-nodesdb reverse-nodesdb-p :hyp (svexl-node-array-p x))
(if (atom x)
nil
(b* ((reverse-nodesdb (svexl-to-svex-aux (cdr x)))
(node-id (caar x))
(node (cdar x))
(res (svexl-node-to-svex node reverse-nodesdb)))
(hons-acons node-id res reverse-nodesdb)))
///
(verify-guards svexl-to-svex-aux))
(define svexl-to-svex ((svexl svexl-p))
:returns (svex svex-p :hyp (svexl-p svexl))
(b* ((node (svexl->top-node svexl))
(node-array (svexl->node-array svexl))
(reverse-nodesdb (svexl-to-svex-aux node-array))
(res (svexl-node-to-svex node reverse-nodesdb))
(- (fast-alist-free reverse-nodesdb)))
res))
(define svexllist-to-svexlist ((svexllist svexllist-p))
:returns (svexlist svexlist-p :hyp (svexllist-p svexllist))
(b* ((top-nodelist (svexllist->top-nodelist svexllist))
(node-array (svexllist->node-array svexllist))
(reverse-nodesdb (svexl-to-svex-aux node-array))
(res (svexl-nodelist-to-svexlist top-nodelist reverse-nodesdb))
(- (fast-alist-free reverse-nodesdb)))
res))
(define svexl-alist-to-svex-alist ((svexl-alist svexl-alist-p))
:returns (svex-alist sv::svex-alist-p :hyp (svexl-alist-p svexl-alist))
:prepwork
((local
(progn
(defthm lemma1
(IMPLIES
(SVEXL-NODE-ALIST-P node-alist)
(SVEXL-NODELIST-P (STRIP-CDRS node-alist)))
:hints (("Goal"
:in-theory (e/d (SVEXL-NODE-ALIST-P SVEXL-NODELIST-P)
()))))
(defthm lemma2
(implies (svexl-node-alist-p alist)
(and (SV::SVARLIST-P (STRIP-CARS alist))
(SVEXL-NODELIST-P (STRIP-CDRS alist))))
:hints (("Goal"
:in-theory (e/d (svexl-node-alist-p) ()))))
(defthm len-of-svexl-nodelist-to-svexlist
(equal (len (svexl-nodelist-to-svexlist lst r))
(len lst))
:hints (("Goal"
:induct (len lst)
:in-theory (e/d (svexl-nodelist-to-svexlist) ()))))
(defthm len-of-strip-cars
(equal (len (strip-cars x))
(len x)))
(defthm len-of-strip-cdrs
(equal (len (strip-cdrs x))
(len x))))))
(b* ((top-node-alist (svexl-alist->top-node-alist svexl-alist))
(node-array (svexl-alist->node-array svexl-alist))
(reverse-nodesdb (svexl-to-svex-aux node-array))
(top-nodelist (strip-cdrs top-node-alist))
(keys (strip-cars top-node-alist))
(res (svexl-nodelist-to-svexlist top-nodelist reverse-nodesdb))
(- (fast-alist-free reverse-nodesdb)))
(pairlis$ keys res)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Eval functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(acl2::defines
svexl-node-eval
:flag-local nil
:flag-defthm-macro defthm-svexl-node-eval
:prepwork
((local
(in-theory (e/d (svexl-node-kind
svex-env-fastlookup-wog
sv::svexlist-p
svexl-node-p
svexl-node-array-p
sv::svex-p)
())))
(local
(defthm lemma1
(implies (and (node-env-p node-env)
(hons-assoc-equal x node-env))
(4vec-p (cdr (hons-assoc-equal x node-env))))
:hints (("goal"
:in-theory (e/d (node-env-p) ()))))))
(define svexl-node-eval ((x svexl-node-p)
(node-env node-env-p)
(env sv::svex-env-p))
:measure (svexl-node-count x)
:verify-guards nil
:returns (res sv::4vec-p :hyp (and (svexl-node-p x)
(node-env-p node-env)
(sv::svex-env-p env)))
(svexl-node-case
x
:var (sv::svex-env-fastlookup x.name env)
:quote x.val
:node (svex-env-fastlookup-wog x.node-id node-env)
:call (sv::svex-apply
x.fn
(svexl-nodelist-eval x.args
node-env
env))))
(define svexl-nodelist-eval ((lst svexl-nodelist-p)
(node-env node-env-p)
(env sv::svex-env-p))
:returns (res sv::4veclist-p :hyp (and (svexl-nodelist-p lst)
(node-env-p node-env)
(sv::svex-env-p env)))
:measure (svexl-nodelist-count lst)
(if (atom lst)
nil
(cons (svexl-node-eval (car lst) node-env env)
(svexl-nodelist-eval (cdr lst) node-env env))))
///
(verify-guards svexl-node-eval))
(define svexl-node-alist-eval ((alist svexl-node-alist-p)
(node-env node-env-p)
(env sv::svex-env-p))
:returns (res sv::svex-env-p :hyp (and (svexl-node-alist-p alist)
(node-env-p node-env)
(sv::svex-env-p env)))
(if (atom alist)
nil
(acons (caar alist)
(svexl-node-eval (cdar alist)
node-env env)
(svexl-node-alist-eval (cdr alist)
node-env
env))))
(define svexl-eval-aux ((x svexl-node-array-p)
(env sv::svex-env-p))
:verify-guards nil
:prepwork
((local
(in-theory (e/d (svexl-node-array-p
node-env-p)
()))))
:returns (res-node-env node-env-p :hyp (and (svexl-node-array-p x)
(sv::svex-env-p env)))
(if (atom x)
nil
(b* ((node-env (svexl-eval-aux (cdr x) env))
(node-id (caar x))
(node (cdar x))
(eval-res (svexl-node-eval node node-env env)))
(hons-acons node-id eval-res node-env)))
///
(verify-guards svexl-eval-aux))
(define svexl-eval ((x svexl-p)
(env sv::svex-env-p))
:returns (res sv::4vec-p :hyp (and (svexl-p x)
(sv::svex-env-p env)))
(b* ((node (svexl->top-node x))
(node-array (svexl->node-array x))
(node-env (svexl-eval-aux node-array env))
(res (svexl-node-eval node node-env env))
(- (fast-alist-free node-env)))
res))
(define svexllist-eval ((x svexllist-p)
(env sv::svex-env-p))
:returns (res sv::4veclist-p :hyp (and (svexllist-p x)
(sv::svex-env-p env)))
(b* ((node-lst (svexllist->top-nodelist x))
(node-array (svexllist->node-array x))
(node-env (svexl-eval-aux node-array env))
(res (svexl-nodelist-eval node-lst node-env env))
(- (fast-alist-free node-env)))
res))
(define svexl-alist-eval ((x svexl-alist-p)
(env sv::svex-env-p))
:returns (res sv::svex-env-p :hyp (and (svexl-alist-p x)
(sv::svex-env-p env)))
(b* ((top-node-alist (svexl-alist->top-node-alist x))
(node-array (svexl-alist->node-array x))
(node-env (svexl-eval-aux node-array env))
(res (svexl-node-alist-eval top-node-alist node-env env))
(- (fast-alist-free node-env)))
res))
;; Example:
#|
(b* ((svex #!SV'(bitor (bitand (bitor a b) (bitor (bitor a b)
(bitor a b)))
(bitor (bitor a b)
(bitor a b))))
(env (make-fast-alist #!SV`((a . 12312321) (b . 331312312))))
(svexl (svex-to-svexl svex)))
`((svex-eval ,(svex-eval svex env))
(svexl-eval ,(svexl-eval svexl env))
(svexl ,svexl)))||#
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Eval functions without guards:
(define svexl-node-kind-wog (x)
:returns kind
:inline t
:guard-hints
(("goal" :in-theory
(disable fty::open-member-equal-on-list-of-tags))
(and stable-under-simplificationp
'(:expand ((svex-p x)))))
:progn t
(cond ((if (atom x)
(or (stringp x) (and x (symbolp x)))
(eq (car x) :var))
:var)
((or (atom x) (integerp (car x)))
:quote)
((and (consp x)
(consp (cdr x))
(not (cddr x))
(eq (car x) ':node))
:node)
(t :call)))
(def-rp-rule$ t nil
svexl-node-kind-is-svexl-node-kind-wog
(equal (svexl-node-kind x)
(svexl-node-kind-wog x))
:hints (("Goal"
:in-theory (e/d (svexl-node-kind-wog
svexl-node-kind) ()))))
(defthmd svexl-node-kind-wog-is-svexl-node-kind
(equal (svexl-node-kind-wog x)
(svexl-node-kind x))
:hints (("Goal"
:in-theory (e/d (svexl-node-kind-wog
svexl-node-kind) ()))))
(acl2::defines
svexl-node-eval-wog
:flag-local nil
:flag-defthm-macro defthm-svexl-node-eval-wog
:prepwork
((local
(in-theory (e/d (svexl-node-kind
sv::svexlist-p
svexl-node-p
svexl-node-array-p
svexl-node-kind-wog-is-svexl-node-kind
sv::svex-p)
()))))
(define svexl-node-eval-wog ((x)
(node-env)
(env))
:measure (acl2-count x)
:verify-guards nil
(b* ((kind (svexl-node-kind-wog x)))
(cond ((eq kind :var)
(svex-env-fastlookup-wog x env))
((eq kind :quote) x)
((eq kind :node)
(svex-env-fastlookup-wog (cadr x) node-env))
(t
(b* ((x.fn (car x))
(x.args (cdr x)))
(svex-apply-wog
x.fn
(svexl-nodelist-eval-wog x.args node-env env)))))))
(define svexl-nodelist-eval-wog ((lst)
(node-env)
(env))
:measure (acl2-count lst)
(if (atom lst)
nil
(cons (svexl-node-eval-wog (car lst) node-env env)
(svexl-nodelist-eval-wog (cdr lst) node-env env))))
///
;; openers:
(def-rp-rule svexl-eval-node-of-var
(implies (eq (svexl-node-kind-wog x) ':var)
(equal (svexl-node-eval-wog x node-env env-wires)
(let ((entry (hons-get x env-wires)))
(if entry (cdr entry)
(sv::4vec-x)))))
:hints (("goal"
:expand (svexl-node-eval-wog x node-env env-wires)
:in-theory (e/d (svex-env-fastlookup-wog) ()))))
(def-rp-rule svexl-eval-node-of-node
(implies (eq (svexl-node-kind-wog x) ':node)
(equal (svexl-node-eval-wog x node-env env-wires)
(let ((entry (hons-get (cadr x) node-env)))
(if entry (cdr entry)
(sv::4vec-x)))))
:hints (("goal"
:expand (svexl-node-eval-wog x node-env env-wires)
:in-theory (e/d (svex-env-fastlookup-wog) ()))))
(def-rp-rule svexl-eval-node-of-quoted
(implies (eq (svexl-node-kind-wog x) ':quote)
(equal (svexl-node-eval-wog x node-env env-wires)
x))
:hints (("goal"
:expand (svexl-node-eval-wog x node-env env-wires)
:in-theory (e/d (svex-env-fastlookup-wog) ()))))
(def-rp-rule svexl-eval-node-of-call
(implies (eq (svexl-node-kind-wog x) ':call)
(equal (svexl-node-eval-wog x node-env env)
(svex-apply-wog
(car x)
(svexl-nodelist-eval-wog (cdr x) node-env env))))
:hints (("goal"
:expand (svexl-node-eval-wog x node-env env)
:in-theory (e/d (svex-env-fastlookup-wog) ()))))
(def-rp-rule svexl-nodelist-eval-wog-of-cons
(equal (svexl-nodelist-eval-wog (cons x rest) node-env env)
(cons (svexl-node-eval-wog x node-env env)
(svexl-nodelist-eval-wog rest node-env env)))
:hints (("Goal"
:expand (svexl-nodelist-eval-wog (cons x rest) node-env env)
:in-theory (e/d () ()))))
(def-rp-rule svexl-nodelist-eval-wog-of-nil
(equal (svexl-nodelist-eval-wog nil node-env env)
nil)
:hints (("Goal"
:expand (svexl-nodelist-eval-wog nil node-env env)
:in-theory (e/d () ()))))
(verify-guards svexl-node-eval-wog))
(define svexl-node-alist-eval-wog ((alist alistp)
(node-env)
(env))
:measure (acl2-count alist)
(if (atom alist)
nil
(acons
(caar alist)
(svexl-node-eval-wog (cdar alist) node-env env)
(svexl-node-alist-eval-wog (cdr alist) node-env env)))
///
(def-rp-rule svexl-node-alist-eval-wog-of-cons
(equal (svexl-node-alist-eval-wog (cons x rest) node-env env)
(acons
(car x)
(svexl-node-eval-wog (cdr x) node-env env)
(svexl-node-alist-eval-wog rest node-env env)))
:hints (("Goal"
:expand (svexl-node-alist-eval-wog (cons x rest) node-env env)
:in-theory (e/d () ()))))
(def-rp-rule svexl-node-alist-eval-wog-of-nil
(equal (svexl-node-alist-eval-wog nil node-env env)
nil)
:hints (("Goal"
:expand (svexl-node-alist-eval-wog nil node-env env)
:in-theory (e/d () ()))))
)
(defthm-svexl-node-eval-wog
(defthm svexl-node-eval-is-svexl-node-eval-wog
(implies (and (svexl-node-p x)
(sv::svex-env-p env))
(equal (svexl-node-eval x node-env env)
(svexl-node-eval-wog x node-env env)))
:flag svexl-node-eval-wog)
(defthm svexl-nodelist-eval-is-svexl-nodelist-eval-wog
(implies (and (svexl-nodelist-p lst)
(sv::svex-env-p env))
(equal (svexl-nodelist-eval lst node-env env)
(svexl-nodelist-eval-wog lst node-env env)))
:flag svexl-nodelist-eval-wog)
:hints (("goal"
:expand ((svexl-node-eval x node-env env))
:in-theory (e/d (svex-call->fn
svexl-nodelist-fix
svexl-node-var->name
svexl-node-quote->val
svexl-node-call->args
svexl-nodelist-p
svexl-node-call->fn
svexl-node-node->node-id
svexl-node-p
svex-kind
svex-env-fastlookup-wog
svex-eval-wog
SVEX-APPLY-IS-SVEX-APPLY-WOG
svex-env-lookup-is-svex-env-fastlookup-wog
svexl-node-kind-wog-is-svexl-node-kind
svexlist-eval-wog
svexl-node-eval
svexl-node-kind
svexl-node-eval-wog
svex-p
sv::svar-p
svex-eval
svex-var->name
sv::svex-quote->val
svex-call->args
svexl-nodelist-eval
svexl-nodelist-eval-wog)
()))))
(rp::add-rp-rule svexl-node-eval-is-svexl-node-eval-wog)
(rp::add-rp-rule svexl-nodelist-eval-is-svexl-nodelist-eval-wog)
(def-rp-rule svexl-node-alist-eval-is-svexl-node-alist-eval-wog
(implies (and (svexl-node-alist-p alist)
(sv::svex-env-p env))
(equal (svexl-node-alist-eval alist node-env env)
(svexl-node-alist-eval-wog alist node-env env)))
:hints (("Goal"
:in-theory (e/d (svexl-node-alist-eval
svexl-node-alist-p
svexl-node-alist-eval-wog)
()))))
(define svexl-eval-aux-wog ((x alistp)
(env))
:prepwork
((local
(in-theory (e/d (svexl-node-array-p
node-env-p)
()))))
(if (atom x)
nil
(b* ((node-env
(svexl-eval-aux-wog (cdr x) env))
(node-id (caar x))
(node (cdar x))
(eval-res (svexl-node-eval-wog node node-env env)))
(hons-acons node-id eval-res node-env)))
///
(def-rp-rule$ t nil
svexl-eval-aux-is-svexl-eval-aux-wog
(implies (and (svexl-node-array-p x)
(sv::svex-env-p env))
(equal (svexl-eval-aux x env)
(svexl-eval-aux-wog x env)))
:hints (("Goal"
:in-theory (e/d (svexl-eval-aux
svexl-eval-aux-wog) ()))))
(rp::defthm-lambda
svexl-eval-aux-wog-cons
(equal (svexl-eval-aux-wog (cons (cons node-id node) rest) env)
(b* ((node-env (svexl-eval-aux-wog rest env))
(eval-res (svexl-node-eval-wog node node-env env)))
(hons-acons node-id eval-res node-env))))
(def-rp-rule
svexl-eval-aux-wog-nil
(equal (svexl-eval-aux-wog nil env)
nil)))
(define svexl-eval-wog ((x)
(env))
:verify-guards nil
(b* ((node (cdar x))
(node-array (cdr (cadr x)))
(node-env (svexl-eval-aux-wog node-array env))
(res (svexl-node-eval-wog node node-env env))
(- (fast-alist-free node-env)))
res)
///
(def-rp-rule$ t nil
svexl-eval-is-svexl-eval-wog
(implies (and (svexl-p x)
(sv::svex-env-p env))
(equal (svexl-eval x env)
(svexl-eval-wog x env)))
:hints (("Goal"
:in-theory (e/d (svexl-eval
svexl->top-node
svexl->node-array
svexl-p
svexl-eval-wog
SVEXL-EVAL-AUX-IS-SVEXL-EVAL-AUX-WOG)
()))))
(defthmd svexl-eval-wog-is-svexl-eval
(implies (and (svexl-p x)
(sv::svex-env-p env))
(equal (svexl-eval-wog x env)
(svexl-eval x env)))
:hints (("Goal"
:in-theory (e/d (svexl-eval-is-svexl-eval-wog)
()))))
(set-ignore-ok t)
(add-rp-rule svexl-eval-wog :beta-reduce t))
(define svexllist-eval-wog ((x)
(env))
:verify-guards nil
(b* ((node-lst (cdr (car x)))
(node-array (cdr (cadr x)))
(node-env (svexl-eval-aux-wog node-array env))
(res (svexl-nodelist-eval-wog node-lst node-env env))
(- (fast-alist-free node-env)))
res)
///
(def-rp-rule$ t nil
svexllist-eval-is-svexllist-eval-wog
(implies (and (svexllist-p x)
(sv::svex-env-p env))
(equal (svexllist-eval x env)
(svexllist-eval-wog x env)))
:hints (("Goal"
:in-theory (e/d (svexllist-eval
SVEXLLIST->TOP-NODELIST
SVEXLLIST->NODE-ARRAY
SVEXLLIST-P
svexllist-eval-wog
SVEXL-EVAL-AUX-IS-SVEXL-EVAL-AUX-WOG)
()))))
(set-ignore-ok t)
(add-rp-rule svexllist-eval-wog :beta-reduce t))
(define svexl-alist-eval-wog ((x)
(env))
:verify-guards nil
(b* ((top-node-alist (cdar x))
(node-array (cdr (cadr x)))
(node-env (svexl-eval-aux-wog node-array env))
(res (svexl-node-alist-eval-wog top-node-alist node-env env))
(- (fast-alist-free node-env)))
res)
///
(def-rp-rule$ t nil
svexl-alist-eval-is-svexl-alist-eval-wog
(implies (and (svexl-alist-p x)
(sv::svex-env-p env))
(equal (svexl-alist-eval x env)
(svexl-alist-eval-wog x env)))
:hints (("Goal"
:in-theory (e/d (svexl-alist-eval
SVEXL-ALIST-P
SVEXL-ALIST->NODE-ARRAY
svexl-alist-eval-wog
SVEXL-ALIST->TOP-NODE-ALIST
svexl-node-alist-eval-is-svexl-node-alist-eval-wog
SVEXL-EVAL-AUX-IS-SVEXL-EVAL-AUX-WOG)
()))))
(set-ignore-ok t)
(add-rp-rule svexl-alist-eval-wog :beta-reduce t))
(memoize 'svexl-alist-p)
(memoize 'svexllist-p)
(memoize 'svexl-p)
(defthm-svexl-node-eval-wog
(defthm svex-p-implies-svexl-node-p
(implies (svex-p x)
(svexl-node-p x))
:flag svexl-node-eval-wog)
(defthm svexlist-p-implies-svexl-nodelist-p
(implies (svexlist-p lst)
(svexl-nodelist-p lst))
:flag svexl-nodelist-eval-wog)
:rule-classes :type-prescription
:hints (("Goal"
:in-theory (e/d (svex-p
svexl-node-kind-wog-is-svexl-node-kind
svexlist-p
svexl-nodelist-p
svexl-node-p
svexl-node-kind
svex-kind) ()))))
| true |
; SVL - Listener-based Hierachical Symbolic Vector Hardware Analysis Framework
; Copyright (C) 2019 Centaur Technology
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
(in-package "SVL")
(include-book "../svex-eval-wog")
(fty::deftypes
svexl-node
:prepwork ((local
(defthm integerp-implies-4vecp
(implies (integerp x)
(4vec-p x))
:hints (("Goal"
:in-theory (e/d (4vec-p) ())))))
(local (defthm car-of-svar-when-consp
(implies (and (sv::svar-p x)
(consp x)
(syntaxp (quotep v)))
(equal (equal (car x) v)
(equal v :var)))
:hints(("Goal" :in-theory (enable sv::svar-p)))))
(local (defthm 4vec-not-svar-p
(implies (sv::svar-p x)
(not (4vec-p x)))
:hints(("Goal" :in-theory (enable 4vec-p sv::svar-p)))))
(local (defthm cons-fnsym-not-svar-p
(implies (not (eq x :var))
(not (sv::svar-p (cons x y))))
:hints(("Goal" :in-theory (enable fnsym-p sv::svar-p)))))
(local (defthm car-of-4vec-fix-integerp
(implies (consp (4vec-fix x))
(integerp (car (4vec-fix x))))
:hints(("Goal" :in-theory (enable 4vec-fix 4vec)))))
(local (defthm car-of-4vec-fix-type
(or (integerp (car (4vec-fix x)))
(not (car (4vec-fix x))))
:hints(("Goal" :in-theory (enable 4vec-fix 4vec)))
:rule-classes ((:type-prescription :typed-term (car (4vec-fix x)))))))
(fty::defflexsum
svexl-node
(:var
:short "A variable, which represents a @(see 4vec)."
:cond (if (atom x)
(or (stringp x)
(and x (symbolp x)))
(eq (car x) :var))
:fields ((name :acc-body x :type sv::svar-p))
:ctor-body name)
(:quote
:short "A ``quoted constant'' @(see 4vec), which represents itself."
:cond (or (atom x)
(integerp (car x)))
:fields ((val :acc-body x
:type 4vec))
:ctor-body val)
(:node
:cond (and (consp x)
(consp (cdr x))
(not (cddr x))
(eq (car x) ':node))
:fields ((node-id :acc-body (cadr x) :type natp))
:ctor-body (hons ':node (hons node-id nil)))
(:call
:short "A function applied to some expressions."
:cond t
:fields ((fn :acc-body (car x)
:type sv::fnsym)
(args :acc-body (cdr x)
:type svexl-nodelist))
:ctor-body (hons fn args)))
(fty::deflist svexl-nodelist
:elt-type svexl-node
:true-listp t))
(fty::defalist svexl-node-array
:key-type natp
:val-type svexl-node
:true-listp t)
(fty::defalist svexl-node-alist
:key-type sv::svar-p
:val-type svexl-node
:true-listp t)
(fty::defprod
svexl
((top-node svexl-node)
(node-array svexl-node-array)))
(fty::defprod
svexllist
((top-nodelist svexl-nodelist)
(node-array svexl-node-array)))
(fty::defprod
svexl-alist
((top-node-alist svexl-node-alist)
(node-array svexl-node-array)))
(define reuse-statsp (x)
:enabled t
(if (atom x)
(eq x nil)
(and (consp (car x))
(natp (cdar x))
(svex-p (caar x))
(reuse-statsp (cdr x)))))
(define nodesdb-p (x)
:enabled t
(reuse-statsp x)
///
(defthm nodesdb-p-implies-reuse-statsp
(implies (nodesdb-p x)
(reuse-statsp x))))
(define reverse-nodesdb-p (x)
:enabled t
(if (atom x)
(eq x nil)
(and (consp (car x))
(natp (caar x))
(svex-p (cdar x))
(reverse-nodesdb-p (cdr x)))))
(define node-env-p (x)
:measure (acl2-count x)
(if (atom x)
(eq x nil)
(and (consp (car x))
(natp (caar x))
(4vec-p (cdar x))
(node-env-p (cdr x)))))
(acl2::defines
svex-to-svexl-get-stats
:prepwork
((local
(in-theory (e/d (sv::svex-kind
sv::svexlist-p
sv::svex-p)
())))
(local
(defthm lemma1
(implies (and (hons-assoc-equal svex acc)
(reuse-statsp acc))
(and (natp (+ 1 (cdr (hons-assoc-equal svex acc))))
(natp (cdr (hons-assoc-equal svex acc))))))))
(define svex-to-svexl-get-stats ((acc reuse-statsp)
(svex svex-p))
:measure (sv::svex-count svex)
:verify-guards nil
:returns (res-acc reuse-statsp :hyp (and (reuse-statsp acc)
(svex-p svex)))
(sv::svex-case
svex
:var acc
:quote acc
:call (b* ((entry (hons-get svex acc)))
(if entry
(hons-acons svex (1+ (cdr entry)) acc)
(svex-to-svexl-get-stats-lst (hons-acons svex 1 acc)
svex.args)))))
(define svex-to-svexl-get-stats-lst ((acc reuse-statsp)
(lst sv::svexlist-p))
:returns (res-acc reuse-statsp :hyp (and (reuse-statsp acc)
(sv::svexlist-p lst)))
:measure (sv::svexlist-count lst)
(if (atom lst)
acc
(b* ((acc (svex-to-svexl-get-stats acc (car lst)))
(acc (svex-to-svexl-get-stats-lst acc (cdr lst))))
acc)))
///
(verify-guards svex-to-svexl-get-stats))
(define should-be-an-svexl-node ((reuse-stats reuse-statsp)
(svex svex-p))
:inline t
(b* ((reuse-stats-entry (hons-get svex reuse-stats)))
(and reuse-stats-entry
(> (cdr reuse-stats-entry) 1))))
(acl2::defines
svex-to-svexl-aux
:flag-defthm-macro defthm-svex-to-svexl-aux
:flag-local nil
:prepwork
((local
(in-theory (e/d (svex-kind
sv::svexlist-p
svexl-node-p
svexl-node-array-p
sv::svex-p)
(natp))))
(local
(defthm lemma1
(implies (and (hons-assoc-equal svex nodesdb)
(reuse-statsp nodesdb))
(natp (cdr (hons-assoc-equal svex nodesdb)))))))
(define svex-to-svexl-aux ((svex svex-p)
(reuse-stats reuse-statsp)
(nodesdb nodesdb-p)
(svexl-node-array svexl-node-array-p)
(cnt natp))
:guard (equal cnt (len svexl-node-array))
:verify-guards nil ;;verified below.
:measure (sv::svex-count svex)
:returns (mv (res-svex svexl-node-p
:hyp (and (svex-p svex)
(nodesdb-p nodesdb)
#|(natp cnt)||#))
(nodesdb-res nodesdb-p
:hyp (and (svex-p svex)
#|(natp cnt)||#
(nodesdb-p nodesdb)))
(svexl-res svexl-node-array-p
:hyp (and (svex-p svex)
(svexl-node-array-p svexl-node-array)
(nodesdb-p nodesdb)
#|(natp cnt)||#))
(cnt-res natp #|:hyp||# #|(natp cnt)||#))
(b* ((cnt (mbe :exec cnt
:logic (len svexl-node-array))))
(sv::svex-case
svex
:quote (mv svex nodesdb svexl-node-array cnt)
:var (mv svex nodesdb svexl-node-array cnt)
:call (b* ((nodesdb-entry (hons-get svex nodesdb))
((when nodesdb-entry)
(mv (make-svexl-node-node :node-id (cdr nodesdb-entry))
nodesdb svexl-node-array cnt))
((mv rest-node nodesdb svexl-node-array cnt)
(svex-to-svexl-aux-lst svex.args reuse-stats nodesdb svexl-node-array cnt))
(cnt (mbe :exec cnt :logic (len svexl-node-array)))
(new-node (make-svexl-node-call
:fn svex.fn
:args rest-node)))
(if (should-be-an-svexl-node reuse-stats svex)
(mv (make-svexl-node-node :node-id cnt)
(hons-acons svex cnt nodesdb)
(hons-acons cnt new-node svexl-node-array)
(1+ cnt))
(mv new-node nodesdb svexl-node-array cnt))))))
(define svex-to-svexl-aux-lst ((lst svexlist-p)
(reuse-stats reuse-statsp)
(nodesdb nodesdb-p)
(svexl-node-array svexl-node-array-p)
(cnt natp))
:measure (sv::svexlist-count lst)
:returns (mv (res-svexlst svexl-nodelist-p
:hyp (and (svexlist-p lst)
(nodesdb-p nodesdb)
(natp cnt)))
(nodesdb-res nodesdb-p
:hyp (and (svexlist-p lst)
(natp cnt)
(nodesdb-p nodesdb)))
(svexl-res svexl-node-array-p
:hyp (and (svexlist-p lst)
(nodesdb-p nodesdb)
(svexl-node-array-p svexl-node-array)
(natp cnt)))
(cnt-res natp :hyp (natp cnt)))
:guard (equal cnt (len svexl-node-array))
(b* ((cnt (mbe :exec cnt
:logic (len svexl-node-array))))
(if (atom lst)
(mv nil nodesdb svexl-node-array cnt)
(b* (((mv new-car-lst nodesdb svexl-node-array cnt)
(svex-to-svexl-aux
(car lst) reuse-stats nodesdb svexl-node-array cnt))
(cnt (mbe :exec cnt
:logic (len svexl-node-array)))
((mv new-cdr-lst nodesdb svexl-node-array cnt)
(svex-to-svexl-aux-lst
(cdr lst) reuse-stats nodesdb svexl-node-array cnt))
(cnt (mbe :exec cnt
:logic (len svexl-node-array))))
(mv (cons new-car-lst
new-cdr-lst)
nodesdb svexl-node-array cnt)))))
///
(local
(defthm lemma2
(implies (natp x)
(rationalp x))))
(defthm-svex-to-svexl-aux
(defthm return-cnt-of-svex-to-svexl-aux
(implies (equal (len svexl-node-array) cnt)
(equal (mv-nth 3 (svex-to-svexl-aux
svex reuse-stats nodesdb svexl-node-array cnt))
(len (mv-nth 2 (svex-to-svexl-aux
svex reuse-stats nodesdb svexl-node-array cnt)))))
:flag svex-to-svexl-aux)
(defthm return-cnt-of-svex-to-svexl-aux-lst
(and
(true-listp (mv-nth 0 (svex-to-svexl-aux-lst
lst reuse-stats nodesdb svexl-node-array cnt)))
(equal (len (mv-nth 0 (svex-to-svexl-aux-lst
lst reuse-stats nodesdb svexl-node-array cnt)))
(len lst))
(implies (equal (len svexl-node-array) cnt)
(equal (mv-nth 3 (svex-to-svexl-aux-lst
lst reuse-stats nodesdb svexl-node-array cnt))
(len (mv-nth 2 (svex-to-svexl-aux-lst
lst reuse-stats nodesdb svexl-node-array cnt))))))
:flag svex-to-svexl-aux-lst))
(verify-guards svex-to-svexl-aux))
(define svex-to-svexl ((svex svex-p))
:returns (svexl svexl-p :hyp (svex-p svex))
(b* ((svex (hons-copy svex))
(reuse-stats (svex-to-svexl-get-stats nil svex))
((mv new-node nodesdb svexl-node-array ?cnt)
(svex-to-svexl-aux svex reuse-stats nil
nil 0))
(- (fast-alist-free nodesdb))
(- (fast-alist-free svexl-node-array))
(- (fast-alist-free reuse-stats))
(svexl (make-svexl
:top-node new-node
:node-array svexl-node-array)))
svexl))
(define svexlist-to-svexllist ((svexlist svexlist-p))
:returns (svexl svexllist-p :hyp (svexlist-p svexlist))
(b* ((svexlist (hons-copy svexlist))
(reuse-stats (svex-to-svexl-get-stats-lst nil svexlist))
((mv new-node-lst nodesdb svexl-node-array ?cnt)
(svex-to-svexl-aux-lst svexlist reuse-stats nil
nil 0))
(- (fast-alist-free nodesdb))
(- (fast-alist-free svexl-node-array))
(- (fast-alist-free reuse-stats))
(svexllist (make-svexllist
:top-nodelist new-node-lst
:node-array svexl-node-array)))
svexllist))
(define svex-alist-to-svexl-alist ((svex-alist sv::svex-alist-p))
:prepwork
((local
(defthm lemma1
(implies (and (sv::svarlist-p svarlist)
(svexl-nodelist-p nodelist)
(equal (len svarlist)
(len nodelist)))
(svexl-node-alist-p (pairlis$ svarlist nodelist)))
:hints (("Goal"
:induct (pairlis$ svarlist nodelist)
:in-theory (e/d (svexl-node-alist-p
svexl-nodelist-p
sv::svarlist-p)
())))))
(local
(defthm lemma2
(implies (SV::SVEX-ALIST-P SVEX-ALIST)
(and (EQUAL (LEN (STRIP-CARS SVEX-ALIST))
(LEN (STRIP-CDRS SVEX-ALIST)))
(SV::SVARLIST-P (STRIP-CARS SVEX-ALIST))
(SVEXLIST-P (STRIP-CDRS SVEX-ALIST))))
:hints (("Goal"
:in-theory (e/d (SV::SVEX-ALIST-P
SVEXLIST-P
SV::SVARLIST-P)
()))))))
:guard-hints (("Goal"
:do-not-induct t
:in-theory (e/d () ())))
:returns (svexl-alist svexl-alist-p :hyp (sv::svex-alist-p svex-alist))
(b* ((keys (strip-cars svex-alist))
(svexlist (strip-cdrs svex-alist))
(svexlist (hons-copy svexlist))
(reuse-stats (svex-to-svexl-get-stats-lst nil svexlist))
((mv new-node-lst nodesdb svexl-node-array ?cnt)
(svex-to-svexl-aux-lst svexlist reuse-stats nil
nil 0))
(top-node-alist (pairlis$ keys new-node-lst))
(- (fast-alist-free nodesdb))
(- (fast-alist-free svexl-node-array))
(- (fast-alist-free reuse-stats))
(svexl-alist (make-svexl-alist
:top-node-alist top-node-alist
:node-array svexl-node-array)))
svexl-alist))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Svexl to Svex functions (convert back)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(acl2::defines
svexl-node-to-svex
:flag-local nil
:flag-defthm-macro defthm-svexl-node-to-svex
:prepwork
((local
(in-theory (e/d ( ;svexl-node-kind
sv::svexlist-p
svexl-node-p
reverse-nodesdb-p
svexl-node-array-p
sv::svex-p)
())))
(local
(defthm lemma1
(implies (and
(hons-assoc-equal x
reverse-nodesdb)
(reverse-nodesdb-p reverse-nodesdb))
(svex-p (cdr (hons-assoc-equal x
reverse-nodesdb))))
:hints (("Goal"
:induct (reverse-nodesdb-p reverse-nodesdb)
:do-not-induct t
:in-theory (e/d () ())))))
(local
(defthm lemma2
(implies (and (equal (svexl-node-kind x) :var)
(svexl-node-p x))
(svex-p x))
:hints (("Goal"
:in-theory (e/d (svexl-node-p svex-p svexl-node-kind) ())))))
(local
(defthm lemma3
(implies (and (equal (svexl-node-kind x) :quote)
(svexl-node-p x))
(svex-p (svexl-node-quote->val x)))
:hints (("Goal"
:in-theory (e/d (svexl-node-p svex-p svexl-node-quote->val 4vec-p svexl-node-kind) ())))))
)
(define svexl-node-to-svex ((x svexl-node-p)
(reverse-nodesdb reverse-nodesdb-p))
:measure (svexl-node-count x)
:verify-guards nil
:returns (res sv::svex-p :hyp (and (svexl-node-p x)
(reverse-nodesdb-p reverse-nodesdb)))
(svexl-node-case
x
:var x
:quote x.val
:node (b* ((node (hons-get x.node-id reverse-nodesdb)))
(if node
(cdr node)
(sv::4vec-x)))
:call (cons
x.fn
(svexl-nodelist-to-svexlist x.args
reverse-nodesdb))))
(define svexl-nodelist-to-svexlist ((lst svexl-nodelist-p)
(reverse-nodesdb reverse-nodesdb-p))
:returns (res sv::svexlist-p :hyp (and (svexl-nodelist-p lst)
(reverse-nodesdb-p reverse-nodesdb)))
:measure (svexl-nodelist-count lst)
(if (atom lst)
nil
(cons (svexl-node-to-svex (car lst) reverse-nodesdb)
(svexl-nodelist-to-svexlist (cdr lst) reverse-nodesdb))))
///
(verify-guards svexl-node-to-svex))
(define svexl-to-svex-aux ((x svexl-node-array-p))
:verify-guards nil
:prepwork
((local
(in-theory (e/d (svexl-node-array-p
node-env-p)
()))))
:returns (reverse-nodesdb reverse-nodesdb-p :hyp (svexl-node-array-p x))
(if (atom x)
nil
(b* ((reverse-nodesdb (svexl-to-svex-aux (cdr x)))
(node-id (caar x))
(node (cdar x))
(res (svexl-node-to-svex node reverse-nodesdb)))
(hons-acons node-id res reverse-nodesdb)))
///
(verify-guards svexl-to-svex-aux))
(define svexl-to-svex ((svexl svexl-p))
:returns (svex svex-p :hyp (svexl-p svexl))
(b* ((node (svexl->top-node svexl))
(node-array (svexl->node-array svexl))
(reverse-nodesdb (svexl-to-svex-aux node-array))
(res (svexl-node-to-svex node reverse-nodesdb))
(- (fast-alist-free reverse-nodesdb)))
res))
(define svexllist-to-svexlist ((svexllist svexllist-p))
:returns (svexlist svexlist-p :hyp (svexllist-p svexllist))
(b* ((top-nodelist (svexllist->top-nodelist svexllist))
(node-array (svexllist->node-array svexllist))
(reverse-nodesdb (svexl-to-svex-aux node-array))
(res (svexl-nodelist-to-svexlist top-nodelist reverse-nodesdb))
(- (fast-alist-free reverse-nodesdb)))
res))
(define svexl-alist-to-svex-alist ((svexl-alist svexl-alist-p))
:returns (svex-alist sv::svex-alist-p :hyp (svexl-alist-p svexl-alist))
:prepwork
((local
(progn
(defthm lemma1
(IMPLIES
(SVEXL-NODE-ALIST-P node-alist)
(SVEXL-NODELIST-P (STRIP-CDRS node-alist)))
:hints (("Goal"
:in-theory (e/d (SVEXL-NODE-ALIST-P SVEXL-NODELIST-P)
()))))
(defthm lemma2
(implies (svexl-node-alist-p alist)
(and (SV::SVARLIST-P (STRIP-CARS alist))
(SVEXL-NODELIST-P (STRIP-CDRS alist))))
:hints (("Goal"
:in-theory (e/d (svexl-node-alist-p) ()))))
(defthm len-of-svexl-nodelist-to-svexlist
(equal (len (svexl-nodelist-to-svexlist lst r))
(len lst))
:hints (("Goal"
:induct (len lst)
:in-theory (e/d (svexl-nodelist-to-svexlist) ()))))
(defthm len-of-strip-cars
(equal (len (strip-cars x))
(len x)))
(defthm len-of-strip-cdrs
(equal (len (strip-cdrs x))
(len x))))))
(b* ((top-node-alist (svexl-alist->top-node-alist svexl-alist))
(node-array (svexl-alist->node-array svexl-alist))
(reverse-nodesdb (svexl-to-svex-aux node-array))
(top-nodelist (strip-cdrs top-node-alist))
(keys (strip-cars top-node-alist))
(res (svexl-nodelist-to-svexlist top-nodelist reverse-nodesdb))
(- (fast-alist-free reverse-nodesdb)))
(pairlis$ keys res)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Eval functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(acl2::defines
svexl-node-eval
:flag-local nil
:flag-defthm-macro defthm-svexl-node-eval
:prepwork
((local
(in-theory (e/d (svexl-node-kind
svex-env-fastlookup-wog
sv::svexlist-p
svexl-node-p
svexl-node-array-p
sv::svex-p)
())))
(local
(defthm lemma1
(implies (and (node-env-p node-env)
(hons-assoc-equal x node-env))
(4vec-p (cdr (hons-assoc-equal x node-env))))
:hints (("goal"
:in-theory (e/d (node-env-p) ()))))))
(define svexl-node-eval ((x svexl-node-p)
(node-env node-env-p)
(env sv::svex-env-p))
:measure (svexl-node-count x)
:verify-guards nil
:returns (res sv::4vec-p :hyp (and (svexl-node-p x)
(node-env-p node-env)
(sv::svex-env-p env)))
(svexl-node-case
x
:var (sv::svex-env-fastlookup x.name env)
:quote x.val
:node (svex-env-fastlookup-wog x.node-id node-env)
:call (sv::svex-apply
x.fn
(svexl-nodelist-eval x.args
node-env
env))))
(define svexl-nodelist-eval ((lst svexl-nodelist-p)
(node-env node-env-p)
(env sv::svex-env-p))
:returns (res sv::4veclist-p :hyp (and (svexl-nodelist-p lst)
(node-env-p node-env)
(sv::svex-env-p env)))
:measure (svexl-nodelist-count lst)
(if (atom lst)
nil
(cons (svexl-node-eval (car lst) node-env env)
(svexl-nodelist-eval (cdr lst) node-env env))))
///
(verify-guards svexl-node-eval))
(define svexl-node-alist-eval ((alist svexl-node-alist-p)
(node-env node-env-p)
(env sv::svex-env-p))
:returns (res sv::svex-env-p :hyp (and (svexl-node-alist-p alist)
(node-env-p node-env)
(sv::svex-env-p env)))
(if (atom alist)
nil
(acons (caar alist)
(svexl-node-eval (cdar alist)
node-env env)
(svexl-node-alist-eval (cdr alist)
node-env
env))))
(define svexl-eval-aux ((x svexl-node-array-p)
(env sv::svex-env-p))
:verify-guards nil
:prepwork
((local
(in-theory (e/d (svexl-node-array-p
node-env-p)
()))))
:returns (res-node-env node-env-p :hyp (and (svexl-node-array-p x)
(sv::svex-env-p env)))
(if (atom x)
nil
(b* ((node-env (svexl-eval-aux (cdr x) env))
(node-id (caar x))
(node (cdar x))
(eval-res (svexl-node-eval node node-env env)))
(hons-acons node-id eval-res node-env)))
///
(verify-guards svexl-eval-aux))
(define svexl-eval ((x svexl-p)
(env sv::svex-env-p))
:returns (res sv::4vec-p :hyp (and (svexl-p x)
(sv::svex-env-p env)))
(b* ((node (svexl->top-node x))
(node-array (svexl->node-array x))
(node-env (svexl-eval-aux node-array env))
(res (svexl-node-eval node node-env env))
(- (fast-alist-free node-env)))
res))
(define svexllist-eval ((x svexllist-p)
(env sv::svex-env-p))
:returns (res sv::4veclist-p :hyp (and (svexllist-p x)
(sv::svex-env-p env)))
(b* ((node-lst (svexllist->top-nodelist x))
(node-array (svexllist->node-array x))
(node-env (svexl-eval-aux node-array env))
(res (svexl-nodelist-eval node-lst node-env env))
(- (fast-alist-free node-env)))
res))
(define svexl-alist-eval ((x svexl-alist-p)
(env sv::svex-env-p))
:returns (res sv::svex-env-p :hyp (and (svexl-alist-p x)
(sv::svex-env-p env)))
(b* ((top-node-alist (svexl-alist->top-node-alist x))
(node-array (svexl-alist->node-array x))
(node-env (svexl-eval-aux node-array env))
(res (svexl-node-alist-eval top-node-alist node-env env))
(- (fast-alist-free node-env)))
res))
;; Example:
#|
(b* ((svex #!SV'(bitor (bitand (bitor a b) (bitor (bitor a b)
(bitor a b)))
(bitor (bitor a b)
(bitor a b))))
(env (make-fast-alist #!SV`((a . 12312321) (b . 331312312))))
(svexl (svex-to-svexl svex)))
`((svex-eval ,(svex-eval svex env))
(svexl-eval ,(svexl-eval svexl env))
(svexl ,svexl)))||#
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Eval functions without guards:
(define svexl-node-kind-wog (x)
:returns kind
:inline t
:guard-hints
(("goal" :in-theory
(disable fty::open-member-equal-on-list-of-tags))
(and stable-under-simplificationp
'(:expand ((svex-p x)))))
:progn t
(cond ((if (atom x)
(or (stringp x) (and x (symbolp x)))
(eq (car x) :var))
:var)
((or (atom x) (integerp (car x)))
:quote)
((and (consp x)
(consp (cdr x))
(not (cddr x))
(eq (car x) ':node))
:node)
(t :call)))
(def-rp-rule$ t nil
svexl-node-kind-is-svexl-node-kind-wog
(equal (svexl-node-kind x)
(svexl-node-kind-wog x))
:hints (("Goal"
:in-theory (e/d (svexl-node-kind-wog
svexl-node-kind) ()))))
(defthmd svexl-node-kind-wog-is-svexl-node-kind
(equal (svexl-node-kind-wog x)
(svexl-node-kind x))
:hints (("Goal"
:in-theory (e/d (svexl-node-kind-wog
svexl-node-kind) ()))))
(acl2::defines
svexl-node-eval-wog
:flag-local nil
:flag-defthm-macro defthm-svexl-node-eval-wog
:prepwork
((local
(in-theory (e/d (svexl-node-kind
sv::svexlist-p
svexl-node-p
svexl-node-array-p
svexl-node-kind-wog-is-svexl-node-kind
sv::svex-p)
()))))
(define svexl-node-eval-wog ((x)
(node-env)
(env))
:measure (acl2-count x)
:verify-guards nil
(b* ((kind (svexl-node-kind-wog x)))
(cond ((eq kind :var)
(svex-env-fastlookup-wog x env))
((eq kind :quote) x)
((eq kind :node)
(svex-env-fastlookup-wog (cadr x) node-env))
(t
(b* ((x.fn (car x))
(x.args (cdr x)))
(svex-apply-wog
x.fn
(svexl-nodelist-eval-wog x.args node-env env)))))))
(define svexl-nodelist-eval-wog ((lst)
(node-env)
(env))
:measure (acl2-count lst)
(if (atom lst)
nil
(cons (svexl-node-eval-wog (car lst) node-env env)
(svexl-nodelist-eval-wog (cdr lst) node-env env))))
///
;; openers:
(def-rp-rule svexl-eval-node-of-var
(implies (eq (svexl-node-kind-wog x) ':var)
(equal (svexl-node-eval-wog x node-env env-wires)
(let ((entry (hons-get x env-wires)))
(if entry (cdr entry)
(sv::4vec-x)))))
:hints (("goal"
:expand (svexl-node-eval-wog x node-env env-wires)
:in-theory (e/d (svex-env-fastlookup-wog) ()))))
(def-rp-rule svexl-eval-node-of-node
(implies (eq (svexl-node-kind-wog x) ':node)
(equal (svexl-node-eval-wog x node-env env-wires)
(let ((entry (hons-get (cadr x) node-env)))
(if entry (cdr entry)
(sv::4vec-x)))))
:hints (("goal"
:expand (svexl-node-eval-wog x node-env env-wires)
:in-theory (e/d (svex-env-fastlookup-wog) ()))))
(def-rp-rule svexl-eval-node-of-quoted
(implies (eq (svexl-node-kind-wog x) ':quote)
(equal (svexl-node-eval-wog x node-env env-wires)
x))
:hints (("goal"
:expand (svexl-node-eval-wog x node-env env-wires)
:in-theory (e/d (svex-env-fastlookup-wog) ()))))
(def-rp-rule svexl-eval-node-of-call
(implies (eq (svexl-node-kind-wog x) ':call)
(equal (svexl-node-eval-wog x node-env env)
(svex-apply-wog
(car x)
(svexl-nodelist-eval-wog (cdr x) node-env env))))
:hints (("goal"
:expand (svexl-node-eval-wog x node-env env)
:in-theory (e/d (svex-env-fastlookup-wog) ()))))
(def-rp-rule svexl-nodelist-eval-wog-of-cons
(equal (svexl-nodelist-eval-wog (cons x rest) node-env env)
(cons (svexl-node-eval-wog x node-env env)
(svexl-nodelist-eval-wog rest node-env env)))
:hints (("Goal"
:expand (svexl-nodelist-eval-wog (cons x rest) node-env env)
:in-theory (e/d () ()))))
(def-rp-rule svexl-nodelist-eval-wog-of-nil
(equal (svexl-nodelist-eval-wog nil node-env env)
nil)
:hints (("Goal"
:expand (svexl-nodelist-eval-wog nil node-env env)
:in-theory (e/d () ()))))
(verify-guards svexl-node-eval-wog))
(define svexl-node-alist-eval-wog ((alist alistp)
(node-env)
(env))
:measure (acl2-count alist)
(if (atom alist)
nil
(acons
(caar alist)
(svexl-node-eval-wog (cdar alist) node-env env)
(svexl-node-alist-eval-wog (cdr alist) node-env env)))
///
(def-rp-rule svexl-node-alist-eval-wog-of-cons
(equal (svexl-node-alist-eval-wog (cons x rest) node-env env)
(acons
(car x)
(svexl-node-eval-wog (cdr x) node-env env)
(svexl-node-alist-eval-wog rest node-env env)))
:hints (("Goal"
:expand (svexl-node-alist-eval-wog (cons x rest) node-env env)
:in-theory (e/d () ()))))
(def-rp-rule svexl-node-alist-eval-wog-of-nil
(equal (svexl-node-alist-eval-wog nil node-env env)
nil)
:hints (("Goal"
:expand (svexl-node-alist-eval-wog nil node-env env)
:in-theory (e/d () ()))))
)
(defthm-svexl-node-eval-wog
(defthm svexl-node-eval-is-svexl-node-eval-wog
(implies (and (svexl-node-p x)
(sv::svex-env-p env))
(equal (svexl-node-eval x node-env env)
(svexl-node-eval-wog x node-env env)))
:flag svexl-node-eval-wog)
(defthm svexl-nodelist-eval-is-svexl-nodelist-eval-wog
(implies (and (svexl-nodelist-p lst)
(sv::svex-env-p env))
(equal (svexl-nodelist-eval lst node-env env)
(svexl-nodelist-eval-wog lst node-env env)))
:flag svexl-nodelist-eval-wog)
:hints (("goal"
:expand ((svexl-node-eval x node-env env))
:in-theory (e/d (svex-call->fn
svexl-nodelist-fix
svexl-node-var->name
svexl-node-quote->val
svexl-node-call->args
svexl-nodelist-p
svexl-node-call->fn
svexl-node-node->node-id
svexl-node-p
svex-kind
svex-env-fastlookup-wog
svex-eval-wog
SVEX-APPLY-IS-SVEX-APPLY-WOG
svex-env-lookup-is-svex-env-fastlookup-wog
svexl-node-kind-wog-is-svexl-node-kind
svexlist-eval-wog
svexl-node-eval
svexl-node-kind
svexl-node-eval-wog
svex-p
sv::svar-p
svex-eval
svex-var->name
sv::svex-quote->val
svex-call->args
svexl-nodelist-eval
svexl-nodelist-eval-wog)
()))))
(rp::add-rp-rule svexl-node-eval-is-svexl-node-eval-wog)
(rp::add-rp-rule svexl-nodelist-eval-is-svexl-nodelist-eval-wog)
(def-rp-rule svexl-node-alist-eval-is-svexl-node-alist-eval-wog
(implies (and (svexl-node-alist-p alist)
(sv::svex-env-p env))
(equal (svexl-node-alist-eval alist node-env env)
(svexl-node-alist-eval-wog alist node-env env)))
:hints (("Goal"
:in-theory (e/d (svexl-node-alist-eval
svexl-node-alist-p
svexl-node-alist-eval-wog)
()))))
(define svexl-eval-aux-wog ((x alistp)
(env))
:prepwork
((local
(in-theory (e/d (svexl-node-array-p
node-env-p)
()))))
(if (atom x)
nil
(b* ((node-env
(svexl-eval-aux-wog (cdr x) env))
(node-id (caar x))
(node (cdar x))
(eval-res (svexl-node-eval-wog node node-env env)))
(hons-acons node-id eval-res node-env)))
///
(def-rp-rule$ t nil
svexl-eval-aux-is-svexl-eval-aux-wog
(implies (and (svexl-node-array-p x)
(sv::svex-env-p env))
(equal (svexl-eval-aux x env)
(svexl-eval-aux-wog x env)))
:hints (("Goal"
:in-theory (e/d (svexl-eval-aux
svexl-eval-aux-wog) ()))))
(rp::defthm-lambda
svexl-eval-aux-wog-cons
(equal (svexl-eval-aux-wog (cons (cons node-id node) rest) env)
(b* ((node-env (svexl-eval-aux-wog rest env))
(eval-res (svexl-node-eval-wog node node-env env)))
(hons-acons node-id eval-res node-env))))
(def-rp-rule
svexl-eval-aux-wog-nil
(equal (svexl-eval-aux-wog nil env)
nil)))
(define svexl-eval-wog ((x)
(env))
:verify-guards nil
(b* ((node (cdar x))
(node-array (cdr (cadr x)))
(node-env (svexl-eval-aux-wog node-array env))
(res (svexl-node-eval-wog node node-env env))
(- (fast-alist-free node-env)))
res)
///
(def-rp-rule$ t nil
svexl-eval-is-svexl-eval-wog
(implies (and (svexl-p x)
(sv::svex-env-p env))
(equal (svexl-eval x env)
(svexl-eval-wog x env)))
:hints (("Goal"
:in-theory (e/d (svexl-eval
svexl->top-node
svexl->node-array
svexl-p
svexl-eval-wog
SVEXL-EVAL-AUX-IS-SVEXL-EVAL-AUX-WOG)
()))))
(defthmd svexl-eval-wog-is-svexl-eval
(implies (and (svexl-p x)
(sv::svex-env-p env))
(equal (svexl-eval-wog x env)
(svexl-eval x env)))
:hints (("Goal"
:in-theory (e/d (svexl-eval-is-svexl-eval-wog)
()))))
(set-ignore-ok t)
(add-rp-rule svexl-eval-wog :beta-reduce t))
(define svexllist-eval-wog ((x)
(env))
:verify-guards nil
(b* ((node-lst (cdr (car x)))
(node-array (cdr (cadr x)))
(node-env (svexl-eval-aux-wog node-array env))
(res (svexl-nodelist-eval-wog node-lst node-env env))
(- (fast-alist-free node-env)))
res)
///
(def-rp-rule$ t nil
svexllist-eval-is-svexllist-eval-wog
(implies (and (svexllist-p x)
(sv::svex-env-p env))
(equal (svexllist-eval x env)
(svexllist-eval-wog x env)))
:hints (("Goal"
:in-theory (e/d (svexllist-eval
SVEXLLIST->TOP-NODELIST
SVEXLLIST->NODE-ARRAY
SVEXLLIST-P
svexllist-eval-wog
SVEXL-EVAL-AUX-IS-SVEXL-EVAL-AUX-WOG)
()))))
(set-ignore-ok t)
(add-rp-rule svexllist-eval-wog :beta-reduce t))
(define svexl-alist-eval-wog ((x)
(env))
:verify-guards nil
(b* ((top-node-alist (cdar x))
(node-array (cdr (cadr x)))
(node-env (svexl-eval-aux-wog node-array env))
(res (svexl-node-alist-eval-wog top-node-alist node-env env))
(- (fast-alist-free node-env)))
res)
///
(def-rp-rule$ t nil
svexl-alist-eval-is-svexl-alist-eval-wog
(implies (and (svexl-alist-p x)
(sv::svex-env-p env))
(equal (svexl-alist-eval x env)
(svexl-alist-eval-wog x env)))
:hints (("Goal"
:in-theory (e/d (svexl-alist-eval
SVEXL-ALIST-P
SVEXL-ALIST->NODE-ARRAY
svexl-alist-eval-wog
SVEXL-ALIST->TOP-NODE-ALIST
svexl-node-alist-eval-is-svexl-node-alist-eval-wog
SVEXL-EVAL-AUX-IS-SVEXL-EVAL-AUX-WOG)
()))))
(set-ignore-ok t)
(add-rp-rule svexl-alist-eval-wog :beta-reduce t))
(memoize 'svexl-alist-p)
(memoize 'svexllist-p)
(memoize 'svexl-p)
(defthm-svexl-node-eval-wog
(defthm svex-p-implies-svexl-node-p
(implies (svex-p x)
(svexl-node-p x))
:flag svexl-node-eval-wog)
(defthm svexlist-p-implies-svexl-nodelist-p
(implies (svexlist-p lst)
(svexl-nodelist-p lst))
:flag svexl-nodelist-eval-wog)
:rule-classes :type-prescription
:hints (("Goal"
:in-theory (e/d (svex-p
svexl-node-kind-wog-is-svexl-node-kind
svexlist-p
svexl-nodelist-p
svexl-node-p
svexl-node-kind
svex-kind) ()))))
|
[
{
"context": "LISP; Package: CCL -*-\n;;;\n;;; Copyright 1994-2009 Clozure Associates\n;;;\n;;; Licensed under the Apache License, Versio",
"end": 80,
"score": 0.9849244356155396,
"start": 62,
"tag": "NAME",
"value": "Clozure Associates"
}
] |
level-1/level-1.lisp
|
digikar99/ccl
| 732 |
;;-*-Mode: LISP; Package: CCL -*-
;;;
;;; Copyright 1994-2009 Clozure Associates
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
; Level-1.lisp
(in-package "CCL")
(macrolet ((l1-load (name)
(let* ((namestring
(concatenate 'simple-base-string
"./l1-fasls/"
(string name)
(namestring (backend-target-fasl-pathname
*target-backend*)))))
`(%fasload ,namestring)))
(bin-load (name)
(let* ((namestring
(concatenate 'simple-base-string
"./bin/"
(string name)
(namestring (backend-target-fasl-pathname
*target-backend*)))))
`(%fasload ,namestring))))
(l1-load "l1-cl-package")
(l1-load "l1-utils")
(l1-load "l1-init")
(l1-load "l1-symhash")
(l1-load "l1-numbers")
(l1-load "l1-aprims")
#+ppc-target
(l1-load "ppc-callback-support")
#+x86-target
(l1-load "x86-callback-support")
#+arm-target
(l1-load "arm-callback-support")
(l1-load "l1-callbacks")
(l1-load "l1-sort")
(bin-load "lists")
(bin-load "sequences")
(l1-load "l1-dcode")
(l1-load "l1-clos-boot")
(bin-load "hash")
(l1-load "l1-clos")
(bin-load "defstruct")
(bin-load "dll-node")
(l1-load "l1-unicode")
(l1-load "l1-streams")
(l1-load "linux-files")
(bin-load "chars")
(l1-load "l1-files")
(provide "SEQUENCES")
(provide "DEFSTRUCT")
(provide "CHARS")
(provide "LISTS")
(provide "DLL-NODE")
(l1-load "l1-typesys")
(l1-load "sysutils")
#+ppc-target
(l1-load "ppc-threads-utils")
#+x86-target
(l1-load "x86-threads-utils")
#+arm-target
(l1-load "arm-threads-utils")
(l1-load "l1-lisp-threads")
(l1-load "l1-application")
(l1-load "l1-processes")
(l1-load "l1-io")
(l1-load "l1-reader")
(l1-load "l1-readloop")
(l1-load "l1-readloop-lds")
(l1-load "l1-error-system")
(l1-load "l1-events")
#+ppc-target
(l1-load "ppc-trap-support")
#+x86-target
(l1-load "x86-trap-support")
#+arm-target
(l1-load "arm-trap-support")
(l1-load "l1-format")
(l1-load "l1-sysio")
(l1-load "l1-pathnames")
(l1-load "l1-boot-lds")
(l1-load "l1-boot-1")
(l1-load "l1-boot-2")
(l1-load "l1-boot-3")
)
(require "PREPARE-MCL-ENVIRONMENT")
(progn
(%set-toplevel #'(lambda ()
(setq *loading-file-source-file* nil
*loading-toplevel-location* nil)
(toplevel-loop)))
(set-user-environment t)
(toplevel))
|
77611
|
;;-*-Mode: LISP; Package: CCL -*-
;;;
;;; Copyright 1994-2009 <NAME>
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
; Level-1.lisp
(in-package "CCL")
(macrolet ((l1-load (name)
(let* ((namestring
(concatenate 'simple-base-string
"./l1-fasls/"
(string name)
(namestring (backend-target-fasl-pathname
*target-backend*)))))
`(%fasload ,namestring)))
(bin-load (name)
(let* ((namestring
(concatenate 'simple-base-string
"./bin/"
(string name)
(namestring (backend-target-fasl-pathname
*target-backend*)))))
`(%fasload ,namestring))))
(l1-load "l1-cl-package")
(l1-load "l1-utils")
(l1-load "l1-init")
(l1-load "l1-symhash")
(l1-load "l1-numbers")
(l1-load "l1-aprims")
#+ppc-target
(l1-load "ppc-callback-support")
#+x86-target
(l1-load "x86-callback-support")
#+arm-target
(l1-load "arm-callback-support")
(l1-load "l1-callbacks")
(l1-load "l1-sort")
(bin-load "lists")
(bin-load "sequences")
(l1-load "l1-dcode")
(l1-load "l1-clos-boot")
(bin-load "hash")
(l1-load "l1-clos")
(bin-load "defstruct")
(bin-load "dll-node")
(l1-load "l1-unicode")
(l1-load "l1-streams")
(l1-load "linux-files")
(bin-load "chars")
(l1-load "l1-files")
(provide "SEQUENCES")
(provide "DEFSTRUCT")
(provide "CHARS")
(provide "LISTS")
(provide "DLL-NODE")
(l1-load "l1-typesys")
(l1-load "sysutils")
#+ppc-target
(l1-load "ppc-threads-utils")
#+x86-target
(l1-load "x86-threads-utils")
#+arm-target
(l1-load "arm-threads-utils")
(l1-load "l1-lisp-threads")
(l1-load "l1-application")
(l1-load "l1-processes")
(l1-load "l1-io")
(l1-load "l1-reader")
(l1-load "l1-readloop")
(l1-load "l1-readloop-lds")
(l1-load "l1-error-system")
(l1-load "l1-events")
#+ppc-target
(l1-load "ppc-trap-support")
#+x86-target
(l1-load "x86-trap-support")
#+arm-target
(l1-load "arm-trap-support")
(l1-load "l1-format")
(l1-load "l1-sysio")
(l1-load "l1-pathnames")
(l1-load "l1-boot-lds")
(l1-load "l1-boot-1")
(l1-load "l1-boot-2")
(l1-load "l1-boot-3")
)
(require "PREPARE-MCL-ENVIRONMENT")
(progn
(%set-toplevel #'(lambda ()
(setq *loading-file-source-file* nil
*loading-toplevel-location* nil)
(toplevel-loop)))
(set-user-environment t)
(toplevel))
| true |
;;-*-Mode: LISP; Package: CCL -*-
;;;
;;; Copyright 1994-2009 PI:NAME:<NAME>END_PI
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
; Level-1.lisp
(in-package "CCL")
(macrolet ((l1-load (name)
(let* ((namestring
(concatenate 'simple-base-string
"./l1-fasls/"
(string name)
(namestring (backend-target-fasl-pathname
*target-backend*)))))
`(%fasload ,namestring)))
(bin-load (name)
(let* ((namestring
(concatenate 'simple-base-string
"./bin/"
(string name)
(namestring (backend-target-fasl-pathname
*target-backend*)))))
`(%fasload ,namestring))))
(l1-load "l1-cl-package")
(l1-load "l1-utils")
(l1-load "l1-init")
(l1-load "l1-symhash")
(l1-load "l1-numbers")
(l1-load "l1-aprims")
#+ppc-target
(l1-load "ppc-callback-support")
#+x86-target
(l1-load "x86-callback-support")
#+arm-target
(l1-load "arm-callback-support")
(l1-load "l1-callbacks")
(l1-load "l1-sort")
(bin-load "lists")
(bin-load "sequences")
(l1-load "l1-dcode")
(l1-load "l1-clos-boot")
(bin-load "hash")
(l1-load "l1-clos")
(bin-load "defstruct")
(bin-load "dll-node")
(l1-load "l1-unicode")
(l1-load "l1-streams")
(l1-load "linux-files")
(bin-load "chars")
(l1-load "l1-files")
(provide "SEQUENCES")
(provide "DEFSTRUCT")
(provide "CHARS")
(provide "LISTS")
(provide "DLL-NODE")
(l1-load "l1-typesys")
(l1-load "sysutils")
#+ppc-target
(l1-load "ppc-threads-utils")
#+x86-target
(l1-load "x86-threads-utils")
#+arm-target
(l1-load "arm-threads-utils")
(l1-load "l1-lisp-threads")
(l1-load "l1-application")
(l1-load "l1-processes")
(l1-load "l1-io")
(l1-load "l1-reader")
(l1-load "l1-readloop")
(l1-load "l1-readloop-lds")
(l1-load "l1-error-system")
(l1-load "l1-events")
#+ppc-target
(l1-load "ppc-trap-support")
#+x86-target
(l1-load "x86-trap-support")
#+arm-target
(l1-load "arm-trap-support")
(l1-load "l1-format")
(l1-load "l1-sysio")
(l1-load "l1-pathnames")
(l1-load "l1-boot-lds")
(l1-load "l1-boot-1")
(l1-load "l1-boot-2")
(l1-load "l1-boot-3")
)
(require "PREPARE-MCL-ENVIRONMENT")
(progn
(%set-toplevel #'(lambda ()
(setq *loading-file-source-file* nil
*loading-toplevel-location* nil)
(toplevel-loop)))
(set-user-environment t)
(toplevel))
|
[
{
"context": " kanji-tree\n (c) 2017 Shirakumo http://tymoon.eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n",
"end": 94,
"score": 0.9999104738235474,
"start": 76,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "umo http://tymoon.eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(in-package #:org.shirak",
"end": 119,
"score": 0.9998824596405029,
"start": 105,
"tag": "NAME",
"value": "Nicolas Hafner"
},
{
"context": ".eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(in-package #:org.shirakumo.radiance.kanji-t",
"end": 139,
"score": 0.9999224543571472,
"start": 121,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
toolkit.lisp
|
Shirakumo/kanji-tree
| 2 |
#|
This file is a part of kanji-tree
(c) 2017 Shirakumo http://tymoon.eu ([email protected])
Author: Nicolas Hafner <[email protected]>
|#
(in-package #:org.shirakumo.radiance.kanji-tree)
(defun gather-kargs (args)
(let ((plist ()))
(loop with key = NIL
for item in args
do (if (keywordp item)
(setf key item)
(push item (getf plist key))))
(loop for (k v) on plist by #'cddr
do (setf (getf plist k) (nreverse v)))
plist))
(defun extract-kanji (text)
(loop for char across text
for block = (nth-value 1 (cl-unicode:code-block char))
when (eql block 'CL-UNICODE-NAMES::CJKUNIFIEDIDEOGRAPHS)
collect char))
|
51101
|
#|
This file is a part of kanji-tree
(c) 2017 Shirakumo http://tymoon.eu (<EMAIL>)
Author: <NAME> <<EMAIL>>
|#
(in-package #:org.shirakumo.radiance.kanji-tree)
(defun gather-kargs (args)
(let ((plist ()))
(loop with key = NIL
for item in args
do (if (keywordp item)
(setf key item)
(push item (getf plist key))))
(loop for (k v) on plist by #'cddr
do (setf (getf plist k) (nreverse v)))
plist))
(defun extract-kanji (text)
(loop for char across text
for block = (nth-value 1 (cl-unicode:code-block char))
when (eql block 'CL-UNICODE-NAMES::CJKUNIFIEDIDEOGRAPHS)
collect char))
| true |
#|
This file is a part of kanji-tree
(c) 2017 Shirakumo http://tymoon.eu (PI:EMAIL:<EMAIL>END_PI)
Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
|#
(in-package #:org.shirakumo.radiance.kanji-tree)
(defun gather-kargs (args)
(let ((plist ()))
(loop with key = NIL
for item in args
do (if (keywordp item)
(setf key item)
(push item (getf plist key))))
(loop for (k v) on plist by #'cddr
do (setf (getf plist k) (nreverse v)))
plist))
(defun extract-kanji (text)
(loop for char across text
for block = (nth-value 1 (cl-unicode:code-block char))
when (eql block 'CL-UNICODE-NAMES::CJKUNIFIEDIDEOGRAPHS)
collect char))
|
[
{
"context": "ols.lisp\n\n\n#|\nThe MIT license.\n\nCopyright (c) 2010 Paul L. Krueger\n\nPermission is hereby granted, free of charge, to",
"end": 77,
"score": 0.9998829364776611,
"start": 62,
"tag": "NAME",
"value": "Paul L. Krueger"
}
] |
Utilities/debug.lisp
|
plkrueger/CocoaInterface
| 34 |
;; debug-tools.lisp
#|
The MIT license.
Copyright (c) 2010 Paul L. Krueger
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|#
;; miscellaneous functions that come in handy once in a while
(eval-when (:compile-toplevel :load-toplevel :execute)
(require :ns-string-utils)
(require :selector-utils))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; hash-table utility functions
(defun ht-keys (ht)
;; return all the keys in a hash-table
(let ((keys nil))
(maphash #'(lambda (k v)
(declare (ignore v))
(push k keys))
ht)
keys))
(defun ht-to-acons (ht)
(let ((pairs nil))
(maphash #'(lambda (k v)
(push (cons k v) pairs))
ht)
pairs))
(defun print-ht (ht)
(maphash #'(lambda (k v)
(format t "~%Key: ~a~%~5t~s" k v))
ht)
(values))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun prl (thing)
;; print a list or Objective-C array readably in the listener
(format t "~{~%~s~}" (iu::coerce-obj thing 'list))
(values))
|
2382
|
;; debug-tools.lisp
#|
The MIT license.
Copyright (c) 2010 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|#
;; miscellaneous functions that come in handy once in a while
(eval-when (:compile-toplevel :load-toplevel :execute)
(require :ns-string-utils)
(require :selector-utils))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; hash-table utility functions
(defun ht-keys (ht)
;; return all the keys in a hash-table
(let ((keys nil))
(maphash #'(lambda (k v)
(declare (ignore v))
(push k keys))
ht)
keys))
(defun ht-to-acons (ht)
(let ((pairs nil))
(maphash #'(lambda (k v)
(push (cons k v) pairs))
ht)
pairs))
(defun print-ht (ht)
(maphash #'(lambda (k v)
(format t "~%Key: ~a~%~5t~s" k v))
ht)
(values))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun prl (thing)
;; print a list or Objective-C array readably in the listener
(format t "~{~%~s~}" (iu::coerce-obj thing 'list))
(values))
| true |
;; debug-tools.lisp
#|
The MIT license.
Copyright (c) 2010 PI:NAME:<NAME>END_PI
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|#
;; miscellaneous functions that come in handy once in a while
(eval-when (:compile-toplevel :load-toplevel :execute)
(require :ns-string-utils)
(require :selector-utils))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; hash-table utility functions
(defun ht-keys (ht)
;; return all the keys in a hash-table
(let ((keys nil))
(maphash #'(lambda (k v)
(declare (ignore v))
(push k keys))
ht)
keys))
(defun ht-to-acons (ht)
(let ((pairs nil))
(maphash #'(lambda (k v)
(push (cons k v) pairs))
ht)
pairs))
(defun print-ht (ht)
(maphash #'(lambda (k v)
(format t "~%Key: ~a~%~5t~s" k v))
ht)
(values))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun prl (thing)
;; print a list or Objective-C array readably in the listener
(format t "~{~%~s~}" (iu::coerce-obj thing 'list))
(values))
|
[
{
"context": "3, Regents of the University of Texas\n; Written by Matt Kaufmann, January, 2011 (revised slightly October, 2011)\n;",
"end": 83,
"score": 0.999708354473114,
"start": 70,
"tag": "NAME",
"value": "Matt Kaufmann"
}
] |
books/misc/defattach-example.lisp
|
mayankmanj/acl2
| 305 |
; Copyright (C) 2013, Regents of the University of Texas
; Written by Matt Kaufmann, January, 2011 (revised slightly October, 2011)
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
; See also defattach-bang.lisp for a macro based
; on defattach that does not require guard verification.
; Defattach was introduced in ACL2 Version 4.0 (July, 2010).
; In this little example we show how defattach may be used
; to build systems of executable programs in which some of
; the functions are constrained. Be sure to see the final
; comment, which is really the punch line.
; For a demo using 800x600 resolution on a 15" laptop:
#||
(set-fmt-soft-right-margin 51 state)
(set-fmt-hard-right-margin 60 state)
||#
(in-package "ACL2")
; Experienced ACL2 users know that by using encapsulate, and
; without any need for defattach, you can deduce theorems
; about concrete functions from theorems about abstract
; functions, using the following steps.
; (1) Write abstract specifications -- basically, axioms
; about functions that are shown to hold for some
; witness functions.
; (2) Prove some theorems about the specification functions.
; (3) Write corresponding concrete definitions.
; (4) Prove that the concrete definitions satisfy the
; abstract specifications.
; (5) Conclude using functional instantiation that the
; theorems (from (2)) hold for the concrete functions
; (defined in (3)).
; Below we present a standard example of that style of
; reasoning. We then show how defattach goes beyond this:
; the idea is still to refine specification functions to
; more concrete definitions, but with defattach one can do
; this in a way that allows evaluation using the original
; function symbols.
; Thus, this file presents an example in two parts:
; traditional functional instantiation without defattach,
; and then evaluation using defattach.
; Here is an outline of the first part, using the numbered
; steps shown above.
; (1) Abstract spec:
; - Specify that abst is associative-commutative
; (example: +).
; - Define fold-abst to apply abst to successive elements
; of list; for example, (fold-abst '(1 2 3) r) is
; (abst 1 (abst 2 (abst 3 r))).
; (2) Prove that fold-abst(x) = fold-abst(reverse x).
; (3) Concrete definitions:
; - Define mult to be multiplication.
; - Define fold-mult in the obvious way.
; (4) Prove that the pair <mult,fold-mult> satisfies the
; abstract spec for <abst,fold-abst>.
; (5) Conclude that (fold-mult x) = (fold-mult (reverse x)).
; The second part then takes advantage of the first part,
; resulting in computation using the abstract functions by
; attaching corresponding concrete functions. We also
; provide a second set of attachments.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;; EXAMPLE WITHOUT DEFATTACH ;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(encapsulate
; (1) Abstract spec: Specify that abst is
; associative-commutative (example: +).
((abst (x y) t))
; We introduce abst, a function of two arguments.
; Our witnessing example is as follows:
(local (defun abst (x y)
(+ x y)))
; Exported specifications:
(defthm abst-comm
(equal (abst x y) (abst y x)))
(defthm abst-assoc
(equal (abst (abst x y) z)
(abst x (abst y z)))))
(defun fold-abst (x root)
; Complete abstract spec: define fold-abst to apply abst to
; successive elements of a list; for example,
; (fold-abst '(1 2 3) r) = (abst 1 (abst 2 (abst 3 r))).
(if (consp x)
(abst (car x)
(fold-abst (cdr x) root))
root))
(encapsulate ()
; (2) Prove some theorems about the specification functions.
; We prove fold-abst-reverse, below; the others are lemmas.
(local (defthm abst-comm2
(equal (abst x (abst y z))
(abst y (abst x z)))
:hints (("Goal"
:use ((:instance abst-assoc (x x) (y y))
(:instance abst-assoc (x y) (y x)))
:in-theory (disable abst-assoc)))))
(local (defthm fold-abst-abst
(equal (fold-abst x (abst a b))
(abst a (fold-abst x b)))))
(local (defthm fold-abst-revappend
(equal (fold-abst (revappend x y) root)
(fold-abst x (fold-abst y root)))))
(defthm fold-abst-reverse
(equal (fold-abst (reverse x) root)
(fold-abst x root))))
(defun mult (x y)
; (3) Write corresponding concrete definitions.
; - Define mult to be multiplication.
; - Below, we define fold-mult in the obvious way.
(* (fix x) (fix y)))
(defun fold-mult (x root)
(if (consp x)
(mult (car x)
(fold-mult (cdr x) root))
root))
(local ; included for (4) below
(include-book "arithmetic/top" :dir :system))
(defthm fold-mult-reverse
; (4) Prove that the concrete definitions satisfy the
; abstract specifications.
; We prove that the pair <mult,fold-mult> satisfies the
; abstract spec for <abst,fold-abst>. It is generated as
; part of the proof obligations from the hint below.
; (5) Conclude using functional instantiation that the
; theorems (from (2)) hold for the concrete functions
; (defined in (3)).
; We conclude that (fold-mult x) = (fold-mult (reverse x)).
(equal (fold-mult (reverse x) root)
(fold-mult x root))
:hints (("Goal" :by (:functional-instance
fold-abst-reverse
(abst mult)
(fold-abst fold-mult)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;; EXAMPLE WITH DEFATTACH ;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#||
(fold-abst '(3 4 5) 100) ; error (undefined function abst)
||#
(verify-guards ; guard verification needed for defattach
mult)
; Next we attach the executable function mult to the
; abstract specification function abst. The proof
; obligations ensure, roughly speaking, that mult satisfies
; the constraints on abst. In this case the proofs of
; those obligations are skipped because they were already
; proved (and then cached) at the earlier functional
; instantiation (see fold-mult-reverse).
(defattach abst mult) ; note cached proof obligations
; Next we do a sample computation using fold-abst
; (interestingly, without calling fold-mult). The
; foundations guarantees that this computation is taking
; place in a consistent extension of the current theory,
; called the "evaluation theory". The equality below is a
; theorem of the evaluation theory, but not of the (weaker)
; current theory.
#||
(fold-abst '(3 4 5) 100)
(trace$ abst mult) ; to see abst transfer control to mult
(fold-abst '(3 4 5) 100)
(untrace$)
||#
(assert-event (equal (fold-abst '(3 4 5) 100)
6000))
; Note that this equality is NOT a theorem of the current
; session; it's only a theorem if we extend the session by
; "attachment equations" such as the following, to obtain
; the so-called "evaluation history":
; (forall x y) (equal (abst x y) (mult x y))
; Not included because the books/make-event/ directory
; depends on books/misc/:
; (include-book "make-event/eval" :dir :system)
; (must-fail (thm (equal (fold-abst '(3 4 5) 100)
; 6000)))
; Here is a second example, which provides a different
; extension of the current theory to the evaluation theory.
(defun add (x y)
(+ (fix x) (fix y)))
(verify-guards add)
(defattach abst add) ; note constraint proof this time
; The following example execution really makes our main
; point: We don't even need to define a fold function for
; add! We execute with the "abstract" function fold-abst,
; which we think of as "abstract" because it calls the
; encapsulated function abst. One can imagine more complex
; examples in which a large system of programs contains a
; few attachments at the leaves of the call trees. In such
; a case, it's particularly helpful that one can instantiate
; the system to different executable programs without
; defining analogues of the higher-level functions (like
; fold-abst), thus giving ACL2 some ability to mimic a
; higher-order programming language.
; To see abst transfer control to add:
; (trace$ abst add)
(assert-event (equal (fold-abst '(3 4 5) 100)
112))
; Here are some forms to run at the end of a demo:
#||
(defattach abst mult) ; note cached proof obligations
(fold-abst '(3 4 5) 100)
(thm
; This FAILS! ACL2 does not use attachments for
; evaluation of ground terms during rewriting, because
; it is proving theorems about the current ACL2 world,
; not the so-called "evaluation theory" in which we know
; (equal (abst x y) (mult x y)).
(equal (fold-abst '(3 4 5) 100)
6000))
||#
|
37207
|
; Copyright (C) 2013, Regents of the University of Texas
; Written by <NAME>, January, 2011 (revised slightly October, 2011)
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
; See also defattach-bang.lisp for a macro based
; on defattach that does not require guard verification.
; Defattach was introduced in ACL2 Version 4.0 (July, 2010).
; In this little example we show how defattach may be used
; to build systems of executable programs in which some of
; the functions are constrained. Be sure to see the final
; comment, which is really the punch line.
; For a demo using 800x600 resolution on a 15" laptop:
#||
(set-fmt-soft-right-margin 51 state)
(set-fmt-hard-right-margin 60 state)
||#
(in-package "ACL2")
; Experienced ACL2 users know that by using encapsulate, and
; without any need for defattach, you can deduce theorems
; about concrete functions from theorems about abstract
; functions, using the following steps.
; (1) Write abstract specifications -- basically, axioms
; about functions that are shown to hold for some
; witness functions.
; (2) Prove some theorems about the specification functions.
; (3) Write corresponding concrete definitions.
; (4) Prove that the concrete definitions satisfy the
; abstract specifications.
; (5) Conclude using functional instantiation that the
; theorems (from (2)) hold for the concrete functions
; (defined in (3)).
; Below we present a standard example of that style of
; reasoning. We then show how defattach goes beyond this:
; the idea is still to refine specification functions to
; more concrete definitions, but with defattach one can do
; this in a way that allows evaluation using the original
; function symbols.
; Thus, this file presents an example in two parts:
; traditional functional instantiation without defattach,
; and then evaluation using defattach.
; Here is an outline of the first part, using the numbered
; steps shown above.
; (1) Abstract spec:
; - Specify that abst is associative-commutative
; (example: +).
; - Define fold-abst to apply abst to successive elements
; of list; for example, (fold-abst '(1 2 3) r) is
; (abst 1 (abst 2 (abst 3 r))).
; (2) Prove that fold-abst(x) = fold-abst(reverse x).
; (3) Concrete definitions:
; - Define mult to be multiplication.
; - Define fold-mult in the obvious way.
; (4) Prove that the pair <mult,fold-mult> satisfies the
; abstract spec for <abst,fold-abst>.
; (5) Conclude that (fold-mult x) = (fold-mult (reverse x)).
; The second part then takes advantage of the first part,
; resulting in computation using the abstract functions by
; attaching corresponding concrete functions. We also
; provide a second set of attachments.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;; EXAMPLE WITHOUT DEFATTACH ;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(encapsulate
; (1) Abstract spec: Specify that abst is
; associative-commutative (example: +).
((abst (x y) t))
; We introduce abst, a function of two arguments.
; Our witnessing example is as follows:
(local (defun abst (x y)
(+ x y)))
; Exported specifications:
(defthm abst-comm
(equal (abst x y) (abst y x)))
(defthm abst-assoc
(equal (abst (abst x y) z)
(abst x (abst y z)))))
(defun fold-abst (x root)
; Complete abstract spec: define fold-abst to apply abst to
; successive elements of a list; for example,
; (fold-abst '(1 2 3) r) = (abst 1 (abst 2 (abst 3 r))).
(if (consp x)
(abst (car x)
(fold-abst (cdr x) root))
root))
(encapsulate ()
; (2) Prove some theorems about the specification functions.
; We prove fold-abst-reverse, below; the others are lemmas.
(local (defthm abst-comm2
(equal (abst x (abst y z))
(abst y (abst x z)))
:hints (("Goal"
:use ((:instance abst-assoc (x x) (y y))
(:instance abst-assoc (x y) (y x)))
:in-theory (disable abst-assoc)))))
(local (defthm fold-abst-abst
(equal (fold-abst x (abst a b))
(abst a (fold-abst x b)))))
(local (defthm fold-abst-revappend
(equal (fold-abst (revappend x y) root)
(fold-abst x (fold-abst y root)))))
(defthm fold-abst-reverse
(equal (fold-abst (reverse x) root)
(fold-abst x root))))
(defun mult (x y)
; (3) Write corresponding concrete definitions.
; - Define mult to be multiplication.
; - Below, we define fold-mult in the obvious way.
(* (fix x) (fix y)))
(defun fold-mult (x root)
(if (consp x)
(mult (car x)
(fold-mult (cdr x) root))
root))
(local ; included for (4) below
(include-book "arithmetic/top" :dir :system))
(defthm fold-mult-reverse
; (4) Prove that the concrete definitions satisfy the
; abstract specifications.
; We prove that the pair <mult,fold-mult> satisfies the
; abstract spec for <abst,fold-abst>. It is generated as
; part of the proof obligations from the hint below.
; (5) Conclude using functional instantiation that the
; theorems (from (2)) hold for the concrete functions
; (defined in (3)).
; We conclude that (fold-mult x) = (fold-mult (reverse x)).
(equal (fold-mult (reverse x) root)
(fold-mult x root))
:hints (("Goal" :by (:functional-instance
fold-abst-reverse
(abst mult)
(fold-abst fold-mult)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;; EXAMPLE WITH DEFATTACH ;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#||
(fold-abst '(3 4 5) 100) ; error (undefined function abst)
||#
(verify-guards ; guard verification needed for defattach
mult)
; Next we attach the executable function mult to the
; abstract specification function abst. The proof
; obligations ensure, roughly speaking, that mult satisfies
; the constraints on abst. In this case the proofs of
; those obligations are skipped because they were already
; proved (and then cached) at the earlier functional
; instantiation (see fold-mult-reverse).
(defattach abst mult) ; note cached proof obligations
; Next we do a sample computation using fold-abst
; (interestingly, without calling fold-mult). The
; foundations guarantees that this computation is taking
; place in a consistent extension of the current theory,
; called the "evaluation theory". The equality below is a
; theorem of the evaluation theory, but not of the (weaker)
; current theory.
#||
(fold-abst '(3 4 5) 100)
(trace$ abst mult) ; to see abst transfer control to mult
(fold-abst '(3 4 5) 100)
(untrace$)
||#
(assert-event (equal (fold-abst '(3 4 5) 100)
6000))
; Note that this equality is NOT a theorem of the current
; session; it's only a theorem if we extend the session by
; "attachment equations" such as the following, to obtain
; the so-called "evaluation history":
; (forall x y) (equal (abst x y) (mult x y))
; Not included because the books/make-event/ directory
; depends on books/misc/:
; (include-book "make-event/eval" :dir :system)
; (must-fail (thm (equal (fold-abst '(3 4 5) 100)
; 6000)))
; Here is a second example, which provides a different
; extension of the current theory to the evaluation theory.
(defun add (x y)
(+ (fix x) (fix y)))
(verify-guards add)
(defattach abst add) ; note constraint proof this time
; The following example execution really makes our main
; point: We don't even need to define a fold function for
; add! We execute with the "abstract" function fold-abst,
; which we think of as "abstract" because it calls the
; encapsulated function abst. One can imagine more complex
; examples in which a large system of programs contains a
; few attachments at the leaves of the call trees. In such
; a case, it's particularly helpful that one can instantiate
; the system to different executable programs without
; defining analogues of the higher-level functions (like
; fold-abst), thus giving ACL2 some ability to mimic a
; higher-order programming language.
; To see abst transfer control to add:
; (trace$ abst add)
(assert-event (equal (fold-abst '(3 4 5) 100)
112))
; Here are some forms to run at the end of a demo:
#||
(defattach abst mult) ; note cached proof obligations
(fold-abst '(3 4 5) 100)
(thm
; This FAILS! ACL2 does not use attachments for
; evaluation of ground terms during rewriting, because
; it is proving theorems about the current ACL2 world,
; not the so-called "evaluation theory" in which we know
; (equal (abst x y) (mult x y)).
(equal (fold-abst '(3 4 5) 100)
6000))
||#
| true |
; Copyright (C) 2013, Regents of the University of Texas
; Written by PI:NAME:<NAME>END_PI, January, 2011 (revised slightly October, 2011)
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
; See also defattach-bang.lisp for a macro based
; on defattach that does not require guard verification.
; Defattach was introduced in ACL2 Version 4.0 (July, 2010).
; In this little example we show how defattach may be used
; to build systems of executable programs in which some of
; the functions are constrained. Be sure to see the final
; comment, which is really the punch line.
; For a demo using 800x600 resolution on a 15" laptop:
#||
(set-fmt-soft-right-margin 51 state)
(set-fmt-hard-right-margin 60 state)
||#
(in-package "ACL2")
; Experienced ACL2 users know that by using encapsulate, and
; without any need for defattach, you can deduce theorems
; about concrete functions from theorems about abstract
; functions, using the following steps.
; (1) Write abstract specifications -- basically, axioms
; about functions that are shown to hold for some
; witness functions.
; (2) Prove some theorems about the specification functions.
; (3) Write corresponding concrete definitions.
; (4) Prove that the concrete definitions satisfy the
; abstract specifications.
; (5) Conclude using functional instantiation that the
; theorems (from (2)) hold for the concrete functions
; (defined in (3)).
; Below we present a standard example of that style of
; reasoning. We then show how defattach goes beyond this:
; the idea is still to refine specification functions to
; more concrete definitions, but with defattach one can do
; this in a way that allows evaluation using the original
; function symbols.
; Thus, this file presents an example in two parts:
; traditional functional instantiation without defattach,
; and then evaluation using defattach.
; Here is an outline of the first part, using the numbered
; steps shown above.
; (1) Abstract spec:
; - Specify that abst is associative-commutative
; (example: +).
; - Define fold-abst to apply abst to successive elements
; of list; for example, (fold-abst '(1 2 3) r) is
; (abst 1 (abst 2 (abst 3 r))).
; (2) Prove that fold-abst(x) = fold-abst(reverse x).
; (3) Concrete definitions:
; - Define mult to be multiplication.
; - Define fold-mult in the obvious way.
; (4) Prove that the pair <mult,fold-mult> satisfies the
; abstract spec for <abst,fold-abst>.
; (5) Conclude that (fold-mult x) = (fold-mult (reverse x)).
; The second part then takes advantage of the first part,
; resulting in computation using the abstract functions by
; attaching corresponding concrete functions. We also
; provide a second set of attachments.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;; EXAMPLE WITHOUT DEFATTACH ;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(encapsulate
; (1) Abstract spec: Specify that abst is
; associative-commutative (example: +).
((abst (x y) t))
; We introduce abst, a function of two arguments.
; Our witnessing example is as follows:
(local (defun abst (x y)
(+ x y)))
; Exported specifications:
(defthm abst-comm
(equal (abst x y) (abst y x)))
(defthm abst-assoc
(equal (abst (abst x y) z)
(abst x (abst y z)))))
(defun fold-abst (x root)
; Complete abstract spec: define fold-abst to apply abst to
; successive elements of a list; for example,
; (fold-abst '(1 2 3) r) = (abst 1 (abst 2 (abst 3 r))).
(if (consp x)
(abst (car x)
(fold-abst (cdr x) root))
root))
(encapsulate ()
; (2) Prove some theorems about the specification functions.
; We prove fold-abst-reverse, below; the others are lemmas.
(local (defthm abst-comm2
(equal (abst x (abst y z))
(abst y (abst x z)))
:hints (("Goal"
:use ((:instance abst-assoc (x x) (y y))
(:instance abst-assoc (x y) (y x)))
:in-theory (disable abst-assoc)))))
(local (defthm fold-abst-abst
(equal (fold-abst x (abst a b))
(abst a (fold-abst x b)))))
(local (defthm fold-abst-revappend
(equal (fold-abst (revappend x y) root)
(fold-abst x (fold-abst y root)))))
(defthm fold-abst-reverse
(equal (fold-abst (reverse x) root)
(fold-abst x root))))
(defun mult (x y)
; (3) Write corresponding concrete definitions.
; - Define mult to be multiplication.
; - Below, we define fold-mult in the obvious way.
(* (fix x) (fix y)))
(defun fold-mult (x root)
(if (consp x)
(mult (car x)
(fold-mult (cdr x) root))
root))
(local ; included for (4) below
(include-book "arithmetic/top" :dir :system))
(defthm fold-mult-reverse
; (4) Prove that the concrete definitions satisfy the
; abstract specifications.
; We prove that the pair <mult,fold-mult> satisfies the
; abstract spec for <abst,fold-abst>. It is generated as
; part of the proof obligations from the hint below.
; (5) Conclude using functional instantiation that the
; theorems (from (2)) hold for the concrete functions
; (defined in (3)).
; We conclude that (fold-mult x) = (fold-mult (reverse x)).
(equal (fold-mult (reverse x) root)
(fold-mult x root))
:hints (("Goal" :by (:functional-instance
fold-abst-reverse
(abst mult)
(fold-abst fold-mult)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;; EXAMPLE WITH DEFATTACH ;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#||
(fold-abst '(3 4 5) 100) ; error (undefined function abst)
||#
(verify-guards ; guard verification needed for defattach
mult)
; Next we attach the executable function mult to the
; abstract specification function abst. The proof
; obligations ensure, roughly speaking, that mult satisfies
; the constraints on abst. In this case the proofs of
; those obligations are skipped because they were already
; proved (and then cached) at the earlier functional
; instantiation (see fold-mult-reverse).
(defattach abst mult) ; note cached proof obligations
; Next we do a sample computation using fold-abst
; (interestingly, without calling fold-mult). The
; foundations guarantees that this computation is taking
; place in a consistent extension of the current theory,
; called the "evaluation theory". The equality below is a
; theorem of the evaluation theory, but not of the (weaker)
; current theory.
#||
(fold-abst '(3 4 5) 100)
(trace$ abst mult) ; to see abst transfer control to mult
(fold-abst '(3 4 5) 100)
(untrace$)
||#
(assert-event (equal (fold-abst '(3 4 5) 100)
6000))
; Note that this equality is NOT a theorem of the current
; session; it's only a theorem if we extend the session by
; "attachment equations" such as the following, to obtain
; the so-called "evaluation history":
; (forall x y) (equal (abst x y) (mult x y))
; Not included because the books/make-event/ directory
; depends on books/misc/:
; (include-book "make-event/eval" :dir :system)
; (must-fail (thm (equal (fold-abst '(3 4 5) 100)
; 6000)))
; Here is a second example, which provides a different
; extension of the current theory to the evaluation theory.
(defun add (x y)
(+ (fix x) (fix y)))
(verify-guards add)
(defattach abst add) ; note constraint proof this time
; The following example execution really makes our main
; point: We don't even need to define a fold function for
; add! We execute with the "abstract" function fold-abst,
; which we think of as "abstract" because it calls the
; encapsulated function abst. One can imagine more complex
; examples in which a large system of programs contains a
; few attachments at the leaves of the call trees. In such
; a case, it's particularly helpful that one can instantiate
; the system to different executable programs without
; defining analogues of the higher-level functions (like
; fold-abst), thus giving ACL2 some ability to mimic a
; higher-order programming language.
; To see abst transfer control to add:
; (trace$ abst add)
(assert-event (equal (fold-abst '(3 4 5) 100)
112))
; Here are some forms to run at the end of a demo:
#||
(defattach abst mult) ; note cached proof obligations
(fold-abst '(3 4 5) 100)
(thm
; This FAILS! ACL2 does not use attachments for
; evaluation of ground terms during rewriting, because
; it is proving theorems about the current ACL2 world,
; not the so-called "evaluation theory" in which we know
; (equal (abst x y) (mult x y)).
(equal (fold-abst '(3 4 5) 100)
6000))
||#
|
[
{
"context": ";;;; typed-memory-tests.lisp\n;;;;\n;;;; Authors: Eric Peterson\n;;;; Robert Smith\n;;;;\n;;;; Tests for ty",
"end": 61,
"score": 0.999825656414032,
"start": 48,
"tag": "NAME",
"value": "Eric Peterson"
},
{
"context": "isp\n;;;;\n;;;; Authors: Eric Peterson\n;;;; Robert Smith\n;;;;\n;;;; Tests for type-safety.lisp and classica",
"end": 88,
"score": 0.9997450709342957,
"start": 76,
"tag": "NAME",
"value": "Robert Smith"
}
] |
tests/typed-memory-tests.lisp
|
stylewarning/quilc
| 348 |
;;;; typed-memory-tests.lisp
;;;;
;;;; Authors: Eric Peterson
;;;; Robert Smith
;;;;
;;;; Tests for type-safety.lisp and classical-memory.lisp
(in-package #:cl-quil-tests)
(deftest test-typed-circuit-expansion ()
(let ((pp (quil::parse-quil "
DECLARE a BIT
DEFCIRCUIT CLEAR q scratch-bit:
MEASURE q scratch-bit
JUMP-UNLESS @end scratch-bit
X q
LABEL @end
CLEAR 0 a")))
(let ((instr (aref (quil::parsed-program-executable-code pp) 0)))
(is (typep instr 'quil::measure))
(is (= (quil::qubit-index (quil::measurement-qubit instr)) 0))
(is (equalp (quil::measure-address instr)
(quil::mref "a" 0 (first (quil::parsed-program-memory-definitions pp))))))))
(deftest test-constant-coercion ()
(let ((pp (quil::parse-quil "
DECLARE stats INTEGER
DECLARE angle REAL
# Initialize
MOVE stats 0
MOVE angle 0
RX(-2.0*angle) 0")))
(let ((code (parsed-program-executable-code pp)))
(is (equalp quil::quil-integer (quil::constant-value-type
(quil::classical-right-operand (aref code 0)))))
(is (equalp quil::quil-real (quil::constant-value-type
(quil::classical-right-operand (aref code 1)))))
(let ((param (first (application-parameters (aref code 2)))))
(is (typep param 'quil::delayed-expression))))))
(deftest test-compression-with-classical-angles ()
(let ((pp (quil::parse-quil "
DECLARE val REAL[8]
DECLARE ro BIT
DECLARE int INTEGER
RZ(val[2]) 0
RZ(val[0]+val[1]) 0
RZ(val[1]) 0
RZ(val[3]) 1")))
(let ((cpp (quil::compiler-hook pp (quil::build-8Q-chip))))
(is (= 3 (length (quil::parsed-program-executable-code cpp)))))))
(deftest test-compression-with-classical-angles-+-resource-usage ()
(let ((pp (quil::parse-quil "
DECLARE val REAL[8]
DECLARE ro BIT
DECLARE int INTEGER
RZ(val[2]) 0
STORE val int[0] val[1]
RZ(val[0]+val[1]) 0
RZ(val[1]) 0
RZ(val[3]) 1")))
(let ((cpp (quil::compiler-hook pp (quil::build-8Q-chip))))
(is (= 5 (length (quil::parsed-program-executable-code cpp)))))))
(deftest test-paltry-type-conversions ()
"Test that we convert classical base classes into specialized classes correctly."
(let ((code (quil:parsed-program-executable-code
(quil:parse-quil "
DECLARE w BIT
DECLARE x OCTET
DECLARE y INTEGER
DECLARE z REAL
NOT w
ADD z z
ADD z 1.0
CONVERT z w
XOR x x
LOAD z z y
STORE w y w
"))))
(is (every #'typep code '(quil:classical-not-bit
quil:classical-addition-real/real
quil:classical-addition-real/immediate
quil:classical-convert-real/bit
quil:classical-exclusive-or-octet/octet
quil:classical-load-real/real*/integer
quil:classical-store-bit*/integer/bit)))))
(deftest test-classical-equality-immediate-types ()
(signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a BIT; EQ r a 1.0"))
(signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a OCTET; EQ r a 1.0"))
(signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a INTEGER; EQ r a 1.0"))
(signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a REAL; EQ r a 1"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a BIT; DECLARE b BIT; EQ r a b"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a BIT; EQ r a 1"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a OCTET; DECLARE b OCTET; EQ r a b"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a OCTET; EQ r a 1"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a INTEGER; DECLARE b INTEGER; EQ r a b"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a INTEGER; EQ r a 1"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a REAL; DECLARE b REAL; EQ r a b"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a REAL; EQ r a 1.0")))
(deftest test-classical-store-types ()
(not-signals quil-type-error (parse-quil "DECLARE ro BIT; DECLARE v BIT; DECLARE index INTEGER; STORE ro index v;"))
(not-signals quil-type-error (parse-quil "DECLARE ro BIT; DECLARE index INTEGER; STORE ro index 1;"))
(not-signals quil-type-error (parse-quil "DECLARE ro OCTET; DECLARE v OCTET; DECLARE index INTEGER; STORE ro index v;"))
(not-signals quil-type-error (parse-quil "DECLARE ro OCTET; DECLARE index INTEGER; STORE ro index 1;"))
(not-signals quil-type-error (parse-quil "DECLARE ro INTEGER; DECLARE v INTEGER; DECLARE index INTEGER; STORE ro index v;"))
(not-signals quil-type-error (parse-quil "DECLARE ro INTEGER; DECLARE index INTEGER; STORE ro index 1;"))
(not-signals quil-type-error (parse-quil "DECLARE ro REAL; DECLARE v REAL; DECLARE index INTEGER; STORE ro index v;"))
(not-signals quil-type-error (parse-quil "DECLARE ro REAL; DECLARE index INTEGER; STORE ro index 1;"))
;; Storing REAL into BIT
(signals quil-type-error (parse-quil "DECLARE ro BIT; DECLARE v REAL; DECLARE index INTEGER; STORE ro index v;"))
(signals quil-type-error (parse-quil "DECLARE ro BIT; DECLARE index INTEGER; STORE ro index 1.0;"))
;; Storing REAL into OCTET
(signals quil-type-error (parse-quil "DECLARE ro OCTET; DECLARE v REAL; DECLARE index INTEGER; STORE ro index v;"))
(signals quil-type-error (parse-quil "DECLARE ro OCTET; DECLARE index INTEGER; STORE ro index 1.0;"))
;; Storing REAL into INTEGER
(signals quil-type-error (parse-quil "DECLARE ro INTEGER; DECLARE v REAL; DECLARE index INTEGER; STORE ro index v;"))
(signals quil-type-error (parse-quil "DECLARE ro INTEGER; DECLARE index INTEGER; STORE ro index 1.0;")))
|
25135
|
;;;; typed-memory-tests.lisp
;;;;
;;;; Authors: <NAME>
;;;; <NAME>
;;;;
;;;; Tests for type-safety.lisp and classical-memory.lisp
(in-package #:cl-quil-tests)
(deftest test-typed-circuit-expansion ()
(let ((pp (quil::parse-quil "
DECLARE a BIT
DEFCIRCUIT CLEAR q scratch-bit:
MEASURE q scratch-bit
JUMP-UNLESS @end scratch-bit
X q
LABEL @end
CLEAR 0 a")))
(let ((instr (aref (quil::parsed-program-executable-code pp) 0)))
(is (typep instr 'quil::measure))
(is (= (quil::qubit-index (quil::measurement-qubit instr)) 0))
(is (equalp (quil::measure-address instr)
(quil::mref "a" 0 (first (quil::parsed-program-memory-definitions pp))))))))
(deftest test-constant-coercion ()
(let ((pp (quil::parse-quil "
DECLARE stats INTEGER
DECLARE angle REAL
# Initialize
MOVE stats 0
MOVE angle 0
RX(-2.0*angle) 0")))
(let ((code (parsed-program-executable-code pp)))
(is (equalp quil::quil-integer (quil::constant-value-type
(quil::classical-right-operand (aref code 0)))))
(is (equalp quil::quil-real (quil::constant-value-type
(quil::classical-right-operand (aref code 1)))))
(let ((param (first (application-parameters (aref code 2)))))
(is (typep param 'quil::delayed-expression))))))
(deftest test-compression-with-classical-angles ()
(let ((pp (quil::parse-quil "
DECLARE val REAL[8]
DECLARE ro BIT
DECLARE int INTEGER
RZ(val[2]) 0
RZ(val[0]+val[1]) 0
RZ(val[1]) 0
RZ(val[3]) 1")))
(let ((cpp (quil::compiler-hook pp (quil::build-8Q-chip))))
(is (= 3 (length (quil::parsed-program-executable-code cpp)))))))
(deftest test-compression-with-classical-angles-+-resource-usage ()
(let ((pp (quil::parse-quil "
DECLARE val REAL[8]
DECLARE ro BIT
DECLARE int INTEGER
RZ(val[2]) 0
STORE val int[0] val[1]
RZ(val[0]+val[1]) 0
RZ(val[1]) 0
RZ(val[3]) 1")))
(let ((cpp (quil::compiler-hook pp (quil::build-8Q-chip))))
(is (= 5 (length (quil::parsed-program-executable-code cpp)))))))
(deftest test-paltry-type-conversions ()
"Test that we convert classical base classes into specialized classes correctly."
(let ((code (quil:parsed-program-executable-code
(quil:parse-quil "
DECLARE w BIT
DECLARE x OCTET
DECLARE y INTEGER
DECLARE z REAL
NOT w
ADD z z
ADD z 1.0
CONVERT z w
XOR x x
LOAD z z y
STORE w y w
"))))
(is (every #'typep code '(quil:classical-not-bit
quil:classical-addition-real/real
quil:classical-addition-real/immediate
quil:classical-convert-real/bit
quil:classical-exclusive-or-octet/octet
quil:classical-load-real/real*/integer
quil:classical-store-bit*/integer/bit)))))
(deftest test-classical-equality-immediate-types ()
(signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a BIT; EQ r a 1.0"))
(signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a OCTET; EQ r a 1.0"))
(signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a INTEGER; EQ r a 1.0"))
(signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a REAL; EQ r a 1"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a BIT; DECLARE b BIT; EQ r a b"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a BIT; EQ r a 1"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a OCTET; DECLARE b OCTET; EQ r a b"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a OCTET; EQ r a 1"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a INTEGER; DECLARE b INTEGER; EQ r a b"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a INTEGER; EQ r a 1"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a REAL; DECLARE b REAL; EQ r a b"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a REAL; EQ r a 1.0")))
(deftest test-classical-store-types ()
(not-signals quil-type-error (parse-quil "DECLARE ro BIT; DECLARE v BIT; DECLARE index INTEGER; STORE ro index v;"))
(not-signals quil-type-error (parse-quil "DECLARE ro BIT; DECLARE index INTEGER; STORE ro index 1;"))
(not-signals quil-type-error (parse-quil "DECLARE ro OCTET; DECLARE v OCTET; DECLARE index INTEGER; STORE ro index v;"))
(not-signals quil-type-error (parse-quil "DECLARE ro OCTET; DECLARE index INTEGER; STORE ro index 1;"))
(not-signals quil-type-error (parse-quil "DECLARE ro INTEGER; DECLARE v INTEGER; DECLARE index INTEGER; STORE ro index v;"))
(not-signals quil-type-error (parse-quil "DECLARE ro INTEGER; DECLARE index INTEGER; STORE ro index 1;"))
(not-signals quil-type-error (parse-quil "DECLARE ro REAL; DECLARE v REAL; DECLARE index INTEGER; STORE ro index v;"))
(not-signals quil-type-error (parse-quil "DECLARE ro REAL; DECLARE index INTEGER; STORE ro index 1;"))
;; Storing REAL into BIT
(signals quil-type-error (parse-quil "DECLARE ro BIT; DECLARE v REAL; DECLARE index INTEGER; STORE ro index v;"))
(signals quil-type-error (parse-quil "DECLARE ro BIT; DECLARE index INTEGER; STORE ro index 1.0;"))
;; Storing REAL into OCTET
(signals quil-type-error (parse-quil "DECLARE ro OCTET; DECLARE v REAL; DECLARE index INTEGER; STORE ro index v;"))
(signals quil-type-error (parse-quil "DECLARE ro OCTET; DECLARE index INTEGER; STORE ro index 1.0;"))
;; Storing REAL into INTEGER
(signals quil-type-error (parse-quil "DECLARE ro INTEGER; DECLARE v REAL; DECLARE index INTEGER; STORE ro index v;"))
(signals quil-type-error (parse-quil "DECLARE ro INTEGER; DECLARE index INTEGER; STORE ro index 1.0;")))
| true |
;;;; typed-memory-tests.lisp
;;;;
;;;; Authors: PI:NAME:<NAME>END_PI
;;;; PI:NAME:<NAME>END_PI
;;;;
;;;; Tests for type-safety.lisp and classical-memory.lisp
(in-package #:cl-quil-tests)
(deftest test-typed-circuit-expansion ()
(let ((pp (quil::parse-quil "
DECLARE a BIT
DEFCIRCUIT CLEAR q scratch-bit:
MEASURE q scratch-bit
JUMP-UNLESS @end scratch-bit
X q
LABEL @end
CLEAR 0 a")))
(let ((instr (aref (quil::parsed-program-executable-code pp) 0)))
(is (typep instr 'quil::measure))
(is (= (quil::qubit-index (quil::measurement-qubit instr)) 0))
(is (equalp (quil::measure-address instr)
(quil::mref "a" 0 (first (quil::parsed-program-memory-definitions pp))))))))
(deftest test-constant-coercion ()
(let ((pp (quil::parse-quil "
DECLARE stats INTEGER
DECLARE angle REAL
# Initialize
MOVE stats 0
MOVE angle 0
RX(-2.0*angle) 0")))
(let ((code (parsed-program-executable-code pp)))
(is (equalp quil::quil-integer (quil::constant-value-type
(quil::classical-right-operand (aref code 0)))))
(is (equalp quil::quil-real (quil::constant-value-type
(quil::classical-right-operand (aref code 1)))))
(let ((param (first (application-parameters (aref code 2)))))
(is (typep param 'quil::delayed-expression))))))
(deftest test-compression-with-classical-angles ()
(let ((pp (quil::parse-quil "
DECLARE val REAL[8]
DECLARE ro BIT
DECLARE int INTEGER
RZ(val[2]) 0
RZ(val[0]+val[1]) 0
RZ(val[1]) 0
RZ(val[3]) 1")))
(let ((cpp (quil::compiler-hook pp (quil::build-8Q-chip))))
(is (= 3 (length (quil::parsed-program-executable-code cpp)))))))
(deftest test-compression-with-classical-angles-+-resource-usage ()
(let ((pp (quil::parse-quil "
DECLARE val REAL[8]
DECLARE ro BIT
DECLARE int INTEGER
RZ(val[2]) 0
STORE val int[0] val[1]
RZ(val[0]+val[1]) 0
RZ(val[1]) 0
RZ(val[3]) 1")))
(let ((cpp (quil::compiler-hook pp (quil::build-8Q-chip))))
(is (= 5 (length (quil::parsed-program-executable-code cpp)))))))
(deftest test-paltry-type-conversions ()
"Test that we convert classical base classes into specialized classes correctly."
(let ((code (quil:parsed-program-executable-code
(quil:parse-quil "
DECLARE w BIT
DECLARE x OCTET
DECLARE y INTEGER
DECLARE z REAL
NOT w
ADD z z
ADD z 1.0
CONVERT z w
XOR x x
LOAD z z y
STORE w y w
"))))
(is (every #'typep code '(quil:classical-not-bit
quil:classical-addition-real/real
quil:classical-addition-real/immediate
quil:classical-convert-real/bit
quil:classical-exclusive-or-octet/octet
quil:classical-load-real/real*/integer
quil:classical-store-bit*/integer/bit)))))
(deftest test-classical-equality-immediate-types ()
(signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a BIT; EQ r a 1.0"))
(signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a OCTET; EQ r a 1.0"))
(signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a INTEGER; EQ r a 1.0"))
(signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a REAL; EQ r a 1"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a BIT; DECLARE b BIT; EQ r a b"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a BIT; EQ r a 1"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a OCTET; DECLARE b OCTET; EQ r a b"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a OCTET; EQ r a 1"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a INTEGER; DECLARE b INTEGER; EQ r a b"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a INTEGER; EQ r a 1"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a REAL; DECLARE b REAL; EQ r a b"))
(not-signals quil-type-error (parse-quil "DECLARE r BIT; DECLARE a REAL; EQ r a 1.0")))
(deftest test-classical-store-types ()
(not-signals quil-type-error (parse-quil "DECLARE ro BIT; DECLARE v BIT; DECLARE index INTEGER; STORE ro index v;"))
(not-signals quil-type-error (parse-quil "DECLARE ro BIT; DECLARE index INTEGER; STORE ro index 1;"))
(not-signals quil-type-error (parse-quil "DECLARE ro OCTET; DECLARE v OCTET; DECLARE index INTEGER; STORE ro index v;"))
(not-signals quil-type-error (parse-quil "DECLARE ro OCTET; DECLARE index INTEGER; STORE ro index 1;"))
(not-signals quil-type-error (parse-quil "DECLARE ro INTEGER; DECLARE v INTEGER; DECLARE index INTEGER; STORE ro index v;"))
(not-signals quil-type-error (parse-quil "DECLARE ro INTEGER; DECLARE index INTEGER; STORE ro index 1;"))
(not-signals quil-type-error (parse-quil "DECLARE ro REAL; DECLARE v REAL; DECLARE index INTEGER; STORE ro index v;"))
(not-signals quil-type-error (parse-quil "DECLARE ro REAL; DECLARE index INTEGER; STORE ro index 1;"))
;; Storing REAL into BIT
(signals quil-type-error (parse-quil "DECLARE ro BIT; DECLARE v REAL; DECLARE index INTEGER; STORE ro index v;"))
(signals quil-type-error (parse-quil "DECLARE ro BIT; DECLARE index INTEGER; STORE ro index 1.0;"))
;; Storing REAL into OCTET
(signals quil-type-error (parse-quil "DECLARE ro OCTET; DECLARE v REAL; DECLARE index INTEGER; STORE ro index v;"))
(signals quil-type-error (parse-quil "DECLARE ro OCTET; DECLARE index INTEGER; STORE ro index 1.0;"))
;; Storing REAL into INTEGER
(signals quil-type-error (parse-quil "DECLARE ro INTEGER; DECLARE v REAL; DECLARE index INTEGER; STORE ro index v;"))
(signals quil-type-error (parse-quil "DECLARE ro INTEGER; DECLARE index INTEGER; STORE ro index 1.0;")))
|
[
{
"context": "tation for CSV Wormtrails\n\n;;;; Copyright (c) 2014 Mark Trapp\n\n;;;; Permission is hereby granted, free of charg",
"end": 82,
"score": 0.99969083070755,
"start": 72,
"tag": "NAME",
"value": "Mark Trapp"
}
] |
examples/states-top-10.lisp
|
itafroma/wormtrails-csv
| 0 |
;;;; Example implementation for CSV Wormtrails
;;;; Copyright (c) 2014 Mark Trapp
;;;; Permission is hereby granted, free of charge, to any person obtaining a
;;;; copy of this software and associated documentation files (the "Software"),
;;;; to deal in the Software without restriction, including without limitation
;;;; the rights to use, copy, modify, merge, publish, distribute, sublicense,
;;;; and/or sell copies of the Software, and to permit persons to whom the
;;;; Software is furnished to do so, subject to the following conditions:
;;;; The above copyright notice and this permission notice shall be included in
;;;; all copies or substantial portions of the Software.
;;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;;; DEALINGS IN THE SOFTWARE.
;;; Load Wormtrails CSV. Note: you must install the Wormtrails and Geometry
;;; libraries or this will fail! See the "Dependencies" section of the README
;;; for more information.
(ql:quickload "wormtrails-csv")
;;;; Configuration options for Wormtrails and Wormtrails CSV
;;;; Feel free to change anything here to your liking.
;;; CSV file to use for data:
;;; - The first row is reserved for the header. Column 1 is ignored but the
;;; rest of the columns are used for time period, or "bucket", names. They
;;; must be numeric (e.g., use "201401" not "2014-01-01").
;;; - The reset of the rows correspond to each ribbon/worm, or "thing", on the
;;; chart. The first column is the thing name, while the rest of the columns
;;; correspond to the values, or "samples", for each bucket. Samples can be
;;; blank, but otherwise must be numeric.
;;; See data/states.csv for an example.
;;; Also accepts an absolute path: (defparameter *infile* "/foo/input.csv")
(defparameter *infile* (asdf:system-relative-pathname 'wormtrails-csv "data/states.csv"))
;;; Output PNG for chart. A companion HTML file with the same name will be
;;; created alongside the PNG.
;;; Also accepts an absolute path: (defparameter *outfile* "/foo/output.png")
(defparameter *outfile* (asdf:system-relative-pathname 'wormtrails-csv "output/states-top-10.png"))
;;; Scale for chart. The correct value to use here is an aesthetic judgment and
;;; should be found via trial-and-error. A basic rule of thumb is to use a scale
;;; that when multiplied by the largest sample value is ~100-200.
(defparameter *scale* 0.00001)
;;; Height of each Y-axis segment in pixels.
;;; Also accepts an integer: (defparameter *metric-height* 100)
(defparameter *metric-height* (* *scale* 10000000))
;;; Cut-off point for worms to show on chart. If a worm is not in the top-n for
;;; a specific time period, it will not show up on the chart, but may show up
;;; in earlier or later time periods if it gets into the top-n then.
(defparameter *top-n* 10)
;;; Label for the Y-axis segmenting.
(defparameter *metric-label* "10M PEOPLE")
;;; Label for the overall chart.
(defparameter wormtrails:*default-name* "Top 10 States")
;;; Width of each time period in pixels.
(defparameter wormtrails:*bucket-width* 100)
;;; Horizontal gap between each time period in pixels.
(defparameter wormtrails:*bucket-gap* 50)
;;; Vertical gap between each worm in pixels.
(defparameter wormtrails:*sample-gap* 2)
;;;; SETQ is used for the next set of options because Wormtrails's vecto.lisp
;;;; uses DEFVAR instead of DEFPARAMETER.
;;; Font size of all labels in points.
(setq wormtrails:*font-size* 13)
;;; Horizontal padding to add to chart in pixels.
(setq wormtrails:*canvas-padding* 25)
;;; Padding on wormtrail labels in pixels.
(setq wormtrails:*text-padding* 2)
;;; Path to the TTF font file to use for labels.
;;; Also acceps an absolute path: (setq wormtrails:*font-file* "/fonts/foo.ttf")
(setq wormtrails:*font-file*
(asdf:system-relative-pathname 'wormtrails "font.ttf"))
;;; Mouseover label formatting.
;;; This example has two values passed to the mouseover label:
;;; the thing name (a string) and the sample value (a number). You can use any
;;; valid FORMAT specifier for the string: see
;;; http://psg.com/~dlamkins/sl/chapter24.html for a list.
;;; Examples:
;;; - "~A (pop. ~:D)" => "New York (pop. 12,345,321)"
;;; - "~A (~D)" => "New York (12345321)"
;;; - "~:@(~a~) ~:x" => "NEW YORK BC5,FE9"
(defmethod wormtrails::mouseover-banner-html ((sample wormtrails-csv::cell))
(format nil
"~A (pop. ~:D)"
(wormtrails:name (wormtrails:thing sample))
(wormtrails:value sample)))
;;;; End Wormtrails and Wormtrails CSV configuration options
;;; Pass all parameters to Wormtrails CSV and generate the chart.
;;; wormtrails-namespaced parameters are pulled in automatically and should not
;;; be passed here.
(wormtrails-csv::generate *infile*
*outfile*
:scale *scale*
:height *metric-height*
:label *metric-label*
:top-n *top-n*)
|
44846
|
;;;; Example implementation for CSV Wormtrails
;;;; Copyright (c) 2014 <NAME>
;;;; Permission is hereby granted, free of charge, to any person obtaining a
;;;; copy of this software and associated documentation files (the "Software"),
;;;; to deal in the Software without restriction, including without limitation
;;;; the rights to use, copy, modify, merge, publish, distribute, sublicense,
;;;; and/or sell copies of the Software, and to permit persons to whom the
;;;; Software is furnished to do so, subject to the following conditions:
;;;; The above copyright notice and this permission notice shall be included in
;;;; all copies or substantial portions of the Software.
;;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;;; DEALINGS IN THE SOFTWARE.
;;; Load Wormtrails CSV. Note: you must install the Wormtrails and Geometry
;;; libraries or this will fail! See the "Dependencies" section of the README
;;; for more information.
(ql:quickload "wormtrails-csv")
;;;; Configuration options for Wormtrails and Wormtrails CSV
;;;; Feel free to change anything here to your liking.
;;; CSV file to use for data:
;;; - The first row is reserved for the header. Column 1 is ignored but the
;;; rest of the columns are used for time period, or "bucket", names. They
;;; must be numeric (e.g., use "201401" not "2014-01-01").
;;; - The reset of the rows correspond to each ribbon/worm, or "thing", on the
;;; chart. The first column is the thing name, while the rest of the columns
;;; correspond to the values, or "samples", for each bucket. Samples can be
;;; blank, but otherwise must be numeric.
;;; See data/states.csv for an example.
;;; Also accepts an absolute path: (defparameter *infile* "/foo/input.csv")
(defparameter *infile* (asdf:system-relative-pathname 'wormtrails-csv "data/states.csv"))
;;; Output PNG for chart. A companion HTML file with the same name will be
;;; created alongside the PNG.
;;; Also accepts an absolute path: (defparameter *outfile* "/foo/output.png")
(defparameter *outfile* (asdf:system-relative-pathname 'wormtrails-csv "output/states-top-10.png"))
;;; Scale for chart. The correct value to use here is an aesthetic judgment and
;;; should be found via trial-and-error. A basic rule of thumb is to use a scale
;;; that when multiplied by the largest sample value is ~100-200.
(defparameter *scale* 0.00001)
;;; Height of each Y-axis segment in pixels.
;;; Also accepts an integer: (defparameter *metric-height* 100)
(defparameter *metric-height* (* *scale* 10000000))
;;; Cut-off point for worms to show on chart. If a worm is not in the top-n for
;;; a specific time period, it will not show up on the chart, but may show up
;;; in earlier or later time periods if it gets into the top-n then.
(defparameter *top-n* 10)
;;; Label for the Y-axis segmenting.
(defparameter *metric-label* "10M PEOPLE")
;;; Label for the overall chart.
(defparameter wormtrails:*default-name* "Top 10 States")
;;; Width of each time period in pixels.
(defparameter wormtrails:*bucket-width* 100)
;;; Horizontal gap between each time period in pixels.
(defparameter wormtrails:*bucket-gap* 50)
;;; Vertical gap between each worm in pixels.
(defparameter wormtrails:*sample-gap* 2)
;;;; SETQ is used for the next set of options because Wormtrails's vecto.lisp
;;;; uses DEFVAR instead of DEFPARAMETER.
;;; Font size of all labels in points.
(setq wormtrails:*font-size* 13)
;;; Horizontal padding to add to chart in pixels.
(setq wormtrails:*canvas-padding* 25)
;;; Padding on wormtrail labels in pixels.
(setq wormtrails:*text-padding* 2)
;;; Path to the TTF font file to use for labels.
;;; Also acceps an absolute path: (setq wormtrails:*font-file* "/fonts/foo.ttf")
(setq wormtrails:*font-file*
(asdf:system-relative-pathname 'wormtrails "font.ttf"))
;;; Mouseover label formatting.
;;; This example has two values passed to the mouseover label:
;;; the thing name (a string) and the sample value (a number). You can use any
;;; valid FORMAT specifier for the string: see
;;; http://psg.com/~dlamkins/sl/chapter24.html for a list.
;;; Examples:
;;; - "~A (pop. ~:D)" => "New York (pop. 12,345,321)"
;;; - "~A (~D)" => "New York (12345321)"
;;; - "~:@(~a~) ~:x" => "NEW YORK BC5,FE9"
(defmethod wormtrails::mouseover-banner-html ((sample wormtrails-csv::cell))
(format nil
"~A (pop. ~:D)"
(wormtrails:name (wormtrails:thing sample))
(wormtrails:value sample)))
;;;; End Wormtrails and Wormtrails CSV configuration options
;;; Pass all parameters to Wormtrails CSV and generate the chart.
;;; wormtrails-namespaced parameters are pulled in automatically and should not
;;; be passed here.
(wormtrails-csv::generate *infile*
*outfile*
:scale *scale*
:height *metric-height*
:label *metric-label*
:top-n *top-n*)
| true |
;;;; Example implementation for CSV Wormtrails
;;;; Copyright (c) 2014 PI:NAME:<NAME>END_PI
;;;; Permission is hereby granted, free of charge, to any person obtaining a
;;;; copy of this software and associated documentation files (the "Software"),
;;;; to deal in the Software without restriction, including without limitation
;;;; the rights to use, copy, modify, merge, publish, distribute, sublicense,
;;;; and/or sell copies of the Software, and to permit persons to whom the
;;;; Software is furnished to do so, subject to the following conditions:
;;;; The above copyright notice and this permission notice shall be included in
;;;; all copies or substantial portions of the Software.
;;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;;; DEALINGS IN THE SOFTWARE.
;;; Load Wormtrails CSV. Note: you must install the Wormtrails and Geometry
;;; libraries or this will fail! See the "Dependencies" section of the README
;;; for more information.
(ql:quickload "wormtrails-csv")
;;;; Configuration options for Wormtrails and Wormtrails CSV
;;;; Feel free to change anything here to your liking.
;;; CSV file to use for data:
;;; - The first row is reserved for the header. Column 1 is ignored but the
;;; rest of the columns are used for time period, or "bucket", names. They
;;; must be numeric (e.g., use "201401" not "2014-01-01").
;;; - The reset of the rows correspond to each ribbon/worm, or "thing", on the
;;; chart. The first column is the thing name, while the rest of the columns
;;; correspond to the values, or "samples", for each bucket. Samples can be
;;; blank, but otherwise must be numeric.
;;; See data/states.csv for an example.
;;; Also accepts an absolute path: (defparameter *infile* "/foo/input.csv")
(defparameter *infile* (asdf:system-relative-pathname 'wormtrails-csv "data/states.csv"))
;;; Output PNG for chart. A companion HTML file with the same name will be
;;; created alongside the PNG.
;;; Also accepts an absolute path: (defparameter *outfile* "/foo/output.png")
(defparameter *outfile* (asdf:system-relative-pathname 'wormtrails-csv "output/states-top-10.png"))
;;; Scale for chart. The correct value to use here is an aesthetic judgment and
;;; should be found via trial-and-error. A basic rule of thumb is to use a scale
;;; that when multiplied by the largest sample value is ~100-200.
(defparameter *scale* 0.00001)
;;; Height of each Y-axis segment in pixels.
;;; Also accepts an integer: (defparameter *metric-height* 100)
(defparameter *metric-height* (* *scale* 10000000))
;;; Cut-off point for worms to show on chart. If a worm is not in the top-n for
;;; a specific time period, it will not show up on the chart, but may show up
;;; in earlier or later time periods if it gets into the top-n then.
(defparameter *top-n* 10)
;;; Label for the Y-axis segmenting.
(defparameter *metric-label* "10M PEOPLE")
;;; Label for the overall chart.
(defparameter wormtrails:*default-name* "Top 10 States")
;;; Width of each time period in pixels.
(defparameter wormtrails:*bucket-width* 100)
;;; Horizontal gap between each time period in pixels.
(defparameter wormtrails:*bucket-gap* 50)
;;; Vertical gap between each worm in pixels.
(defparameter wormtrails:*sample-gap* 2)
;;;; SETQ is used for the next set of options because Wormtrails's vecto.lisp
;;;; uses DEFVAR instead of DEFPARAMETER.
;;; Font size of all labels in points.
(setq wormtrails:*font-size* 13)
;;; Horizontal padding to add to chart in pixels.
(setq wormtrails:*canvas-padding* 25)
;;; Padding on wormtrail labels in pixels.
(setq wormtrails:*text-padding* 2)
;;; Path to the TTF font file to use for labels.
;;; Also acceps an absolute path: (setq wormtrails:*font-file* "/fonts/foo.ttf")
(setq wormtrails:*font-file*
(asdf:system-relative-pathname 'wormtrails "font.ttf"))
;;; Mouseover label formatting.
;;; This example has two values passed to the mouseover label:
;;; the thing name (a string) and the sample value (a number). You can use any
;;; valid FORMAT specifier for the string: see
;;; http://psg.com/~dlamkins/sl/chapter24.html for a list.
;;; Examples:
;;; - "~A (pop. ~:D)" => "New York (pop. 12,345,321)"
;;; - "~A (~D)" => "New York (12345321)"
;;; - "~:@(~a~) ~:x" => "NEW YORK BC5,FE9"
(defmethod wormtrails::mouseover-banner-html ((sample wormtrails-csv::cell))
(format nil
"~A (pop. ~:D)"
(wormtrails:name (wormtrails:thing sample))
(wormtrails:value sample)))
;;;; End Wormtrails and Wormtrails CSV configuration options
;;; Pass all parameters to Wormtrails CSV and generate the chart.
;;; wormtrails-namespaced parameters are pulled in automatically and should not
;;; be passed here.
(wormtrails-csv::generate *infile*
*outfile*
:scale *scale*
:height *metric-height*
:label *metric-label*
:top-n *top-n*)
|
[
{
"context": " \"565b600080549050905600a165627a7a72305820e1f98c821c12eea52047d7\"\n \"324b034ddccc",
"end": 841,
"score": 0.5381452441215515,
"start": 840,
"tag": "KEY",
"value": "1"
},
{
"context": " \"565b600080549050905600a165627a7a72305820e1f98c821c12eea52047d7\"\n \"324b034ddccc41eaa7",
"end": 847,
"score": 0.51483553647995,
"start": 846,
"tag": "KEY",
"value": "2"
},
{
"context": "565b600080549050905600a165627a7a72305820e1f98c821c12eea52047d7\"\n \"324b034ddccc41eaa7365d369b34",
"end": 857,
"score": 0.5379798412322998,
"start": 849,
"tag": "KEY",
"value": "12eea520"
},
{
"context": "ffff16806360fe47b114604e\"\n \"5780636d4ce63c14606e575b600080fd5b3415605857600080fd5b606c6",
"end": 1204,
"score": 0.5843507051467896,
"start": 1203,
"tag": "KEY",
"value": "4"
},
{
"context": "806360fe47b114604e\"\n \"5780636d4ce63c14606e575b600080fd5b3415605857600080fd5b606c6004\"\n ",
"end": 1211,
"score": 0.518817663192749,
"start": 1209,
"tag": "KEY",
"value": "14"
},
{
"context": "fe47b114604e\"\n \"5780636d4ce63c14606e575b600080fd5b3415605857600080fd5b606c6004\"\n ",
"end": 1216,
"score": 0.5918881297111511,
"start": 1215,
"tag": "KEY",
"value": "5"
},
{
"context": "47b114604e\"\n \"5780636d4ce63c14606e575b600080fd5b3415605857600080fd5b606c6004\"\n ",
"end": 1218,
"score": 0.5383596420288086,
"start": 1217,
"tag": "KEY",
"value": "5"
},
{
"context": "b114604e\"\n \"5780636d4ce63c14606e575b600080fd5b3415605857600080fd5b606c6004\"\n ",
"end": 1220,
"score": 0.5149889588356018,
"start": 1219,
"tag": "KEY",
"value": "6"
},
{
"context": "604e\"\n \"5780636d4ce63c14606e575b600080fd5b3415605857600080fd5b606c6004\"\n ",
"end": 1224,
"score": 0.5072020292282104,
"start": 1223,
"tag": "KEY",
"value": "8"
},
{
"context": "\"\n \"5780636d4ce63c14606e575b600080fd5b3415605857600080fd5b606c6004\"\n \"808",
"end": 1228,
"score": 0.5383879542350769,
"start": 1227,
"tag": "KEY",
"value": "5"
},
{
"context": " \"5780636d4ce63c14606e575b600080fd5b3415605857600080fd5b606c6004\"\n \"80803590",
"end": 1233,
"score": 0.5537540316581726,
"start": 1231,
"tag": "KEY",
"value": "15"
},
{
"context": " \"5780636d4ce63c14606e575b600080fd5b3415605857600080fd5b606c6004\"\n \"80803590602",
"end": 1236,
"score": 0.515053391456604,
"start": 1235,
"tag": "KEY",
"value": "5"
},
{
"context": " \"5780636d4ce63c14606e575b600080fd5b3415605857600080fd5b606c6004\"\n \"8080359060200",
"end": 1238,
"score": 0.5306114554405212,
"start": 1237,
"tag": "KEY",
"value": "5"
},
{
"context": "80636d4ce63c14606e575b600080fd5b3415605857600080fd5b606c6004\"\n \"80803590602001909190505",
"end": 1248,
"score": 0.5384113192558289,
"start": 1247,
"tag": "KEY",
"value": "5"
},
{
"context": "eed contract runtime opcode\n;; https://github.com/ethereum/ens/blob/f3334337083728728da56824a5d0a30a8712b60c",
"end": 1632,
"score": 0.8820742964744568,
"start": 1624,
"tag": "USERNAME",
"value": "ethereum"
},
{
"context": "50\"\n \"5050151561052257600080fd5b7fbb2ce2f51803bba16bc85282b47deeea9a\"\n \"5c62",
"end": 5174,
"score": 0.5688610672950745,
"start": 5170,
"tag": "KEY",
"value": "2ce2"
},
{
"context": " \"5050151561052257600080fd5b7fbb2ce2f51803bba16bc85282b47deeea9a\"\n \"5c6223",
"end": 5176,
"score": 0.5150418281555176,
"start": 5175,
"tag": "KEY",
"value": "5"
},
{
"context": " \"5050151561052257600080fd5b7fbb2ce2f51803bba16bc85282b47deeea9a\"\n \"5c6223eabe",
"end": 5180,
"score": 0.5461133718490601,
"start": 5179,
"tag": "KEY",
"value": "3"
},
{
"context": " \"5050151561052257600080fd5b7fbb2ce2f51803bba16bc85282b47deeea9a\"\n \"5c6223eabea1077",
"end": 5185,
"score": 0.549584150314331,
"start": 5183,
"tag": "KEY",
"value": "16"
},
{
"context": " \"5050151561052257600080fd5b7fbb2ce2f51803bba16bc85282b47deeea9a\"\n \"5c6223eabea1077be6",
"end": 5188,
"score": 0.5460353493690491,
"start": 5187,
"tag": "KEY",
"value": "8"
},
{
"context": "0151561052257600080fd5b7fbb2ce2f51803bba16bc85282b47deeea9a\"\n \"5c6223eabea1077be696b3f2",
"end": 5194,
"score": 0.5995062589645386,
"start": 5193,
"tag": "KEY",
"value": "4"
},
{
"context": "51561052257600080fd5b7fbb2ce2f51803bba16bc85282b47deeea9a\"\n \"5c6223eabea1077be696b3f265cf1360",
"end": 5202,
"score": 0.6725509762763977,
"start": 5195,
"tag": "KEY",
"value": "deeea9a"
},
{
"context": "000000000000000\"\n \"00000000000000900463ffffffff1680631003e2d214604e5780636d4ce63c14606e575b6000\"\n \"80fd5b3415605857600080fd5b606c60",
"end": 15051,
"score": 0.9969831705093384,
"start": 14992,
"tag": "KEY",
"value": "463ffffffff1680631003e2d214604e5780636d4ce63c14606e575b6000"
},
{
"context": "604e5780636d4ce63c14606e575b6000\"\n \"80fd5b3415605857600080fd5b606c60048080359060200190919050506094565b005b341560\"\n \"7857600080fd5b607e60a2565b604051",
"end": 15145,
"score": 0.9975519776344299,
"start": 15069,
"tag": "KEY",
"value": "80fd5b3415605857600080fd5b606c60048080359060200190919050506094565b005b341560"
},
{
"context": "200190919050506094565b005b341560\"\n \"7857600080fd5b607e60a2565b6040518082815260200191505060405180910390f35b806000\"\n \"540160008190555050565b6000805490",
"end": 15239,
"score": 0.9982877373695374,
"start": 15163,
"tag": "KEY",
"value": "7857600080fd5b607e60a2565b6040518082815260200191505060405180910390f35b806000"
},
{
"context": "0191505060405180910390f35b806000\"\n \"540160008190555050565b600080549050905600a165627a7a7230582091b075ec0707939174\"\n \"0f0cc0b84e6fb576312f8a346c44f6a4",
"end": 15333,
"score": 0.9987744092941284,
"start": 15257,
"tag": "KEY",
"value": "540160008190555050565b600080549050905600a165627a7a7230582091b075ec0707939174"
},
{
"context": "627a7a7230582091b075ec0707939174\"\n \"0f0cc0b84e6fb576312f8a346c44f6a431b1f0eb5b88e60029\"))\n",
"end": 15401,
"score": 0.9977922439575195,
"start": 15351,
"tag": "KEY",
"value": "0f0cc0b84e6fb576312f8a346c44f6a431b1f0eb5b88e60029"
}
] |
books/evm/contracts.lisp
|
zchn/eth-acl2
| 4 |
(in-package "ACL2")
;; contract SimpleStorage {
;; uint storedData;
;; function set(uint x) {
;; storedData = x;
;; }
;; function get() constant returns (uint retVal) {
;; return storedData;
;; }
;; }
;; Contract registration:
(defconst *simple-storage-create*
(concatenate 'string
"6060604052341561000f57600080fd5b60d38061001d6000396000f3006060"
"604052600436106049576000357c0100000000000000000000000000000000"
"000000000000000000000000900463ffffffff16806360fe47b114604e5780"
"636d4ce63c14606e575b600080fd5b3415605857600080fd5b606c60048080"
"359060200190919050506094565b005b3415607857600080fd5b607e609e56"
"5b6040518082815260200191505060405180910390f35b8060008190555050"
"565b600080549050905600a165627a7a72305820e1f98c821c12eea52047d7"
"324b034ddccc41eaa7365d369b34580ab73c71a8940029"))
;; Contract being registered:
(defconst *simple-storage-contract*
(concatenate 'string
"6060604052600436106049576000357c010000000000000000000000000000"
"0000000000000000000000000000900463ffffffff16806360fe47b114604e"
"5780636d4ce63c14606e575b600080fd5b3415605857600080fd5b606c6004"
"8080359060200190919050506094565b005b3415607857600080fd5b607e60"
"9e565b6040518082815260200191505060405180910390f35b806000819055"
"5050565b600080549050905600a165627a7a72305820e1f98c821c12eea520"
"47d7324b034ddccc41eaa7365d369b34580ab73c71a8940029"))
;; Deed contract runtime opcode
;; https://github.com/ethereum/ens/blob/f3334337083728728da56824a5d0a30a8712b60c/HashRegistrarSimplified.sol#L25
(defconst *deed-contract*
(concatenate 'string
"60606040526004361061008e576000357c0100000000000000000000000000"
"000000000000000000000000000000900463ffffffff16806305b344101461"
"00905780630b5ab3d5146100b957806313af4035146100ce5780632b20e397"
"146101075780638da5cb5b1461015c578063bbe42771146101b1578063faab"
"9d39146101d4578063fb1669ca1461020d575b005b341561009b57600080fd"
"5b6100a3610225565b6040518082815260200191505060405180910390f35b"
"34156100c457600080fd5b6100cc61022b565b005b34156100d957600080fd"
"5b610105600480803573ffffffffffffffffffffffffffffffffffffffff16"
"9060200190919050506102d8565b005b341561011257600080fd5b61011a61"
"03da565b604051808273ffffffffffffffffffffffffffffffffffffffff16"
"73ffffffffffffffffffffffffffffffffffffffff16815260200191505060"
"405180910390f35b341561016757600080fd5b61016f6103ff565b60405180"
"8273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffff"
"ffffffffffffffffffffffffff16815260200191505060405180910390f35b"
"34156101bc57600080fd5b6101d26004808035906020019091905050610425"
"565b005b34156101df57600080fd5b61020b600480803573ffffffffffffff"
"ffffffffffffffffffffffffff16906020019091905050610559565b005b61"
"022360048080359060200190919050506105f7565b005b60015481565b6002"
"60149054906101000a900460ff161561024557600080fd5b60026000905490"
"6101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffff"
"ffffffffffffffffffffffffffffffffffff166108fc3073ffffffffffffff"
"ffffffffffffffffffffffffff163190811502906040516000604051808303"
"81858888f19350505050156102d35761dead73ffffffffffffffffffffffff"
"ffffffffffffffff16ff5b600080fd5b6000809054906101000a900473ffff"
"ffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffff"
"ffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffff"
"ff1614151561033357600080fd5b80600260006101000a81548173ffffffff"
"ffffffffffffffffffffffffffffffff021916908373ffffffffffffffffff"
"ffffffffffffffffffffff1602179055507fa2ea9883a321a3e97b8266c2b0"
"78bfeec6d50c711ed71f874a90d500ae2eaf3681604051808273ffffffffff"
"ffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffff"
"ffffffffffff16815260200191505060405180910390a150565b6000809054"
"906101000a900473ffffffffffffffffffffffffffffffffffffffff168156"
"5b600260009054906101000a900473ffffffffffffffffffffffffffffffff"
"ffffffff1681565b6000809054906101000a900473ffffffffffffffffffff"
"ffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffff"
"ff163373ffffffffffffffffffffffffffffffffffffffff16141515610480"
"57600080fd5b600260149054906101000a900460ff16151561049b57600080"
"fd5b6000600260146101000a81548160ff02191690831515021790555061de"
"ad73ffffffffffffffffffffffffffffffffffffffff166108fc6103e83073"
"ffffffffffffffffffffffffffffffffffffffff1631846103e80302811515"
"6104fc57fe5b049081150290604051600060405180830381858888f1935050"
"5050151561052257600080fd5b7fbb2ce2f51803bba16bc85282b47deeea9a"
"5c6223eabea1077be696b3f265cf1360405160405180910390a16105566102"
"2b565b50565b6000809054906101000a900473ffffffffffffffffffffffff"
"ffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16"
"3373ffffffffffffffffffffffffffffffffffffffff161415156105b45760"
"0080fd5b806000806101000a81548173ffffffffffffffffffffffffffffff"
"ffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff"
"16021790555050565b6000809054906101000a900473ffffffffffffffffff"
"ffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffff"
"ffff163373ffffffffffffffffffffffffffffffffffffffff161415156106"
"5257600080fd5b600260149054906101000a900460ff16151561066d576000"
"80fd5b803073ffffffffffffffffffffffffffffffffffffffff1631101561"
"069157600080fd5b600260009054906101000a900473ffffffffffffffffff"
"ffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffff"
"ffff166108fc823073ffffffffffffffffffffffffffffffffffffffff1631"
"039081150290604051600060405180830381858888f1935050505015156107"
"0c57600080fd5b505600a165627a7a7230582099b524f367ac8f6d64a5b0de"
"ae6fb395bb563d711c6ed83685ea7c6352aa3bdd0029"))
;; contract SimpleStorage {
;; uint storedData;
;; function add(uint x) {
;; storedData = storedData + x;
;; }
;; function get() constant returns (uint retVal) {
;; return storedData;
;; }
;; }
;; .code
;; PUSH 60 contract SimpleStorage {\n ...
;; PUSH 40 contract SimpleStorage {\n ...
;; MSTORE contract SimpleStorage {\n ...
;; CALLVALUE contract SimpleStorage {\n ...
;; ISZERO contract SimpleStorage {\n ...
;; PUSH [tag] 1 contract SimpleStorage {\n ...
;; JUMPI contract SimpleStorage {\n ...
;; PUSH 0 contract SimpleStorage {\n ...
;; DUP1 contract SimpleStorage {\n ...
;; REVERT contract SimpleStorage {\n ...
;; tag 1 contract SimpleStorage {\n ...
;; JUMPDEST contract SimpleStorage {\n ...
;; PUSH #[$] 0000000000000000000000000000000000000000000000000000000000000000 contract SimpleStorage {\n ...
;; DUP1 contract SimpleStorage {\n ...
;; PUSH [$] 0000000000000000000000000000000000000000000000000000000000000000 contract SimpleStorage {\n ...
;; PUSH 0 contract SimpleStorage {\n ...
;; CODECOPY contract SimpleStorage {\n ...
;; PUSH 0 contract SimpleStorage {\n ...
;; RETURN contract SimpleStorage {\n ...
;; .data
;; 0:
;; .code
;; PUSH 60 contract SimpleStorage {\n ...
;; PUSH 40 contract SimpleStorage {\n ...
;; MSTORE contract SimpleStorage {\n ...
;; PUSH 4 contract SimpleStorage {\n ...
;; CALLDATASIZE contract SimpleStorage {\n ...
;; LT contract SimpleStorage {\n ...
;; PUSH [tag] 1 contract SimpleStorage {\n ...
;; JUMPI contract SimpleStorage {\n ...
;; PUSH 0 contract SimpleStorage {\n ...
;; CALLDATALOAD contract SimpleStorage {\n ...
;; PUSH 100000000000000000000000000000000000000000000000000000000 contract SimpleStorage {\n ...
;; SWAP1 contract SimpleStorage {\n ...
;; DIV contract SimpleStorage {\n ...
;; PUSH FFFFFFFF contract SimpleStorage {\n ...
;; AND contract SimpleStorage {\n ...
;; DUP1 contract SimpleStorage {\n ...
;; PUSH 1003E2D2 contract SimpleStorage {\n ...
;; EQ contract SimpleStorage {\n ...
;; PUSH [tag] 2 contract SimpleStorage {\n ...
;; JUMPI contract SimpleStorage {\n ...
;; DUP1 contract SimpleStorage {\n ...
;; PUSH 6D4CE63C contract SimpleStorage {\n ...
;; EQ contract SimpleStorage {\n ...
;; PUSH [tag] 3 contract SimpleStorage {\n ...
;; JUMPI contract SimpleStorage {\n ...
;; tag 1 contract SimpleStorage {\n ...
;; JUMPDEST contract SimpleStorage {\n ...
;; PUSH 0 contract SimpleStorage {\n ...
;; DUP1 contract SimpleStorage {\n ...
;; REVERT contract SimpleStorage {\n ...
;; tag 2 function add(uint x) {\n ...
;; JUMPDEST function add(uint x) {\n ...
;; CALLVALUE function add(uint x) {\n ...
;; ISZERO function add(uint x) {\n ...
;; PUSH [tag] 4 function add(uint x) {\n ...
;; JUMPI function add(uint x) {\n ...
;; PUSH 0 function add(uint x) {\n ...
;; DUP1 function add(uint x) {\n ...
;; REVERT function add(uint x) {\n ...
;; tag 4 function add(uint x) {\n ...
;; JUMPDEST function add(uint x) {\n ...
;; PUSH [tag] 5 function add(uint x) {\n ...
;; PUSH 4 function add(uint x) {\n ...
;; DUP1 function add(uint x) {\n ...
;; DUP1 function add(uint x) {\n ...
;; CALLDATALOAD function add(uint x) {\n ...
;; SWAP1 function add(uint x) {\n ...
;; PUSH 20 function add(uint x) {\n ...
;; ADD function add(uint x) {\n ...
;; SWAP1 function add(uint x) {\n ...
;; SWAP2 function add(uint x) {\n ...
;; SWAP1 function add(uint x) {\n ...
;; POP function add(uint x) {\n ...
;; POP function add(uint x) {\n ...
;; PUSH [tag] 6 function add(uint x) {\n ...
;; JUMP function add(uint x) {\n ...
;; tag 5 function add(uint x) {\n ...
;; JUMPDEST function add(uint x) {\n ...
;; STOP function add(uint x) {\n ...
;; tag 3 function get() constant return...
;; JUMPDEST function get() constant return...
;; CALLVALUE function get() constant return...
;; ISZERO function get() constant return...
;; PUSH [tag] 7 function get() constant return...
;; JUMPI function get() constant return...
;; PUSH 0 function get() constant return...
;; DUP1 function get() constant return...
;; REVERT function get() constant return...
;; tag 7 function get() constant return...
;; JUMPDEST function get() constant return...
;; PUSH [tag] 8 function get() constant return...
;; PUSH [tag] 9 function get() constant return...
;; JUMP function get() constant return...
;; tag 8 function get() constant return...
;; JUMPDEST function get() constant return...
;; PUSH 40 function get() constant return...
;; MLOAD function get() constant return...
;; DUP1 function get() constant return...
;; DUP3 function get() constant return...
;; DUP2 function get() constant return...
;; MSTORE function get() constant return...
;; PUSH 20 function get() constant return...
;; ADD function get() constant return...
;; SWAP2 function get() constant return...
;; POP function get() constant return...
;; POP function get() constant return...
;; PUSH 40 function get() constant return...
;; MLOAD function get() constant return...
;; DUP1 function get() constant return...
;; SWAP2 function get() constant return...
;; SUB function get() constant return...
;; SWAP1 function get() constant return...
;; RETURN function get() constant return...
;; tag 6 function add(uint x) {\n ...
;; JUMPDEST function add(uint x) {\n ...
;; DUP1 x
;; PUSH 0 storedData
;; SLOAD storedData
;; ADD storedData + x
;; PUSH 0 storedData
;; DUP2 storedData = storedData + x
;; SWAP1 storedData = storedData + x
;; SSTORE storedData = storedData + x
;; POP storedData = storedData + x
;; POP function add(uint x) {\n ...
;; JUMP [out] function add(uint x) {\n ...
;; tag 9 function get() constant return...
;; JUMPDEST function get() constant return...
;; PUSH 0 uint retVal
;; DUP1 storedData
;; SLOAD storedData
;; SWAP1 return storedData
;; POP return storedData
;; SWAP1 function get() constant return...
;; JUMP [out] function get() constant return...
;; .data
;;
;; PUSH1 0x60 PUSH1 0x40 MSTORE PUSH1 0x4 CALLDATASIZE LT PUSH1 0x49
;; JUMPI PUSH1 0x0 CALLDATALOAD PUSH29
;; 0x100000000000000000000000000000000000000000000000000000000 SWAP1
;; DIV PUSH4 0xFFFFFFFF AND DUP1 PUSH4 0x1003E2D2 EQ PUSH1 0x4E JUMPI
;; DUP1 PUSH4 0x6D4CE63C EQ PUSH1 0x6E JUMPI JUMPDEST PUSH1 0x0 DUP1
;; REVERT JUMPDEST CALLVALUE ISZERO PUSH1 0x58 JUMPI PUSH1 0x0 DUP1
;; REVERT JUMPDEST PUSH1 0x6C PUSH1 0x4 DUP1 DUP1 CALLDATALOAD SWAP1
;; PUSH1 0x20 ADD SWAP1 SWAP2 SWAP1 POP POP PUSH1 0x94 JUMP JUMPDEST
;; STOP JUMPDEST CALLVALUE ISZERO PUSH1 0x78 JUMPI PUSH1 0x0 DUP1
;; REVERT JUMPDEST PUSH1 0x7E PUSH1 0xA2 JUMP JUMPDEST PUSH1 0x40
;; MLOAD DUP1 DUP3 DUP2 MSTORE PUSH1 0x20 ADD SWAP2 POP POP PUSH1 0x40
;; MLOAD DUP1 SWAP2 SUB SWAP1 RETURN JUMPDEST DUP1 PUSH1 0x0 SLOAD ADD
;; PUSH1 0x0 DUP2 SWAP1 SSTORE POP POP JUMP JUMPDEST PUSH1 0x0 DUP1
;; SLOAD SWAP1 POP SWAP1 JUMP STOP LOG1 PUSH6 0x627A7A723058 KECCAK256
;; SWAP2 0xb0 PUSH22 0xEC07079391740F0CC0B84E6FB576312F8A346C44F6A4
;; BALANCE 0xb1 CREATE 0xeb JUMPDEST DUP9 0xe6 STOP 0x29
(defconst *simple-adder-contract*
(concatenate 'string
"6060604052600436106049576000357c01000000000000000000000000000000000000000000"
"00000000000000900463ffffffff1680631003e2d214604e5780636d4ce63c14606e575b6000"
"80fd5b3415605857600080fd5b606c60048080359060200190919050506094565b005b341560"
"7857600080fd5b607e60a2565b6040518082815260200191505060405180910390f35b806000"
"540160008190555050565b600080549050905600a165627a7a7230582091b075ec0707939174"
"0f0cc0b84e6fb576312f8a346c44f6a431b1f0eb5b88e60029"))
|
80631
|
(in-package "ACL2")
;; contract SimpleStorage {
;; uint storedData;
;; function set(uint x) {
;; storedData = x;
;; }
;; function get() constant returns (uint retVal) {
;; return storedData;
;; }
;; }
;; Contract registration:
(defconst *simple-storage-create*
(concatenate 'string
"6060604052341561000f57600080fd5b60d38061001d6000396000f3006060"
"604052600436106049576000357c0100000000000000000000000000000000"
"000000000000000000000000900463ffffffff16806360fe47b114604e5780"
"636d4ce63c14606e575b600080fd5b3415605857600080fd5b606c60048080"
"359060200190919050506094565b005b3415607857600080fd5b607e609e56"
"5b6040518082815260200191505060405180910390f35b8060008190555050"
"565b600080549050905600a165627a7a72305820e<KEY>f98c8<KEY>1c<KEY>47d7"
"324b034ddccc41eaa7365d369b34580ab73c71a8940029"))
;; Contract being registered:
(defconst *simple-storage-contract*
(concatenate 'string
"6060604052600436106049576000357c010000000000000000000000000000"
"0000000000000000000000000000900463ffffffff16806360fe47b114604e"
"5780636d<KEY>ce63c<KEY>606e<KEY>7<KEY>b<KEY>000<KEY>0fd<KEY>b34<KEY>60<KEY>8<KEY>7600080fd<KEY>b606c6004"
"8080359060200190919050506094565b005b3415607857600080fd5b607e60"
"9e565b6040518082815260200191505060405180910390f35b806000819055"
"5050565b600080549050905600a165627a7a72305820e1f98c821c12eea520"
"47d7324b034ddccc41eaa7365d369b34580ab73c71a8940029"))
;; Deed contract runtime opcode
;; https://github.com/ethereum/ens/blob/f3334337083728728da56824a5d0a30a8712b60c/HashRegistrarSimplified.sol#L25
(defconst *deed-contract*
(concatenate 'string
"60606040526004361061008e576000357c0100000000000000000000000000"
"000000000000000000000000000000900463ffffffff16806305b344101461"
"00905780630b5ab3d5146100b957806313af4035146100ce5780632b20e397"
"146101075780638da5cb5b1461015c578063bbe42771146101b1578063faab"
"9d39146101d4578063fb1669ca1461020d575b005b341561009b57600080fd"
"5b6100a3610225565b6040518082815260200191505060405180910390f35b"
"34156100c457600080fd5b6100cc61022b565b005b34156100d957600080fd"
"5b610105600480803573ffffffffffffffffffffffffffffffffffffffff16"
"9060200190919050506102d8565b005b341561011257600080fd5b61011a61"
"03da565b604051808273ffffffffffffffffffffffffffffffffffffffff16"
"73ffffffffffffffffffffffffffffffffffffffff16815260200191505060"
"405180910390f35b341561016757600080fd5b61016f6103ff565b60405180"
"8273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffff"
"ffffffffffffffffffffffffff16815260200191505060405180910390f35b"
"34156101bc57600080fd5b6101d26004808035906020019091905050610425"
"565b005b34156101df57600080fd5b61020b600480803573ffffffffffffff"
"ffffffffffffffffffffffffff16906020019091905050610559565b005b61"
"022360048080359060200190919050506105f7565b005b60015481565b6002"
"60149054906101000a900460ff161561024557600080fd5b60026000905490"
"6101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffff"
"ffffffffffffffffffffffffffffffffffff166108fc3073ffffffffffffff"
"ffffffffffffffffffffffffff163190811502906040516000604051808303"
"81858888f19350505050156102d35761dead73ffffffffffffffffffffffff"
"ffffffffffffffff16ff5b600080fd5b6000809054906101000a900473ffff"
"ffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffff"
"ffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffff"
"ff1614151561033357600080fd5b80600260006101000a81548173ffffffff"
"ffffffffffffffffffffffffffffffff021916908373ffffffffffffffffff"
"ffffffffffffffffffffff1602179055507fa2ea9883a321a3e97b8266c2b0"
"78bfeec6d50c711ed71f874a90d500ae2eaf3681604051808273ffffffffff"
"ffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffff"
"ffffffffffff16815260200191505060405180910390a150565b6000809054"
"906101000a900473ffffffffffffffffffffffffffffffffffffffff168156"
"5b600260009054906101000a900473ffffffffffffffffffffffffffffffff"
"ffffffff1681565b6000809054906101000a900473ffffffffffffffffffff"
"ffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffff"
"ff163373ffffffffffffffffffffffffffffffffffffffff16141515610480"
"57600080fd5b600260149054906101000a900460ff16151561049b57600080"
"fd5b6000600260146101000a81548160ff02191690831515021790555061de"
"ad73ffffffffffffffffffffffffffffffffffffffff166108fc6103e83073"
"ffffffffffffffffffffffffffffffffffffffff1631846103e80302811515"
"6104fc57fe5b049081150290604051600060405180830381858888f1935050"
"5050151561052257600080fd5b7fbb<KEY>f<KEY>180<KEY>bba<KEY>bc<KEY>5282b<KEY>7<KEY>"
"5c6223eabea1077be696b3f265cf1360405160405180910390a16105566102"
"2b565b50565b6000809054906101000a900473ffffffffffffffffffffffff"
"ffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16"
"3373ffffffffffffffffffffffffffffffffffffffff161415156105b45760"
"0080fd5b806000806101000a81548173ffffffffffffffffffffffffffffff"
"ffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff"
"16021790555050565b6000809054906101000a900473ffffffffffffffffff"
"ffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffff"
"ffff163373ffffffffffffffffffffffffffffffffffffffff161415156106"
"5257600080fd5b600260149054906101000a900460ff16151561066d576000"
"80fd5b803073ffffffffffffffffffffffffffffffffffffffff1631101561"
"069157600080fd5b600260009054906101000a900473ffffffffffffffffff"
"ffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffff"
"ffff166108fc823073ffffffffffffffffffffffffffffffffffffffff1631"
"039081150290604051600060405180830381858888f1935050505015156107"
"0c57600080fd5b505600a165627a7a7230582099b524f367ac8f6d64a5b0de"
"ae6fb395bb563d711c6ed83685ea7c6352aa3bdd0029"))
;; contract SimpleStorage {
;; uint storedData;
;; function add(uint x) {
;; storedData = storedData + x;
;; }
;; function get() constant returns (uint retVal) {
;; return storedData;
;; }
;; }
;; .code
;; PUSH 60 contract SimpleStorage {\n ...
;; PUSH 40 contract SimpleStorage {\n ...
;; MSTORE contract SimpleStorage {\n ...
;; CALLVALUE contract SimpleStorage {\n ...
;; ISZERO contract SimpleStorage {\n ...
;; PUSH [tag] 1 contract SimpleStorage {\n ...
;; JUMPI contract SimpleStorage {\n ...
;; PUSH 0 contract SimpleStorage {\n ...
;; DUP1 contract SimpleStorage {\n ...
;; REVERT contract SimpleStorage {\n ...
;; tag 1 contract SimpleStorage {\n ...
;; JUMPDEST contract SimpleStorage {\n ...
;; PUSH #[$] 0000000000000000000000000000000000000000000000000000000000000000 contract SimpleStorage {\n ...
;; DUP1 contract SimpleStorage {\n ...
;; PUSH [$] 0000000000000000000000000000000000000000000000000000000000000000 contract SimpleStorage {\n ...
;; PUSH 0 contract SimpleStorage {\n ...
;; CODECOPY contract SimpleStorage {\n ...
;; PUSH 0 contract SimpleStorage {\n ...
;; RETURN contract SimpleStorage {\n ...
;; .data
;; 0:
;; .code
;; PUSH 60 contract SimpleStorage {\n ...
;; PUSH 40 contract SimpleStorage {\n ...
;; MSTORE contract SimpleStorage {\n ...
;; PUSH 4 contract SimpleStorage {\n ...
;; CALLDATASIZE contract SimpleStorage {\n ...
;; LT contract SimpleStorage {\n ...
;; PUSH [tag] 1 contract SimpleStorage {\n ...
;; JUMPI contract SimpleStorage {\n ...
;; PUSH 0 contract SimpleStorage {\n ...
;; CALLDATALOAD contract SimpleStorage {\n ...
;; PUSH 100000000000000000000000000000000000000000000000000000000 contract SimpleStorage {\n ...
;; SWAP1 contract SimpleStorage {\n ...
;; DIV contract SimpleStorage {\n ...
;; PUSH FFFFFFFF contract SimpleStorage {\n ...
;; AND contract SimpleStorage {\n ...
;; DUP1 contract SimpleStorage {\n ...
;; PUSH 1003E2D2 contract SimpleStorage {\n ...
;; EQ contract SimpleStorage {\n ...
;; PUSH [tag] 2 contract SimpleStorage {\n ...
;; JUMPI contract SimpleStorage {\n ...
;; DUP1 contract SimpleStorage {\n ...
;; PUSH 6D4CE63C contract SimpleStorage {\n ...
;; EQ contract SimpleStorage {\n ...
;; PUSH [tag] 3 contract SimpleStorage {\n ...
;; JUMPI contract SimpleStorage {\n ...
;; tag 1 contract SimpleStorage {\n ...
;; JUMPDEST contract SimpleStorage {\n ...
;; PUSH 0 contract SimpleStorage {\n ...
;; DUP1 contract SimpleStorage {\n ...
;; REVERT contract SimpleStorage {\n ...
;; tag 2 function add(uint x) {\n ...
;; JUMPDEST function add(uint x) {\n ...
;; CALLVALUE function add(uint x) {\n ...
;; ISZERO function add(uint x) {\n ...
;; PUSH [tag] 4 function add(uint x) {\n ...
;; JUMPI function add(uint x) {\n ...
;; PUSH 0 function add(uint x) {\n ...
;; DUP1 function add(uint x) {\n ...
;; REVERT function add(uint x) {\n ...
;; tag 4 function add(uint x) {\n ...
;; JUMPDEST function add(uint x) {\n ...
;; PUSH [tag] 5 function add(uint x) {\n ...
;; PUSH 4 function add(uint x) {\n ...
;; DUP1 function add(uint x) {\n ...
;; DUP1 function add(uint x) {\n ...
;; CALLDATALOAD function add(uint x) {\n ...
;; SWAP1 function add(uint x) {\n ...
;; PUSH 20 function add(uint x) {\n ...
;; ADD function add(uint x) {\n ...
;; SWAP1 function add(uint x) {\n ...
;; SWAP2 function add(uint x) {\n ...
;; SWAP1 function add(uint x) {\n ...
;; POP function add(uint x) {\n ...
;; POP function add(uint x) {\n ...
;; PUSH [tag] 6 function add(uint x) {\n ...
;; JUMP function add(uint x) {\n ...
;; tag 5 function add(uint x) {\n ...
;; JUMPDEST function add(uint x) {\n ...
;; STOP function add(uint x) {\n ...
;; tag 3 function get() constant return...
;; JUMPDEST function get() constant return...
;; CALLVALUE function get() constant return...
;; ISZERO function get() constant return...
;; PUSH [tag] 7 function get() constant return...
;; JUMPI function get() constant return...
;; PUSH 0 function get() constant return...
;; DUP1 function get() constant return...
;; REVERT function get() constant return...
;; tag 7 function get() constant return...
;; JUMPDEST function get() constant return...
;; PUSH [tag] 8 function get() constant return...
;; PUSH [tag] 9 function get() constant return...
;; JUMP function get() constant return...
;; tag 8 function get() constant return...
;; JUMPDEST function get() constant return...
;; PUSH 40 function get() constant return...
;; MLOAD function get() constant return...
;; DUP1 function get() constant return...
;; DUP3 function get() constant return...
;; DUP2 function get() constant return...
;; MSTORE function get() constant return...
;; PUSH 20 function get() constant return...
;; ADD function get() constant return...
;; SWAP2 function get() constant return...
;; POP function get() constant return...
;; POP function get() constant return...
;; PUSH 40 function get() constant return...
;; MLOAD function get() constant return...
;; DUP1 function get() constant return...
;; SWAP2 function get() constant return...
;; SUB function get() constant return...
;; SWAP1 function get() constant return...
;; RETURN function get() constant return...
;; tag 6 function add(uint x) {\n ...
;; JUMPDEST function add(uint x) {\n ...
;; DUP1 x
;; PUSH 0 storedData
;; SLOAD storedData
;; ADD storedData + x
;; PUSH 0 storedData
;; DUP2 storedData = storedData + x
;; SWAP1 storedData = storedData + x
;; SSTORE storedData = storedData + x
;; POP storedData = storedData + x
;; POP function add(uint x) {\n ...
;; JUMP [out] function add(uint x) {\n ...
;; tag 9 function get() constant return...
;; JUMPDEST function get() constant return...
;; PUSH 0 uint retVal
;; DUP1 storedData
;; SLOAD storedData
;; SWAP1 return storedData
;; POP return storedData
;; SWAP1 function get() constant return...
;; JUMP [out] function get() constant return...
;; .data
;;
;; PUSH1 0x60 PUSH1 0x40 MSTORE PUSH1 0x4 CALLDATASIZE LT PUSH1 0x49
;; JUMPI PUSH1 0x0 CALLDATALOAD PUSH29
;; 0x100000000000000000000000000000000000000000000000000000000 SWAP1
;; DIV PUSH4 0xFFFFFFFF AND DUP1 PUSH4 0x1003E2D2 EQ PUSH1 0x4E JUMPI
;; DUP1 PUSH4 0x6D4CE63C EQ PUSH1 0x6E JUMPI JUMPDEST PUSH1 0x0 DUP1
;; REVERT JUMPDEST CALLVALUE ISZERO PUSH1 0x58 JUMPI PUSH1 0x0 DUP1
;; REVERT JUMPDEST PUSH1 0x6C PUSH1 0x4 DUP1 DUP1 CALLDATALOAD SWAP1
;; PUSH1 0x20 ADD SWAP1 SWAP2 SWAP1 POP POP PUSH1 0x94 JUMP JUMPDEST
;; STOP JUMPDEST CALLVALUE ISZERO PUSH1 0x78 JUMPI PUSH1 0x0 DUP1
;; REVERT JUMPDEST PUSH1 0x7E PUSH1 0xA2 JUMP JUMPDEST PUSH1 0x40
;; MLOAD DUP1 DUP3 DUP2 MSTORE PUSH1 0x20 ADD SWAP2 POP POP PUSH1 0x40
;; MLOAD DUP1 SWAP2 SUB SWAP1 RETURN JUMPDEST DUP1 PUSH1 0x0 SLOAD ADD
;; PUSH1 0x0 DUP2 SWAP1 SSTORE POP POP JUMP JUMPDEST PUSH1 0x0 DUP1
;; SLOAD SWAP1 POP SWAP1 JUMP STOP LOG1 PUSH6 0x627A7A723058 KECCAK256
;; SWAP2 0xb0 PUSH22 0xEC07079391740F0CC0B84E6FB576312F8A346C44F6A4
;; BALANCE 0xb1 CREATE 0xeb JUMPDEST DUP9 0xe6 STOP 0x29
(defconst *simple-adder-contract*
(concatenate 'string
"6060604052600436106049576000357c01000000000000000000000000000000000000000000"
"00000000000000900<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"))
| true |
(in-package "ACL2")
;; contract SimpleStorage {
;; uint storedData;
;; function set(uint x) {
;; storedData = x;
;; }
;; function get() constant returns (uint retVal) {
;; return storedData;
;; }
;; }
;; Contract registration:
(defconst *simple-storage-create*
(concatenate 'string
"6060604052341561000f57600080fd5b60d38061001d6000396000f3006060"
"604052600436106049576000357c0100000000000000000000000000000000"
"000000000000000000000000900463ffffffff16806360fe47b114604e5780"
"636d4ce63c14606e575b600080fd5b3415605857600080fd5b606c60048080"
"359060200190919050506094565b005b3415607857600080fd5b607e609e56"
"5b6040518082815260200191505060405180910390f35b8060008190555050"
"565b600080549050905600a165627a7a72305820ePI:KEY:<KEY>END_PIf98c8PI:KEY:<KEY>END_PI1cPI:KEY:<KEY>END_PI47d7"
"324b034ddccc41eaa7365d369b34580ab73c71a8940029"))
;; Contract being registered:
(defconst *simple-storage-contract*
(concatenate 'string
"6060604052600436106049576000357c010000000000000000000000000000"
"0000000000000000000000000000900463ffffffff16806360fe47b114604e"
"5780636dPI:KEY:<KEY>END_PIce63cPI:KEY:<KEY>END_PI606ePI:KEY:<KEY>END_PI7PI:KEY:<KEY>END_PIbPI:KEY:<KEY>END_PI000PI:KEY:<KEY>END_PI0fdPI:KEY:<KEY>END_PIb34PI:KEY:<KEY>END_PI60PI:KEY:<KEY>END_PI8PI:KEY:<KEY>END_PI7600080fdPI:KEY:<KEY>END_PIb606c6004"
"8080359060200190919050506094565b005b3415607857600080fd5b607e60"
"9e565b6040518082815260200191505060405180910390f35b806000819055"
"5050565b600080549050905600a165627a7a72305820e1f98c821c12eea520"
"47d7324b034ddccc41eaa7365d369b34580ab73c71a8940029"))
;; Deed contract runtime opcode
;; https://github.com/ethereum/ens/blob/f3334337083728728da56824a5d0a30a8712b60c/HashRegistrarSimplified.sol#L25
(defconst *deed-contract*
(concatenate 'string
"60606040526004361061008e576000357c0100000000000000000000000000"
"000000000000000000000000000000900463ffffffff16806305b344101461"
"00905780630b5ab3d5146100b957806313af4035146100ce5780632b20e397"
"146101075780638da5cb5b1461015c578063bbe42771146101b1578063faab"
"9d39146101d4578063fb1669ca1461020d575b005b341561009b57600080fd"
"5b6100a3610225565b6040518082815260200191505060405180910390f35b"
"34156100c457600080fd5b6100cc61022b565b005b34156100d957600080fd"
"5b610105600480803573ffffffffffffffffffffffffffffffffffffffff16"
"9060200190919050506102d8565b005b341561011257600080fd5b61011a61"
"03da565b604051808273ffffffffffffffffffffffffffffffffffffffff16"
"73ffffffffffffffffffffffffffffffffffffffff16815260200191505060"
"405180910390f35b341561016757600080fd5b61016f6103ff565b60405180"
"8273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffff"
"ffffffffffffffffffffffffff16815260200191505060405180910390f35b"
"34156101bc57600080fd5b6101d26004808035906020019091905050610425"
"565b005b34156101df57600080fd5b61020b600480803573ffffffffffffff"
"ffffffffffffffffffffffffff16906020019091905050610559565b005b61"
"022360048080359060200190919050506105f7565b005b60015481565b6002"
"60149054906101000a900460ff161561024557600080fd5b60026000905490"
"6101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffff"
"ffffffffffffffffffffffffffffffffffff166108fc3073ffffffffffffff"
"ffffffffffffffffffffffffff163190811502906040516000604051808303"
"81858888f19350505050156102d35761dead73ffffffffffffffffffffffff"
"ffffffffffffffff16ff5b600080fd5b6000809054906101000a900473ffff"
"ffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffff"
"ffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffff"
"ff1614151561033357600080fd5b80600260006101000a81548173ffffffff"
"ffffffffffffffffffffffffffffffff021916908373ffffffffffffffffff"
"ffffffffffffffffffffff1602179055507fa2ea9883a321a3e97b8266c2b0"
"78bfeec6d50c711ed71f874a90d500ae2eaf3681604051808273ffffffffff"
"ffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffff"
"ffffffffffff16815260200191505060405180910390a150565b6000809054"
"906101000a900473ffffffffffffffffffffffffffffffffffffffff168156"
"5b600260009054906101000a900473ffffffffffffffffffffffffffffffff"
"ffffffff1681565b6000809054906101000a900473ffffffffffffffffffff"
"ffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffff"
"ff163373ffffffffffffffffffffffffffffffffffffffff16141515610480"
"57600080fd5b600260149054906101000a900460ff16151561049b57600080"
"fd5b6000600260146101000a81548160ff02191690831515021790555061de"
"ad73ffffffffffffffffffffffffffffffffffffffff166108fc6103e83073"
"ffffffffffffffffffffffffffffffffffffffff1631846103e80302811515"
"6104fc57fe5b049081150290604051600060405180830381858888f1935050"
"5050151561052257600080fd5b7fbbPI:KEY:<KEY>END_PIfPI:KEY:<KEY>END_PI180PI:KEY:<KEY>END_PIbbaPI:KEY:<KEY>END_PIbcPI:KEY:<KEY>END_PI5282bPI:KEY:<KEY>END_PI7PI:KEY:<KEY>END_PI"
"5c6223eabea1077be696b3f265cf1360405160405180910390a16105566102"
"2b565b50565b6000809054906101000a900473ffffffffffffffffffffffff"
"ffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16"
"3373ffffffffffffffffffffffffffffffffffffffff161415156105b45760"
"0080fd5b806000806101000a81548173ffffffffffffffffffffffffffffff"
"ffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff"
"16021790555050565b6000809054906101000a900473ffffffffffffffffff"
"ffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffff"
"ffff163373ffffffffffffffffffffffffffffffffffffffff161415156106"
"5257600080fd5b600260149054906101000a900460ff16151561066d576000"
"80fd5b803073ffffffffffffffffffffffffffffffffffffffff1631101561"
"069157600080fd5b600260009054906101000a900473ffffffffffffffffff"
"ffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffff"
"ffff166108fc823073ffffffffffffffffffffffffffffffffffffffff1631"
"039081150290604051600060405180830381858888f1935050505015156107"
"0c57600080fd5b505600a165627a7a7230582099b524f367ac8f6d64a5b0de"
"ae6fb395bb563d711c6ed83685ea7c6352aa3bdd0029"))
;; contract SimpleStorage {
;; uint storedData;
;; function add(uint x) {
;; storedData = storedData + x;
;; }
;; function get() constant returns (uint retVal) {
;; return storedData;
;; }
;; }
;; .code
;; PUSH 60 contract SimpleStorage {\n ...
;; PUSH 40 contract SimpleStorage {\n ...
;; MSTORE contract SimpleStorage {\n ...
;; CALLVALUE contract SimpleStorage {\n ...
;; ISZERO contract SimpleStorage {\n ...
;; PUSH [tag] 1 contract SimpleStorage {\n ...
;; JUMPI contract SimpleStorage {\n ...
;; PUSH 0 contract SimpleStorage {\n ...
;; DUP1 contract SimpleStorage {\n ...
;; REVERT contract SimpleStorage {\n ...
;; tag 1 contract SimpleStorage {\n ...
;; JUMPDEST contract SimpleStorage {\n ...
;; PUSH #[$] 0000000000000000000000000000000000000000000000000000000000000000 contract SimpleStorage {\n ...
;; DUP1 contract SimpleStorage {\n ...
;; PUSH [$] 0000000000000000000000000000000000000000000000000000000000000000 contract SimpleStorage {\n ...
;; PUSH 0 contract SimpleStorage {\n ...
;; CODECOPY contract SimpleStorage {\n ...
;; PUSH 0 contract SimpleStorage {\n ...
;; RETURN contract SimpleStorage {\n ...
;; .data
;; 0:
;; .code
;; PUSH 60 contract SimpleStorage {\n ...
;; PUSH 40 contract SimpleStorage {\n ...
;; MSTORE contract SimpleStorage {\n ...
;; PUSH 4 contract SimpleStorage {\n ...
;; CALLDATASIZE contract SimpleStorage {\n ...
;; LT contract SimpleStorage {\n ...
;; PUSH [tag] 1 contract SimpleStorage {\n ...
;; JUMPI contract SimpleStorage {\n ...
;; PUSH 0 contract SimpleStorage {\n ...
;; CALLDATALOAD contract SimpleStorage {\n ...
;; PUSH 100000000000000000000000000000000000000000000000000000000 contract SimpleStorage {\n ...
;; SWAP1 contract SimpleStorage {\n ...
;; DIV contract SimpleStorage {\n ...
;; PUSH FFFFFFFF contract SimpleStorage {\n ...
;; AND contract SimpleStorage {\n ...
;; DUP1 contract SimpleStorage {\n ...
;; PUSH 1003E2D2 contract SimpleStorage {\n ...
;; EQ contract SimpleStorage {\n ...
;; PUSH [tag] 2 contract SimpleStorage {\n ...
;; JUMPI contract SimpleStorage {\n ...
;; DUP1 contract SimpleStorage {\n ...
;; PUSH 6D4CE63C contract SimpleStorage {\n ...
;; EQ contract SimpleStorage {\n ...
;; PUSH [tag] 3 contract SimpleStorage {\n ...
;; JUMPI contract SimpleStorage {\n ...
;; tag 1 contract SimpleStorage {\n ...
;; JUMPDEST contract SimpleStorage {\n ...
;; PUSH 0 contract SimpleStorage {\n ...
;; DUP1 contract SimpleStorage {\n ...
;; REVERT contract SimpleStorage {\n ...
;; tag 2 function add(uint x) {\n ...
;; JUMPDEST function add(uint x) {\n ...
;; CALLVALUE function add(uint x) {\n ...
;; ISZERO function add(uint x) {\n ...
;; PUSH [tag] 4 function add(uint x) {\n ...
;; JUMPI function add(uint x) {\n ...
;; PUSH 0 function add(uint x) {\n ...
;; DUP1 function add(uint x) {\n ...
;; REVERT function add(uint x) {\n ...
;; tag 4 function add(uint x) {\n ...
;; JUMPDEST function add(uint x) {\n ...
;; PUSH [tag] 5 function add(uint x) {\n ...
;; PUSH 4 function add(uint x) {\n ...
;; DUP1 function add(uint x) {\n ...
;; DUP1 function add(uint x) {\n ...
;; CALLDATALOAD function add(uint x) {\n ...
;; SWAP1 function add(uint x) {\n ...
;; PUSH 20 function add(uint x) {\n ...
;; ADD function add(uint x) {\n ...
;; SWAP1 function add(uint x) {\n ...
;; SWAP2 function add(uint x) {\n ...
;; SWAP1 function add(uint x) {\n ...
;; POP function add(uint x) {\n ...
;; POP function add(uint x) {\n ...
;; PUSH [tag] 6 function add(uint x) {\n ...
;; JUMP function add(uint x) {\n ...
;; tag 5 function add(uint x) {\n ...
;; JUMPDEST function add(uint x) {\n ...
;; STOP function add(uint x) {\n ...
;; tag 3 function get() constant return...
;; JUMPDEST function get() constant return...
;; CALLVALUE function get() constant return...
;; ISZERO function get() constant return...
;; PUSH [tag] 7 function get() constant return...
;; JUMPI function get() constant return...
;; PUSH 0 function get() constant return...
;; DUP1 function get() constant return...
;; REVERT function get() constant return...
;; tag 7 function get() constant return...
;; JUMPDEST function get() constant return...
;; PUSH [tag] 8 function get() constant return...
;; PUSH [tag] 9 function get() constant return...
;; JUMP function get() constant return...
;; tag 8 function get() constant return...
;; JUMPDEST function get() constant return...
;; PUSH 40 function get() constant return...
;; MLOAD function get() constant return...
;; DUP1 function get() constant return...
;; DUP3 function get() constant return...
;; DUP2 function get() constant return...
;; MSTORE function get() constant return...
;; PUSH 20 function get() constant return...
;; ADD function get() constant return...
;; SWAP2 function get() constant return...
;; POP function get() constant return...
;; POP function get() constant return...
;; PUSH 40 function get() constant return...
;; MLOAD function get() constant return...
;; DUP1 function get() constant return...
;; SWAP2 function get() constant return...
;; SUB function get() constant return...
;; SWAP1 function get() constant return...
;; RETURN function get() constant return...
;; tag 6 function add(uint x) {\n ...
;; JUMPDEST function add(uint x) {\n ...
;; DUP1 x
;; PUSH 0 storedData
;; SLOAD storedData
;; ADD storedData + x
;; PUSH 0 storedData
;; DUP2 storedData = storedData + x
;; SWAP1 storedData = storedData + x
;; SSTORE storedData = storedData + x
;; POP storedData = storedData + x
;; POP function add(uint x) {\n ...
;; JUMP [out] function add(uint x) {\n ...
;; tag 9 function get() constant return...
;; JUMPDEST function get() constant return...
;; PUSH 0 uint retVal
;; DUP1 storedData
;; SLOAD storedData
;; SWAP1 return storedData
;; POP return storedData
;; SWAP1 function get() constant return...
;; JUMP [out] function get() constant return...
;; .data
;;
;; PUSH1 0x60 PUSH1 0x40 MSTORE PUSH1 0x4 CALLDATASIZE LT PUSH1 0x49
;; JUMPI PUSH1 0x0 CALLDATALOAD PUSH29
;; 0x100000000000000000000000000000000000000000000000000000000 SWAP1
;; DIV PUSH4 0xFFFFFFFF AND DUP1 PUSH4 0x1003E2D2 EQ PUSH1 0x4E JUMPI
;; DUP1 PUSH4 0x6D4CE63C EQ PUSH1 0x6E JUMPI JUMPDEST PUSH1 0x0 DUP1
;; REVERT JUMPDEST CALLVALUE ISZERO PUSH1 0x58 JUMPI PUSH1 0x0 DUP1
;; REVERT JUMPDEST PUSH1 0x6C PUSH1 0x4 DUP1 DUP1 CALLDATALOAD SWAP1
;; PUSH1 0x20 ADD SWAP1 SWAP2 SWAP1 POP POP PUSH1 0x94 JUMP JUMPDEST
;; STOP JUMPDEST CALLVALUE ISZERO PUSH1 0x78 JUMPI PUSH1 0x0 DUP1
;; REVERT JUMPDEST PUSH1 0x7E PUSH1 0xA2 JUMP JUMPDEST PUSH1 0x40
;; MLOAD DUP1 DUP3 DUP2 MSTORE PUSH1 0x20 ADD SWAP2 POP POP PUSH1 0x40
;; MLOAD DUP1 SWAP2 SUB SWAP1 RETURN JUMPDEST DUP1 PUSH1 0x0 SLOAD ADD
;; PUSH1 0x0 DUP2 SWAP1 SSTORE POP POP JUMP JUMPDEST PUSH1 0x0 DUP1
;; SLOAD SWAP1 POP SWAP1 JUMP STOP LOG1 PUSH6 0x627A7A723058 KECCAK256
;; SWAP2 0xb0 PUSH22 0xEC07079391740F0CC0B84E6FB576312F8A346C44F6A4
;; BALANCE 0xb1 CREATE 0xeb JUMPDEST DUP9 0xe6 STOP 0x29
(defconst *simple-adder-contract*
(concatenate 'string
"6060604052600436106049576000357c01000000000000000000000000000000000000000000"
"00000000000000900PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"
"PI:KEY:<KEY>END_PI"))
|
[
{
"context": "\"\")\n(make-instance 'comic\n :name \"wulffmorgenthaler\"\n :mainurl \"http://www.wulffm",
"end": 5140,
"score": 0.5818041563034058,
"start": 5129,
"tag": "USERNAME",
"value": "ulffmorgent"
},
{
"context": ")\n(make-instance 'comic\n :name \"pennyarcade\" \n :mainurl \"http://www.penny-arca",
"end": 6112,
"score": 0.6261276602745056,
"start": 6104,
"tag": "USERNAME",
"value": "nyarcade"
},
{
"context": "\\\"\")\n(make-instance 'comic\n :name \"collegeroomies\" \n :mainurl \"http://crfh.net/\" \n ",
"end": 6313,
"score": 0.87513267993927,
"start": 6299,
"tag": "USERNAME",
"value": "collegeroomies"
},
{
"context": "\")\n(make-instance 'comic\n :name \"reallife\" \n :mainurl \"http://www.reallifeco",
"end": 8292,
"score": 0.655954122543335,
"start": 8286,
"tag": "USERNAME",
"value": "allife"
},
{
"context": "\n(make-instance 'comic\n :name \"striptease\" \n :mainurl \"http://www.striptease",
"end": 8461,
"score": 0.6457322835922241,
"start": 8455,
"tag": "USERNAME",
"value": "ptease"
},
{
"context": "\\\"\")\n(make-instance 'comic\n :name \"littlegamers\" \n :mainurl \"http://www.little-gam",
"end": 8653,
"score": 0.9352880716323853,
"start": 8641,
"tag": "USERNAME",
"value": "littlegamers"
},
{
"context": ")'\")\n(make-instance 'comic\n :name \"jackiesfridge\" \n :mainurl \"http://jackiesfridge.",
"end": 8824,
"score": 0.986136257648468,
"start": 8811,
"tag": "USERNAME",
"value": "jackiesfridge"
},
{
"context": "\\\"\")\n(make-instance 'comic\n :name \"langlang\" \n :mainurl \"http://langlang.keens",
"end": 9026,
"score": 0.6777129769325256,
"start": 9018,
"tag": "USERNAME",
"value": "langlang"
},
{
"context": "\\\"\")\n(make-instance 'comic\n :name \"purplepussy\" \n :mainurl \"http://purplepussy.ne",
"end": 9413,
"score": 0.8766164183616638,
"start": 9402,
"tag": "USERNAME",
"value": "purplepussy"
},
{
"context": "\\\"\")\n(make-instance 'comic\n :name \"nichtlustig\" \n :mainurl \"http://www.nichtlusti",
"end": 9600,
"score": 0.9052639007568359,
"start": 9589,
"tag": "USERNAME",
"value": "nichtlustig"
},
{
"context": "\"\" )\n(make-instance 'comic\n :name \"samandfuzzy\"\n :mainurl \"http://www.samandfuzzy",
"end": 11563,
"score": 0.812122642993927,
"start": 11552,
"tag": "USERNAME",
"value": "samandfuzzy"
},
{
"context": "\"\" )\n(make-instance 'comic\n :name \"lizard\"\n :mainurl \"http://www.lizardcomic",
"end": 12334,
"score": 0.5224590301513672,
"start": 12328,
"tag": "NAME",
"value": "lizard"
}
] |
modules/comics/comics.lisp
|
hanshuebner/bknr-web
| 8 |
(in-package :bknr-user)
(enable-interpol-syntax)
(define-persistent-class comic ()
((name :read
:index-type string-unique-index
:index-reader comic-with-name
:index-values all-comics)
(keywords :update :initform nil
:index-type hash-list-index
:index-reader get-keyword-comics)
(mainurl :update)
(imgregexp :update)
(imgregexp-scanner :update :transient t)
(mainregexp :update :initform nil)
(mainregexp-scanner :update :transient t)
(last-updated :update :transient t :initform 0)
(url-hash :update :initform (make-hash-table :test #'equal))))
(defmethod initialize-transient-instance ((comic comic))
(with-slots (mainurl mainurl-scanner
imgregexp imgregexp-scanner
mainregexp mainregexp-scanner) comic
(when imgregexp
(setf imgregexp-scanner (create-scanner imgregexp :case-insensitive-mode t)))
(when mainregexp
(setf mainregexp-scanner (create-scanner mainregexp :case-insensitive-mode t)))))
(defmethod print-object ((object comic) stream)
(format stream "#<COMIC ~a ID: ~a>" (comic-name object)
(store-object-id object))
object)
(deftransaction comic-get-image-uri (comic image-uri)
(setf (gethash image-uri (comic-url-hash comic)) t))
(defun make-image-uri (image mainurl)
(let* ((mainuri (parse-uri mainurl))
(uri (parse-uri image))
(host (uri-host mainuri))
(path (uri-parsed-path uri)))
(cond ((uri-host uri) image)
((eq :absolute (car path))
(concatenate 'string "http://" host image))
(t (render-uri (puri:merge-uris uri mainuri) nil)))))
#+(or)
(defmethod get-comic ((comic comic) &key force)
(with-slots (name url mainurl imgregexp mainregexp) comic
(let* ((date (daytag))
(image-name (format nil "~a-~a" name date))
(image (store-image-with-name image-name))
(parent-url mainurl))
(if (and (not force)
(or image
(<= (get-universal-time) (+ (comic-last-updated comic) (* 60 24)))))
image
(progn
(setf (comic-last-updated comic) (get-universal-time))
;; get main page
(multiple-value-bind (page code)
(net.aserve.client:do-http-request mainurl)
(unless (= code 200)
(error "Could not get ~a" mainurl))
(when mainregexp
(multiple-value-bind (match substrings)
(scan-to-strings (comic-mainregexp-scanner comic) page)
(unless match
(error "Could not get second page from ~a" mainurl))
(let ((second-uri (make-image-uri (aref substrings 0) mainurl)))
(multiple-value-bind (page2 code)
(net.aserve.client:do-http-request second-uri
:headers (list (cons "Referrer" mainurl)))
(unless (= code 200)
(error "Could not get second page ~a" second-uri))
(setf page page2
parent-url second-uri)))))
(multiple-value-bind (match substrings)
(scan-to-strings (comic-imgregexp-scanner comic) page)
(unless match
(error "Could not get comic image from ~a" mainurl))
(let ((image-uri (make-image-uri (aref substrings 0) parent-url)))
(format t "image-uri: ~a, hash value ~A ~%"
image-uri (gethash image-uri (comic-url-hash comic)))
(unless (gethash image-uri (comic-url-hash comic))
;; get image
(multiple-value-bind (page code headers)
(net.aserve.client:do-http-request image-uri :format :binary)
(unless (= code 200)
(error "Could not get ~a" image-uri))
(comic-get-image-uri comic image-uri)
(let ((content-type (cdr (assoc "content-type" headers :test #'string-equal))))
(unless (and content-type
(member content-type
'("image/jpeg" "image/gif" "image/png")
:test #'string-equal))
(error "Image ~a of wrong type" image-uri))
(let ((image (make-instance 'store-image
:name image-name
:timestamp (get-universal-time)
:keywords (list (make-keyword-from-string name)
:comic)
:type (image-type-symbol content-type))))
(when image
(blob-from-array image page)
(with-store-image (i image)
(change-slot-values image
'width (cl-gd:image-width i)
'height (cl-gd:image-height i)))
image)))))))))))))
(defun get-all-comics (&key (debug nil) force)
(mapcar #'(lambda (comic)
(if debug
(get-comic comic :force force)
(ignore-errors (get-comic comic :force force))))
(all-comics)))
#+(or)
(unless (cron-job-with-name "update comics")
(make-instance 'cron-job :name "update comics"
:minute 0
:hour 11
:job 'get-all-comics))
#|
(make-instance 'comic
:name "userfriendly"
:mainurl "http://ars.userfriendly.org/"
:imgregexp "src=\"(http://www.userfriendly.org/cartoons/archives/[0-9]*[a-z]*/xuf[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "wulffmorgenthaler"
:mainurl "http://www.wulffmorgenthaler.com/thestrip.asp"
:imgregexp "src=\"(log/DD[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "jerkcity"
:mainurl "http://www.jerkcity.com/"
:imgregexp "src=\"(\/jerkcity[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "sinfest"
:mainurl "http://www.sinfest.net/"
:imgregexp "src=\"(\/comics\/sf[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "nonsequitur"
:mainurl "http://www.non-sequitur.com/"
:imgregexp "src=\"(http:\/\/images.ucomics.com/comics/nq/[0-9]*/nq[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "megatokyo"
:mainurl "http://www.megatokyo.com/"
:imgregexp "src=\"(/strips/[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "pennyarcade"
:mainurl "http://www.penny-arcade.com/view.php3"
:imgregexp "src=\"(images/[0-9]*/.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "collegeroomies"
:mainurl "http://crfh.net/"
:imgregexp "src=\"(/comics/crfh[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "rpgworld"
:mainurl "http://www.rpgworldcomic.com/"
:imgregexp "src=\"(/comics/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "brunothebandit"
:mainurl "http://www.brunothebandit.com/"
:imgregexp "src=\"(/comics/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "itswalky"
:mainurl "http://www.itswalky.com/"
:imgregexp "src=\"(/comics/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "dieselsweeties"
:mainurl "http://www.dieselsweeties.com/"
:imgregexp "src=\"(http://images.clango.org/strips/.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "choppingblock"
:mainurl "http://www.choppingblock.org/"
:imgregexp "src=\"(/comics/cb[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "sheldon"
:mainurl "http://www.comics.com/comics/sheldon/index.html"
:imgregexp "src=\"(/comics/sheldon/archive/images/sheldon[0-9]*.(gif|png|jpg))\"")
(make-instance 'comic
:name "shawisland"
:mainurl "http://students.washington.edu/durandal/shawisland/"
:imgregexp "src=\"(strips/shaw[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "residencelife"
:mainurl "http://www.reslifecomics.com"
:imgregexp "src=\"(http://www.reslifecomics.com/comics/[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "lostfound"
:mainurl "http://www.lostandfoundcomic.com/"
:imgregexp "src=\"(/comics/[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "reallife"
:mainurl "http://www.reallifecomics.com/"
:imgregexp "src=\'(/index.php.*)\'")
(make-instance 'comic
:name "striptease"
:mainurl "http://www.stripteasecomic.com/"
:imgregexp "src=\"(strips2002/[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "littlegamers"
:mainurl "http://www.little-gamers.com/"
:imgregexp "src='(/index.php\?.*)'")
(make-instance 'comic
:name "jackiesfridge"
:mainurl "http://jackiesfridge.keenspace.com"
:imgregexp "src=\"(http://.*/comics/jf[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "langlang"
:mainurl "http://langlang.keenspace.com/right.html"
:imgregexp "src=\"(/comics/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "tang"
:mainurl "http://tang.keenspace.com"
:imgregexp "src=\"(http://.*/comics/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "purplepussy"
:mainurl "http://purplepussy.net/"
:imgregexp "src=\"(/comics/puss[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "nichtlustig"
:mainurl "http://www.nichtlustig.de/main.html"
:mainregexp "href=\"(toondb/[0-9]*.html)\" alt=\"zu den Cartoons\""
:imgregexp "src=\"(../comics/full/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "underpower"
:mainurl "http://underpower.non-essential.com"
:imgregexp "src=\"(comics/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "gpf"
:mainurl "http://www.gpf-comics.com/"
:imgregexp "src=\"(/comics/gpf[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "applegeeks"
:mainurl "http://www.applegeeks.com/"
:imgregexp "src=\"(/comics/issue[0-9]*.*?\.(gif|png|jpg))\"" )
(make-instance 'comic
:name "bobandgeorge"
:mainurl "http://www.bobandgeorge.com"
:imgregexp "src=\"([0-9]+.(gif|png|jpg))\"" )
(make-instance 'comic
:name "machall"
:imgregexp "src='(/index.php.do_command=show_strip&strip_id=[0-9].*)'"
:mainurl "http://www.machall.com/" )
(make-instance 'comic
:name "kungfool"
:imgregexp "src=\"(images/CK_comics/[0-9_]+.(gif|png|jpg))\""
:mainurl "http://kungfool.transpect.net/index.php" )
(make-instance 'comic
:name "ivy"
:mainurl "http://ivy.de/"
:imgregexp "src=\"([0-9]+/img/ib/[0-9]+.(png|jpg|gif))\"" )
(make-instance 'comic
:name "spooner"
:mainurl "http://www.hookedoncomics.com/spooner.php"
:imgregexp "src=\"(strips/[0-9]+.(gif|png|jpg))\"" )
(make-instance 'comic
:name "vgcat"
:mainurl "http://www.vgcats.com/vgc_comics/"
:imgregexp "src=\"(images/[0-9]+.(gif|png|jpg))\"" )
(make-instance 'comic
:name "samandfuzzy"
:mainurl "http://www.samandfuzzy.com/"
:imgregexp "src=\"(comics/[0-9]+.(jpg|png|gif))\"" )
(make-instance 'comic
:name "butternutsquash"
:mainurl "http://www.butternutsquash.net/assets/pages/bns-current.html"
:imgregexp "src=\"(../library/[0-9]+-bns.(jpg|png|gif))\"" )
(make-instance 'comic
:name "somethingpositive"
:mainurl "http://www.somethingpositive.net/"
:imgregexp "src=\"(arch/sp[0-9]+.(gif|png|jpg))\"" )
(make-instance 'comic
:name "boasas"
:mainurl "http://www.boasas.com/"
:imgregexp "src=\"(boasas/[0-9]+.(png|jpg|gif))\"" )
(make-instance 'comic
:name "lizard"
:mainurl "http://www.lizardcomics.com/"
:imgregexp "SRC=\"(/comics/liz[0-9]+.(jpg|png|gif))\"" )
|#
|
67325
|
(in-package :bknr-user)
(enable-interpol-syntax)
(define-persistent-class comic ()
((name :read
:index-type string-unique-index
:index-reader comic-with-name
:index-values all-comics)
(keywords :update :initform nil
:index-type hash-list-index
:index-reader get-keyword-comics)
(mainurl :update)
(imgregexp :update)
(imgregexp-scanner :update :transient t)
(mainregexp :update :initform nil)
(mainregexp-scanner :update :transient t)
(last-updated :update :transient t :initform 0)
(url-hash :update :initform (make-hash-table :test #'equal))))
(defmethod initialize-transient-instance ((comic comic))
(with-slots (mainurl mainurl-scanner
imgregexp imgregexp-scanner
mainregexp mainregexp-scanner) comic
(when imgregexp
(setf imgregexp-scanner (create-scanner imgregexp :case-insensitive-mode t)))
(when mainregexp
(setf mainregexp-scanner (create-scanner mainregexp :case-insensitive-mode t)))))
(defmethod print-object ((object comic) stream)
(format stream "#<COMIC ~a ID: ~a>" (comic-name object)
(store-object-id object))
object)
(deftransaction comic-get-image-uri (comic image-uri)
(setf (gethash image-uri (comic-url-hash comic)) t))
(defun make-image-uri (image mainurl)
(let* ((mainuri (parse-uri mainurl))
(uri (parse-uri image))
(host (uri-host mainuri))
(path (uri-parsed-path uri)))
(cond ((uri-host uri) image)
((eq :absolute (car path))
(concatenate 'string "http://" host image))
(t (render-uri (puri:merge-uris uri mainuri) nil)))))
#+(or)
(defmethod get-comic ((comic comic) &key force)
(with-slots (name url mainurl imgregexp mainregexp) comic
(let* ((date (daytag))
(image-name (format nil "~a-~a" name date))
(image (store-image-with-name image-name))
(parent-url mainurl))
(if (and (not force)
(or image
(<= (get-universal-time) (+ (comic-last-updated comic) (* 60 24)))))
image
(progn
(setf (comic-last-updated comic) (get-universal-time))
;; get main page
(multiple-value-bind (page code)
(net.aserve.client:do-http-request mainurl)
(unless (= code 200)
(error "Could not get ~a" mainurl))
(when mainregexp
(multiple-value-bind (match substrings)
(scan-to-strings (comic-mainregexp-scanner comic) page)
(unless match
(error "Could not get second page from ~a" mainurl))
(let ((second-uri (make-image-uri (aref substrings 0) mainurl)))
(multiple-value-bind (page2 code)
(net.aserve.client:do-http-request second-uri
:headers (list (cons "Referrer" mainurl)))
(unless (= code 200)
(error "Could not get second page ~a" second-uri))
(setf page page2
parent-url second-uri)))))
(multiple-value-bind (match substrings)
(scan-to-strings (comic-imgregexp-scanner comic) page)
(unless match
(error "Could not get comic image from ~a" mainurl))
(let ((image-uri (make-image-uri (aref substrings 0) parent-url)))
(format t "image-uri: ~a, hash value ~A ~%"
image-uri (gethash image-uri (comic-url-hash comic)))
(unless (gethash image-uri (comic-url-hash comic))
;; get image
(multiple-value-bind (page code headers)
(net.aserve.client:do-http-request image-uri :format :binary)
(unless (= code 200)
(error "Could not get ~a" image-uri))
(comic-get-image-uri comic image-uri)
(let ((content-type (cdr (assoc "content-type" headers :test #'string-equal))))
(unless (and content-type
(member content-type
'("image/jpeg" "image/gif" "image/png")
:test #'string-equal))
(error "Image ~a of wrong type" image-uri))
(let ((image (make-instance 'store-image
:name image-name
:timestamp (get-universal-time)
:keywords (list (make-keyword-from-string name)
:comic)
:type (image-type-symbol content-type))))
(when image
(blob-from-array image page)
(with-store-image (i image)
(change-slot-values image
'width (cl-gd:image-width i)
'height (cl-gd:image-height i)))
image)))))))))))))
(defun get-all-comics (&key (debug nil) force)
(mapcar #'(lambda (comic)
(if debug
(get-comic comic :force force)
(ignore-errors (get-comic comic :force force))))
(all-comics)))
#+(or)
(unless (cron-job-with-name "update comics")
(make-instance 'cron-job :name "update comics"
:minute 0
:hour 11
:job 'get-all-comics))
#|
(make-instance 'comic
:name "userfriendly"
:mainurl "http://ars.userfriendly.org/"
:imgregexp "src=\"(http://www.userfriendly.org/cartoons/archives/[0-9]*[a-z]*/xuf[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "wulffmorgenthaler"
:mainurl "http://www.wulffmorgenthaler.com/thestrip.asp"
:imgregexp "src=\"(log/DD[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "jerkcity"
:mainurl "http://www.jerkcity.com/"
:imgregexp "src=\"(\/jerkcity[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "sinfest"
:mainurl "http://www.sinfest.net/"
:imgregexp "src=\"(\/comics\/sf[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "nonsequitur"
:mainurl "http://www.non-sequitur.com/"
:imgregexp "src=\"(http:\/\/images.ucomics.com/comics/nq/[0-9]*/nq[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "megatokyo"
:mainurl "http://www.megatokyo.com/"
:imgregexp "src=\"(/strips/[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "pennyarcade"
:mainurl "http://www.penny-arcade.com/view.php3"
:imgregexp "src=\"(images/[0-9]*/.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "collegeroomies"
:mainurl "http://crfh.net/"
:imgregexp "src=\"(/comics/crfh[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "rpgworld"
:mainurl "http://www.rpgworldcomic.com/"
:imgregexp "src=\"(/comics/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "brunothebandit"
:mainurl "http://www.brunothebandit.com/"
:imgregexp "src=\"(/comics/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "itswalky"
:mainurl "http://www.itswalky.com/"
:imgregexp "src=\"(/comics/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "dieselsweeties"
:mainurl "http://www.dieselsweeties.com/"
:imgregexp "src=\"(http://images.clango.org/strips/.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "choppingblock"
:mainurl "http://www.choppingblock.org/"
:imgregexp "src=\"(/comics/cb[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "sheldon"
:mainurl "http://www.comics.com/comics/sheldon/index.html"
:imgregexp "src=\"(/comics/sheldon/archive/images/sheldon[0-9]*.(gif|png|jpg))\"")
(make-instance 'comic
:name "shawisland"
:mainurl "http://students.washington.edu/durandal/shawisland/"
:imgregexp "src=\"(strips/shaw[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "residencelife"
:mainurl "http://www.reslifecomics.com"
:imgregexp "src=\"(http://www.reslifecomics.com/comics/[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "lostfound"
:mainurl "http://www.lostandfoundcomic.com/"
:imgregexp "src=\"(/comics/[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "reallife"
:mainurl "http://www.reallifecomics.com/"
:imgregexp "src=\'(/index.php.*)\'")
(make-instance 'comic
:name "striptease"
:mainurl "http://www.stripteasecomic.com/"
:imgregexp "src=\"(strips2002/[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "littlegamers"
:mainurl "http://www.little-gamers.com/"
:imgregexp "src='(/index.php\?.*)'")
(make-instance 'comic
:name "jackiesfridge"
:mainurl "http://jackiesfridge.keenspace.com"
:imgregexp "src=\"(http://.*/comics/jf[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "langlang"
:mainurl "http://langlang.keenspace.com/right.html"
:imgregexp "src=\"(/comics/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "tang"
:mainurl "http://tang.keenspace.com"
:imgregexp "src=\"(http://.*/comics/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "purplepussy"
:mainurl "http://purplepussy.net/"
:imgregexp "src=\"(/comics/puss[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "nichtlustig"
:mainurl "http://www.nichtlustig.de/main.html"
:mainregexp "href=\"(toondb/[0-9]*.html)\" alt=\"zu den Cartoons\""
:imgregexp "src=\"(../comics/full/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "underpower"
:mainurl "http://underpower.non-essential.com"
:imgregexp "src=\"(comics/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "gpf"
:mainurl "http://www.gpf-comics.com/"
:imgregexp "src=\"(/comics/gpf[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "applegeeks"
:mainurl "http://www.applegeeks.com/"
:imgregexp "src=\"(/comics/issue[0-9]*.*?\.(gif|png|jpg))\"" )
(make-instance 'comic
:name "bobandgeorge"
:mainurl "http://www.bobandgeorge.com"
:imgregexp "src=\"([0-9]+.(gif|png|jpg))\"" )
(make-instance 'comic
:name "machall"
:imgregexp "src='(/index.php.do_command=show_strip&strip_id=[0-9].*)'"
:mainurl "http://www.machall.com/" )
(make-instance 'comic
:name "kungfool"
:imgregexp "src=\"(images/CK_comics/[0-9_]+.(gif|png|jpg))\""
:mainurl "http://kungfool.transpect.net/index.php" )
(make-instance 'comic
:name "ivy"
:mainurl "http://ivy.de/"
:imgregexp "src=\"([0-9]+/img/ib/[0-9]+.(png|jpg|gif))\"" )
(make-instance 'comic
:name "spooner"
:mainurl "http://www.hookedoncomics.com/spooner.php"
:imgregexp "src=\"(strips/[0-9]+.(gif|png|jpg))\"" )
(make-instance 'comic
:name "vgcat"
:mainurl "http://www.vgcats.com/vgc_comics/"
:imgregexp "src=\"(images/[0-9]+.(gif|png|jpg))\"" )
(make-instance 'comic
:name "samandfuzzy"
:mainurl "http://www.samandfuzzy.com/"
:imgregexp "src=\"(comics/[0-9]+.(jpg|png|gif))\"" )
(make-instance 'comic
:name "butternutsquash"
:mainurl "http://www.butternutsquash.net/assets/pages/bns-current.html"
:imgregexp "src=\"(../library/[0-9]+-bns.(jpg|png|gif))\"" )
(make-instance 'comic
:name "somethingpositive"
:mainurl "http://www.somethingpositive.net/"
:imgregexp "src=\"(arch/sp[0-9]+.(gif|png|jpg))\"" )
(make-instance 'comic
:name "boasas"
:mainurl "http://www.boasas.com/"
:imgregexp "src=\"(boasas/[0-9]+.(png|jpg|gif))\"" )
(make-instance 'comic
:name "<NAME>"
:mainurl "http://www.lizardcomics.com/"
:imgregexp "SRC=\"(/comics/liz[0-9]+.(jpg|png|gif))\"" )
|#
| true |
(in-package :bknr-user)
(enable-interpol-syntax)
(define-persistent-class comic ()
((name :read
:index-type string-unique-index
:index-reader comic-with-name
:index-values all-comics)
(keywords :update :initform nil
:index-type hash-list-index
:index-reader get-keyword-comics)
(mainurl :update)
(imgregexp :update)
(imgregexp-scanner :update :transient t)
(mainregexp :update :initform nil)
(mainregexp-scanner :update :transient t)
(last-updated :update :transient t :initform 0)
(url-hash :update :initform (make-hash-table :test #'equal))))
(defmethod initialize-transient-instance ((comic comic))
(with-slots (mainurl mainurl-scanner
imgregexp imgregexp-scanner
mainregexp mainregexp-scanner) comic
(when imgregexp
(setf imgregexp-scanner (create-scanner imgregexp :case-insensitive-mode t)))
(when mainregexp
(setf mainregexp-scanner (create-scanner mainregexp :case-insensitive-mode t)))))
(defmethod print-object ((object comic) stream)
(format stream "#<COMIC ~a ID: ~a>" (comic-name object)
(store-object-id object))
object)
(deftransaction comic-get-image-uri (comic image-uri)
(setf (gethash image-uri (comic-url-hash comic)) t))
(defun make-image-uri (image mainurl)
(let* ((mainuri (parse-uri mainurl))
(uri (parse-uri image))
(host (uri-host mainuri))
(path (uri-parsed-path uri)))
(cond ((uri-host uri) image)
((eq :absolute (car path))
(concatenate 'string "http://" host image))
(t (render-uri (puri:merge-uris uri mainuri) nil)))))
#+(or)
(defmethod get-comic ((comic comic) &key force)
(with-slots (name url mainurl imgregexp mainregexp) comic
(let* ((date (daytag))
(image-name (format nil "~a-~a" name date))
(image (store-image-with-name image-name))
(parent-url mainurl))
(if (and (not force)
(or image
(<= (get-universal-time) (+ (comic-last-updated comic) (* 60 24)))))
image
(progn
(setf (comic-last-updated comic) (get-universal-time))
;; get main page
(multiple-value-bind (page code)
(net.aserve.client:do-http-request mainurl)
(unless (= code 200)
(error "Could not get ~a" mainurl))
(when mainregexp
(multiple-value-bind (match substrings)
(scan-to-strings (comic-mainregexp-scanner comic) page)
(unless match
(error "Could not get second page from ~a" mainurl))
(let ((second-uri (make-image-uri (aref substrings 0) mainurl)))
(multiple-value-bind (page2 code)
(net.aserve.client:do-http-request second-uri
:headers (list (cons "Referrer" mainurl)))
(unless (= code 200)
(error "Could not get second page ~a" second-uri))
(setf page page2
parent-url second-uri)))))
(multiple-value-bind (match substrings)
(scan-to-strings (comic-imgregexp-scanner comic) page)
(unless match
(error "Could not get comic image from ~a" mainurl))
(let ((image-uri (make-image-uri (aref substrings 0) parent-url)))
(format t "image-uri: ~a, hash value ~A ~%"
image-uri (gethash image-uri (comic-url-hash comic)))
(unless (gethash image-uri (comic-url-hash comic))
;; get image
(multiple-value-bind (page code headers)
(net.aserve.client:do-http-request image-uri :format :binary)
(unless (= code 200)
(error "Could not get ~a" image-uri))
(comic-get-image-uri comic image-uri)
(let ((content-type (cdr (assoc "content-type" headers :test #'string-equal))))
(unless (and content-type
(member content-type
'("image/jpeg" "image/gif" "image/png")
:test #'string-equal))
(error "Image ~a of wrong type" image-uri))
(let ((image (make-instance 'store-image
:name image-name
:timestamp (get-universal-time)
:keywords (list (make-keyword-from-string name)
:comic)
:type (image-type-symbol content-type))))
(when image
(blob-from-array image page)
(with-store-image (i image)
(change-slot-values image
'width (cl-gd:image-width i)
'height (cl-gd:image-height i)))
image)))))))))))))
(defun get-all-comics (&key (debug nil) force)
(mapcar #'(lambda (comic)
(if debug
(get-comic comic :force force)
(ignore-errors (get-comic comic :force force))))
(all-comics)))
#+(or)
(unless (cron-job-with-name "update comics")
(make-instance 'cron-job :name "update comics"
:minute 0
:hour 11
:job 'get-all-comics))
#|
(make-instance 'comic
:name "userfriendly"
:mainurl "http://ars.userfriendly.org/"
:imgregexp "src=\"(http://www.userfriendly.org/cartoons/archives/[0-9]*[a-z]*/xuf[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "wulffmorgenthaler"
:mainurl "http://www.wulffmorgenthaler.com/thestrip.asp"
:imgregexp "src=\"(log/DD[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "jerkcity"
:mainurl "http://www.jerkcity.com/"
:imgregexp "src=\"(\/jerkcity[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "sinfest"
:mainurl "http://www.sinfest.net/"
:imgregexp "src=\"(\/comics\/sf[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "nonsequitur"
:mainurl "http://www.non-sequitur.com/"
:imgregexp "src=\"(http:\/\/images.ucomics.com/comics/nq/[0-9]*/nq[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "megatokyo"
:mainurl "http://www.megatokyo.com/"
:imgregexp "src=\"(/strips/[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "pennyarcade"
:mainurl "http://www.penny-arcade.com/view.php3"
:imgregexp "src=\"(images/[0-9]*/.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "collegeroomies"
:mainurl "http://crfh.net/"
:imgregexp "src=\"(/comics/crfh[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "rpgworld"
:mainurl "http://www.rpgworldcomic.com/"
:imgregexp "src=\"(/comics/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "brunothebandit"
:mainurl "http://www.brunothebandit.com/"
:imgregexp "src=\"(/comics/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "itswalky"
:mainurl "http://www.itswalky.com/"
:imgregexp "src=\"(/comics/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "dieselsweeties"
:mainurl "http://www.dieselsweeties.com/"
:imgregexp "src=\"(http://images.clango.org/strips/.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "choppingblock"
:mainurl "http://www.choppingblock.org/"
:imgregexp "src=\"(/comics/cb[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "sheldon"
:mainurl "http://www.comics.com/comics/sheldon/index.html"
:imgregexp "src=\"(/comics/sheldon/archive/images/sheldon[0-9]*.(gif|png|jpg))\"")
(make-instance 'comic
:name "shawisland"
:mainurl "http://students.washington.edu/durandal/shawisland/"
:imgregexp "src=\"(strips/shaw[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "residencelife"
:mainurl "http://www.reslifecomics.com"
:imgregexp "src=\"(http://www.reslifecomics.com/comics/[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "lostfound"
:mainurl "http://www.lostandfoundcomic.com/"
:imgregexp "src=\"(/comics/[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "reallife"
:mainurl "http://www.reallifecomics.com/"
:imgregexp "src=\'(/index.php.*)\'")
(make-instance 'comic
:name "striptease"
:mainurl "http://www.stripteasecomic.com/"
:imgregexp "src=\"(strips2002/[0-9]*\.(gif|png|jpg))\"")
(make-instance 'comic
:name "littlegamers"
:mainurl "http://www.little-gamers.com/"
:imgregexp "src='(/index.php\?.*)'")
(make-instance 'comic
:name "jackiesfridge"
:mainurl "http://jackiesfridge.keenspace.com"
:imgregexp "src=\"(http://.*/comics/jf[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "langlang"
:mainurl "http://langlang.keenspace.com/right.html"
:imgregexp "src=\"(/comics/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "tang"
:mainurl "http://tang.keenspace.com"
:imgregexp "src=\"(http://.*/comics/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "purplepussy"
:mainurl "http://purplepussy.net/"
:imgregexp "src=\"(/comics/puss[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "nichtlustig"
:mainurl "http://www.nichtlustig.de/main.html"
:mainregexp "href=\"(toondb/[0-9]*.html)\" alt=\"zu den Cartoons\""
:imgregexp "src=\"(../comics/full/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "underpower"
:mainurl "http://underpower.non-essential.com"
:imgregexp "src=\"(comics/[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "gpf"
:mainurl "http://www.gpf-comics.com/"
:imgregexp "src=\"(/comics/gpf[0-9]*.*?\.(gif|png|jpg))\"")
(make-instance 'comic
:name "applegeeks"
:mainurl "http://www.applegeeks.com/"
:imgregexp "src=\"(/comics/issue[0-9]*.*?\.(gif|png|jpg))\"" )
(make-instance 'comic
:name "bobandgeorge"
:mainurl "http://www.bobandgeorge.com"
:imgregexp "src=\"([0-9]+.(gif|png|jpg))\"" )
(make-instance 'comic
:name "machall"
:imgregexp "src='(/index.php.do_command=show_strip&strip_id=[0-9].*)'"
:mainurl "http://www.machall.com/" )
(make-instance 'comic
:name "kungfool"
:imgregexp "src=\"(images/CK_comics/[0-9_]+.(gif|png|jpg))\""
:mainurl "http://kungfool.transpect.net/index.php" )
(make-instance 'comic
:name "ivy"
:mainurl "http://ivy.de/"
:imgregexp "src=\"([0-9]+/img/ib/[0-9]+.(png|jpg|gif))\"" )
(make-instance 'comic
:name "spooner"
:mainurl "http://www.hookedoncomics.com/spooner.php"
:imgregexp "src=\"(strips/[0-9]+.(gif|png|jpg))\"" )
(make-instance 'comic
:name "vgcat"
:mainurl "http://www.vgcats.com/vgc_comics/"
:imgregexp "src=\"(images/[0-9]+.(gif|png|jpg))\"" )
(make-instance 'comic
:name "samandfuzzy"
:mainurl "http://www.samandfuzzy.com/"
:imgregexp "src=\"(comics/[0-9]+.(jpg|png|gif))\"" )
(make-instance 'comic
:name "butternutsquash"
:mainurl "http://www.butternutsquash.net/assets/pages/bns-current.html"
:imgregexp "src=\"(../library/[0-9]+-bns.(jpg|png|gif))\"" )
(make-instance 'comic
:name "somethingpositive"
:mainurl "http://www.somethingpositive.net/"
:imgregexp "src=\"(arch/sp[0-9]+.(gif|png|jpg))\"" )
(make-instance 'comic
:name "boasas"
:mainurl "http://www.boasas.com/"
:imgregexp "src=\"(boasas/[0-9]+.(png|jpg|gif))\"" )
(make-instance 'comic
:name "PI:NAME:<NAME>END_PI"
:mainurl "http://www.lizardcomics.com/"
:imgregexp "SRC=\"(/comics/liz[0-9]+.(jpg|png|gif))\"" )
|#
|
[
{
"context": ";;;; Copyright (c) 2011-2016 Henry Harrington <[email protected]>\n;;;; This code is li",
"end": 45,
"score": 0.9998776316642761,
"start": 29,
"tag": "NAME",
"value": "Henry Harrington"
},
{
"context": ";;;; Copyright (c) 2011-2016 Henry Harrington <[email protected]>\n;;;; This code is licensed under the MIT license",
"end": 73,
"score": 0.9999282956123352,
"start": 47,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "Lisp operating system.\"\n :version \"0\"\n :author \"Henry Harrington <[email protected]>\"\n :licence \"MIT\"\n ",
"end": 248,
"score": 0.9998813271522522,
"start": 232,
"tag": "NAME",
"value": "Henry Harrington"
},
{
"context": "tem.\"\n :version \"0\"\n :author \"Henry Harrington <[email protected]>\"\n :licence \"MIT\"\n :depends-on (#:nibbles #:cl-",
"end": 276,
"score": 0.9999234676361084,
"start": 250,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
lispos.asd
|
salewski/cl-os-mezzano
| 0 |
;;;; Copyright (c) 2011-2016 Henry Harrington <[email protected]>
;;;; This code is licensed under the MIT license.
(in-package :asdf)
(defsystem "lispos"
:description "Lisp operating system."
:version "0"
:author "Henry Harrington <[email protected]>"
:licence "MIT"
:depends-on (#:nibbles #:cl-ppcre #:iterate
#:alexandria)
:serial t
:components ((:file "compiler/cross")
(:file "compiler/cross-boot")
(:file "compiler/package")
(:file "system/data-types")
(:file "system/parse")
(:file "system/backquote")
(:file "compiler/compiler")
(:file "compiler/environment")
(:file "compiler/cross-compile")
(:file "compiler/lap")
(:file "compiler/lap-x86")
(:file "compiler/lap-arm64")
(:file "compiler/ast")
(:file "compiler/ast-generator")
(:file "compiler/keyword-arguments")
(:file "compiler/simplify-arguments")
(:file "compiler/pass1")
(:file "compiler/inline")
(:file "compiler/lift")
(:file "compiler/simplify")
(:file "compiler/constprop")
(:file "compiler/kill-temps")
(:file "compiler/value-aware-lowering")
(:file "compiler/lower-environment")
(:file "compiler/lower-special-bindings")
(:file "compiler/simplify-control-flow")
(:file "compiler/blexit")
(:file "compiler/transforms")
(:file "compiler/dynamic-extent")
(:file "compiler/codegen-x86-64")
(:file "compiler/branch-tension")
(:file "compiler/builtins-x86-64/builtins")
(:file "compiler/builtins-x86-64/array")
(:file "compiler/builtins-x86-64/cons")
(:file "compiler/builtins-x86-64/memory")
(:file "compiler/builtins-x86-64/misc")
(:file "compiler/builtins-x86-64/numbers")
(:file "compiler/builtins-x86-64/objects")
(:file "compiler/builtins-x86-64/unwind")
(:file "compiler/codegen-arm64")
(:file "compiler/builtins-arm64/builtins")
(:file "compiler/builtins-arm64/cons")
(:file "compiler/builtins-arm64/memory")
(:file "compiler/builtins-arm64/misc")
(:file "compiler/builtins-arm64/numbers")
(:file "compiler/builtins-arm64/objects")
(:file "compiler/builtins-arm64/unwind")
(:file "compiler/backend/backend")
(:file "compiler/backend/instructions")
(:file "compiler/backend/cfg")
(:file "compiler/backend/analysis")
(:file "compiler/backend/dominance")
(:file "compiler/backend/convert-ast")
(:file "compiler/backend/multiple-values")
(:file "compiler/backend/ssa")
(:file "compiler/backend/passes")
(:file "compiler/backend/debug")
(:file "compiler/backend/register-allocation")
(:file "compiler/backend/canon")
(:file "compiler/backend/x86-64/x86-64")
(:file "compiler/backend/x86-64/target")
(:file "compiler/backend/x86-64/codegen")
(:file "compiler/backend/x86-64/builtin")
(:file "compiler/backend/x86-64/misc")
(:file "compiler/backend/x86-64/object")
(:file "compiler/backend/x86-64/memory")
(:file "compiler/backend/x86-64/number")
(:file "compiler/backend/x86-64/simd")
(:file "compiler/backend/arm64/arm64")
(:file "compiler/backend/arm64/target")
(:file "compiler/backend/arm64/codegen")
(:file "compiler/backend/arm64/builtin")
(:file "compiler/backend/arm64/misc")
(:file "compiler/backend/arm64/object")
(:file "compiler/backend/arm64/number")
(:file "tools/cold-generator2/build-unicode")
(:file "tools/cold-generator2/build-pci-ids")
(:file "tools/cold-generator2/util")
(:file "tools/cold-generator2/environment")
(:file "tools/cold-generator2/load")
(:file "tools/cold-generator2/eval")
(:file "tools/cold-generator2/serialize")
(:file "tools/cold-generator2/write")
(:file "tools/cold-generator2/clos")
(:file "tools/cold-generator2/cold-generator")
(:file "tools/cold-generator2/x86-64")
(:file "tools/cold-generator2/arm64")))
|
16761
|
;;;; Copyright (c) 2011-2016 <NAME> <<EMAIL>>
;;;; This code is licensed under the MIT license.
(in-package :asdf)
(defsystem "lispos"
:description "Lisp operating system."
:version "0"
:author "<NAME> <<EMAIL>>"
:licence "MIT"
:depends-on (#:nibbles #:cl-ppcre #:iterate
#:alexandria)
:serial t
:components ((:file "compiler/cross")
(:file "compiler/cross-boot")
(:file "compiler/package")
(:file "system/data-types")
(:file "system/parse")
(:file "system/backquote")
(:file "compiler/compiler")
(:file "compiler/environment")
(:file "compiler/cross-compile")
(:file "compiler/lap")
(:file "compiler/lap-x86")
(:file "compiler/lap-arm64")
(:file "compiler/ast")
(:file "compiler/ast-generator")
(:file "compiler/keyword-arguments")
(:file "compiler/simplify-arguments")
(:file "compiler/pass1")
(:file "compiler/inline")
(:file "compiler/lift")
(:file "compiler/simplify")
(:file "compiler/constprop")
(:file "compiler/kill-temps")
(:file "compiler/value-aware-lowering")
(:file "compiler/lower-environment")
(:file "compiler/lower-special-bindings")
(:file "compiler/simplify-control-flow")
(:file "compiler/blexit")
(:file "compiler/transforms")
(:file "compiler/dynamic-extent")
(:file "compiler/codegen-x86-64")
(:file "compiler/branch-tension")
(:file "compiler/builtins-x86-64/builtins")
(:file "compiler/builtins-x86-64/array")
(:file "compiler/builtins-x86-64/cons")
(:file "compiler/builtins-x86-64/memory")
(:file "compiler/builtins-x86-64/misc")
(:file "compiler/builtins-x86-64/numbers")
(:file "compiler/builtins-x86-64/objects")
(:file "compiler/builtins-x86-64/unwind")
(:file "compiler/codegen-arm64")
(:file "compiler/builtins-arm64/builtins")
(:file "compiler/builtins-arm64/cons")
(:file "compiler/builtins-arm64/memory")
(:file "compiler/builtins-arm64/misc")
(:file "compiler/builtins-arm64/numbers")
(:file "compiler/builtins-arm64/objects")
(:file "compiler/builtins-arm64/unwind")
(:file "compiler/backend/backend")
(:file "compiler/backend/instructions")
(:file "compiler/backend/cfg")
(:file "compiler/backend/analysis")
(:file "compiler/backend/dominance")
(:file "compiler/backend/convert-ast")
(:file "compiler/backend/multiple-values")
(:file "compiler/backend/ssa")
(:file "compiler/backend/passes")
(:file "compiler/backend/debug")
(:file "compiler/backend/register-allocation")
(:file "compiler/backend/canon")
(:file "compiler/backend/x86-64/x86-64")
(:file "compiler/backend/x86-64/target")
(:file "compiler/backend/x86-64/codegen")
(:file "compiler/backend/x86-64/builtin")
(:file "compiler/backend/x86-64/misc")
(:file "compiler/backend/x86-64/object")
(:file "compiler/backend/x86-64/memory")
(:file "compiler/backend/x86-64/number")
(:file "compiler/backend/x86-64/simd")
(:file "compiler/backend/arm64/arm64")
(:file "compiler/backend/arm64/target")
(:file "compiler/backend/arm64/codegen")
(:file "compiler/backend/arm64/builtin")
(:file "compiler/backend/arm64/misc")
(:file "compiler/backend/arm64/object")
(:file "compiler/backend/arm64/number")
(:file "tools/cold-generator2/build-unicode")
(:file "tools/cold-generator2/build-pci-ids")
(:file "tools/cold-generator2/util")
(:file "tools/cold-generator2/environment")
(:file "tools/cold-generator2/load")
(:file "tools/cold-generator2/eval")
(:file "tools/cold-generator2/serialize")
(:file "tools/cold-generator2/write")
(:file "tools/cold-generator2/clos")
(:file "tools/cold-generator2/cold-generator")
(:file "tools/cold-generator2/x86-64")
(:file "tools/cold-generator2/arm64")))
| true |
;;;; Copyright (c) 2011-2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;;; This code is licensed under the MIT license.
(in-package :asdf)
(defsystem "lispos"
:description "Lisp operating system."
:version "0"
:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:licence "MIT"
:depends-on (#:nibbles #:cl-ppcre #:iterate
#:alexandria)
:serial t
:components ((:file "compiler/cross")
(:file "compiler/cross-boot")
(:file "compiler/package")
(:file "system/data-types")
(:file "system/parse")
(:file "system/backquote")
(:file "compiler/compiler")
(:file "compiler/environment")
(:file "compiler/cross-compile")
(:file "compiler/lap")
(:file "compiler/lap-x86")
(:file "compiler/lap-arm64")
(:file "compiler/ast")
(:file "compiler/ast-generator")
(:file "compiler/keyword-arguments")
(:file "compiler/simplify-arguments")
(:file "compiler/pass1")
(:file "compiler/inline")
(:file "compiler/lift")
(:file "compiler/simplify")
(:file "compiler/constprop")
(:file "compiler/kill-temps")
(:file "compiler/value-aware-lowering")
(:file "compiler/lower-environment")
(:file "compiler/lower-special-bindings")
(:file "compiler/simplify-control-flow")
(:file "compiler/blexit")
(:file "compiler/transforms")
(:file "compiler/dynamic-extent")
(:file "compiler/codegen-x86-64")
(:file "compiler/branch-tension")
(:file "compiler/builtins-x86-64/builtins")
(:file "compiler/builtins-x86-64/array")
(:file "compiler/builtins-x86-64/cons")
(:file "compiler/builtins-x86-64/memory")
(:file "compiler/builtins-x86-64/misc")
(:file "compiler/builtins-x86-64/numbers")
(:file "compiler/builtins-x86-64/objects")
(:file "compiler/builtins-x86-64/unwind")
(:file "compiler/codegen-arm64")
(:file "compiler/builtins-arm64/builtins")
(:file "compiler/builtins-arm64/cons")
(:file "compiler/builtins-arm64/memory")
(:file "compiler/builtins-arm64/misc")
(:file "compiler/builtins-arm64/numbers")
(:file "compiler/builtins-arm64/objects")
(:file "compiler/builtins-arm64/unwind")
(:file "compiler/backend/backend")
(:file "compiler/backend/instructions")
(:file "compiler/backend/cfg")
(:file "compiler/backend/analysis")
(:file "compiler/backend/dominance")
(:file "compiler/backend/convert-ast")
(:file "compiler/backend/multiple-values")
(:file "compiler/backend/ssa")
(:file "compiler/backend/passes")
(:file "compiler/backend/debug")
(:file "compiler/backend/register-allocation")
(:file "compiler/backend/canon")
(:file "compiler/backend/x86-64/x86-64")
(:file "compiler/backend/x86-64/target")
(:file "compiler/backend/x86-64/codegen")
(:file "compiler/backend/x86-64/builtin")
(:file "compiler/backend/x86-64/misc")
(:file "compiler/backend/x86-64/object")
(:file "compiler/backend/x86-64/memory")
(:file "compiler/backend/x86-64/number")
(:file "compiler/backend/x86-64/simd")
(:file "compiler/backend/arm64/arm64")
(:file "compiler/backend/arm64/target")
(:file "compiler/backend/arm64/codegen")
(:file "compiler/backend/arm64/builtin")
(:file "compiler/backend/arm64/misc")
(:file "compiler/backend/arm64/object")
(:file "compiler/backend/arm64/number")
(:file "tools/cold-generator2/build-unicode")
(:file "tools/cold-generator2/build-pci-ids")
(:file "tools/cold-generator2/util")
(:file "tools/cold-generator2/environment")
(:file "tools/cold-generator2/load")
(:file "tools/cold-generator2/eval")
(:file "tools/cold-generator2/serialize")
(:file "tools/cold-generator2/write")
(:file "tools/cold-generator2/clos")
(:file "tools/cold-generator2/cold-generator")
(:file "tools/cold-generator2/x86-64")
(:file "tools/cold-generator2/arm64")))
|
[
{
"context": "***************************\n;;; Copyright (c) 1991 Venue\n;;; All rights reserved.\n;;; ********************",
"end": 189,
"score": 0.9451584815979004,
"start": 184,
"tag": "NAME",
"value": "Venue"
},
{
"context": " ;; use the LEX debugger command (thank you, Herbie) and\n ;; shift-select pieces of code from t",
"end": 46614,
"score": 0.9988369345664978,
"start": 46608,
"tag": "NAME",
"value": "Herbie"
},
{
"context": "so we need to support that too. This is due\n;; to Harley Davis. Really.\n\n(push (cons :slot-spec\n\t '(((sedit:",
"end": 57471,
"score": 0.9997321963310242,
"start": 57459,
"tag": "NAME",
"value": "Harley Davis"
},
{
"context": "tance)\n\f\n;;; PrettyFileIndex stuff, the product of Harley Davis.\n\n(defvar *pfi-class-type* '(class defcl",
"end": 59276,
"score": 0.7753055691719055,
"start": 59273,
"tag": "NAME",
"value": "Har"
}
] |
obsolete/clos/2.0/clos-env.lisp
|
FultonBrowne/medley
| 152 |
;;;-*-Mode:LISP; Package:(CLOS (LISP WALKER)); Base:10; Syntax:Common-lisp -*-
;;;
;;; *************************************************************************
;;; Copyright (c) 1991 Venue
;;; All rights reserved.
;;; *************************************************************************
;;;
;;; Medley-Lisp specific environment hacking for CLOS
(in-package "CLOS")
;;
;; Protect the Corporation
;;
(eval-when (eval load)
(format *terminal-io*
"~&;CLOS-ENV Copyright (c) 1991 by ~
Venue Corporation. All rights reserved.~%"))
;;; Make funcallable instances (FINs) print by calling print-object.
(eval-when (eval load)
(il:defprint 'il:compiled-closure 'il:print-closure))
(defun il:print-closure (x &optional stream depth)
;; See the IRM, section 25.3.3. Unfortunatly, that documentation is
;; not correct. In particular, it makes no mention of the third argument.
(cond ((not (funcallable-instance-p x))
;; IL:\CCLOSURE.DEFPRINT is the orginal system function for
;; printing closures
(il:\\cclosure.defprint x stream))
((streamp stream)
;; Use the standard CLOS printing method, then return T to tell
;; the printer that we have done the printing ourselves.
(print-object x stream)
t)
(t
;; Internal printing (again, see the IRM section 25.3.3).
;; Return a list containing the string of characters that
;; would be printed, if the object were being printed for
;; real.
(with-output-to-string (stream)
(list (print-object x stream))))))
;;; Naming methods
(defun gf-named (gf-name)
(let ((spec (cond ((symbolp gf-name) gf-name)
((and (consp gf-name)
(eq (first gf-name) 'setf)
(symbolp (second gf-name))
(null (cddr gf-name)))
(get-setf-function-name (second gf-name)))
(t nil))))
(if (and (fboundp spec)
(generic-function-p (symbol-function spec)))
(symbol-function spec)
nil)))
(defun generic-function-method-names (gf-name hasdefp)
(if hasdefp
(let ((names nil))
(maphash #'(lambda (key value)
(declare (ignore value))
(when (and (consp key) (eql (car key) gf-name))
(pushnew key names)))
(gethash 'methods xcl:*definition-hash-table*))
names)
(let ((gf (gf-named gf-name)))
(when gf
(mapcar #'full-method-name (generic-function-methods gf))))))
(defun full-method-name (method)
"Return the full name of the method"
(let ((specializers (mapcar #'(lambda (x)
(cond ((eq x 't) t)
((and (consp x) (eq (car x) 'eql)) x)
(t (class-name x))))
(method-specializers method))))
;; Now go through some hair to make sure that specializer is
;; really right. Once CLOS returns the right value for
;; specializers this can be taken out.
(let* ((arglist (method-lambda-list method))
(number-required (or (position-if
#'(lambda (x) (member x lambda-list-keywords))
arglist)
(length arglist)))
(diff (- number-required (length specializers))))
(when (> diff 0)
(setq specializers (nconc (copy-list specializers)
(make-list diff :initial-element 't)))))
(make-full-method-name (generic-function-name
(method-generic-function method))
(method-qualifiers method)
specializers)))
(defun make-full-method-name (generic-function-name qualifiers arg-types)
"Return the full name of a method, given the generic-function name, the method
qualifiers, and the arg-types"
;; The name of the method is:
;; (<generic-function-name> <qualifier-1> ..
;; (<arg-specializer-1>..))
(labels ((remove-trailing-ts (l)
(if (null l)
nil
(let ((tail (remove-trailing-ts (cdr l))))
(if (null tail)
(if (eq (car l) 't)
nil
(list (car l)))
(if (eq l tail)
l
(cons (car l) tail)))))))
`(,generic-function-name ,@qualifiers
,(remove-trailing-ts arg-types))))
(defun parse-full-method-name (method-name)
"Parse the method name, returning the gf-name, the qualifiers, and the
arg-types."
(values (first method-name)
(butlast (rest method-name))
(car (last method-name))))
(defun prompt-for-full-method-name (gf-name &optional has-def-p)
"Prompt the user for the full name of a method on the given generic function name"
(let ((method-names (generic-function-method-names gf-name has-def-p)))
(cond ((null method-names)
nil)
((null (cdr method-names))
(car method-names))
(t (il:menu
(il:create
il:menu il:items il:_ ;If HAS-DEF-P, include only
; those methods that have a
; symbolic def'n that we can
; find
(remove-if #'null
(mapcar #'(lambda (m)
(if (or (not has-def-p)
(il:hasdef m 'methods))
`(,(with-output-to-string (s)
(dolist (x m)
(format s "~A " x))
s)
',m)
nil))
method-names))
il:title il:_ "Which method?"))))))
;;; Converting generic defining macros into DEFDEFINER macros
(defmacro make-defdefiner (definer-name definer-type type-description &body
definer-options)
"Make the DEFINER-NAME use DEFDEFINER, defining items of type DEFINER-TYPE"
(let ((old-definer-macro-name (intern (string-append definer-name
" old definition")
(symbol-package definer-name)))
(old-definer-macro-expander (intern (string-append definer-name
" old expander")
(symbol-package definer-name))))
`(progn
;; First, move the current defining function off to some safe
;; place
(unmake-defdefiner ',definer-name)
(cond ((not (fboundp ',definer-name))
(error "~A has no definition!" ',definer-name))
((fboundp ',old-definer-macro-name))
((macro-function ',definer-name)
; We have to move the macro
; expansion function as well,
; so it won't get clobbered
; when the original macro is
; redefined. See AR 7410.
(let* ((expansion-function (macro-function ',definer-name)))
(setf (symbol-function ',old-definer-macro-expander)
(loop (if (symbolp expansion-function)
(setq expansion-function
(symbol-function expansion-function))
(return expansion-function))))
(setf (macro-function ',old-definer-macro-name)
',old-definer-macro-expander)
(setf (get ',definer-name 'make-defdefiner) expansion-function)))
(t (error "~A does not name a macro." ',definer-name)))
;; Make sure the type is defined
(xcl:def-define-type ,definer-type ,type-description)
;; Now redefine the definer, using DEFEDFINER and the original def'n
(xcl:defdefiner ,(if definer-options
(cons definer-name definer-options)
definer-name)
,definer-type (&body b) `(,',old-definer-macro-name ,@,'b)))))
(defun unmake-defdefiner (definer-name)
(let ((old-expander (get definer-name 'make-defdefiner)))
(when old-expander
(setf (macro-function definer-name old-expander))
(remprop definer-name 'make-defdefiner))))
;;; For tricking ED into being able to use just the generic-function-name
;;; instead of the full method name
(defun source-manager-method-edit-fn (name type source editcoms options)
"Edit a method of the given name"
(let ((full-name (if (gf-named name)
;If given the name of a
; generic-function, try to get
; the full method name
(prompt-for-full-method-name name t)
; Otherwise it should name the
; method
name)))
(when (not (null full-name))
(il:default.editdef full-name type source editcoms options))
(or full-name name))) ;Return the name
(defun source-manager-method-hasdef-fn (name type &optional source)
"Is there a method defined with the given name?"
(cond ((not (eq type 'methods)) nil)
((or (symbolp name)
(and (consp name)
(eq (first name) 'setf)
(symbolp (second name))
(null (cddr name))))
;; If passed in the name of a generic-function, pretend that
;; there is a method by that name if there is a generic function
;; by that name, and there is a method whose source we can find.
(if (and (not (null (gf-named name)))
(find-if #'(lambda (m)
(il:hasdef m type source))
(generic-function-method-names name t)))
name
nil))
((and (consp name) (>= (length name) 2))
;; Standard methods are named (gf-name {qualifiers}* ({specializers}*))
(when (il:getdef name type source '(il:nocopy il:noerror))
name))
(t
;; Nothing else can name a method
nil)))
;;; Initialize the CLOS env
(defun initialize-clos-env nil
"Initialize the Medley CLOS environment"
;; Set up SourceManager DEFDEFINERS for classes and methods.
;;
;; Make sure to define methods before classes, so that (IL:FILES?) will build
;; filecoms that have classes before methods.
(unless (il:hasdef 'methods 'il:filepkgtype)
(make-defdefiner defmethod methods "methods"
(:name (lambda (form)
(multiple-value-bind (name qualifiers arglist)
(parse-defmethod (cdr form))
(make-full-method-name name qualifiers
(specialized-lambda-list-specializers
arglist)))))
(:undefiner
(lambda (method-name)
(multiple-value-bind
(name qualifiers arg-types)
(parse-full-method-name method-name)
(let* ((gf (gf-named name))
(method (when gf
(get-method gf qualifiers
(mapcar #'find-class
arg-types)))))
(when method (remove-method gf method))))))))
;; Include support for DEFGENERIC, if that is defined
(unless (or (not (fboundp 'defgeneric))
(il:hasdef 'generic-functions 'il:filepkgtype))
(make-defdefiner defgeneric generic-functions "generic-function definitions"))
;; DEFCLASS FileManager stuff
(unless (il:hasdef 'classes 'il:filepkgtype)
(make-defdefiner defclass classes "class definitions"
(:undefiner (lambda (name)
(when (find-class name t)
(setf (find-class name) nil)))))
;; CLASSES "include" TYPES.
(il:filepkgcom 'classes 'il:contents
#'(lambda (com name type &optional reason)
(declare (ignore name reason))
(if (member type '(il:types classes) :test #'eq)
(cdr com)
nil))))
;; Set up the hooks so that ED can be handed the name of a generic function,
;; and end up editing a method instead
(il:filepkgtype 'methods 'il:editdef 'source-manager-method-edit-fn
'il:hasdef 'source-manager-method-hasdef-fn)
;; Set up the inspect macro. The right way to do this is to
;; (ENSURE-GENERIC-FUNCTION 'IL:INSPECT...), but for now...
(push '((il:function clos-object-p) . \\internal-inspect-object)
il:inspectmacros)
;; Unmark any SourceManager changes caused by this loadup
(dolist (com (il:filepkgchanges))
(dolist (name (cdr com))
(when (and (symbolp name)
(eq (symbol-package name) (find-package "CLOS")))
(il:unmarkaschanged name (car com))))))
(eval-when (eval load)
(initialize-clos-env))
;;; Inspecting CLOS objects
(defun clos-object-p (x)
"Is the datum a CLOS object?"
(or (std-instance-p x)
(fsc-instance-p x)))
(defun \\internal-inspect-object (x type where)
(inspect-object x type where))
(defun \\internal-inspect-slot-names (x)
(inspect-slot-names x))
(defun \\internal-inspect-slot-value (x slot-name)
(inspect-slot-value x slot-name))
(defun \\internal-inspect-setf-slot-value (x slot-name value)
(inspect-setf-slot-value x slot-name value))
(defun \\internal-inspect-slot-name-command (slot-name x window)
(inspect-slot-name-command slot-name x window))
(defun \\internal-inspect-title (x y)
(inspect-title x y))
(defmethod inspect-object (x type where)
"Open an insect window on the object x"
(il:inspectw.create x '\\internal-inspect-slot-names
'\\internal-inspect-slot-value
'\\internal-inspect-setf-slot-value
'\\internal-inspect-slot-name-command nil nil
'\\internal-inspect-title nil where
#'(lambda (n v) ;Same effect as NIL, but avoids bug in
(declare (ignore v)) ; INSPECTW.CREATE
n)))
(defmethod inspect-slot-names (x)
"Return a list of names of slots of the object that should be shown in the
inspector"
(mapcar #'(lambda (slotd) (slot-value slotd 'name))
(slots-to-inspect (class-of x) x)))
(defmethod inspect-slot-value (x slot-name)
(cond ((not (slot-exists-p x slot-name)) "** no such slot **")
((not (slot-boundp x slot-name)) "** slot not bound **")
(t (slot-value x slot-name))))
(defmethod inspect-setf-slot-value (x slot-name value)
"Used by the inspector to set the value fo a slot"
;; Make this UNDO-able
(il:undosave `(inspect-setf-slot-value ,x ,slot-name
,(slot-value x slot-name)))
;; Then change the value
(setf (slot-value x slot-name) value))
(defmethod inspect-slot-name-command (slot-name x window)
"Allows the user to select a menu item to change a slot value in an inspect
window"
;; This code is a very slightly hacked version of the system function
;; DEFAULT.INSPECTW.PROPCOMMANDFN. We have to do this because the
;; standard version makes some nasty assumptions about
;; structure-objects that are not true for CLOS objects.
(declare (special il:|SetPropertyMenu|))
(case (il:menu (cond ((typep il:|SetPropertyMenu| 'il:menu)
il:|SetPropertyMenu|)
(t (il:setq il:|SetPropertyMenu|
(il:|create| il:menu il:items il:_
'((set 'set
"Allows a new value to be entered"
)))))))
(set
;; The user want to set the value
(il:ersetq (prog ((il:oldvalueitem (il:itemofpropertyvalue slot-name
window))
il:newvalue il:pwindow)
(il:ttydisplaystream (il:setq il:pwindow
(il:getpromptwindow window 3)))
(il:clearbuf t t)
(il:resetlst
(il:resetsave (il:\\itemw.flipitem il:oldvalueitem window)
(list 'il:\\itemw.flipitem
il:oldvalueitem window))
(il:resetsave (il:tty.process (il:this.process)))
(il:resetsave (il:printlevel 4 3))
(il:|printout| t "Enter the new "
slot-name " for " x t
"The expression read will be EVALuated."
t "> ")
(il:setq il:newvalue (il:lispx (il:lispxread t t)
'>))
; clear tty buffer because it
; sometimes has stuff left.
(il:clearbuf t t))
(il:closew il:pwindow)
(return (il:inspectw.replace window slot-name il:newvalue)))))))
(defmethod inspect-title (x window)
"Return the title to use in an inspect window viewing x"
(format nil "Inspecting a ~A" (class-name (class-of x))))
(defmethod inspect-title ((x standard-class) window)
(format nil "Inspecting the class ~A" (class-name x)))
;;; Debugger support for CLOS
(il:filesload clos-env-internal)
;; Non-CLOS specific changes to the debugger
;; Redefining the standard INTERESTING-FRAME-P function. Now functions can be
;; declared uninteresting to BT by giving them an XCL::UNINTERESTINGP
;; property.
(dolist (fn '(si::*unwind-protect* il:*env*
evalhook xcl::nohook xcl::undohook
xcl::execa0001 xcl::execa0001a0002
xcl::|interpret-UNDOABLY|
cl::|interpret-IF| cl::|interpret-FLET|
cl::|interpret-LET| cl::|interpret-LETA0001|
cl::|interpret-BLOCK| cl::|interpret-BLOCKA0001|
il:do-event il:eval-input
apply t))
(setf (get fn 'xcl::uninterestingp) t))
(defun xcl::interesting-frame-p (xcl::pos &optional xcl::interpflg)
"Return TRUE iff the frame should be visible for a short backtrace."
(declare (special il:openfns))
(let ((xcl::name (if (il:stackp xcl::pos) (il:stkname xcl::pos) xcl::pos)))
(typecase xcl::name
(symbol (case xcl::name
(il:*env*
;; *ENV* is used by ENVEVAL etc.
nil)
(il:errorset
(or (<= (il:stknargs xcl::pos) 1)
(not (eq (il:stkarg 2 xcl::pos nil)
'il:internal))))
(il:eval
(or (<= (il:stknargs xcl::pos) 1)
(not (eq (il:stkarg 2 xcl::pos nil)
'xcl::internal))))
(il:apply
(or (<= (il:stknargs xcl::pos) 2)
(not (il:stkarg 3 xcl::pos nil))))
(otherwise
(cond ((get xcl::name 'xcl::uninterestingp)
;; Explicitly declared uninteresting.
nil)
((eq (il:chcon1 xcl::name) (char-code #\\))
;; Implicitly declared uninteresting by starting the
;; name with a "\".
nil)
((or (member xcl::name il:openfns :test #'eq)
(eq xcl::name 'funcall))
;;The function won't be seen when compiled, so only show
;;it if INTERPFLG it true
xcl::interpflg)
(t
;; Interesting by default.
t)))))
(cons (case (car xcl::name)
(:broken t)
(otherwise nil)))
(otherwise nil))))
(setq il:*short-backtrace-filter* 'xcl::interesting-frame-p)
(eval-when (eval compile)
(il:record il:bkmenuitem (il:label (il:bkmenuinfo il:frame-name))))
;; Change the frame inspector to open up lexical environments
;; Since the DEFSTRUCT is going to build the accessors in the package that is
;; current at read-time, and we want the accessors to reside in the IL
;; package, we have got to make sure that the defstruct happens when the
;; package is IL.
(in-package "IL")
(cl:defstruct (frame-prop-name (:type cl:list))
(label-fn 'nill)
(value-fn
(function
(lambda (prop-name framespec)
(frame-prop-name-data prop-name))))
(setf-fn 'nill)
(inspect-fn
(function
(lambda (value prop-name framespec window)
(default.inspectw.valuecommandfn value prop-name (car framespec) window))))
(data nil))
(cl:in-package "CLOS")
(defun il:debugger-stack-frame-prop-names (il:framespec)
;; Frame prop-names are structures of the form
;; (LABEL-FN VALUE-FN SETF-FN EDIT-FN DATA)
(let ((il:pos (car il:framespec))
(il:backtrace-item (cadr il:framespec)))
(il:if (eq 'eval (il:stkname il:pos))
il:then
(let ((il:expression (il:stkarg 1 il:pos))
(il:environment (il:stkarg 2 il:pos)))
`(,(il:make-frame-prop-name :inspect-fn
(il:function
(il:lambda (il:value il:prop-name il:framespec il:window)
(il:inspect/as/function il:value (car il:framespec) il:window)))
:data il:expression)
,(il:make-frame-prop-name :data "ENVIRONMENT")
,@(il:for il:aspect il:in
`((,(and il:environment (il:environment-vars il:environment))
"vars")
(,(and il:environment (il:environment-functions il:environment))
"functions")
(,(and il:environment (il:environment-blocks il:environment))
"blocks")
(,(and il:environment (il:environment-tagbodies il:environment))
"tag bodies"))
il:bind il:group-name il:p-list
il:eachtime (il:setq il:group-name (cadr il:aspect))
(il:setq il:p-list (car il:aspect))
il:when (not (null il:p-list))
il:join
`(,(il:make-frame-prop-name :data il:group-name)
,@(il:for il:p il:on il:p-list il:by cddr il:collect
(il:make-frame-prop-name :label-fn
(il:function (il:lambda (il:prop-name il:framespec)
(car (il:frame-prop-name-data il:prop-name))))
:value-fn
(il:function (il:lambda (il:prop-name il:framespec)
(cadr (il:frame-prop-name-data il:prop-name))))
:setf-fn
(il:function (il:lambda (il:prop-name il:framespec il:new-value)
(il:change (cadr (il:frame-prop-name-data
il:prop-name))
il:new-value)))
:data il:p))))))
il:else
(flet ((il:build-name (&key il:arg-name il:arg-number)
(il:make-frame-prop-name :label-fn
(il:function (il:lambda (il:prop-name il:framespec)
(car (il:frame-prop-name-data il:prop-name))))
:value-fn
(il:function (il:lambda (il:prop-name il:framespec)
(il:stkarg (cadr (il:frame-prop-name-data
il:prop-name))
(car il:framespec))))
:setf-fn
(il:function (il:lambda (il:prop-name il:framespec il:new-value)
(il:setstkarg (cadr (il:frame-prop-name-data
il:prop-name))
(car il:framespec)
il:new-value)))
:data
(list il:arg-name il:arg-number))))
(let ((il:nargs (il:stknargs il:pos t))
(il:nargs1 (il:stknargs il:pos))
(il:fnname (il:stkname il:pos))
il:argname
(il:arglist))
(and (il:litatom il:fnname)
(il:ccodep il:fnname)
(il:setq il:arglist (il:listp (il:smartarglist il:fnname))))
`(,(il:make-frame-prop-name :inspect-fn
(il:function (il:lambda (il:value il:prop-name il:framespec
il:window)
(il:inspect/as/function il:value
(car il:framespec)
il:window)))
:data
(il:fetch (il:bkmenuitem il:frame-name) il:of il:backtrace-item))
,@(il:bind il:mode il:for il:i il:from 1 il:to il:nargs1 il:collect
(progn (il:while (il:fmemb (il:setq il:argname (il:pop il:arglist))
lambda-list-keywords)
il:do
(il:setq il:mode il:argname))
(il:build-name :arg-name
(or (il:stkargname il:i il:pos)
; special
(if (case il:mode
((nil &optional) il:argname)
(t nil))
(string il:argname)
(il:concat "arg " (- il:i 1))))
:arg-number il:i)))
,@(let* ((il:novalue "No value")
(il:slots (il:for il:pvar il:from 0 il:as il:i il:from
(il:add1 il:nargs1)
il:to il:nargs il:by 1 il:when
(and (il:neq il:novalue (il:stkarg il:i il:pos
il:novalue))
(or (il:setq il:argname (il:stkargname
il:i il:pos))
(il:setq il:argname (il:concat
"local "
il:pvar)))
)
il:collect
(il:build-name :arg-name il:argname
:arg-number il:i))))
(and il:slots (cons (il:make-frame-prop-name :data "locals")
il:slots)))))))))
(defun il:debugger-stack-frame-fetchfn (il:framespec il:prop-name)
(il:apply* (il:frame-prop-name-value-fn il:prop-name)
il:prop-name il:framespec))
(defun il:debugger-stack-frame-storefn (il:framespec il:prop-name il:newvalue)
(il:apply* (il:frame-prop-name-setf-fn il:prop-name)
il:prop-name il:framespec il:newvalue))
(defun il:debugger-stack-frame-value-command (il:datum il:prop-name
il:framespec il:window)
(il:apply* (il:frame-prop-name-inspect-fn il:prop-name)
il:datum il:prop-name il:framespec il:window))
(defun il:debugger-stack-frame-title (il:framespec &optional il:window)
(declare (ignore il:window))
(il:concat (il:stkname (car il:framespec)) " Frame"))
(defun il:debugger-stack-frame-property (il:prop-name il:framespec)
(il:apply* (il:frame-prop-name-label-fn il:prop-name)
il:prop-name il:framespec))
;; Teaching the debugger that there are other file-manager types that can
;; appear on the stack
(defvar xcl::*function-types* '(il:fns il:functions)
"Manager types that can appear on the stack")
;; Redefine a couple of system functions to use the above stuff
#+Xerox-Lyric
(progn
(defun il:attach-backtrace-menu (&optional (il:ttywindow
(il:wfromds (il:ttydisplaystream)))
il:skip)
(let ((il:bkmenu (il:|create| il:menu
il:items il:_
(il:collect-backtrace-items il:ttywindow il:skip)
il:whenselectedfn il:_
(il:function il:backtrace-item-selected)
il:whenheldfn il:_
#'(il:lambda (il:item il:menu il:button)
(declare (ignore il:item il:menu))
(case il:button
(il:left (il:promptprint
"Open a frame inspector on this stack frame"
))
(il:middle (il:promptprint
"Inspect/Edit this function"))
))
il:menuoutlinesize il:_ 0
il:menufont il:_ il:backtracefont
il:menucolumns il:_ 1))
(il:ttyregion (il:windowprop il:ttywindow 'il:region))
il:btw)
(cond
((il:setq il:btw (il:|for| il:atw il:|in| (il:attachedwindows il:ttywindow)
il:|when| (and (il:setq il:btw (il:windowprop il:atw 'il:menu))
(eql (il:|fetch| (il:menu il:whenselectedfn)
il:|of| (car il:btw))
(il:function il:backtrace-item-selected)))
il:|do|
(return il:atw)))
(il:deletemenu (car (il:windowprop il:btw 'il:menu))
nil il:btw)
(il:windowprop il:btw 'il:extent nil)
(il:clearw il:btw))
((il:setq il:btw (il:createw (il:region-next-to (il:windowprop il:ttywindow 'il:region)
(il:widthifwindow (il:imin (il:|fetch| (il:menu
il:imagewidth
)
il:|of| il:bkmenu)
il:|MaxBkMenuWidth|))
(il:|fetch| (il:region il:height) il:|of| il:ttyregion
)
'il:left)))
(il:attachwindow il:btw il:ttywindow (cond
((il:igreaterp (il:|fetch| (il:region il:left)
il:|of| (il:windowprop
il:btw
'il:region))
(il:|fetch| (il:region il:left)
il:|of| il:ttyregion))
'il:right)
(t 'il:left))
nil
'il:localclose)
(il:windowprop il:btw 'il:process (il:windowprop il:ttywindow 'il:process))
))
(il:addmenu il:bkmenu il:btw (il:|create| il:_ il:position
il:xcoord il:_ 0
il:ycoord il:_ (il:idifference (il:windowprop
il:btw
'il:height)
(il:|fetch| (il:menu il:imageheight
) il:|of|
il:bkmenu
))))))
(defun il:backtrace-item-selected (il:item il:menu il:button)
(il:resetlst
(prog (il:olditem il:ttywindow il:bkpos il:pos il:positions il:framewindow
(il:framespecn (il:|fetch| (il:bkmenuitem il:bkmenuinfo) il:|of| il:item)
))
(cond
((il:setq il:olditem (il:|fetch| (il:menu il:menuuserdata) il:|of| il:menu))
(il:menudeselect il:olditem il:menu)
))
(il:setq il:ttywindow (il:windowprop (il:wfrommenu il:menu)
'il:mainwindow))
(il:setq il:bkpos (il:windowprop il:ttywindow 'il:stack-position))
(il:setq il:pos (il:stknth (- il:framespecn)
il:bkpos))
(let ((il:lp (il:windowprop il:ttywindow 'il:lastpos)))
(and il:lp (il:stknth 0 il:pos il:lp)))
(il:menuselect il:item il:menu)
(if (eq il:button 'il:middle)
(progn
(il:resetsave nil (list 'il:relstk il:pos))
(il:inspect/as/function (il:|fetch| (il:bkmenuitem il:frame-name)
il:|of| il:item)
il:pos il:ttywindow))
(progn
(il:setq il:framewindow
(xcl:with-profile (il:process.eval
(il:windowprop il:ttywindow 'il:process)
'(let ((il:profile (xcl:copy-profile (xcl:find-profile
"READ-PRINT"))))
(setf (xcl::profile-entry-value '
xcl:*eval-function* il:profile)
xcl:*eval-function*)
(xcl:save-profile il:profile))
t)
(il:inspectw.create (list il:pos il:item)
'il:debugger-stack-frame-prop-names
'il:debugger-stack-frame-fetchfn
'il:debugger-stack-frame-storefn nil '
il:debugger-stack-frame-value-command nil '
il:debugger-stack-frame-title nil (
il:make-frame-inspect-window
il:ttywindow)
'il:debugger-stack-frame-property)))
(cond
((not (il:windowprop il:framewindow 'il:mainwindow))
(il:attachwindow il:framewindow il:ttywindow
(cond
((il:igreaterp (il:|fetch| (il:region il:bottom)
il:|of| (il:windowprop il:framewindow
'il:region))
(il:|fetch| (il:region il:bottom)
il:|of| (il:windowprop il:ttywindow 'il:region)))
'il:top)
(t 'il:bottom))
nil
'il:localclose)
(il:windowaddprop il:framewindow 'il:closefn (il:function il:detachwindow
))))))
(return))))
(defun il:collect-backtrace-items (xcl::tty-window xcl::skip)
(let* ((xcl::items (cons nil nil))
(xcl::items-tail xcl::items))
(macrolet ((xcl::collect-item (xcl::new-item)
`(progn (setf (rest xcl::items-tail)
(cons ,xcl::new-item nil))
(pop xcl::items-tail))))
(let* ((xcl::filter-fn (cond
((null xcl::skip)
#'xcl:true)
((eq xcl::skip t)
il:*short-backtrace-filter*)
(t xcl::skip)))
(xcl::top-frame (il:stknth 0 (il:getwindowprop xcl::tty-window '
il:stack-position)))
(xcl::next-frame xcl::top-frame)
(xcl::frame-number 0)
xcl::interesting-p xcl::last-frame-consumed xcl::use-frame xcl::label)
(loop (when (null xcl::next-frame)
(return))
(multiple-value-setq (xcl::interesting-p xcl::last-frame-consumed
xcl::use-frame xcl::label)
(funcall xcl::filter-fn xcl::next-frame))
(when (null xcl::last-frame-consumed)
(setf xcl::last-frame-consumed xcl::next-frame))
(when xcl::interesting-p
(when (null xcl::use-frame)
(setf xcl::use-frame xcl::last-frame-consumed))
(when (null xcl::label)
(setf xcl::label (il:stkname xcl::use-frame))
(if (member xcl::label '(eval il:eval il:apply apply)
:test
'eq)
(setf xcl::label (il:stkarg 1 xcl::use-frame))))
(loop (cond
((not (typep xcl::next-frame 'il:stackp))
(error "~%Use-frame ~S not found" xcl::use-frame))
((xcl::stack-eql xcl::next-frame xcl::use-frame)
(return))
(t (incf xcl::frame-number)
(setf xcl::next-frame (il:stknth -1 xcl::next-frame
xcl::next-frame)))))
(xcl::collect-item (il:|create| il:bkmenuitem
il:label il:_ (let ((*print-level* 2)
(*print-length* 3)
(*print-escape* t)
(*print-gensym* t)
(*print-pretty* nil)
(*print-circle* nil)
(*print-radix* 10)
(*print-array* nil)
(il:*print-structure*
nil))
(prin1-to-string
xcl::label))
il:bkmenuinfo il:_ xcl::frame-number
il:frame-name il:_ xcl::label)))
(loop (cond
((not (typep xcl::next-frame 'il:stackp))
(error "~%Last-frame-consumed ~S not found"
xcl::last-frame-consumed))
((prog1 (xcl::stack-eql xcl::next-frame xcl::last-frame-consumed
)
(incf xcl::frame-number)
(setf xcl::next-frame (il:stknth -1 xcl::next-frame
xcl::next-frame)))
(return)))))))
(rest xcl::items)))
)
#+Xerox-Medley
(progn
(defun dbg::attach-backtrace-menu (&optional tty-window skip)
(declare (special il:\\term.ofd il:backtracefont))
(or tty-window (il:setq tty-window (il:wfromds (il:ttydisplaystream))))
(prog (btw bkmenu
(tty-region (il:windowprop tty-window 'il:region))
;; And, for the FORMAT below...
(*print-level* 2)
(*print-length* 3)
(*print-escape* t)
(*print-gensym* t)
(*print-pretty* nil)
(*print-circle* nil)
(*print-radix* 10)
(*print-array* nil)
(il:*print-structure* nil))
(setq bkmenu
(il:|create| il:menu
il:items il:_ (dbg::collect-backtrace-items tty-window skip)
il:whenselectedfn il:_ 'dbg::backtrace-item-selected
il:menuoutlinesize il:_ 0
il:menufont il:_ il:backtracefont
il:menucolumns il:_ 1
il:whenheldfn il:_
#'(il:lambda (item menu button)
(declare (ignore item menu))
(case button
(il:left
(il:promptprint
"Open a frame inspector on this stack frame"))
(il:middle
(il:promptprint "Inspect/Edit this function"))))))
(cond ((setq btw
(dolist (atw (il:attachedwindows tty-window))
;; Test for an attached window that has a backtrace menu in
;; it.
(when (and (setq btw (il:windowprop atw 'il:menu))
(eq (il:|fetch| (il:menu il:whenselectedfn)
il:|of| (car btw))
'dbg::backtrace-item-selected))
(return atw))))
;; If there is alread a backtrace window, delete the old menu from
;; it.
(il:deletemenu (car (il:windowprop btw 'il:menu)) nil btw)
(il:windowprop btw 'il:extent nil)
(il:clearw btw))
((setq btw
(il:createw (dbg::region-next-to
(il:windowprop tty-window 'il:region)
(il:widthifwindow
(il:imin (il:|fetch| (il:menu il:imagewidth)
il:|of| bkmenu)
il:|MaxBkMenuWidth|))
(il:|fetch| (il:region il:height)
il:|of| tty-region)
:left)))
; put bt window at left of TTY
; window unless ttywindow is
; near left edge.
(il:attachwindow btw tty-window
(if (il:igreaterp (il:|fetch| (il:region il:left)
il:|of|
(il:windowprop btw
'il:region))
(il:|fetch| (il:region il:left)
il:|of| tty-region))
'il:right
'il:left)
nil
'il:localclose)
;; So that button clicks will switch the TTY
(il:windowprop btw 'il:process
(il:windowprop tty-window 'il:process))))
(il:addmenu bkmenu btw (il:|create| il:position
il:xcoord il:_ 0
il:ycoord il:_ (- (il:windowprop btw 'il:height)
(il:|fetch| (il:menu
il:imageheight)
il:|of| bkmenu))))
;; IL:ADDMENU sets up buttoneventfn for window that we don't
;; want. We want to catch middle button events before the menu
;; handler, so that we can pop up edit/inspect menu for the frame
;; currently selected. So replace the buttoneventfn, and can
;; nuke the cursorin and cursormoved guys, cause don't need them.
(il:windowprop btw 'il:buttoneventfn 'dbg::backtrace-menu-buttoneventfn)
(il:windowprop btw 'il:cursorinfn nil)
(il:windowprop btw 'il:cursormovedfn nil)))
(defun dbg::collect-backtrace-items (tty-window skip)
(xcl:with-collection
;;
;; There are a number of possibilities for the values returned by the
;; filter-fn.
;;
;; (1) INTERESTING-P is false, and the other values are all NIL. This
;; is the simple case where the stack frame NEXT-POS should be ignored
;; completly, and processing should continue with the next frame.
;;
;; (2) INTERESTING-P is true, and the other values are all NIL. This
;; is the simple case where the stack frame NEXT-POS should appear in
;; the backtrace as is, and processing should continue with the next
;; frame.
;;
;; [Note that these two cases take care of old values of the
;; filter-fn.]
;;
;; (3) INTERESTING-P is false, and LAST-FRAME-CONSUMED is a stack
;; frame. In that case, ignore all stack frames from NEXT-POS to
;; LAST-FRAME-CONSUMED, inclusive.
;;
;; (4) INTERESTING-P is true, and LAST-FRAME-CONSUMED is a stack
;; frame. In this case, the backtrace should include a single entry
;; coresponding to the frame USE-FRAME (which defaults to
;; LAST-FRAME-CONSUMED), and processing should continue with the next
;; frame after LAST-FRAME-CONSUMED. If LABEL is non-NIL, it will be
;; the label that appears in the backtrace menu; otherwise the name of
;; USE-FRAME will be used (or the form being EVALed if the frame is an
;; EVAL frame).
;;
(let* ((filter (cond ((null skip) #'xcl:true)
((eq skip t) il:*short-backtrace-filter*)
(t skip)))
(top-frame (il:stknth 0 (il:getwindowprop tty-window
'dbg::stack-position)))
(next-frame top-frame)
(frame-number 0)
interestingp last-frame-consumed frame-to-use label-to-use)
(loop (when (null next-frame) (return))
;; Get the values of INTERSTINGP, LAST-FRAME-CONSUMED,
;; FRAME-TO-USE, and LABEL-TO-USE
(multiple-value-setq (interestingp last-frame-consumed
frame-to-use label-to-use)
(funcall filter next-frame))
(when (null last-frame-consumed)
(setf last-frame-consumed next-frame))
(when interestingp
(when (null frame-to-use)
(setf frame-to-use last-frame-consumed))
(when (null label-to-use)
(setf label-to-use (il:stkname frame-to-use))
(if (member label-to-use '(eval il:eval il:apply apply)
:test 'eq)
(setf label-to-use (il:stkarg 1 frame-to-use))))
;; Walk the stack until we find the frame to use
(loop (cond ((not (typep next-frame 'il:stackp))
(error "~%Use-frame ~S not found" frame-to-use))
((xcl::stack-eql next-frame frame-to-use)
(return))
(t (incf frame-number)
(setf next-frame
(il:stknth -1 next-frame next-frame)))))
;; Add the menu item to the list under construction
(xcl:collect (il:|create| il:bkmenuitem
il:label il:_ (let ((*print-level* 2)
(*print-length* 3)
(*print-escape* t)
(*print-gensym* t)
(*print-pretty* nil)
(*print-circle* nil)
(*print-radix* 10)
(*print-array* nil)
(il:*print-structure* nil))
(prin1-to-string label-to-use))
il:bkmenuinfo il:_ frame-number
il:frame-name il:_ label-to-use)))
;; Update NEXT-POS
(loop (cond ((not (typep next-frame 'il:stackp))
(error "~%Last-frame-consumed ~S not found"
last-frame-consumed))
((prog1
(xcl::stack-eql next-frame last-frame-consumed)
(incf frame-number)
(setf next-frame (il:stknth -1 next-frame
next-frame)))
(return))))))))
(defun dbg::backtrace-menu-buttoneventfn (window &aux menu)
(setq menu (car (il:listp (il:windowprop window 'il:menu))))
(unless (or (il:lastmousestate il:up) (null menu))
(il:totopw window)
(cond ((il:lastmousestate il:middle)
;; look for a selected frame in this menu, and then pop up
;; the editor invoke menu for that frame. don't change the
;; selection, just present the edit menu.
(let* ((selection (il:menu.handler menu
(il:windowprop window 'il:dsp)))
(tty-window (il:windowprop window 'il:mainwindow))
(last-pos (il:windowprop tty-window 'dbg::lastpos)))
;; don't have to worry about releasing POS because we
;; only look at it here (nobody here hangs on to it)
;; and we will be around for less time than LASTPOS.
;; The debugger is responsible for releasing LASTPOS.
(il:inspect/as/function (cond
((and selection
(il:|fetch| (il:bkmenuitem il:frame-name)
il:|of| (car selection))))
((and (symbolp (il:stkname last-pos))
(il:getd (il:stkname last-pos)))
(il:stkname last-pos))
(t 'il:nill))
last-pos tty-window)))
(t (let ((selection (il:menu.handler menu
(il:windowprop window 'il:dsp))))
(when selection
(il:doselecteditem menu (car selection) (cdr selection))))))))
;; This function isn't really redefined, but it needs to be recomiled since we
;; changed the def'n of the BKMENUITEM record.
(defun dbg::backtrace-item-selected (item menu button)
;;When a frame name is selected in the backtrace menu, this is the function
;;that gets called.
(declare (special il:brkenv) (ignore button))
(let* ((frame-spec (il:|fetch| (il:bkmenuitem il:bkmenuinfo) il:|of| item))
(tty-window (il:windowprop (il:wfrommenu menu) 'il:mainwindow))
(bkpos (il:windowprop tty-window 'dbg::stack-position))
(pos (il:stknth (- frame-spec) bkpos)))
(let ((lp (il:windowprop tty-window 'dbg::lastpos)))
(and lp (il:stknth 0 pos lp)))
;; change the item selected from OLDITEM to ITEM. Only do this on left
;; buttons now. Middle just pops up the edit menu, doesn't select. -woz
(let ((old-item (il:|fetch| (il:menu il:menuuserdata) il:|of| menu)))
(when old-item (il:menudeselect old-item menu))
(il:menuselect item menu))
;; Change the lexical environment so it is the one in effect as of this
;; frame.
(il:process.eval (il:windowprop tty-window (quote dbg::process))
`(setq il:brkenv ',(il:find-lexical-environment pos))
t)
(let ((frame-window (xcl:with-profile
(il:process.eval (il:windowprop tty-window
'il:process)
`(let ((profile (xcl:copy-profile
(xcl:find-profile
"READ-PRINT"))))
(setf
(xcl::profile-entry-value
'xcl:*eval-function* profile)
xcl:*eval-function*)
(xcl:save-profile profile))
t)
(il:inspectw.create pos
#'(lambda (pos)
(dbg::stack-frame-properties pos t))
'dbg::stack-frame-fetchfn
'dbg::stack-frame-storefn
nil
'dbg::stack-frame-value-command
nil
(format nil "~S Frame" (il:stkname pos))
nil (dbg::make-frame-inspect-window
tty-window)
'dbg::stack-frame-property))))
(when (not (il:windowprop frame-window 'il:mainwindow))
(il:attachwindow frame-window tty-window
(if (> (il:|fetch| (il:region il:bottom) il:|of|
(il:windowprop frame-window 'il:region))
(il:|fetch| (il:region il:bottom) il:|of|
(il:windowprop tty-window 'il:region)))
'il:top 'il:bottom)
nil 'il:localclose)
(il:windowaddprop frame-window 'il:closefn 'il:detachwindow)))))
) ;end of Xerox-Medley
(defun il:select.fns.editor (&optional function)
;; gives the user a menu choice of editors.
(il:menu (il:|create| il:menu
il:items il:_ (cond ((il:ccodep function)
'((il:|InspectCode| 'il:inspectcode
"Shows the compiled code.")
(il:|DisplayEdit| 'ed
"Edit it with the display editor")
(il:|TtyEdit| 'il:ef
"Edit it with the standard editor")))
((il:closure-p function)
'((il:|Inspect| 'inspect
"Inspect this object")))
(t '((il:|DisplayEdit| 'ed
"Edit it with the display editor")
(il:|TtyEdit| 'il:ef
"Edit it with the standard editor"))))
il:centerflg il:_ t)))
;;
;; CLOS specific extensions to the debugger
;; There are some new things that act as functions, and that we want to be
;; able to edit from a backtrace window
(pushnew 'methods xcl::*function-types*)
(eval-when (eval compile load)
(unless (generic-function-p (symbol-function 'il:inspect/as/function))
(make-specializable 'il:inspect/as/function)))
(defmethod il:inspect/as/function (name stack-pointer debugger-window)
;; Calls an editor on function NAME. STKP and WINDOW are the stack pointer
;; and window of the break in which this inspect command was called.
(declare (ignore debugger-window))
(let ((editor (il:select.fns.editor name)))
(case editor
((nil)
;; No editor chosen, so don't do anything
nil)
(il:inspectcode
;; Inspect the compiled code
(let ((frame (xcl::stack-pointer-frame stack-pointer)))
(if (and (il:stackp stack-pointer)
(xcl::stack-frame-valid-p frame))
(il:inspectcode (let ((code-base (xcl::stack-frame-fn-header frame)))
(cond ((eq (il:\\get-compiled-code-base name)
code-base)
name)
(t
;; Function executing in this frame is not
;; the one in the definition cell of its
;; name, so fetch the real code. Have to
;; pass a CCODEP
(il:make-compiled-closure code-base))))
nil nil nil (xcl::stack-frame-pc frame))
(il:inspectcode name))))
(ed
;; Use the standard editor.
;; This used to take care to apply the editor in the debugger
;; process, so forms evaluated in the editor happen in the
;; context of the break. But that doesn't count for much any
;; more, now that lexical variables are the way to go. Better to
;; use the LEX debugger command (thank you, Herbie) and
;; shift-select pieces of code from the editor into the debugger
;; window.
(ed name `(,@xcl::*function-types* :display)))
(otherwise (funcall editor name)))))
(defmethod il:inspect/as/function ((name standard-object) stkp window)
(when (il:menu (il:|create| il:menu
il:items il:_ '(("Inspect" t "Inspect this object"))))
(inspect name)))
(defmethod il:inspect/as/function ((x standard-method) stkp window)
(let* ((generic-function-name (slot-value (slot-value x 'generic-function)
'name))
(method-name (full-method-name x))
(editor (il:select.fns.editor method-name)))
(il:allow.button.events)
(case editor
(ed (ed method-name '(:display methods)))
(il:inspectcode (il:inspectcode (slot-value x 'function)))
((nil) nil)
(otherwise (funcall editor method-name)))))
;; A replacement for the vanilla IL:INTERESTING-FRAME-P so we can see methods
;; and generic-functions on the stack.
(defun interesting-frame-p (stack-pos &optional interp-flag)
;; Return up to four values: INTERESTING-P LAST-FRAME-CONSUMED USE-FRAME and
;; LABEL. See the function IL:COLLECT-BACKTRACE-ITEMS for a full description
;; of how these values are used.
(labels
((function-matches-frame-p (function frame)
"Is the function being called in this frame?"
(let* ((frame-name (il:stkname frame))
(code-being-run (cond
((typep frame-name 'il:closure)
frame-name)
((and (consp frame-name)
(eq 'il:\\interpreter
(xcl::stack-frame-name
(il:\\stackargptr frame))))
frame-name)
(t (xcl::stack-frame-fn-header
(il:\\stackargptr frame))))))
(or (eq function code-being-run)
(and (typep function 'il:compiled-closure)
(eq (xcl::compiled-closure-fnheader function)
code-being-run)))))
(generic-function-from-frame (frame)
"If this the frame of a generic function return the gf, otherwise
return NIL."
;; Generic functions are implemented as compiled closures. On the
;; stack, we only see the fnheader for the the closure. This could
;; be a discriminator code, or in the default method only case it
;; will be the actual method function. To tell if this is a generic
;; function frame, we have to check very carefully to see if the
;; right stuff is on the stack. Specifically, the closure's ccode,
;; and the first local variable has to be a ptrhunk big enough to be
;; a FIN environment, and fin-env-fin of that ptrhunk has to point
;; to a generic function whose ccode and environment match.
(let ((n-args (il:stknargs frame))
(env nil)
(gf nil))
(if (and ;; is there at least one local?
(> (il:stknargs frame t) n-args)
;; and does the local contain something that might be
;; the closure environment of a funcallable instance?
(setf env (il:stkarg (1+ n-args) frame))
;; and does the local contain something that might be
;; the closure environment of a funcallable instance?
(typep env *fin-env-type*)
(setf gf (fin-env-fin env))
;; whose fin-env-fin points to a generic function?
(generic-function-p gf)
;; whose environment is the same as env?
(eq (xcl::compiled-closure-env gf) env)
;; and whose code is the same as the code for this
;; frame?
(function-matches-frame-p gf frame))
gf
nil))))
(let ((frame-name (il:stkname stack-pos)))
;; See if there is a generic-function on the stack at this
;; location.
(let ((gf (generic-function-from-frame stack-pos)))
(when gf
(return-from interesting-frame-p (values t stack-pos stack-pos gf))))
;; See if this is an interpreted method. The method body is
;; wrapped in a (BLOCK <function-name> ...). We look for an
;; interpreted call to BLOCK whose block-name is the name of
;; generic-function.
(when (and (eq frame-name 'eval)
(consp (il:stkarg 1 stack-pos))
(eq (first (il:stkarg 1 stack-pos)) 'block)
(symbolp (second (il:stkarg 1 stack-pos)))
(fboundp (second (il:stkarg 1 stack-pos)))
(generic-function-p
(symbol-function (second (il:stkarg 1 stack-pos)))))
(let* ((form (il:stkarg 1 stack-pos))
(block-name (second form))
(generic-function (symbol-function block-name))
(methods (generic-function-methods (symbol-function block-name))))
;; If this is really a method being called from a
;; generic-function, the g-f should be no more than a
;; few(?) frames up the stack. Check for the method call
;; by looking for a call to APPLY, where the function
;; being applied is the code in one of the methods.
(do ((i 100 (1- i))
(previous-pos stack-pos current-pos)
(current-pos (il:stknth -1 stack-pos) (il:stknth -1 current-pos))
(found-method nil)
(method-pos))
((or (null current-pos) (<= i 0)) nil)
(cond ((equalp generic-function
(generic-function-from-frame current-pos))
(if found-method
(return-from interesting-frame-p
(values t previous-pos method-pos found-method))
(return)))
(found-method nil)
((eq (il:stkname current-pos) 'apply)
(dolist (method methods)
(when (eq (method-function method)
(il:stkarg 1 current-pos))
(setq method-pos current-pos)
(setq found-method method)
(return))))))))
;; Try to handle compiled methods
(when (and (symbolp frame-name)
(not (fboundp frame-name))
(eq (il:chcon1 frame-name)
(il:charcode il:\())
(or (string-equal "(method " (symbol-name frame-name)
:start2 0 :end2 13)
(string-equal "(method " (symbol-name frame-name)
:start2 0 :end2 12)
(string-equal "(method " (symbol-name frame-name)
:start2 0 :end2 8)))
;; Looks like a name that CLOS consed up. See if there is a
;; GF nearby up the stack. If there is, use it to help
;; determine which method we have.
(do ((i 30 (1- i))
(current-pos (il:stknth -1 stack-pos)
(il:stknth -1 current-pos))
(gf))
((or (null current-pos)
(<= i 0))
nil)
(setq gf (generic-function-from-frame current-pos))
(when gf
(dolist (method (generic-function-methods gf))
(when (function-matches-frame-p (method-function method)
stack-pos)
(return-from interesting-frame-p
(values t stack-pos stack-pos method))))
(return))))
;; If we haven't already returned, use the default method.
(xcl::interesting-frame-p stack-pos interp-flag))))
(setq il:*short-backtrace-filter* 'interesting-frame-p)
;;; Support for undo
(defun undoable-setf-slot-value (object slot-name new-value)
(if (slot-boundp object slot-name)
(il:undosave (list 'undoable-setf-slot-value
object slot-name (slot-value object slot-name)))
(il:undosave (list 'slot-makunbound object slot-name)))
(setf (slot-value object slot-name) new-value))
(setf (get 'slot-value :undoable-setf-inverse) 'undoable-setf-slot-value)
;;; Support for ?= and friends
;; The arglists for generic-functions are built using gensyms, and don't reflect
;; any keywords (they are all included in an &REST arg). Rather then use the
;; arglist in the code, we use the one that CLOS kindly keeps in the generic-function.
(xcl:advise-function 'il:smartarglist
'(if (and il:explainflg
(symbolp il:fn)
(fboundp il:fn)
(generic-function-p (symbol-function il:fn)))
(generic-function-pretty-arglist (symbol-function il:fn))
(xcl:inner))
:when :around :priority :last)
(setf (get 'defclass 'il:argnames)
'(nil (class-name (#\{ superclass-name #\} #\*)
(#\{ slot-specifier #\} #\*)
#\{ slot-option #\} #\*)))
(setf (get 'defmethod 'il:argnames)
'(nil (#\{ name #\| (setf name) #\} #\{ method-qualifier #\} #\*
specialized-lambda-list #\{ declaration #\| doc-string #\} #\*
#\{ form #\} #\*)))
;;; Prettyprinting support, the result of Harley Davis.
;; Support the standard Prettyprinter. This is really minimal right now. If
;; anybody wants to fix this, I'd be happy to include their code. In fact,
;; there is almost no support for Commonlisp in the standard Prettyprinter, so
;; the field is wide open to hackers with time on their hands.
(setf (get 'defmethod :definition-print-template) ;Not quite right, since it
'(:name :arglist :body)) ; doesn't handle qualifiers,
; but it will have to do.
(defun defclass-prettyprint (form)
(let ((left (il:dspxposition))
(char-width (il:charwidth (il:charcode x) *standard-output*)))
(xcl:destructuring-bind (defclass name supers slots . options) form
(princ "(")
(prin1 defclass)
(princ " ")
(prin1 name)
(princ " ")
(if (null supers)
(princ "()") ;Print "()" instead of "nil"
(il:sequential.prettyprint (list supers) (il:dspxposition)))
(if (null slots)
(progn (il:prinendline (+ left (* 4 char-width)) *standard-output*)
(princ "()"))
(il:sequential.prettyprint (list slots) (+ left (* 4 char-width))))
(when options
(il:sequential.prettyprint options (+ left (* 2 char-width))))
(princ ")")
nil)))
(let ((pprint-macro (assoc 'defclass il:prettyprintmacros)))
(if (null pprint-macro)
(push (cons 'defclass 'defclass-prettyprint)
il:prettyprintmacros)
(setf (cdr pprint-macro) 'defclass-prettyprint)))
(defun binder-prettyprint (form)
;; Prettyprints expressions like MULTIPLE-VALUE-BIND and WITH-SLOTS
;; that are of the form (fn (var ...) form &rest body).
;; This code is far from correct, but it's better than nothing.
(if (and (consp form)
(not (null (cdddr form))))
;; I have no idea what I'm doing here. Seems I can copy and edit somebody
;; elses code without understanding it.
(let ((body-indent (+ (il:dspxposition)
(* 2 (il:charwidth (il:charcode x)
*standard-output*))))
(form-indent (+ (il:dspxposition)
(* 4 (il:charwidth (il:charcode x)
*standard-output*)))))
(princ "(")
(prin1 (first form))
(princ " ")
(il:superprint (second form) form nil *standard-output*)
(il:sequential.prettyprint (list (third form)) form-indent)
(il:sequential.prettyprint (cdddr form) body-indent)
(princ ")")
nil) ;Return NIL to indicate that we did
; the printing
t)) ;Return true to use default printing
(dolist (fn '(multiple-value-bind with-accessors with-slots))
(let ((pprint-macro (assoc fn 'il:prettyprintmacros)))
(if (null pprint-macro)
(push (cons fn 'binder-prettyprint)
il:prettyprintmacros)
(setf (cdr pprint-macro) 'binder-prettyprint))))
;; SEdit has its own prettyprinter, so we need to support that too. This is due
;; to Harley Davis. Really.
(push (cons :slot-spec
'(((sedit::prev-keyword? (sedit::next-inline? 1 break sedit::from-indent . 1)
break sedit::from-indent . 0)
(sedit::set-indent . 1)
(sedit::next-inline? 1 break sedit::from-indent . 1)
(sedit::prev-keyword? (sedit::next-inline? 1 break sedit::from-indent . 1)
break sedit::from-indent . 0))
((sedit::prev-keyword? (sedit::next-inline? 1 break sedit::from-indent . 1)
break sedit::from-indent . 0)
(sedit::set-indent . 1)
(sedit::next-inline? 1 break sedit::from-indent . 1)
(sedit::prev-keyword? (sedit::next-inline? 1 break sedit::from-indent . 1)
break sedit::from-indent . 0))))
sedit:*indent-alist*)
(setf (sedit:get-format :slot-spec)
'(:indent :slot-spec :inline t))
(setf (sedit:get-format :slot-spec-list)
'(:indent :binding-list :args (:slot-spec) :inline nil))
(setf (sedit:get-format 'defclass)
'(:indent ((2) 1)
:args (:keyword nil nil :slot-spec-list nil)
:sublists (4)))
(setf (sedit:get-format 'defmethod)
'(:indent ((2))
:args (:keyword nil :lambda-list nil)
:sublists (3)))
(setf (sedit:get-format 'defgeneric) 'defun)
(setf (sedit:get-format 'generic-flet) 'flet)
(setf (sedit:get-format 'generic-labels) 'flet)
(setf (sedit:get-format 'call-next-method)
'(:indent (1) :args (:keyword nil)))
(setf (sedit:get-format 'symbol-macrolet) 'let)
(setf (sedit:get-format 'with-accessors)
'(:indent ((1) 1)
:args (:keyword :binding-list nil)
:sublists (2)
:miser :never))
(setf (sedit:get-format 'with-slots) 'with-accessors)
(setf (sedit:get-format 'make-instance)
'(:indent ((1))
:args (:keyword nil :slot-spec-list)))
(setf (sedit:get-format '*make-instance) 'make-instance)
;;; PrettyFileIndex stuff, the product of Harley Davis.
(defvar *pfi-class-type* '(class defclass pfi-class-namer))
(defvar *pfi-method-type* '(method defmethod pfi-method-namer)
"Handles method for prettyfileindex")
(defvar *pfi-index-accessors* nil
"t -> each slot accessor gets a listing in the index.")
(defvar *pfi-method-index* :group
":group, :separate, :both, or nil")
(defun pfi-add-class-type ()
(pushnew *pfi-class-type* il:*pfi-types*))
(defun pfi-add-method-type ()
(pushnew *pfi-method-type* il:*pfi-types*))
(defun pfi-class-namer (expression entry)
(let ((class-name (second expression)))
;; Following adds all slot readers/writers/accessors as separate entries in
;; the index. Probably a mistake.
(if *pfi-index-accessors*
(let ((slot-list (fourth expression))
(accessor-names nil))
(labels ((add-accessor (method-index name-index)
(push (case *pfi-method-index*
(:group method-index)
(:separate name-index)
((t :both) (list method-index name-index))
((nil) nil)
(otherwise (error "Illegal value for *pfi-method-index*: ~S"
*pfi-method-index*)))
accessor-names))
(add-reader (reader-name)
(add-accessor `(method (,reader-name (,class-name)))
`(,reader-name (,class-name))))
(add-writer (writer-name)
(add-accessor `(method ((setf ,writer-name) (t ,class-name)))
`((setf ,writer-name) (t ,class-name)))))
(dolist (slot-def slot-list)
(do* ((rest-slot-args (cdr slot-def) (cddr rest-slot-args))
(slot-arg (first rest-slot-args) (first rest-slot-args)))
((null rest-slot-args))
(case slot-arg
(:reader (add-reader (second rest-slot-args)))
(:writer (add-writer (second rest-slot-args)))
(:accessor (add-reader (second rest-slot-args))
(add-writer (second rest-slot-args)))
(otherwise nil))))
(cons `(class (,class-name)) accessor-names)))
class-name)))
(defun pfi-method-namer (expression entry)
(let ((method-name (second expression))
(specializers nil)
(qualifiers nil)
lambda-list)
(do* ((rest-qualifiers (cddr expression) (cdr rest-qualifiers))
(qualifier (first rest-qualifiers) (first rest-qualifiers)))
((listp qualifier) (setq lambda-list qualifier)
(setq qualifiers (reverse qualifiers)) qualifiers)
(push qualifier qualifiers))
(do* ((rest-lambda-list lambda-list (cdr rest-lambda-list))
(arg (first rest-lambda-list) (first rest-lambda-list)))
((or (member arg lambda-list-keywords) (null rest-lambda-list))
(setq specializers (reverse specializers)))
(push (if (listp arg) (second arg) t) specializers))
(let ((method-index `(method (,method-name ,@qualifiers ,specializers)))
(name-index `(,method-name ,@qualifiers ,specializers)))
(case *pfi-method-index*
(:group method-index)
(:separate name-index)
((t :both) (list method-index name-index))
((nil) nil)
(otherwise (error "Illegal value for *pfi-method-index*: ~S" *pfi-method-index*))))))
(defun pfi-install-clos ()
(pfi-add-method-type)
(pfi-add-class-type))
(eval-when (eval load)
(when (boundp (quote il:*pfi-types*))
(pfi-install-clos))
)
|
7402
|
;;;-*-Mode:LISP; Package:(CLOS (LISP WALKER)); Base:10; Syntax:Common-lisp -*-
;;;
;;; *************************************************************************
;;; Copyright (c) 1991 <NAME>
;;; All rights reserved.
;;; *************************************************************************
;;;
;;; Medley-Lisp specific environment hacking for CLOS
(in-package "CLOS")
;;
;; Protect the Corporation
;;
(eval-when (eval load)
(format *terminal-io*
"~&;CLOS-ENV Copyright (c) 1991 by ~
Venue Corporation. All rights reserved.~%"))
;;; Make funcallable instances (FINs) print by calling print-object.
(eval-when (eval load)
(il:defprint 'il:compiled-closure 'il:print-closure))
(defun il:print-closure (x &optional stream depth)
;; See the IRM, section 25.3.3. Unfortunatly, that documentation is
;; not correct. In particular, it makes no mention of the third argument.
(cond ((not (funcallable-instance-p x))
;; IL:\CCLOSURE.DEFPRINT is the orginal system function for
;; printing closures
(il:\\cclosure.defprint x stream))
((streamp stream)
;; Use the standard CLOS printing method, then return T to tell
;; the printer that we have done the printing ourselves.
(print-object x stream)
t)
(t
;; Internal printing (again, see the IRM section 25.3.3).
;; Return a list containing the string of characters that
;; would be printed, if the object were being printed for
;; real.
(with-output-to-string (stream)
(list (print-object x stream))))))
;;; Naming methods
(defun gf-named (gf-name)
(let ((spec (cond ((symbolp gf-name) gf-name)
((and (consp gf-name)
(eq (first gf-name) 'setf)
(symbolp (second gf-name))
(null (cddr gf-name)))
(get-setf-function-name (second gf-name)))
(t nil))))
(if (and (fboundp spec)
(generic-function-p (symbol-function spec)))
(symbol-function spec)
nil)))
(defun generic-function-method-names (gf-name hasdefp)
(if hasdefp
(let ((names nil))
(maphash #'(lambda (key value)
(declare (ignore value))
(when (and (consp key) (eql (car key) gf-name))
(pushnew key names)))
(gethash 'methods xcl:*definition-hash-table*))
names)
(let ((gf (gf-named gf-name)))
(when gf
(mapcar #'full-method-name (generic-function-methods gf))))))
(defun full-method-name (method)
"Return the full name of the method"
(let ((specializers (mapcar #'(lambda (x)
(cond ((eq x 't) t)
((and (consp x) (eq (car x) 'eql)) x)
(t (class-name x))))
(method-specializers method))))
;; Now go through some hair to make sure that specializer is
;; really right. Once CLOS returns the right value for
;; specializers this can be taken out.
(let* ((arglist (method-lambda-list method))
(number-required (or (position-if
#'(lambda (x) (member x lambda-list-keywords))
arglist)
(length arglist)))
(diff (- number-required (length specializers))))
(when (> diff 0)
(setq specializers (nconc (copy-list specializers)
(make-list diff :initial-element 't)))))
(make-full-method-name (generic-function-name
(method-generic-function method))
(method-qualifiers method)
specializers)))
(defun make-full-method-name (generic-function-name qualifiers arg-types)
"Return the full name of a method, given the generic-function name, the method
qualifiers, and the arg-types"
;; The name of the method is:
;; (<generic-function-name> <qualifier-1> ..
;; (<arg-specializer-1>..))
(labels ((remove-trailing-ts (l)
(if (null l)
nil
(let ((tail (remove-trailing-ts (cdr l))))
(if (null tail)
(if (eq (car l) 't)
nil
(list (car l)))
(if (eq l tail)
l
(cons (car l) tail)))))))
`(,generic-function-name ,@qualifiers
,(remove-trailing-ts arg-types))))
(defun parse-full-method-name (method-name)
"Parse the method name, returning the gf-name, the qualifiers, and the
arg-types."
(values (first method-name)
(butlast (rest method-name))
(car (last method-name))))
(defun prompt-for-full-method-name (gf-name &optional has-def-p)
"Prompt the user for the full name of a method on the given generic function name"
(let ((method-names (generic-function-method-names gf-name has-def-p)))
(cond ((null method-names)
nil)
((null (cdr method-names))
(car method-names))
(t (il:menu
(il:create
il:menu il:items il:_ ;If HAS-DEF-P, include only
; those methods that have a
; symbolic def'n that we can
; find
(remove-if #'null
(mapcar #'(lambda (m)
(if (or (not has-def-p)
(il:hasdef m 'methods))
`(,(with-output-to-string (s)
(dolist (x m)
(format s "~A " x))
s)
',m)
nil))
method-names))
il:title il:_ "Which method?"))))))
;;; Converting generic defining macros into DEFDEFINER macros
(defmacro make-defdefiner (definer-name definer-type type-description &body
definer-options)
"Make the DEFINER-NAME use DEFDEFINER, defining items of type DEFINER-TYPE"
(let ((old-definer-macro-name (intern (string-append definer-name
" old definition")
(symbol-package definer-name)))
(old-definer-macro-expander (intern (string-append definer-name
" old expander")
(symbol-package definer-name))))
`(progn
;; First, move the current defining function off to some safe
;; place
(unmake-defdefiner ',definer-name)
(cond ((not (fboundp ',definer-name))
(error "~A has no definition!" ',definer-name))
((fboundp ',old-definer-macro-name))
((macro-function ',definer-name)
; We have to move the macro
; expansion function as well,
; so it won't get clobbered
; when the original macro is
; redefined. See AR 7410.
(let* ((expansion-function (macro-function ',definer-name)))
(setf (symbol-function ',old-definer-macro-expander)
(loop (if (symbolp expansion-function)
(setq expansion-function
(symbol-function expansion-function))
(return expansion-function))))
(setf (macro-function ',old-definer-macro-name)
',old-definer-macro-expander)
(setf (get ',definer-name 'make-defdefiner) expansion-function)))
(t (error "~A does not name a macro." ',definer-name)))
;; Make sure the type is defined
(xcl:def-define-type ,definer-type ,type-description)
;; Now redefine the definer, using DEFEDFINER and the original def'n
(xcl:defdefiner ,(if definer-options
(cons definer-name definer-options)
definer-name)
,definer-type (&body b) `(,',old-definer-macro-name ,@,'b)))))
(defun unmake-defdefiner (definer-name)
(let ((old-expander (get definer-name 'make-defdefiner)))
(when old-expander
(setf (macro-function definer-name old-expander))
(remprop definer-name 'make-defdefiner))))
;;; For tricking ED into being able to use just the generic-function-name
;;; instead of the full method name
(defun source-manager-method-edit-fn (name type source editcoms options)
"Edit a method of the given name"
(let ((full-name (if (gf-named name)
;If given the name of a
; generic-function, try to get
; the full method name
(prompt-for-full-method-name name t)
; Otherwise it should name the
; method
name)))
(when (not (null full-name))
(il:default.editdef full-name type source editcoms options))
(or full-name name))) ;Return the name
(defun source-manager-method-hasdef-fn (name type &optional source)
"Is there a method defined with the given name?"
(cond ((not (eq type 'methods)) nil)
((or (symbolp name)
(and (consp name)
(eq (first name) 'setf)
(symbolp (second name))
(null (cddr name))))
;; If passed in the name of a generic-function, pretend that
;; there is a method by that name if there is a generic function
;; by that name, and there is a method whose source we can find.
(if (and (not (null (gf-named name)))
(find-if #'(lambda (m)
(il:hasdef m type source))
(generic-function-method-names name t)))
name
nil))
((and (consp name) (>= (length name) 2))
;; Standard methods are named (gf-name {qualifiers}* ({specializers}*))
(when (il:getdef name type source '(il:nocopy il:noerror))
name))
(t
;; Nothing else can name a method
nil)))
;;; Initialize the CLOS env
(defun initialize-clos-env nil
"Initialize the Medley CLOS environment"
;; Set up SourceManager DEFDEFINERS for classes and methods.
;;
;; Make sure to define methods before classes, so that (IL:FILES?) will build
;; filecoms that have classes before methods.
(unless (il:hasdef 'methods 'il:filepkgtype)
(make-defdefiner defmethod methods "methods"
(:name (lambda (form)
(multiple-value-bind (name qualifiers arglist)
(parse-defmethod (cdr form))
(make-full-method-name name qualifiers
(specialized-lambda-list-specializers
arglist)))))
(:undefiner
(lambda (method-name)
(multiple-value-bind
(name qualifiers arg-types)
(parse-full-method-name method-name)
(let* ((gf (gf-named name))
(method (when gf
(get-method gf qualifiers
(mapcar #'find-class
arg-types)))))
(when method (remove-method gf method))))))))
;; Include support for DEFGENERIC, if that is defined
(unless (or (not (fboundp 'defgeneric))
(il:hasdef 'generic-functions 'il:filepkgtype))
(make-defdefiner defgeneric generic-functions "generic-function definitions"))
;; DEFCLASS FileManager stuff
(unless (il:hasdef 'classes 'il:filepkgtype)
(make-defdefiner defclass classes "class definitions"
(:undefiner (lambda (name)
(when (find-class name t)
(setf (find-class name) nil)))))
;; CLASSES "include" TYPES.
(il:filepkgcom 'classes 'il:contents
#'(lambda (com name type &optional reason)
(declare (ignore name reason))
(if (member type '(il:types classes) :test #'eq)
(cdr com)
nil))))
;; Set up the hooks so that ED can be handed the name of a generic function,
;; and end up editing a method instead
(il:filepkgtype 'methods 'il:editdef 'source-manager-method-edit-fn
'il:hasdef 'source-manager-method-hasdef-fn)
;; Set up the inspect macro. The right way to do this is to
;; (ENSURE-GENERIC-FUNCTION 'IL:INSPECT...), but for now...
(push '((il:function clos-object-p) . \\internal-inspect-object)
il:inspectmacros)
;; Unmark any SourceManager changes caused by this loadup
(dolist (com (il:filepkgchanges))
(dolist (name (cdr com))
(when (and (symbolp name)
(eq (symbol-package name) (find-package "CLOS")))
(il:unmarkaschanged name (car com))))))
(eval-when (eval load)
(initialize-clos-env))
;;; Inspecting CLOS objects
(defun clos-object-p (x)
"Is the datum a CLOS object?"
(or (std-instance-p x)
(fsc-instance-p x)))
(defun \\internal-inspect-object (x type where)
(inspect-object x type where))
(defun \\internal-inspect-slot-names (x)
(inspect-slot-names x))
(defun \\internal-inspect-slot-value (x slot-name)
(inspect-slot-value x slot-name))
(defun \\internal-inspect-setf-slot-value (x slot-name value)
(inspect-setf-slot-value x slot-name value))
(defun \\internal-inspect-slot-name-command (slot-name x window)
(inspect-slot-name-command slot-name x window))
(defun \\internal-inspect-title (x y)
(inspect-title x y))
(defmethod inspect-object (x type where)
"Open an insect window on the object x"
(il:inspectw.create x '\\internal-inspect-slot-names
'\\internal-inspect-slot-value
'\\internal-inspect-setf-slot-value
'\\internal-inspect-slot-name-command nil nil
'\\internal-inspect-title nil where
#'(lambda (n v) ;Same effect as NIL, but avoids bug in
(declare (ignore v)) ; INSPECTW.CREATE
n)))
(defmethod inspect-slot-names (x)
"Return a list of names of slots of the object that should be shown in the
inspector"
(mapcar #'(lambda (slotd) (slot-value slotd 'name))
(slots-to-inspect (class-of x) x)))
(defmethod inspect-slot-value (x slot-name)
(cond ((not (slot-exists-p x slot-name)) "** no such slot **")
((not (slot-boundp x slot-name)) "** slot not bound **")
(t (slot-value x slot-name))))
(defmethod inspect-setf-slot-value (x slot-name value)
"Used by the inspector to set the value fo a slot"
;; Make this UNDO-able
(il:undosave `(inspect-setf-slot-value ,x ,slot-name
,(slot-value x slot-name)))
;; Then change the value
(setf (slot-value x slot-name) value))
(defmethod inspect-slot-name-command (slot-name x window)
"Allows the user to select a menu item to change a slot value in an inspect
window"
;; This code is a very slightly hacked version of the system function
;; DEFAULT.INSPECTW.PROPCOMMANDFN. We have to do this because the
;; standard version makes some nasty assumptions about
;; structure-objects that are not true for CLOS objects.
(declare (special il:|SetPropertyMenu|))
(case (il:menu (cond ((typep il:|SetPropertyMenu| 'il:menu)
il:|SetPropertyMenu|)
(t (il:setq il:|SetPropertyMenu|
(il:|create| il:menu il:items il:_
'((set 'set
"Allows a new value to be entered"
)))))))
(set
;; The user want to set the value
(il:ersetq (prog ((il:oldvalueitem (il:itemofpropertyvalue slot-name
window))
il:newvalue il:pwindow)
(il:ttydisplaystream (il:setq il:pwindow
(il:getpromptwindow window 3)))
(il:clearbuf t t)
(il:resetlst
(il:resetsave (il:\\itemw.flipitem il:oldvalueitem window)
(list 'il:\\itemw.flipitem
il:oldvalueitem window))
(il:resetsave (il:tty.process (il:this.process)))
(il:resetsave (il:printlevel 4 3))
(il:|printout| t "Enter the new "
slot-name " for " x t
"The expression read will be EVALuated."
t "> ")
(il:setq il:newvalue (il:lispx (il:lispxread t t)
'>))
; clear tty buffer because it
; sometimes has stuff left.
(il:clearbuf t t))
(il:closew il:pwindow)
(return (il:inspectw.replace window slot-name il:newvalue)))))))
(defmethod inspect-title (x window)
"Return the title to use in an inspect window viewing x"
(format nil "Inspecting a ~A" (class-name (class-of x))))
(defmethod inspect-title ((x standard-class) window)
(format nil "Inspecting the class ~A" (class-name x)))
;;; Debugger support for CLOS
(il:filesload clos-env-internal)
;; Non-CLOS specific changes to the debugger
;; Redefining the standard INTERESTING-FRAME-P function. Now functions can be
;; declared uninteresting to BT by giving them an XCL::UNINTERESTINGP
;; property.
(dolist (fn '(si::*unwind-protect* il:*env*
evalhook xcl::nohook xcl::undohook
xcl::execa0001 xcl::execa0001a0002
xcl::|interpret-UNDOABLY|
cl::|interpret-IF| cl::|interpret-FLET|
cl::|interpret-LET| cl::|interpret-LETA0001|
cl::|interpret-BLOCK| cl::|interpret-BLOCKA0001|
il:do-event il:eval-input
apply t))
(setf (get fn 'xcl::uninterestingp) t))
(defun xcl::interesting-frame-p (xcl::pos &optional xcl::interpflg)
"Return TRUE iff the frame should be visible for a short backtrace."
(declare (special il:openfns))
(let ((xcl::name (if (il:stackp xcl::pos) (il:stkname xcl::pos) xcl::pos)))
(typecase xcl::name
(symbol (case xcl::name
(il:*env*
;; *ENV* is used by ENVEVAL etc.
nil)
(il:errorset
(or (<= (il:stknargs xcl::pos) 1)
(not (eq (il:stkarg 2 xcl::pos nil)
'il:internal))))
(il:eval
(or (<= (il:stknargs xcl::pos) 1)
(not (eq (il:stkarg 2 xcl::pos nil)
'xcl::internal))))
(il:apply
(or (<= (il:stknargs xcl::pos) 2)
(not (il:stkarg 3 xcl::pos nil))))
(otherwise
(cond ((get xcl::name 'xcl::uninterestingp)
;; Explicitly declared uninteresting.
nil)
((eq (il:chcon1 xcl::name) (char-code #\\))
;; Implicitly declared uninteresting by starting the
;; name with a "\".
nil)
((or (member xcl::name il:openfns :test #'eq)
(eq xcl::name 'funcall))
;;The function won't be seen when compiled, so only show
;;it if INTERPFLG it true
xcl::interpflg)
(t
;; Interesting by default.
t)))))
(cons (case (car xcl::name)
(:broken t)
(otherwise nil)))
(otherwise nil))))
(setq il:*short-backtrace-filter* 'xcl::interesting-frame-p)
(eval-when (eval compile)
(il:record il:bkmenuitem (il:label (il:bkmenuinfo il:frame-name))))
;; Change the frame inspector to open up lexical environments
;; Since the DEFSTRUCT is going to build the accessors in the package that is
;; current at read-time, and we want the accessors to reside in the IL
;; package, we have got to make sure that the defstruct happens when the
;; package is IL.
(in-package "IL")
(cl:defstruct (frame-prop-name (:type cl:list))
(label-fn 'nill)
(value-fn
(function
(lambda (prop-name framespec)
(frame-prop-name-data prop-name))))
(setf-fn 'nill)
(inspect-fn
(function
(lambda (value prop-name framespec window)
(default.inspectw.valuecommandfn value prop-name (car framespec) window))))
(data nil))
(cl:in-package "CLOS")
(defun il:debugger-stack-frame-prop-names (il:framespec)
;; Frame prop-names are structures of the form
;; (LABEL-FN VALUE-FN SETF-FN EDIT-FN DATA)
(let ((il:pos (car il:framespec))
(il:backtrace-item (cadr il:framespec)))
(il:if (eq 'eval (il:stkname il:pos))
il:then
(let ((il:expression (il:stkarg 1 il:pos))
(il:environment (il:stkarg 2 il:pos)))
`(,(il:make-frame-prop-name :inspect-fn
(il:function
(il:lambda (il:value il:prop-name il:framespec il:window)
(il:inspect/as/function il:value (car il:framespec) il:window)))
:data il:expression)
,(il:make-frame-prop-name :data "ENVIRONMENT")
,@(il:for il:aspect il:in
`((,(and il:environment (il:environment-vars il:environment))
"vars")
(,(and il:environment (il:environment-functions il:environment))
"functions")
(,(and il:environment (il:environment-blocks il:environment))
"blocks")
(,(and il:environment (il:environment-tagbodies il:environment))
"tag bodies"))
il:bind il:group-name il:p-list
il:eachtime (il:setq il:group-name (cadr il:aspect))
(il:setq il:p-list (car il:aspect))
il:when (not (null il:p-list))
il:join
`(,(il:make-frame-prop-name :data il:group-name)
,@(il:for il:p il:on il:p-list il:by cddr il:collect
(il:make-frame-prop-name :label-fn
(il:function (il:lambda (il:prop-name il:framespec)
(car (il:frame-prop-name-data il:prop-name))))
:value-fn
(il:function (il:lambda (il:prop-name il:framespec)
(cadr (il:frame-prop-name-data il:prop-name))))
:setf-fn
(il:function (il:lambda (il:prop-name il:framespec il:new-value)
(il:change (cadr (il:frame-prop-name-data
il:prop-name))
il:new-value)))
:data il:p))))))
il:else
(flet ((il:build-name (&key il:arg-name il:arg-number)
(il:make-frame-prop-name :label-fn
(il:function (il:lambda (il:prop-name il:framespec)
(car (il:frame-prop-name-data il:prop-name))))
:value-fn
(il:function (il:lambda (il:prop-name il:framespec)
(il:stkarg (cadr (il:frame-prop-name-data
il:prop-name))
(car il:framespec))))
:setf-fn
(il:function (il:lambda (il:prop-name il:framespec il:new-value)
(il:setstkarg (cadr (il:frame-prop-name-data
il:prop-name))
(car il:framespec)
il:new-value)))
:data
(list il:arg-name il:arg-number))))
(let ((il:nargs (il:stknargs il:pos t))
(il:nargs1 (il:stknargs il:pos))
(il:fnname (il:stkname il:pos))
il:argname
(il:arglist))
(and (il:litatom il:fnname)
(il:ccodep il:fnname)
(il:setq il:arglist (il:listp (il:smartarglist il:fnname))))
`(,(il:make-frame-prop-name :inspect-fn
(il:function (il:lambda (il:value il:prop-name il:framespec
il:window)
(il:inspect/as/function il:value
(car il:framespec)
il:window)))
:data
(il:fetch (il:bkmenuitem il:frame-name) il:of il:backtrace-item))
,@(il:bind il:mode il:for il:i il:from 1 il:to il:nargs1 il:collect
(progn (il:while (il:fmemb (il:setq il:argname (il:pop il:arglist))
lambda-list-keywords)
il:do
(il:setq il:mode il:argname))
(il:build-name :arg-name
(or (il:stkargname il:i il:pos)
; special
(if (case il:mode
((nil &optional) il:argname)
(t nil))
(string il:argname)
(il:concat "arg " (- il:i 1))))
:arg-number il:i)))
,@(let* ((il:novalue "No value")
(il:slots (il:for il:pvar il:from 0 il:as il:i il:from
(il:add1 il:nargs1)
il:to il:nargs il:by 1 il:when
(and (il:neq il:novalue (il:stkarg il:i il:pos
il:novalue))
(or (il:setq il:argname (il:stkargname
il:i il:pos))
(il:setq il:argname (il:concat
"local "
il:pvar)))
)
il:collect
(il:build-name :arg-name il:argname
:arg-number il:i))))
(and il:slots (cons (il:make-frame-prop-name :data "locals")
il:slots)))))))))
(defun il:debugger-stack-frame-fetchfn (il:framespec il:prop-name)
(il:apply* (il:frame-prop-name-value-fn il:prop-name)
il:prop-name il:framespec))
(defun il:debugger-stack-frame-storefn (il:framespec il:prop-name il:newvalue)
(il:apply* (il:frame-prop-name-setf-fn il:prop-name)
il:prop-name il:framespec il:newvalue))
(defun il:debugger-stack-frame-value-command (il:datum il:prop-name
il:framespec il:window)
(il:apply* (il:frame-prop-name-inspect-fn il:prop-name)
il:datum il:prop-name il:framespec il:window))
(defun il:debugger-stack-frame-title (il:framespec &optional il:window)
(declare (ignore il:window))
(il:concat (il:stkname (car il:framespec)) " Frame"))
(defun il:debugger-stack-frame-property (il:prop-name il:framespec)
(il:apply* (il:frame-prop-name-label-fn il:prop-name)
il:prop-name il:framespec))
;; Teaching the debugger that there are other file-manager types that can
;; appear on the stack
(defvar xcl::*function-types* '(il:fns il:functions)
"Manager types that can appear on the stack")
;; Redefine a couple of system functions to use the above stuff
#+Xerox-Lyric
(progn
(defun il:attach-backtrace-menu (&optional (il:ttywindow
(il:wfromds (il:ttydisplaystream)))
il:skip)
(let ((il:bkmenu (il:|create| il:menu
il:items il:_
(il:collect-backtrace-items il:ttywindow il:skip)
il:whenselectedfn il:_
(il:function il:backtrace-item-selected)
il:whenheldfn il:_
#'(il:lambda (il:item il:menu il:button)
(declare (ignore il:item il:menu))
(case il:button
(il:left (il:promptprint
"Open a frame inspector on this stack frame"
))
(il:middle (il:promptprint
"Inspect/Edit this function"))
))
il:menuoutlinesize il:_ 0
il:menufont il:_ il:backtracefont
il:menucolumns il:_ 1))
(il:ttyregion (il:windowprop il:ttywindow 'il:region))
il:btw)
(cond
((il:setq il:btw (il:|for| il:atw il:|in| (il:attachedwindows il:ttywindow)
il:|when| (and (il:setq il:btw (il:windowprop il:atw 'il:menu))
(eql (il:|fetch| (il:menu il:whenselectedfn)
il:|of| (car il:btw))
(il:function il:backtrace-item-selected)))
il:|do|
(return il:atw)))
(il:deletemenu (car (il:windowprop il:btw 'il:menu))
nil il:btw)
(il:windowprop il:btw 'il:extent nil)
(il:clearw il:btw))
((il:setq il:btw (il:createw (il:region-next-to (il:windowprop il:ttywindow 'il:region)
(il:widthifwindow (il:imin (il:|fetch| (il:menu
il:imagewidth
)
il:|of| il:bkmenu)
il:|MaxBkMenuWidth|))
(il:|fetch| (il:region il:height) il:|of| il:ttyregion
)
'il:left)))
(il:attachwindow il:btw il:ttywindow (cond
((il:igreaterp (il:|fetch| (il:region il:left)
il:|of| (il:windowprop
il:btw
'il:region))
(il:|fetch| (il:region il:left)
il:|of| il:ttyregion))
'il:right)
(t 'il:left))
nil
'il:localclose)
(il:windowprop il:btw 'il:process (il:windowprop il:ttywindow 'il:process))
))
(il:addmenu il:bkmenu il:btw (il:|create| il:_ il:position
il:xcoord il:_ 0
il:ycoord il:_ (il:idifference (il:windowprop
il:btw
'il:height)
(il:|fetch| (il:menu il:imageheight
) il:|of|
il:bkmenu
))))))
(defun il:backtrace-item-selected (il:item il:menu il:button)
(il:resetlst
(prog (il:olditem il:ttywindow il:bkpos il:pos il:positions il:framewindow
(il:framespecn (il:|fetch| (il:bkmenuitem il:bkmenuinfo) il:|of| il:item)
))
(cond
((il:setq il:olditem (il:|fetch| (il:menu il:menuuserdata) il:|of| il:menu))
(il:menudeselect il:olditem il:menu)
))
(il:setq il:ttywindow (il:windowprop (il:wfrommenu il:menu)
'il:mainwindow))
(il:setq il:bkpos (il:windowprop il:ttywindow 'il:stack-position))
(il:setq il:pos (il:stknth (- il:framespecn)
il:bkpos))
(let ((il:lp (il:windowprop il:ttywindow 'il:lastpos)))
(and il:lp (il:stknth 0 il:pos il:lp)))
(il:menuselect il:item il:menu)
(if (eq il:button 'il:middle)
(progn
(il:resetsave nil (list 'il:relstk il:pos))
(il:inspect/as/function (il:|fetch| (il:bkmenuitem il:frame-name)
il:|of| il:item)
il:pos il:ttywindow))
(progn
(il:setq il:framewindow
(xcl:with-profile (il:process.eval
(il:windowprop il:ttywindow 'il:process)
'(let ((il:profile (xcl:copy-profile (xcl:find-profile
"READ-PRINT"))))
(setf (xcl::profile-entry-value '
xcl:*eval-function* il:profile)
xcl:*eval-function*)
(xcl:save-profile il:profile))
t)
(il:inspectw.create (list il:pos il:item)
'il:debugger-stack-frame-prop-names
'il:debugger-stack-frame-fetchfn
'il:debugger-stack-frame-storefn nil '
il:debugger-stack-frame-value-command nil '
il:debugger-stack-frame-title nil (
il:make-frame-inspect-window
il:ttywindow)
'il:debugger-stack-frame-property)))
(cond
((not (il:windowprop il:framewindow 'il:mainwindow))
(il:attachwindow il:framewindow il:ttywindow
(cond
((il:igreaterp (il:|fetch| (il:region il:bottom)
il:|of| (il:windowprop il:framewindow
'il:region))
(il:|fetch| (il:region il:bottom)
il:|of| (il:windowprop il:ttywindow 'il:region)))
'il:top)
(t 'il:bottom))
nil
'il:localclose)
(il:windowaddprop il:framewindow 'il:closefn (il:function il:detachwindow
))))))
(return))))
(defun il:collect-backtrace-items (xcl::tty-window xcl::skip)
(let* ((xcl::items (cons nil nil))
(xcl::items-tail xcl::items))
(macrolet ((xcl::collect-item (xcl::new-item)
`(progn (setf (rest xcl::items-tail)
(cons ,xcl::new-item nil))
(pop xcl::items-tail))))
(let* ((xcl::filter-fn (cond
((null xcl::skip)
#'xcl:true)
((eq xcl::skip t)
il:*short-backtrace-filter*)
(t xcl::skip)))
(xcl::top-frame (il:stknth 0 (il:getwindowprop xcl::tty-window '
il:stack-position)))
(xcl::next-frame xcl::top-frame)
(xcl::frame-number 0)
xcl::interesting-p xcl::last-frame-consumed xcl::use-frame xcl::label)
(loop (when (null xcl::next-frame)
(return))
(multiple-value-setq (xcl::interesting-p xcl::last-frame-consumed
xcl::use-frame xcl::label)
(funcall xcl::filter-fn xcl::next-frame))
(when (null xcl::last-frame-consumed)
(setf xcl::last-frame-consumed xcl::next-frame))
(when xcl::interesting-p
(when (null xcl::use-frame)
(setf xcl::use-frame xcl::last-frame-consumed))
(when (null xcl::label)
(setf xcl::label (il:stkname xcl::use-frame))
(if (member xcl::label '(eval il:eval il:apply apply)
:test
'eq)
(setf xcl::label (il:stkarg 1 xcl::use-frame))))
(loop (cond
((not (typep xcl::next-frame 'il:stackp))
(error "~%Use-frame ~S not found" xcl::use-frame))
((xcl::stack-eql xcl::next-frame xcl::use-frame)
(return))
(t (incf xcl::frame-number)
(setf xcl::next-frame (il:stknth -1 xcl::next-frame
xcl::next-frame)))))
(xcl::collect-item (il:|create| il:bkmenuitem
il:label il:_ (let ((*print-level* 2)
(*print-length* 3)
(*print-escape* t)
(*print-gensym* t)
(*print-pretty* nil)
(*print-circle* nil)
(*print-radix* 10)
(*print-array* nil)
(il:*print-structure*
nil))
(prin1-to-string
xcl::label))
il:bkmenuinfo il:_ xcl::frame-number
il:frame-name il:_ xcl::label)))
(loop (cond
((not (typep xcl::next-frame 'il:stackp))
(error "~%Last-frame-consumed ~S not found"
xcl::last-frame-consumed))
((prog1 (xcl::stack-eql xcl::next-frame xcl::last-frame-consumed
)
(incf xcl::frame-number)
(setf xcl::next-frame (il:stknth -1 xcl::next-frame
xcl::next-frame)))
(return)))))))
(rest xcl::items)))
)
#+Xerox-Medley
(progn
(defun dbg::attach-backtrace-menu (&optional tty-window skip)
(declare (special il:\\term.ofd il:backtracefont))
(or tty-window (il:setq tty-window (il:wfromds (il:ttydisplaystream))))
(prog (btw bkmenu
(tty-region (il:windowprop tty-window 'il:region))
;; And, for the FORMAT below...
(*print-level* 2)
(*print-length* 3)
(*print-escape* t)
(*print-gensym* t)
(*print-pretty* nil)
(*print-circle* nil)
(*print-radix* 10)
(*print-array* nil)
(il:*print-structure* nil))
(setq bkmenu
(il:|create| il:menu
il:items il:_ (dbg::collect-backtrace-items tty-window skip)
il:whenselectedfn il:_ 'dbg::backtrace-item-selected
il:menuoutlinesize il:_ 0
il:menufont il:_ il:backtracefont
il:menucolumns il:_ 1
il:whenheldfn il:_
#'(il:lambda (item menu button)
(declare (ignore item menu))
(case button
(il:left
(il:promptprint
"Open a frame inspector on this stack frame"))
(il:middle
(il:promptprint "Inspect/Edit this function"))))))
(cond ((setq btw
(dolist (atw (il:attachedwindows tty-window))
;; Test for an attached window that has a backtrace menu in
;; it.
(when (and (setq btw (il:windowprop atw 'il:menu))
(eq (il:|fetch| (il:menu il:whenselectedfn)
il:|of| (car btw))
'dbg::backtrace-item-selected))
(return atw))))
;; If there is alread a backtrace window, delete the old menu from
;; it.
(il:deletemenu (car (il:windowprop btw 'il:menu)) nil btw)
(il:windowprop btw 'il:extent nil)
(il:clearw btw))
((setq btw
(il:createw (dbg::region-next-to
(il:windowprop tty-window 'il:region)
(il:widthifwindow
(il:imin (il:|fetch| (il:menu il:imagewidth)
il:|of| bkmenu)
il:|MaxBkMenuWidth|))
(il:|fetch| (il:region il:height)
il:|of| tty-region)
:left)))
; put bt window at left of TTY
; window unless ttywindow is
; near left edge.
(il:attachwindow btw tty-window
(if (il:igreaterp (il:|fetch| (il:region il:left)
il:|of|
(il:windowprop btw
'il:region))
(il:|fetch| (il:region il:left)
il:|of| tty-region))
'il:right
'il:left)
nil
'il:localclose)
;; So that button clicks will switch the TTY
(il:windowprop btw 'il:process
(il:windowprop tty-window 'il:process))))
(il:addmenu bkmenu btw (il:|create| il:position
il:xcoord il:_ 0
il:ycoord il:_ (- (il:windowprop btw 'il:height)
(il:|fetch| (il:menu
il:imageheight)
il:|of| bkmenu))))
;; IL:ADDMENU sets up buttoneventfn for window that we don't
;; want. We want to catch middle button events before the menu
;; handler, so that we can pop up edit/inspect menu for the frame
;; currently selected. So replace the buttoneventfn, and can
;; nuke the cursorin and cursormoved guys, cause don't need them.
(il:windowprop btw 'il:buttoneventfn 'dbg::backtrace-menu-buttoneventfn)
(il:windowprop btw 'il:cursorinfn nil)
(il:windowprop btw 'il:cursormovedfn nil)))
(defun dbg::collect-backtrace-items (tty-window skip)
(xcl:with-collection
;;
;; There are a number of possibilities for the values returned by the
;; filter-fn.
;;
;; (1) INTERESTING-P is false, and the other values are all NIL. This
;; is the simple case where the stack frame NEXT-POS should be ignored
;; completly, and processing should continue with the next frame.
;;
;; (2) INTERESTING-P is true, and the other values are all NIL. This
;; is the simple case where the stack frame NEXT-POS should appear in
;; the backtrace as is, and processing should continue with the next
;; frame.
;;
;; [Note that these two cases take care of old values of the
;; filter-fn.]
;;
;; (3) INTERESTING-P is false, and LAST-FRAME-CONSUMED is a stack
;; frame. In that case, ignore all stack frames from NEXT-POS to
;; LAST-FRAME-CONSUMED, inclusive.
;;
;; (4) INTERESTING-P is true, and LAST-FRAME-CONSUMED is a stack
;; frame. In this case, the backtrace should include a single entry
;; coresponding to the frame USE-FRAME (which defaults to
;; LAST-FRAME-CONSUMED), and processing should continue with the next
;; frame after LAST-FRAME-CONSUMED. If LABEL is non-NIL, it will be
;; the label that appears in the backtrace menu; otherwise the name of
;; USE-FRAME will be used (or the form being EVALed if the frame is an
;; EVAL frame).
;;
(let* ((filter (cond ((null skip) #'xcl:true)
((eq skip t) il:*short-backtrace-filter*)
(t skip)))
(top-frame (il:stknth 0 (il:getwindowprop tty-window
'dbg::stack-position)))
(next-frame top-frame)
(frame-number 0)
interestingp last-frame-consumed frame-to-use label-to-use)
(loop (when (null next-frame) (return))
;; Get the values of INTERSTINGP, LAST-FRAME-CONSUMED,
;; FRAME-TO-USE, and LABEL-TO-USE
(multiple-value-setq (interestingp last-frame-consumed
frame-to-use label-to-use)
(funcall filter next-frame))
(when (null last-frame-consumed)
(setf last-frame-consumed next-frame))
(when interestingp
(when (null frame-to-use)
(setf frame-to-use last-frame-consumed))
(when (null label-to-use)
(setf label-to-use (il:stkname frame-to-use))
(if (member label-to-use '(eval il:eval il:apply apply)
:test 'eq)
(setf label-to-use (il:stkarg 1 frame-to-use))))
;; Walk the stack until we find the frame to use
(loop (cond ((not (typep next-frame 'il:stackp))
(error "~%Use-frame ~S not found" frame-to-use))
((xcl::stack-eql next-frame frame-to-use)
(return))
(t (incf frame-number)
(setf next-frame
(il:stknth -1 next-frame next-frame)))))
;; Add the menu item to the list under construction
(xcl:collect (il:|create| il:bkmenuitem
il:label il:_ (let ((*print-level* 2)
(*print-length* 3)
(*print-escape* t)
(*print-gensym* t)
(*print-pretty* nil)
(*print-circle* nil)
(*print-radix* 10)
(*print-array* nil)
(il:*print-structure* nil))
(prin1-to-string label-to-use))
il:bkmenuinfo il:_ frame-number
il:frame-name il:_ label-to-use)))
;; Update NEXT-POS
(loop (cond ((not (typep next-frame 'il:stackp))
(error "~%Last-frame-consumed ~S not found"
last-frame-consumed))
((prog1
(xcl::stack-eql next-frame last-frame-consumed)
(incf frame-number)
(setf next-frame (il:stknth -1 next-frame
next-frame)))
(return))))))))
(defun dbg::backtrace-menu-buttoneventfn (window &aux menu)
(setq menu (car (il:listp (il:windowprop window 'il:menu))))
(unless (or (il:lastmousestate il:up) (null menu))
(il:totopw window)
(cond ((il:lastmousestate il:middle)
;; look for a selected frame in this menu, and then pop up
;; the editor invoke menu for that frame. don't change the
;; selection, just present the edit menu.
(let* ((selection (il:menu.handler menu
(il:windowprop window 'il:dsp)))
(tty-window (il:windowprop window 'il:mainwindow))
(last-pos (il:windowprop tty-window 'dbg::lastpos)))
;; don't have to worry about releasing POS because we
;; only look at it here (nobody here hangs on to it)
;; and we will be around for less time than LASTPOS.
;; The debugger is responsible for releasing LASTPOS.
(il:inspect/as/function (cond
((and selection
(il:|fetch| (il:bkmenuitem il:frame-name)
il:|of| (car selection))))
((and (symbolp (il:stkname last-pos))
(il:getd (il:stkname last-pos)))
(il:stkname last-pos))
(t 'il:nill))
last-pos tty-window)))
(t (let ((selection (il:menu.handler menu
(il:windowprop window 'il:dsp))))
(when selection
(il:doselecteditem menu (car selection) (cdr selection))))))))
;; This function isn't really redefined, but it needs to be recomiled since we
;; changed the def'n of the BKMENUITEM record.
(defun dbg::backtrace-item-selected (item menu button)
;;When a frame name is selected in the backtrace menu, this is the function
;;that gets called.
(declare (special il:brkenv) (ignore button))
(let* ((frame-spec (il:|fetch| (il:bkmenuitem il:bkmenuinfo) il:|of| item))
(tty-window (il:windowprop (il:wfrommenu menu) 'il:mainwindow))
(bkpos (il:windowprop tty-window 'dbg::stack-position))
(pos (il:stknth (- frame-spec) bkpos)))
(let ((lp (il:windowprop tty-window 'dbg::lastpos)))
(and lp (il:stknth 0 pos lp)))
;; change the item selected from OLDITEM to ITEM. Only do this on left
;; buttons now. Middle just pops up the edit menu, doesn't select. -woz
(let ((old-item (il:|fetch| (il:menu il:menuuserdata) il:|of| menu)))
(when old-item (il:menudeselect old-item menu))
(il:menuselect item menu))
;; Change the lexical environment so it is the one in effect as of this
;; frame.
(il:process.eval (il:windowprop tty-window (quote dbg::process))
`(setq il:brkenv ',(il:find-lexical-environment pos))
t)
(let ((frame-window (xcl:with-profile
(il:process.eval (il:windowprop tty-window
'il:process)
`(let ((profile (xcl:copy-profile
(xcl:find-profile
"READ-PRINT"))))
(setf
(xcl::profile-entry-value
'xcl:*eval-function* profile)
xcl:*eval-function*)
(xcl:save-profile profile))
t)
(il:inspectw.create pos
#'(lambda (pos)
(dbg::stack-frame-properties pos t))
'dbg::stack-frame-fetchfn
'dbg::stack-frame-storefn
nil
'dbg::stack-frame-value-command
nil
(format nil "~S Frame" (il:stkname pos))
nil (dbg::make-frame-inspect-window
tty-window)
'dbg::stack-frame-property))))
(when (not (il:windowprop frame-window 'il:mainwindow))
(il:attachwindow frame-window tty-window
(if (> (il:|fetch| (il:region il:bottom) il:|of|
(il:windowprop frame-window 'il:region))
(il:|fetch| (il:region il:bottom) il:|of|
(il:windowprop tty-window 'il:region)))
'il:top 'il:bottom)
nil 'il:localclose)
(il:windowaddprop frame-window 'il:closefn 'il:detachwindow)))))
) ;end of Xerox-Medley
(defun il:select.fns.editor (&optional function)
;; gives the user a menu choice of editors.
(il:menu (il:|create| il:menu
il:items il:_ (cond ((il:ccodep function)
'((il:|InspectCode| 'il:inspectcode
"Shows the compiled code.")
(il:|DisplayEdit| 'ed
"Edit it with the display editor")
(il:|TtyEdit| 'il:ef
"Edit it with the standard editor")))
((il:closure-p function)
'((il:|Inspect| 'inspect
"Inspect this object")))
(t '((il:|DisplayEdit| 'ed
"Edit it with the display editor")
(il:|TtyEdit| 'il:ef
"Edit it with the standard editor"))))
il:centerflg il:_ t)))
;;
;; CLOS specific extensions to the debugger
;; There are some new things that act as functions, and that we want to be
;; able to edit from a backtrace window
(pushnew 'methods xcl::*function-types*)
(eval-when (eval compile load)
(unless (generic-function-p (symbol-function 'il:inspect/as/function))
(make-specializable 'il:inspect/as/function)))
(defmethod il:inspect/as/function (name stack-pointer debugger-window)
;; Calls an editor on function NAME. STKP and WINDOW are the stack pointer
;; and window of the break in which this inspect command was called.
(declare (ignore debugger-window))
(let ((editor (il:select.fns.editor name)))
(case editor
((nil)
;; No editor chosen, so don't do anything
nil)
(il:inspectcode
;; Inspect the compiled code
(let ((frame (xcl::stack-pointer-frame stack-pointer)))
(if (and (il:stackp stack-pointer)
(xcl::stack-frame-valid-p frame))
(il:inspectcode (let ((code-base (xcl::stack-frame-fn-header frame)))
(cond ((eq (il:\\get-compiled-code-base name)
code-base)
name)
(t
;; Function executing in this frame is not
;; the one in the definition cell of its
;; name, so fetch the real code. Have to
;; pass a CCODEP
(il:make-compiled-closure code-base))))
nil nil nil (xcl::stack-frame-pc frame))
(il:inspectcode name))))
(ed
;; Use the standard editor.
;; This used to take care to apply the editor in the debugger
;; process, so forms evaluated in the editor happen in the
;; context of the break. But that doesn't count for much any
;; more, now that lexical variables are the way to go. Better to
;; use the LEX debugger command (thank you, <NAME>) and
;; shift-select pieces of code from the editor into the debugger
;; window.
(ed name `(,@xcl::*function-types* :display)))
(otherwise (funcall editor name)))))
(defmethod il:inspect/as/function ((name standard-object) stkp window)
(when (il:menu (il:|create| il:menu
il:items il:_ '(("Inspect" t "Inspect this object"))))
(inspect name)))
(defmethod il:inspect/as/function ((x standard-method) stkp window)
(let* ((generic-function-name (slot-value (slot-value x 'generic-function)
'name))
(method-name (full-method-name x))
(editor (il:select.fns.editor method-name)))
(il:allow.button.events)
(case editor
(ed (ed method-name '(:display methods)))
(il:inspectcode (il:inspectcode (slot-value x 'function)))
((nil) nil)
(otherwise (funcall editor method-name)))))
;; A replacement for the vanilla IL:INTERESTING-FRAME-P so we can see methods
;; and generic-functions on the stack.
(defun interesting-frame-p (stack-pos &optional interp-flag)
;; Return up to four values: INTERESTING-P LAST-FRAME-CONSUMED USE-FRAME and
;; LABEL. See the function IL:COLLECT-BACKTRACE-ITEMS for a full description
;; of how these values are used.
(labels
((function-matches-frame-p (function frame)
"Is the function being called in this frame?"
(let* ((frame-name (il:stkname frame))
(code-being-run (cond
((typep frame-name 'il:closure)
frame-name)
((and (consp frame-name)
(eq 'il:\\interpreter
(xcl::stack-frame-name
(il:\\stackargptr frame))))
frame-name)
(t (xcl::stack-frame-fn-header
(il:\\stackargptr frame))))))
(or (eq function code-being-run)
(and (typep function 'il:compiled-closure)
(eq (xcl::compiled-closure-fnheader function)
code-being-run)))))
(generic-function-from-frame (frame)
"If this the frame of a generic function return the gf, otherwise
return NIL."
;; Generic functions are implemented as compiled closures. On the
;; stack, we only see the fnheader for the the closure. This could
;; be a discriminator code, or in the default method only case it
;; will be the actual method function. To tell if this is a generic
;; function frame, we have to check very carefully to see if the
;; right stuff is on the stack. Specifically, the closure's ccode,
;; and the first local variable has to be a ptrhunk big enough to be
;; a FIN environment, and fin-env-fin of that ptrhunk has to point
;; to a generic function whose ccode and environment match.
(let ((n-args (il:stknargs frame))
(env nil)
(gf nil))
(if (and ;; is there at least one local?
(> (il:stknargs frame t) n-args)
;; and does the local contain something that might be
;; the closure environment of a funcallable instance?
(setf env (il:stkarg (1+ n-args) frame))
;; and does the local contain something that might be
;; the closure environment of a funcallable instance?
(typep env *fin-env-type*)
(setf gf (fin-env-fin env))
;; whose fin-env-fin points to a generic function?
(generic-function-p gf)
;; whose environment is the same as env?
(eq (xcl::compiled-closure-env gf) env)
;; and whose code is the same as the code for this
;; frame?
(function-matches-frame-p gf frame))
gf
nil))))
(let ((frame-name (il:stkname stack-pos)))
;; See if there is a generic-function on the stack at this
;; location.
(let ((gf (generic-function-from-frame stack-pos)))
(when gf
(return-from interesting-frame-p (values t stack-pos stack-pos gf))))
;; See if this is an interpreted method. The method body is
;; wrapped in a (BLOCK <function-name> ...). We look for an
;; interpreted call to BLOCK whose block-name is the name of
;; generic-function.
(when (and (eq frame-name 'eval)
(consp (il:stkarg 1 stack-pos))
(eq (first (il:stkarg 1 stack-pos)) 'block)
(symbolp (second (il:stkarg 1 stack-pos)))
(fboundp (second (il:stkarg 1 stack-pos)))
(generic-function-p
(symbol-function (second (il:stkarg 1 stack-pos)))))
(let* ((form (il:stkarg 1 stack-pos))
(block-name (second form))
(generic-function (symbol-function block-name))
(methods (generic-function-methods (symbol-function block-name))))
;; If this is really a method being called from a
;; generic-function, the g-f should be no more than a
;; few(?) frames up the stack. Check for the method call
;; by looking for a call to APPLY, where the function
;; being applied is the code in one of the methods.
(do ((i 100 (1- i))
(previous-pos stack-pos current-pos)
(current-pos (il:stknth -1 stack-pos) (il:stknth -1 current-pos))
(found-method nil)
(method-pos))
((or (null current-pos) (<= i 0)) nil)
(cond ((equalp generic-function
(generic-function-from-frame current-pos))
(if found-method
(return-from interesting-frame-p
(values t previous-pos method-pos found-method))
(return)))
(found-method nil)
((eq (il:stkname current-pos) 'apply)
(dolist (method methods)
(when (eq (method-function method)
(il:stkarg 1 current-pos))
(setq method-pos current-pos)
(setq found-method method)
(return))))))))
;; Try to handle compiled methods
(when (and (symbolp frame-name)
(not (fboundp frame-name))
(eq (il:chcon1 frame-name)
(il:charcode il:\())
(or (string-equal "(method " (symbol-name frame-name)
:start2 0 :end2 13)
(string-equal "(method " (symbol-name frame-name)
:start2 0 :end2 12)
(string-equal "(method " (symbol-name frame-name)
:start2 0 :end2 8)))
;; Looks like a name that CLOS consed up. See if there is a
;; GF nearby up the stack. If there is, use it to help
;; determine which method we have.
(do ((i 30 (1- i))
(current-pos (il:stknth -1 stack-pos)
(il:stknth -1 current-pos))
(gf))
((or (null current-pos)
(<= i 0))
nil)
(setq gf (generic-function-from-frame current-pos))
(when gf
(dolist (method (generic-function-methods gf))
(when (function-matches-frame-p (method-function method)
stack-pos)
(return-from interesting-frame-p
(values t stack-pos stack-pos method))))
(return))))
;; If we haven't already returned, use the default method.
(xcl::interesting-frame-p stack-pos interp-flag))))
(setq il:*short-backtrace-filter* 'interesting-frame-p)
;;; Support for undo
(defun undoable-setf-slot-value (object slot-name new-value)
(if (slot-boundp object slot-name)
(il:undosave (list 'undoable-setf-slot-value
object slot-name (slot-value object slot-name)))
(il:undosave (list 'slot-makunbound object slot-name)))
(setf (slot-value object slot-name) new-value))
(setf (get 'slot-value :undoable-setf-inverse) 'undoable-setf-slot-value)
;;; Support for ?= and friends
;; The arglists for generic-functions are built using gensyms, and don't reflect
;; any keywords (they are all included in an &REST arg). Rather then use the
;; arglist in the code, we use the one that CLOS kindly keeps in the generic-function.
(xcl:advise-function 'il:smartarglist
'(if (and il:explainflg
(symbolp il:fn)
(fboundp il:fn)
(generic-function-p (symbol-function il:fn)))
(generic-function-pretty-arglist (symbol-function il:fn))
(xcl:inner))
:when :around :priority :last)
(setf (get 'defclass 'il:argnames)
'(nil (class-name (#\{ superclass-name #\} #\*)
(#\{ slot-specifier #\} #\*)
#\{ slot-option #\} #\*)))
(setf (get 'defmethod 'il:argnames)
'(nil (#\{ name #\| (setf name) #\} #\{ method-qualifier #\} #\*
specialized-lambda-list #\{ declaration #\| doc-string #\} #\*
#\{ form #\} #\*)))
;;; Prettyprinting support, the result of Harley Davis.
;; Support the standard Prettyprinter. This is really minimal right now. If
;; anybody wants to fix this, I'd be happy to include their code. In fact,
;; there is almost no support for Commonlisp in the standard Prettyprinter, so
;; the field is wide open to hackers with time on their hands.
(setf (get 'defmethod :definition-print-template) ;Not quite right, since it
'(:name :arglist :body)) ; doesn't handle qualifiers,
; but it will have to do.
(defun defclass-prettyprint (form)
(let ((left (il:dspxposition))
(char-width (il:charwidth (il:charcode x) *standard-output*)))
(xcl:destructuring-bind (defclass name supers slots . options) form
(princ "(")
(prin1 defclass)
(princ " ")
(prin1 name)
(princ " ")
(if (null supers)
(princ "()") ;Print "()" instead of "nil"
(il:sequential.prettyprint (list supers) (il:dspxposition)))
(if (null slots)
(progn (il:prinendline (+ left (* 4 char-width)) *standard-output*)
(princ "()"))
(il:sequential.prettyprint (list slots) (+ left (* 4 char-width))))
(when options
(il:sequential.prettyprint options (+ left (* 2 char-width))))
(princ ")")
nil)))
(let ((pprint-macro (assoc 'defclass il:prettyprintmacros)))
(if (null pprint-macro)
(push (cons 'defclass 'defclass-prettyprint)
il:prettyprintmacros)
(setf (cdr pprint-macro) 'defclass-prettyprint)))
(defun binder-prettyprint (form)
;; Prettyprints expressions like MULTIPLE-VALUE-BIND and WITH-SLOTS
;; that are of the form (fn (var ...) form &rest body).
;; This code is far from correct, but it's better than nothing.
(if (and (consp form)
(not (null (cdddr form))))
;; I have no idea what I'm doing here. Seems I can copy and edit somebody
;; elses code without understanding it.
(let ((body-indent (+ (il:dspxposition)
(* 2 (il:charwidth (il:charcode x)
*standard-output*))))
(form-indent (+ (il:dspxposition)
(* 4 (il:charwidth (il:charcode x)
*standard-output*)))))
(princ "(")
(prin1 (first form))
(princ " ")
(il:superprint (second form) form nil *standard-output*)
(il:sequential.prettyprint (list (third form)) form-indent)
(il:sequential.prettyprint (cdddr form) body-indent)
(princ ")")
nil) ;Return NIL to indicate that we did
; the printing
t)) ;Return true to use default printing
(dolist (fn '(multiple-value-bind with-accessors with-slots))
(let ((pprint-macro (assoc fn 'il:prettyprintmacros)))
(if (null pprint-macro)
(push (cons fn 'binder-prettyprint)
il:prettyprintmacros)
(setf (cdr pprint-macro) 'binder-prettyprint))))
;; SEdit has its own prettyprinter, so we need to support that too. This is due
;; to <NAME>. Really.
(push (cons :slot-spec
'(((sedit::prev-keyword? (sedit::next-inline? 1 break sedit::from-indent . 1)
break sedit::from-indent . 0)
(sedit::set-indent . 1)
(sedit::next-inline? 1 break sedit::from-indent . 1)
(sedit::prev-keyword? (sedit::next-inline? 1 break sedit::from-indent . 1)
break sedit::from-indent . 0))
((sedit::prev-keyword? (sedit::next-inline? 1 break sedit::from-indent . 1)
break sedit::from-indent . 0)
(sedit::set-indent . 1)
(sedit::next-inline? 1 break sedit::from-indent . 1)
(sedit::prev-keyword? (sedit::next-inline? 1 break sedit::from-indent . 1)
break sedit::from-indent . 0))))
sedit:*indent-alist*)
(setf (sedit:get-format :slot-spec)
'(:indent :slot-spec :inline t))
(setf (sedit:get-format :slot-spec-list)
'(:indent :binding-list :args (:slot-spec) :inline nil))
(setf (sedit:get-format 'defclass)
'(:indent ((2) 1)
:args (:keyword nil nil :slot-spec-list nil)
:sublists (4)))
(setf (sedit:get-format 'defmethod)
'(:indent ((2))
:args (:keyword nil :lambda-list nil)
:sublists (3)))
(setf (sedit:get-format 'defgeneric) 'defun)
(setf (sedit:get-format 'generic-flet) 'flet)
(setf (sedit:get-format 'generic-labels) 'flet)
(setf (sedit:get-format 'call-next-method)
'(:indent (1) :args (:keyword nil)))
(setf (sedit:get-format 'symbol-macrolet) 'let)
(setf (sedit:get-format 'with-accessors)
'(:indent ((1) 1)
:args (:keyword :binding-list nil)
:sublists (2)
:miser :never))
(setf (sedit:get-format 'with-slots) 'with-accessors)
(setf (sedit:get-format 'make-instance)
'(:indent ((1))
:args (:keyword nil :slot-spec-list)))
(setf (sedit:get-format '*make-instance) 'make-instance)
;;; PrettyFileIndex stuff, the product of <NAME>ley Davis.
(defvar *pfi-class-type* '(class defclass pfi-class-namer))
(defvar *pfi-method-type* '(method defmethod pfi-method-namer)
"Handles method for prettyfileindex")
(defvar *pfi-index-accessors* nil
"t -> each slot accessor gets a listing in the index.")
(defvar *pfi-method-index* :group
":group, :separate, :both, or nil")
(defun pfi-add-class-type ()
(pushnew *pfi-class-type* il:*pfi-types*))
(defun pfi-add-method-type ()
(pushnew *pfi-method-type* il:*pfi-types*))
(defun pfi-class-namer (expression entry)
(let ((class-name (second expression)))
;; Following adds all slot readers/writers/accessors as separate entries in
;; the index. Probably a mistake.
(if *pfi-index-accessors*
(let ((slot-list (fourth expression))
(accessor-names nil))
(labels ((add-accessor (method-index name-index)
(push (case *pfi-method-index*
(:group method-index)
(:separate name-index)
((t :both) (list method-index name-index))
((nil) nil)
(otherwise (error "Illegal value for *pfi-method-index*: ~S"
*pfi-method-index*)))
accessor-names))
(add-reader (reader-name)
(add-accessor `(method (,reader-name (,class-name)))
`(,reader-name (,class-name))))
(add-writer (writer-name)
(add-accessor `(method ((setf ,writer-name) (t ,class-name)))
`((setf ,writer-name) (t ,class-name)))))
(dolist (slot-def slot-list)
(do* ((rest-slot-args (cdr slot-def) (cddr rest-slot-args))
(slot-arg (first rest-slot-args) (first rest-slot-args)))
((null rest-slot-args))
(case slot-arg
(:reader (add-reader (second rest-slot-args)))
(:writer (add-writer (second rest-slot-args)))
(:accessor (add-reader (second rest-slot-args))
(add-writer (second rest-slot-args)))
(otherwise nil))))
(cons `(class (,class-name)) accessor-names)))
class-name)))
(defun pfi-method-namer (expression entry)
(let ((method-name (second expression))
(specializers nil)
(qualifiers nil)
lambda-list)
(do* ((rest-qualifiers (cddr expression) (cdr rest-qualifiers))
(qualifier (first rest-qualifiers) (first rest-qualifiers)))
((listp qualifier) (setq lambda-list qualifier)
(setq qualifiers (reverse qualifiers)) qualifiers)
(push qualifier qualifiers))
(do* ((rest-lambda-list lambda-list (cdr rest-lambda-list))
(arg (first rest-lambda-list) (first rest-lambda-list)))
((or (member arg lambda-list-keywords) (null rest-lambda-list))
(setq specializers (reverse specializers)))
(push (if (listp arg) (second arg) t) specializers))
(let ((method-index `(method (,method-name ,@qualifiers ,specializers)))
(name-index `(,method-name ,@qualifiers ,specializers)))
(case *pfi-method-index*
(:group method-index)
(:separate name-index)
((t :both) (list method-index name-index))
((nil) nil)
(otherwise (error "Illegal value for *pfi-method-index*: ~S" *pfi-method-index*))))))
(defun pfi-install-clos ()
(pfi-add-method-type)
(pfi-add-class-type))
(eval-when (eval load)
(when (boundp (quote il:*pfi-types*))
(pfi-install-clos))
)
| true |
;;;-*-Mode:LISP; Package:(CLOS (LISP WALKER)); Base:10; Syntax:Common-lisp -*-
;;;
;;; *************************************************************************
;;; Copyright (c) 1991 PI:NAME:<NAME>END_PI
;;; All rights reserved.
;;; *************************************************************************
;;;
;;; Medley-Lisp specific environment hacking for CLOS
(in-package "CLOS")
;;
;; Protect the Corporation
;;
(eval-when (eval load)
(format *terminal-io*
"~&;CLOS-ENV Copyright (c) 1991 by ~
Venue Corporation. All rights reserved.~%"))
;;; Make funcallable instances (FINs) print by calling print-object.
(eval-when (eval load)
(il:defprint 'il:compiled-closure 'il:print-closure))
(defun il:print-closure (x &optional stream depth)
;; See the IRM, section 25.3.3. Unfortunatly, that documentation is
;; not correct. In particular, it makes no mention of the third argument.
(cond ((not (funcallable-instance-p x))
;; IL:\CCLOSURE.DEFPRINT is the orginal system function for
;; printing closures
(il:\\cclosure.defprint x stream))
((streamp stream)
;; Use the standard CLOS printing method, then return T to tell
;; the printer that we have done the printing ourselves.
(print-object x stream)
t)
(t
;; Internal printing (again, see the IRM section 25.3.3).
;; Return a list containing the string of characters that
;; would be printed, if the object were being printed for
;; real.
(with-output-to-string (stream)
(list (print-object x stream))))))
;;; Naming methods
(defun gf-named (gf-name)
(let ((spec (cond ((symbolp gf-name) gf-name)
((and (consp gf-name)
(eq (first gf-name) 'setf)
(symbolp (second gf-name))
(null (cddr gf-name)))
(get-setf-function-name (second gf-name)))
(t nil))))
(if (and (fboundp spec)
(generic-function-p (symbol-function spec)))
(symbol-function spec)
nil)))
(defun generic-function-method-names (gf-name hasdefp)
(if hasdefp
(let ((names nil))
(maphash #'(lambda (key value)
(declare (ignore value))
(when (and (consp key) (eql (car key) gf-name))
(pushnew key names)))
(gethash 'methods xcl:*definition-hash-table*))
names)
(let ((gf (gf-named gf-name)))
(when gf
(mapcar #'full-method-name (generic-function-methods gf))))))
(defun full-method-name (method)
"Return the full name of the method"
(let ((specializers (mapcar #'(lambda (x)
(cond ((eq x 't) t)
((and (consp x) (eq (car x) 'eql)) x)
(t (class-name x))))
(method-specializers method))))
;; Now go through some hair to make sure that specializer is
;; really right. Once CLOS returns the right value for
;; specializers this can be taken out.
(let* ((arglist (method-lambda-list method))
(number-required (or (position-if
#'(lambda (x) (member x lambda-list-keywords))
arglist)
(length arglist)))
(diff (- number-required (length specializers))))
(when (> diff 0)
(setq specializers (nconc (copy-list specializers)
(make-list diff :initial-element 't)))))
(make-full-method-name (generic-function-name
(method-generic-function method))
(method-qualifiers method)
specializers)))
(defun make-full-method-name (generic-function-name qualifiers arg-types)
"Return the full name of a method, given the generic-function name, the method
qualifiers, and the arg-types"
;; The name of the method is:
;; (<generic-function-name> <qualifier-1> ..
;; (<arg-specializer-1>..))
(labels ((remove-trailing-ts (l)
(if (null l)
nil
(let ((tail (remove-trailing-ts (cdr l))))
(if (null tail)
(if (eq (car l) 't)
nil
(list (car l)))
(if (eq l tail)
l
(cons (car l) tail)))))))
`(,generic-function-name ,@qualifiers
,(remove-trailing-ts arg-types))))
(defun parse-full-method-name (method-name)
"Parse the method name, returning the gf-name, the qualifiers, and the
arg-types."
(values (first method-name)
(butlast (rest method-name))
(car (last method-name))))
(defun prompt-for-full-method-name (gf-name &optional has-def-p)
"Prompt the user for the full name of a method on the given generic function name"
(let ((method-names (generic-function-method-names gf-name has-def-p)))
(cond ((null method-names)
nil)
((null (cdr method-names))
(car method-names))
(t (il:menu
(il:create
il:menu il:items il:_ ;If HAS-DEF-P, include only
; those methods that have a
; symbolic def'n that we can
; find
(remove-if #'null
(mapcar #'(lambda (m)
(if (or (not has-def-p)
(il:hasdef m 'methods))
`(,(with-output-to-string (s)
(dolist (x m)
(format s "~A " x))
s)
',m)
nil))
method-names))
il:title il:_ "Which method?"))))))
;;; Converting generic defining macros into DEFDEFINER macros
(defmacro make-defdefiner (definer-name definer-type type-description &body
definer-options)
"Make the DEFINER-NAME use DEFDEFINER, defining items of type DEFINER-TYPE"
(let ((old-definer-macro-name (intern (string-append definer-name
" old definition")
(symbol-package definer-name)))
(old-definer-macro-expander (intern (string-append definer-name
" old expander")
(symbol-package definer-name))))
`(progn
;; First, move the current defining function off to some safe
;; place
(unmake-defdefiner ',definer-name)
(cond ((not (fboundp ',definer-name))
(error "~A has no definition!" ',definer-name))
((fboundp ',old-definer-macro-name))
((macro-function ',definer-name)
; We have to move the macro
; expansion function as well,
; so it won't get clobbered
; when the original macro is
; redefined. See AR 7410.
(let* ((expansion-function (macro-function ',definer-name)))
(setf (symbol-function ',old-definer-macro-expander)
(loop (if (symbolp expansion-function)
(setq expansion-function
(symbol-function expansion-function))
(return expansion-function))))
(setf (macro-function ',old-definer-macro-name)
',old-definer-macro-expander)
(setf (get ',definer-name 'make-defdefiner) expansion-function)))
(t (error "~A does not name a macro." ',definer-name)))
;; Make sure the type is defined
(xcl:def-define-type ,definer-type ,type-description)
;; Now redefine the definer, using DEFEDFINER and the original def'n
(xcl:defdefiner ,(if definer-options
(cons definer-name definer-options)
definer-name)
,definer-type (&body b) `(,',old-definer-macro-name ,@,'b)))))
(defun unmake-defdefiner (definer-name)
(let ((old-expander (get definer-name 'make-defdefiner)))
(when old-expander
(setf (macro-function definer-name old-expander))
(remprop definer-name 'make-defdefiner))))
;;; For tricking ED into being able to use just the generic-function-name
;;; instead of the full method name
(defun source-manager-method-edit-fn (name type source editcoms options)
"Edit a method of the given name"
(let ((full-name (if (gf-named name)
;If given the name of a
; generic-function, try to get
; the full method name
(prompt-for-full-method-name name t)
; Otherwise it should name the
; method
name)))
(when (not (null full-name))
(il:default.editdef full-name type source editcoms options))
(or full-name name))) ;Return the name
(defun source-manager-method-hasdef-fn (name type &optional source)
"Is there a method defined with the given name?"
(cond ((not (eq type 'methods)) nil)
((or (symbolp name)
(and (consp name)
(eq (first name) 'setf)
(symbolp (second name))
(null (cddr name))))
;; If passed in the name of a generic-function, pretend that
;; there is a method by that name if there is a generic function
;; by that name, and there is a method whose source we can find.
(if (and (not (null (gf-named name)))
(find-if #'(lambda (m)
(il:hasdef m type source))
(generic-function-method-names name t)))
name
nil))
((and (consp name) (>= (length name) 2))
;; Standard methods are named (gf-name {qualifiers}* ({specializers}*))
(when (il:getdef name type source '(il:nocopy il:noerror))
name))
(t
;; Nothing else can name a method
nil)))
;;; Initialize the CLOS env
(defun initialize-clos-env nil
"Initialize the Medley CLOS environment"
;; Set up SourceManager DEFDEFINERS for classes and methods.
;;
;; Make sure to define methods before classes, so that (IL:FILES?) will build
;; filecoms that have classes before methods.
(unless (il:hasdef 'methods 'il:filepkgtype)
(make-defdefiner defmethod methods "methods"
(:name (lambda (form)
(multiple-value-bind (name qualifiers arglist)
(parse-defmethod (cdr form))
(make-full-method-name name qualifiers
(specialized-lambda-list-specializers
arglist)))))
(:undefiner
(lambda (method-name)
(multiple-value-bind
(name qualifiers arg-types)
(parse-full-method-name method-name)
(let* ((gf (gf-named name))
(method (when gf
(get-method gf qualifiers
(mapcar #'find-class
arg-types)))))
(when method (remove-method gf method))))))))
;; Include support for DEFGENERIC, if that is defined
(unless (or (not (fboundp 'defgeneric))
(il:hasdef 'generic-functions 'il:filepkgtype))
(make-defdefiner defgeneric generic-functions "generic-function definitions"))
;; DEFCLASS FileManager stuff
(unless (il:hasdef 'classes 'il:filepkgtype)
(make-defdefiner defclass classes "class definitions"
(:undefiner (lambda (name)
(when (find-class name t)
(setf (find-class name) nil)))))
;; CLASSES "include" TYPES.
(il:filepkgcom 'classes 'il:contents
#'(lambda (com name type &optional reason)
(declare (ignore name reason))
(if (member type '(il:types classes) :test #'eq)
(cdr com)
nil))))
;; Set up the hooks so that ED can be handed the name of a generic function,
;; and end up editing a method instead
(il:filepkgtype 'methods 'il:editdef 'source-manager-method-edit-fn
'il:hasdef 'source-manager-method-hasdef-fn)
;; Set up the inspect macro. The right way to do this is to
;; (ENSURE-GENERIC-FUNCTION 'IL:INSPECT...), but for now...
(push '((il:function clos-object-p) . \\internal-inspect-object)
il:inspectmacros)
;; Unmark any SourceManager changes caused by this loadup
(dolist (com (il:filepkgchanges))
(dolist (name (cdr com))
(when (and (symbolp name)
(eq (symbol-package name) (find-package "CLOS")))
(il:unmarkaschanged name (car com))))))
(eval-when (eval load)
(initialize-clos-env))
;;; Inspecting CLOS objects
(defun clos-object-p (x)
"Is the datum a CLOS object?"
(or (std-instance-p x)
(fsc-instance-p x)))
(defun \\internal-inspect-object (x type where)
(inspect-object x type where))
(defun \\internal-inspect-slot-names (x)
(inspect-slot-names x))
(defun \\internal-inspect-slot-value (x slot-name)
(inspect-slot-value x slot-name))
(defun \\internal-inspect-setf-slot-value (x slot-name value)
(inspect-setf-slot-value x slot-name value))
(defun \\internal-inspect-slot-name-command (slot-name x window)
(inspect-slot-name-command slot-name x window))
(defun \\internal-inspect-title (x y)
(inspect-title x y))
(defmethod inspect-object (x type where)
"Open an insect window on the object x"
(il:inspectw.create x '\\internal-inspect-slot-names
'\\internal-inspect-slot-value
'\\internal-inspect-setf-slot-value
'\\internal-inspect-slot-name-command nil nil
'\\internal-inspect-title nil where
#'(lambda (n v) ;Same effect as NIL, but avoids bug in
(declare (ignore v)) ; INSPECTW.CREATE
n)))
(defmethod inspect-slot-names (x)
"Return a list of names of slots of the object that should be shown in the
inspector"
(mapcar #'(lambda (slotd) (slot-value slotd 'name))
(slots-to-inspect (class-of x) x)))
(defmethod inspect-slot-value (x slot-name)
(cond ((not (slot-exists-p x slot-name)) "** no such slot **")
((not (slot-boundp x slot-name)) "** slot not bound **")
(t (slot-value x slot-name))))
(defmethod inspect-setf-slot-value (x slot-name value)
"Used by the inspector to set the value fo a slot"
;; Make this UNDO-able
(il:undosave `(inspect-setf-slot-value ,x ,slot-name
,(slot-value x slot-name)))
;; Then change the value
(setf (slot-value x slot-name) value))
(defmethod inspect-slot-name-command (slot-name x window)
"Allows the user to select a menu item to change a slot value in an inspect
window"
;; This code is a very slightly hacked version of the system function
;; DEFAULT.INSPECTW.PROPCOMMANDFN. We have to do this because the
;; standard version makes some nasty assumptions about
;; structure-objects that are not true for CLOS objects.
(declare (special il:|SetPropertyMenu|))
(case (il:menu (cond ((typep il:|SetPropertyMenu| 'il:menu)
il:|SetPropertyMenu|)
(t (il:setq il:|SetPropertyMenu|
(il:|create| il:menu il:items il:_
'((set 'set
"Allows a new value to be entered"
)))))))
(set
;; The user want to set the value
(il:ersetq (prog ((il:oldvalueitem (il:itemofpropertyvalue slot-name
window))
il:newvalue il:pwindow)
(il:ttydisplaystream (il:setq il:pwindow
(il:getpromptwindow window 3)))
(il:clearbuf t t)
(il:resetlst
(il:resetsave (il:\\itemw.flipitem il:oldvalueitem window)
(list 'il:\\itemw.flipitem
il:oldvalueitem window))
(il:resetsave (il:tty.process (il:this.process)))
(il:resetsave (il:printlevel 4 3))
(il:|printout| t "Enter the new "
slot-name " for " x t
"The expression read will be EVALuated."
t "> ")
(il:setq il:newvalue (il:lispx (il:lispxread t t)
'>))
; clear tty buffer because it
; sometimes has stuff left.
(il:clearbuf t t))
(il:closew il:pwindow)
(return (il:inspectw.replace window slot-name il:newvalue)))))))
(defmethod inspect-title (x window)
"Return the title to use in an inspect window viewing x"
(format nil "Inspecting a ~A" (class-name (class-of x))))
(defmethod inspect-title ((x standard-class) window)
(format nil "Inspecting the class ~A" (class-name x)))
;;; Debugger support for CLOS
(il:filesload clos-env-internal)
;; Non-CLOS specific changes to the debugger
;; Redefining the standard INTERESTING-FRAME-P function. Now functions can be
;; declared uninteresting to BT by giving them an XCL::UNINTERESTINGP
;; property.
(dolist (fn '(si::*unwind-protect* il:*env*
evalhook xcl::nohook xcl::undohook
xcl::execa0001 xcl::execa0001a0002
xcl::|interpret-UNDOABLY|
cl::|interpret-IF| cl::|interpret-FLET|
cl::|interpret-LET| cl::|interpret-LETA0001|
cl::|interpret-BLOCK| cl::|interpret-BLOCKA0001|
il:do-event il:eval-input
apply t))
(setf (get fn 'xcl::uninterestingp) t))
(defun xcl::interesting-frame-p (xcl::pos &optional xcl::interpflg)
"Return TRUE iff the frame should be visible for a short backtrace."
(declare (special il:openfns))
(let ((xcl::name (if (il:stackp xcl::pos) (il:stkname xcl::pos) xcl::pos)))
(typecase xcl::name
(symbol (case xcl::name
(il:*env*
;; *ENV* is used by ENVEVAL etc.
nil)
(il:errorset
(or (<= (il:stknargs xcl::pos) 1)
(not (eq (il:stkarg 2 xcl::pos nil)
'il:internal))))
(il:eval
(or (<= (il:stknargs xcl::pos) 1)
(not (eq (il:stkarg 2 xcl::pos nil)
'xcl::internal))))
(il:apply
(or (<= (il:stknargs xcl::pos) 2)
(not (il:stkarg 3 xcl::pos nil))))
(otherwise
(cond ((get xcl::name 'xcl::uninterestingp)
;; Explicitly declared uninteresting.
nil)
((eq (il:chcon1 xcl::name) (char-code #\\))
;; Implicitly declared uninteresting by starting the
;; name with a "\".
nil)
((or (member xcl::name il:openfns :test #'eq)
(eq xcl::name 'funcall))
;;The function won't be seen when compiled, so only show
;;it if INTERPFLG it true
xcl::interpflg)
(t
;; Interesting by default.
t)))))
(cons (case (car xcl::name)
(:broken t)
(otherwise nil)))
(otherwise nil))))
(setq il:*short-backtrace-filter* 'xcl::interesting-frame-p)
(eval-when (eval compile)
(il:record il:bkmenuitem (il:label (il:bkmenuinfo il:frame-name))))
;; Change the frame inspector to open up lexical environments
;; Since the DEFSTRUCT is going to build the accessors in the package that is
;; current at read-time, and we want the accessors to reside in the IL
;; package, we have got to make sure that the defstruct happens when the
;; package is IL.
(in-package "IL")
(cl:defstruct (frame-prop-name (:type cl:list))
(label-fn 'nill)
(value-fn
(function
(lambda (prop-name framespec)
(frame-prop-name-data prop-name))))
(setf-fn 'nill)
(inspect-fn
(function
(lambda (value prop-name framespec window)
(default.inspectw.valuecommandfn value prop-name (car framespec) window))))
(data nil))
(cl:in-package "CLOS")
(defun il:debugger-stack-frame-prop-names (il:framespec)
;; Frame prop-names are structures of the form
;; (LABEL-FN VALUE-FN SETF-FN EDIT-FN DATA)
(let ((il:pos (car il:framespec))
(il:backtrace-item (cadr il:framespec)))
(il:if (eq 'eval (il:stkname il:pos))
il:then
(let ((il:expression (il:stkarg 1 il:pos))
(il:environment (il:stkarg 2 il:pos)))
`(,(il:make-frame-prop-name :inspect-fn
(il:function
(il:lambda (il:value il:prop-name il:framespec il:window)
(il:inspect/as/function il:value (car il:framespec) il:window)))
:data il:expression)
,(il:make-frame-prop-name :data "ENVIRONMENT")
,@(il:for il:aspect il:in
`((,(and il:environment (il:environment-vars il:environment))
"vars")
(,(and il:environment (il:environment-functions il:environment))
"functions")
(,(and il:environment (il:environment-blocks il:environment))
"blocks")
(,(and il:environment (il:environment-tagbodies il:environment))
"tag bodies"))
il:bind il:group-name il:p-list
il:eachtime (il:setq il:group-name (cadr il:aspect))
(il:setq il:p-list (car il:aspect))
il:when (not (null il:p-list))
il:join
`(,(il:make-frame-prop-name :data il:group-name)
,@(il:for il:p il:on il:p-list il:by cddr il:collect
(il:make-frame-prop-name :label-fn
(il:function (il:lambda (il:prop-name il:framespec)
(car (il:frame-prop-name-data il:prop-name))))
:value-fn
(il:function (il:lambda (il:prop-name il:framespec)
(cadr (il:frame-prop-name-data il:prop-name))))
:setf-fn
(il:function (il:lambda (il:prop-name il:framespec il:new-value)
(il:change (cadr (il:frame-prop-name-data
il:prop-name))
il:new-value)))
:data il:p))))))
il:else
(flet ((il:build-name (&key il:arg-name il:arg-number)
(il:make-frame-prop-name :label-fn
(il:function (il:lambda (il:prop-name il:framespec)
(car (il:frame-prop-name-data il:prop-name))))
:value-fn
(il:function (il:lambda (il:prop-name il:framespec)
(il:stkarg (cadr (il:frame-prop-name-data
il:prop-name))
(car il:framespec))))
:setf-fn
(il:function (il:lambda (il:prop-name il:framespec il:new-value)
(il:setstkarg (cadr (il:frame-prop-name-data
il:prop-name))
(car il:framespec)
il:new-value)))
:data
(list il:arg-name il:arg-number))))
(let ((il:nargs (il:stknargs il:pos t))
(il:nargs1 (il:stknargs il:pos))
(il:fnname (il:stkname il:pos))
il:argname
(il:arglist))
(and (il:litatom il:fnname)
(il:ccodep il:fnname)
(il:setq il:arglist (il:listp (il:smartarglist il:fnname))))
`(,(il:make-frame-prop-name :inspect-fn
(il:function (il:lambda (il:value il:prop-name il:framespec
il:window)
(il:inspect/as/function il:value
(car il:framespec)
il:window)))
:data
(il:fetch (il:bkmenuitem il:frame-name) il:of il:backtrace-item))
,@(il:bind il:mode il:for il:i il:from 1 il:to il:nargs1 il:collect
(progn (il:while (il:fmemb (il:setq il:argname (il:pop il:arglist))
lambda-list-keywords)
il:do
(il:setq il:mode il:argname))
(il:build-name :arg-name
(or (il:stkargname il:i il:pos)
; special
(if (case il:mode
((nil &optional) il:argname)
(t nil))
(string il:argname)
(il:concat "arg " (- il:i 1))))
:arg-number il:i)))
,@(let* ((il:novalue "No value")
(il:slots (il:for il:pvar il:from 0 il:as il:i il:from
(il:add1 il:nargs1)
il:to il:nargs il:by 1 il:when
(and (il:neq il:novalue (il:stkarg il:i il:pos
il:novalue))
(or (il:setq il:argname (il:stkargname
il:i il:pos))
(il:setq il:argname (il:concat
"local "
il:pvar)))
)
il:collect
(il:build-name :arg-name il:argname
:arg-number il:i))))
(and il:slots (cons (il:make-frame-prop-name :data "locals")
il:slots)))))))))
(defun il:debugger-stack-frame-fetchfn (il:framespec il:prop-name)
(il:apply* (il:frame-prop-name-value-fn il:prop-name)
il:prop-name il:framespec))
(defun il:debugger-stack-frame-storefn (il:framespec il:prop-name il:newvalue)
(il:apply* (il:frame-prop-name-setf-fn il:prop-name)
il:prop-name il:framespec il:newvalue))
(defun il:debugger-stack-frame-value-command (il:datum il:prop-name
il:framespec il:window)
(il:apply* (il:frame-prop-name-inspect-fn il:prop-name)
il:datum il:prop-name il:framespec il:window))
(defun il:debugger-stack-frame-title (il:framespec &optional il:window)
(declare (ignore il:window))
(il:concat (il:stkname (car il:framespec)) " Frame"))
(defun il:debugger-stack-frame-property (il:prop-name il:framespec)
(il:apply* (il:frame-prop-name-label-fn il:prop-name)
il:prop-name il:framespec))
;; Teaching the debugger that there are other file-manager types that can
;; appear on the stack
(defvar xcl::*function-types* '(il:fns il:functions)
"Manager types that can appear on the stack")
;; Redefine a couple of system functions to use the above stuff
#+Xerox-Lyric
(progn
(defun il:attach-backtrace-menu (&optional (il:ttywindow
(il:wfromds (il:ttydisplaystream)))
il:skip)
(let ((il:bkmenu (il:|create| il:menu
il:items il:_
(il:collect-backtrace-items il:ttywindow il:skip)
il:whenselectedfn il:_
(il:function il:backtrace-item-selected)
il:whenheldfn il:_
#'(il:lambda (il:item il:menu il:button)
(declare (ignore il:item il:menu))
(case il:button
(il:left (il:promptprint
"Open a frame inspector on this stack frame"
))
(il:middle (il:promptprint
"Inspect/Edit this function"))
))
il:menuoutlinesize il:_ 0
il:menufont il:_ il:backtracefont
il:menucolumns il:_ 1))
(il:ttyregion (il:windowprop il:ttywindow 'il:region))
il:btw)
(cond
((il:setq il:btw (il:|for| il:atw il:|in| (il:attachedwindows il:ttywindow)
il:|when| (and (il:setq il:btw (il:windowprop il:atw 'il:menu))
(eql (il:|fetch| (il:menu il:whenselectedfn)
il:|of| (car il:btw))
(il:function il:backtrace-item-selected)))
il:|do|
(return il:atw)))
(il:deletemenu (car (il:windowprop il:btw 'il:menu))
nil il:btw)
(il:windowprop il:btw 'il:extent nil)
(il:clearw il:btw))
((il:setq il:btw (il:createw (il:region-next-to (il:windowprop il:ttywindow 'il:region)
(il:widthifwindow (il:imin (il:|fetch| (il:menu
il:imagewidth
)
il:|of| il:bkmenu)
il:|MaxBkMenuWidth|))
(il:|fetch| (il:region il:height) il:|of| il:ttyregion
)
'il:left)))
(il:attachwindow il:btw il:ttywindow (cond
((il:igreaterp (il:|fetch| (il:region il:left)
il:|of| (il:windowprop
il:btw
'il:region))
(il:|fetch| (il:region il:left)
il:|of| il:ttyregion))
'il:right)
(t 'il:left))
nil
'il:localclose)
(il:windowprop il:btw 'il:process (il:windowprop il:ttywindow 'il:process))
))
(il:addmenu il:bkmenu il:btw (il:|create| il:_ il:position
il:xcoord il:_ 0
il:ycoord il:_ (il:idifference (il:windowprop
il:btw
'il:height)
(il:|fetch| (il:menu il:imageheight
) il:|of|
il:bkmenu
))))))
(defun il:backtrace-item-selected (il:item il:menu il:button)
(il:resetlst
(prog (il:olditem il:ttywindow il:bkpos il:pos il:positions il:framewindow
(il:framespecn (il:|fetch| (il:bkmenuitem il:bkmenuinfo) il:|of| il:item)
))
(cond
((il:setq il:olditem (il:|fetch| (il:menu il:menuuserdata) il:|of| il:menu))
(il:menudeselect il:olditem il:menu)
))
(il:setq il:ttywindow (il:windowprop (il:wfrommenu il:menu)
'il:mainwindow))
(il:setq il:bkpos (il:windowprop il:ttywindow 'il:stack-position))
(il:setq il:pos (il:stknth (- il:framespecn)
il:bkpos))
(let ((il:lp (il:windowprop il:ttywindow 'il:lastpos)))
(and il:lp (il:stknth 0 il:pos il:lp)))
(il:menuselect il:item il:menu)
(if (eq il:button 'il:middle)
(progn
(il:resetsave nil (list 'il:relstk il:pos))
(il:inspect/as/function (il:|fetch| (il:bkmenuitem il:frame-name)
il:|of| il:item)
il:pos il:ttywindow))
(progn
(il:setq il:framewindow
(xcl:with-profile (il:process.eval
(il:windowprop il:ttywindow 'il:process)
'(let ((il:profile (xcl:copy-profile (xcl:find-profile
"READ-PRINT"))))
(setf (xcl::profile-entry-value '
xcl:*eval-function* il:profile)
xcl:*eval-function*)
(xcl:save-profile il:profile))
t)
(il:inspectw.create (list il:pos il:item)
'il:debugger-stack-frame-prop-names
'il:debugger-stack-frame-fetchfn
'il:debugger-stack-frame-storefn nil '
il:debugger-stack-frame-value-command nil '
il:debugger-stack-frame-title nil (
il:make-frame-inspect-window
il:ttywindow)
'il:debugger-stack-frame-property)))
(cond
((not (il:windowprop il:framewindow 'il:mainwindow))
(il:attachwindow il:framewindow il:ttywindow
(cond
((il:igreaterp (il:|fetch| (il:region il:bottom)
il:|of| (il:windowprop il:framewindow
'il:region))
(il:|fetch| (il:region il:bottom)
il:|of| (il:windowprop il:ttywindow 'il:region)))
'il:top)
(t 'il:bottom))
nil
'il:localclose)
(il:windowaddprop il:framewindow 'il:closefn (il:function il:detachwindow
))))))
(return))))
(defun il:collect-backtrace-items (xcl::tty-window xcl::skip)
(let* ((xcl::items (cons nil nil))
(xcl::items-tail xcl::items))
(macrolet ((xcl::collect-item (xcl::new-item)
`(progn (setf (rest xcl::items-tail)
(cons ,xcl::new-item nil))
(pop xcl::items-tail))))
(let* ((xcl::filter-fn (cond
((null xcl::skip)
#'xcl:true)
((eq xcl::skip t)
il:*short-backtrace-filter*)
(t xcl::skip)))
(xcl::top-frame (il:stknth 0 (il:getwindowprop xcl::tty-window '
il:stack-position)))
(xcl::next-frame xcl::top-frame)
(xcl::frame-number 0)
xcl::interesting-p xcl::last-frame-consumed xcl::use-frame xcl::label)
(loop (when (null xcl::next-frame)
(return))
(multiple-value-setq (xcl::interesting-p xcl::last-frame-consumed
xcl::use-frame xcl::label)
(funcall xcl::filter-fn xcl::next-frame))
(when (null xcl::last-frame-consumed)
(setf xcl::last-frame-consumed xcl::next-frame))
(when xcl::interesting-p
(when (null xcl::use-frame)
(setf xcl::use-frame xcl::last-frame-consumed))
(when (null xcl::label)
(setf xcl::label (il:stkname xcl::use-frame))
(if (member xcl::label '(eval il:eval il:apply apply)
:test
'eq)
(setf xcl::label (il:stkarg 1 xcl::use-frame))))
(loop (cond
((not (typep xcl::next-frame 'il:stackp))
(error "~%Use-frame ~S not found" xcl::use-frame))
((xcl::stack-eql xcl::next-frame xcl::use-frame)
(return))
(t (incf xcl::frame-number)
(setf xcl::next-frame (il:stknth -1 xcl::next-frame
xcl::next-frame)))))
(xcl::collect-item (il:|create| il:bkmenuitem
il:label il:_ (let ((*print-level* 2)
(*print-length* 3)
(*print-escape* t)
(*print-gensym* t)
(*print-pretty* nil)
(*print-circle* nil)
(*print-radix* 10)
(*print-array* nil)
(il:*print-structure*
nil))
(prin1-to-string
xcl::label))
il:bkmenuinfo il:_ xcl::frame-number
il:frame-name il:_ xcl::label)))
(loop (cond
((not (typep xcl::next-frame 'il:stackp))
(error "~%Last-frame-consumed ~S not found"
xcl::last-frame-consumed))
((prog1 (xcl::stack-eql xcl::next-frame xcl::last-frame-consumed
)
(incf xcl::frame-number)
(setf xcl::next-frame (il:stknth -1 xcl::next-frame
xcl::next-frame)))
(return)))))))
(rest xcl::items)))
)
#+Xerox-Medley
(progn
(defun dbg::attach-backtrace-menu (&optional tty-window skip)
(declare (special il:\\term.ofd il:backtracefont))
(or tty-window (il:setq tty-window (il:wfromds (il:ttydisplaystream))))
(prog (btw bkmenu
(tty-region (il:windowprop tty-window 'il:region))
;; And, for the FORMAT below...
(*print-level* 2)
(*print-length* 3)
(*print-escape* t)
(*print-gensym* t)
(*print-pretty* nil)
(*print-circle* nil)
(*print-radix* 10)
(*print-array* nil)
(il:*print-structure* nil))
(setq bkmenu
(il:|create| il:menu
il:items il:_ (dbg::collect-backtrace-items tty-window skip)
il:whenselectedfn il:_ 'dbg::backtrace-item-selected
il:menuoutlinesize il:_ 0
il:menufont il:_ il:backtracefont
il:menucolumns il:_ 1
il:whenheldfn il:_
#'(il:lambda (item menu button)
(declare (ignore item menu))
(case button
(il:left
(il:promptprint
"Open a frame inspector on this stack frame"))
(il:middle
(il:promptprint "Inspect/Edit this function"))))))
(cond ((setq btw
(dolist (atw (il:attachedwindows tty-window))
;; Test for an attached window that has a backtrace menu in
;; it.
(when (and (setq btw (il:windowprop atw 'il:menu))
(eq (il:|fetch| (il:menu il:whenselectedfn)
il:|of| (car btw))
'dbg::backtrace-item-selected))
(return atw))))
;; If there is alread a backtrace window, delete the old menu from
;; it.
(il:deletemenu (car (il:windowprop btw 'il:menu)) nil btw)
(il:windowprop btw 'il:extent nil)
(il:clearw btw))
((setq btw
(il:createw (dbg::region-next-to
(il:windowprop tty-window 'il:region)
(il:widthifwindow
(il:imin (il:|fetch| (il:menu il:imagewidth)
il:|of| bkmenu)
il:|MaxBkMenuWidth|))
(il:|fetch| (il:region il:height)
il:|of| tty-region)
:left)))
; put bt window at left of TTY
; window unless ttywindow is
; near left edge.
(il:attachwindow btw tty-window
(if (il:igreaterp (il:|fetch| (il:region il:left)
il:|of|
(il:windowprop btw
'il:region))
(il:|fetch| (il:region il:left)
il:|of| tty-region))
'il:right
'il:left)
nil
'il:localclose)
;; So that button clicks will switch the TTY
(il:windowprop btw 'il:process
(il:windowprop tty-window 'il:process))))
(il:addmenu bkmenu btw (il:|create| il:position
il:xcoord il:_ 0
il:ycoord il:_ (- (il:windowprop btw 'il:height)
(il:|fetch| (il:menu
il:imageheight)
il:|of| bkmenu))))
;; IL:ADDMENU sets up buttoneventfn for window that we don't
;; want. We want to catch middle button events before the menu
;; handler, so that we can pop up edit/inspect menu for the frame
;; currently selected. So replace the buttoneventfn, and can
;; nuke the cursorin and cursormoved guys, cause don't need them.
(il:windowprop btw 'il:buttoneventfn 'dbg::backtrace-menu-buttoneventfn)
(il:windowprop btw 'il:cursorinfn nil)
(il:windowprop btw 'il:cursormovedfn nil)))
(defun dbg::collect-backtrace-items (tty-window skip)
(xcl:with-collection
;;
;; There are a number of possibilities for the values returned by the
;; filter-fn.
;;
;; (1) INTERESTING-P is false, and the other values are all NIL. This
;; is the simple case where the stack frame NEXT-POS should be ignored
;; completly, and processing should continue with the next frame.
;;
;; (2) INTERESTING-P is true, and the other values are all NIL. This
;; is the simple case where the stack frame NEXT-POS should appear in
;; the backtrace as is, and processing should continue with the next
;; frame.
;;
;; [Note that these two cases take care of old values of the
;; filter-fn.]
;;
;; (3) INTERESTING-P is false, and LAST-FRAME-CONSUMED is a stack
;; frame. In that case, ignore all stack frames from NEXT-POS to
;; LAST-FRAME-CONSUMED, inclusive.
;;
;; (4) INTERESTING-P is true, and LAST-FRAME-CONSUMED is a stack
;; frame. In this case, the backtrace should include a single entry
;; coresponding to the frame USE-FRAME (which defaults to
;; LAST-FRAME-CONSUMED), and processing should continue with the next
;; frame after LAST-FRAME-CONSUMED. If LABEL is non-NIL, it will be
;; the label that appears in the backtrace menu; otherwise the name of
;; USE-FRAME will be used (or the form being EVALed if the frame is an
;; EVAL frame).
;;
(let* ((filter (cond ((null skip) #'xcl:true)
((eq skip t) il:*short-backtrace-filter*)
(t skip)))
(top-frame (il:stknth 0 (il:getwindowprop tty-window
'dbg::stack-position)))
(next-frame top-frame)
(frame-number 0)
interestingp last-frame-consumed frame-to-use label-to-use)
(loop (when (null next-frame) (return))
;; Get the values of INTERSTINGP, LAST-FRAME-CONSUMED,
;; FRAME-TO-USE, and LABEL-TO-USE
(multiple-value-setq (interestingp last-frame-consumed
frame-to-use label-to-use)
(funcall filter next-frame))
(when (null last-frame-consumed)
(setf last-frame-consumed next-frame))
(when interestingp
(when (null frame-to-use)
(setf frame-to-use last-frame-consumed))
(when (null label-to-use)
(setf label-to-use (il:stkname frame-to-use))
(if (member label-to-use '(eval il:eval il:apply apply)
:test 'eq)
(setf label-to-use (il:stkarg 1 frame-to-use))))
;; Walk the stack until we find the frame to use
(loop (cond ((not (typep next-frame 'il:stackp))
(error "~%Use-frame ~S not found" frame-to-use))
((xcl::stack-eql next-frame frame-to-use)
(return))
(t (incf frame-number)
(setf next-frame
(il:stknth -1 next-frame next-frame)))))
;; Add the menu item to the list under construction
(xcl:collect (il:|create| il:bkmenuitem
il:label il:_ (let ((*print-level* 2)
(*print-length* 3)
(*print-escape* t)
(*print-gensym* t)
(*print-pretty* nil)
(*print-circle* nil)
(*print-radix* 10)
(*print-array* nil)
(il:*print-structure* nil))
(prin1-to-string label-to-use))
il:bkmenuinfo il:_ frame-number
il:frame-name il:_ label-to-use)))
;; Update NEXT-POS
(loop (cond ((not (typep next-frame 'il:stackp))
(error "~%Last-frame-consumed ~S not found"
last-frame-consumed))
((prog1
(xcl::stack-eql next-frame last-frame-consumed)
(incf frame-number)
(setf next-frame (il:stknth -1 next-frame
next-frame)))
(return))))))))
(defun dbg::backtrace-menu-buttoneventfn (window &aux menu)
(setq menu (car (il:listp (il:windowprop window 'il:menu))))
(unless (or (il:lastmousestate il:up) (null menu))
(il:totopw window)
(cond ((il:lastmousestate il:middle)
;; look for a selected frame in this menu, and then pop up
;; the editor invoke menu for that frame. don't change the
;; selection, just present the edit menu.
(let* ((selection (il:menu.handler menu
(il:windowprop window 'il:dsp)))
(tty-window (il:windowprop window 'il:mainwindow))
(last-pos (il:windowprop tty-window 'dbg::lastpos)))
;; don't have to worry about releasing POS because we
;; only look at it here (nobody here hangs on to it)
;; and we will be around for less time than LASTPOS.
;; The debugger is responsible for releasing LASTPOS.
(il:inspect/as/function (cond
((and selection
(il:|fetch| (il:bkmenuitem il:frame-name)
il:|of| (car selection))))
((and (symbolp (il:stkname last-pos))
(il:getd (il:stkname last-pos)))
(il:stkname last-pos))
(t 'il:nill))
last-pos tty-window)))
(t (let ((selection (il:menu.handler menu
(il:windowprop window 'il:dsp))))
(when selection
(il:doselecteditem menu (car selection) (cdr selection))))))))
;; This function isn't really redefined, but it needs to be recomiled since we
;; changed the def'n of the BKMENUITEM record.
(defun dbg::backtrace-item-selected (item menu button)
;;When a frame name is selected in the backtrace menu, this is the function
;;that gets called.
(declare (special il:brkenv) (ignore button))
(let* ((frame-spec (il:|fetch| (il:bkmenuitem il:bkmenuinfo) il:|of| item))
(tty-window (il:windowprop (il:wfrommenu menu) 'il:mainwindow))
(bkpos (il:windowprop tty-window 'dbg::stack-position))
(pos (il:stknth (- frame-spec) bkpos)))
(let ((lp (il:windowprop tty-window 'dbg::lastpos)))
(and lp (il:stknth 0 pos lp)))
;; change the item selected from OLDITEM to ITEM. Only do this on left
;; buttons now. Middle just pops up the edit menu, doesn't select. -woz
(let ((old-item (il:|fetch| (il:menu il:menuuserdata) il:|of| menu)))
(when old-item (il:menudeselect old-item menu))
(il:menuselect item menu))
;; Change the lexical environment so it is the one in effect as of this
;; frame.
(il:process.eval (il:windowprop tty-window (quote dbg::process))
`(setq il:brkenv ',(il:find-lexical-environment pos))
t)
(let ((frame-window (xcl:with-profile
(il:process.eval (il:windowprop tty-window
'il:process)
`(let ((profile (xcl:copy-profile
(xcl:find-profile
"READ-PRINT"))))
(setf
(xcl::profile-entry-value
'xcl:*eval-function* profile)
xcl:*eval-function*)
(xcl:save-profile profile))
t)
(il:inspectw.create pos
#'(lambda (pos)
(dbg::stack-frame-properties pos t))
'dbg::stack-frame-fetchfn
'dbg::stack-frame-storefn
nil
'dbg::stack-frame-value-command
nil
(format nil "~S Frame" (il:stkname pos))
nil (dbg::make-frame-inspect-window
tty-window)
'dbg::stack-frame-property))))
(when (not (il:windowprop frame-window 'il:mainwindow))
(il:attachwindow frame-window tty-window
(if (> (il:|fetch| (il:region il:bottom) il:|of|
(il:windowprop frame-window 'il:region))
(il:|fetch| (il:region il:bottom) il:|of|
(il:windowprop tty-window 'il:region)))
'il:top 'il:bottom)
nil 'il:localclose)
(il:windowaddprop frame-window 'il:closefn 'il:detachwindow)))))
) ;end of Xerox-Medley
(defun il:select.fns.editor (&optional function)
;; gives the user a menu choice of editors.
(il:menu (il:|create| il:menu
il:items il:_ (cond ((il:ccodep function)
'((il:|InspectCode| 'il:inspectcode
"Shows the compiled code.")
(il:|DisplayEdit| 'ed
"Edit it with the display editor")
(il:|TtyEdit| 'il:ef
"Edit it with the standard editor")))
((il:closure-p function)
'((il:|Inspect| 'inspect
"Inspect this object")))
(t '((il:|DisplayEdit| 'ed
"Edit it with the display editor")
(il:|TtyEdit| 'il:ef
"Edit it with the standard editor"))))
il:centerflg il:_ t)))
;;
;; CLOS specific extensions to the debugger
;; There are some new things that act as functions, and that we want to be
;; able to edit from a backtrace window
(pushnew 'methods xcl::*function-types*)
(eval-when (eval compile load)
(unless (generic-function-p (symbol-function 'il:inspect/as/function))
(make-specializable 'il:inspect/as/function)))
(defmethod il:inspect/as/function (name stack-pointer debugger-window)
;; Calls an editor on function NAME. STKP and WINDOW are the stack pointer
;; and window of the break in which this inspect command was called.
(declare (ignore debugger-window))
(let ((editor (il:select.fns.editor name)))
(case editor
((nil)
;; No editor chosen, so don't do anything
nil)
(il:inspectcode
;; Inspect the compiled code
(let ((frame (xcl::stack-pointer-frame stack-pointer)))
(if (and (il:stackp stack-pointer)
(xcl::stack-frame-valid-p frame))
(il:inspectcode (let ((code-base (xcl::stack-frame-fn-header frame)))
(cond ((eq (il:\\get-compiled-code-base name)
code-base)
name)
(t
;; Function executing in this frame is not
;; the one in the definition cell of its
;; name, so fetch the real code. Have to
;; pass a CCODEP
(il:make-compiled-closure code-base))))
nil nil nil (xcl::stack-frame-pc frame))
(il:inspectcode name))))
(ed
;; Use the standard editor.
;; This used to take care to apply the editor in the debugger
;; process, so forms evaluated in the editor happen in the
;; context of the break. But that doesn't count for much any
;; more, now that lexical variables are the way to go. Better to
;; use the LEX debugger command (thank you, PI:NAME:<NAME>END_PI) and
;; shift-select pieces of code from the editor into the debugger
;; window.
(ed name `(,@xcl::*function-types* :display)))
(otherwise (funcall editor name)))))
(defmethod il:inspect/as/function ((name standard-object) stkp window)
(when (il:menu (il:|create| il:menu
il:items il:_ '(("Inspect" t "Inspect this object"))))
(inspect name)))
(defmethod il:inspect/as/function ((x standard-method) stkp window)
(let* ((generic-function-name (slot-value (slot-value x 'generic-function)
'name))
(method-name (full-method-name x))
(editor (il:select.fns.editor method-name)))
(il:allow.button.events)
(case editor
(ed (ed method-name '(:display methods)))
(il:inspectcode (il:inspectcode (slot-value x 'function)))
((nil) nil)
(otherwise (funcall editor method-name)))))
;; A replacement for the vanilla IL:INTERESTING-FRAME-P so we can see methods
;; and generic-functions on the stack.
(defun interesting-frame-p (stack-pos &optional interp-flag)
;; Return up to four values: INTERESTING-P LAST-FRAME-CONSUMED USE-FRAME and
;; LABEL. See the function IL:COLLECT-BACKTRACE-ITEMS for a full description
;; of how these values are used.
(labels
((function-matches-frame-p (function frame)
"Is the function being called in this frame?"
(let* ((frame-name (il:stkname frame))
(code-being-run (cond
((typep frame-name 'il:closure)
frame-name)
((and (consp frame-name)
(eq 'il:\\interpreter
(xcl::stack-frame-name
(il:\\stackargptr frame))))
frame-name)
(t (xcl::stack-frame-fn-header
(il:\\stackargptr frame))))))
(or (eq function code-being-run)
(and (typep function 'il:compiled-closure)
(eq (xcl::compiled-closure-fnheader function)
code-being-run)))))
(generic-function-from-frame (frame)
"If this the frame of a generic function return the gf, otherwise
return NIL."
;; Generic functions are implemented as compiled closures. On the
;; stack, we only see the fnheader for the the closure. This could
;; be a discriminator code, or in the default method only case it
;; will be the actual method function. To tell if this is a generic
;; function frame, we have to check very carefully to see if the
;; right stuff is on the stack. Specifically, the closure's ccode,
;; and the first local variable has to be a ptrhunk big enough to be
;; a FIN environment, and fin-env-fin of that ptrhunk has to point
;; to a generic function whose ccode and environment match.
(let ((n-args (il:stknargs frame))
(env nil)
(gf nil))
(if (and ;; is there at least one local?
(> (il:stknargs frame t) n-args)
;; and does the local contain something that might be
;; the closure environment of a funcallable instance?
(setf env (il:stkarg (1+ n-args) frame))
;; and does the local contain something that might be
;; the closure environment of a funcallable instance?
(typep env *fin-env-type*)
(setf gf (fin-env-fin env))
;; whose fin-env-fin points to a generic function?
(generic-function-p gf)
;; whose environment is the same as env?
(eq (xcl::compiled-closure-env gf) env)
;; and whose code is the same as the code for this
;; frame?
(function-matches-frame-p gf frame))
gf
nil))))
(let ((frame-name (il:stkname stack-pos)))
;; See if there is a generic-function on the stack at this
;; location.
(let ((gf (generic-function-from-frame stack-pos)))
(when gf
(return-from interesting-frame-p (values t stack-pos stack-pos gf))))
;; See if this is an interpreted method. The method body is
;; wrapped in a (BLOCK <function-name> ...). We look for an
;; interpreted call to BLOCK whose block-name is the name of
;; generic-function.
(when (and (eq frame-name 'eval)
(consp (il:stkarg 1 stack-pos))
(eq (first (il:stkarg 1 stack-pos)) 'block)
(symbolp (second (il:stkarg 1 stack-pos)))
(fboundp (second (il:stkarg 1 stack-pos)))
(generic-function-p
(symbol-function (second (il:stkarg 1 stack-pos)))))
(let* ((form (il:stkarg 1 stack-pos))
(block-name (second form))
(generic-function (symbol-function block-name))
(methods (generic-function-methods (symbol-function block-name))))
;; If this is really a method being called from a
;; generic-function, the g-f should be no more than a
;; few(?) frames up the stack. Check for the method call
;; by looking for a call to APPLY, where the function
;; being applied is the code in one of the methods.
(do ((i 100 (1- i))
(previous-pos stack-pos current-pos)
(current-pos (il:stknth -1 stack-pos) (il:stknth -1 current-pos))
(found-method nil)
(method-pos))
((or (null current-pos) (<= i 0)) nil)
(cond ((equalp generic-function
(generic-function-from-frame current-pos))
(if found-method
(return-from interesting-frame-p
(values t previous-pos method-pos found-method))
(return)))
(found-method nil)
((eq (il:stkname current-pos) 'apply)
(dolist (method methods)
(when (eq (method-function method)
(il:stkarg 1 current-pos))
(setq method-pos current-pos)
(setq found-method method)
(return))))))))
;; Try to handle compiled methods
(when (and (symbolp frame-name)
(not (fboundp frame-name))
(eq (il:chcon1 frame-name)
(il:charcode il:\())
(or (string-equal "(method " (symbol-name frame-name)
:start2 0 :end2 13)
(string-equal "(method " (symbol-name frame-name)
:start2 0 :end2 12)
(string-equal "(method " (symbol-name frame-name)
:start2 0 :end2 8)))
;; Looks like a name that CLOS consed up. See if there is a
;; GF nearby up the stack. If there is, use it to help
;; determine which method we have.
(do ((i 30 (1- i))
(current-pos (il:stknth -1 stack-pos)
(il:stknth -1 current-pos))
(gf))
((or (null current-pos)
(<= i 0))
nil)
(setq gf (generic-function-from-frame current-pos))
(when gf
(dolist (method (generic-function-methods gf))
(when (function-matches-frame-p (method-function method)
stack-pos)
(return-from interesting-frame-p
(values t stack-pos stack-pos method))))
(return))))
;; If we haven't already returned, use the default method.
(xcl::interesting-frame-p stack-pos interp-flag))))
(setq il:*short-backtrace-filter* 'interesting-frame-p)
;;; Support for undo
(defun undoable-setf-slot-value (object slot-name new-value)
(if (slot-boundp object slot-name)
(il:undosave (list 'undoable-setf-slot-value
object slot-name (slot-value object slot-name)))
(il:undosave (list 'slot-makunbound object slot-name)))
(setf (slot-value object slot-name) new-value))
(setf (get 'slot-value :undoable-setf-inverse) 'undoable-setf-slot-value)
;;; Support for ?= and friends
;; The arglists for generic-functions are built using gensyms, and don't reflect
;; any keywords (they are all included in an &REST arg). Rather then use the
;; arglist in the code, we use the one that CLOS kindly keeps in the generic-function.
(xcl:advise-function 'il:smartarglist
'(if (and il:explainflg
(symbolp il:fn)
(fboundp il:fn)
(generic-function-p (symbol-function il:fn)))
(generic-function-pretty-arglist (symbol-function il:fn))
(xcl:inner))
:when :around :priority :last)
(setf (get 'defclass 'il:argnames)
'(nil (class-name (#\{ superclass-name #\} #\*)
(#\{ slot-specifier #\} #\*)
#\{ slot-option #\} #\*)))
(setf (get 'defmethod 'il:argnames)
'(nil (#\{ name #\| (setf name) #\} #\{ method-qualifier #\} #\*
specialized-lambda-list #\{ declaration #\| doc-string #\} #\*
#\{ form #\} #\*)))
;;; Prettyprinting support, the result of Harley Davis.
;; Support the standard Prettyprinter. This is really minimal right now. If
;; anybody wants to fix this, I'd be happy to include their code. In fact,
;; there is almost no support for Commonlisp in the standard Prettyprinter, so
;; the field is wide open to hackers with time on their hands.
(setf (get 'defmethod :definition-print-template) ;Not quite right, since it
'(:name :arglist :body)) ; doesn't handle qualifiers,
; but it will have to do.
(defun defclass-prettyprint (form)
(let ((left (il:dspxposition))
(char-width (il:charwidth (il:charcode x) *standard-output*)))
(xcl:destructuring-bind (defclass name supers slots . options) form
(princ "(")
(prin1 defclass)
(princ " ")
(prin1 name)
(princ " ")
(if (null supers)
(princ "()") ;Print "()" instead of "nil"
(il:sequential.prettyprint (list supers) (il:dspxposition)))
(if (null slots)
(progn (il:prinendline (+ left (* 4 char-width)) *standard-output*)
(princ "()"))
(il:sequential.prettyprint (list slots) (+ left (* 4 char-width))))
(when options
(il:sequential.prettyprint options (+ left (* 2 char-width))))
(princ ")")
nil)))
(let ((pprint-macro (assoc 'defclass il:prettyprintmacros)))
(if (null pprint-macro)
(push (cons 'defclass 'defclass-prettyprint)
il:prettyprintmacros)
(setf (cdr pprint-macro) 'defclass-prettyprint)))
(defun binder-prettyprint (form)
;; Prettyprints expressions like MULTIPLE-VALUE-BIND and WITH-SLOTS
;; that are of the form (fn (var ...) form &rest body).
;; This code is far from correct, but it's better than nothing.
(if (and (consp form)
(not (null (cdddr form))))
;; I have no idea what I'm doing here. Seems I can copy and edit somebody
;; elses code without understanding it.
(let ((body-indent (+ (il:dspxposition)
(* 2 (il:charwidth (il:charcode x)
*standard-output*))))
(form-indent (+ (il:dspxposition)
(* 4 (il:charwidth (il:charcode x)
*standard-output*)))))
(princ "(")
(prin1 (first form))
(princ " ")
(il:superprint (second form) form nil *standard-output*)
(il:sequential.prettyprint (list (third form)) form-indent)
(il:sequential.prettyprint (cdddr form) body-indent)
(princ ")")
nil) ;Return NIL to indicate that we did
; the printing
t)) ;Return true to use default printing
(dolist (fn '(multiple-value-bind with-accessors with-slots))
(let ((pprint-macro (assoc fn 'il:prettyprintmacros)))
(if (null pprint-macro)
(push (cons fn 'binder-prettyprint)
il:prettyprintmacros)
(setf (cdr pprint-macro) 'binder-prettyprint))))
;; SEdit has its own prettyprinter, so we need to support that too. This is due
;; to PI:NAME:<NAME>END_PI. Really.
(push (cons :slot-spec
'(((sedit::prev-keyword? (sedit::next-inline? 1 break sedit::from-indent . 1)
break sedit::from-indent . 0)
(sedit::set-indent . 1)
(sedit::next-inline? 1 break sedit::from-indent . 1)
(sedit::prev-keyword? (sedit::next-inline? 1 break sedit::from-indent . 1)
break sedit::from-indent . 0))
((sedit::prev-keyword? (sedit::next-inline? 1 break sedit::from-indent . 1)
break sedit::from-indent . 0)
(sedit::set-indent . 1)
(sedit::next-inline? 1 break sedit::from-indent . 1)
(sedit::prev-keyword? (sedit::next-inline? 1 break sedit::from-indent . 1)
break sedit::from-indent . 0))))
sedit:*indent-alist*)
(setf (sedit:get-format :slot-spec)
'(:indent :slot-spec :inline t))
(setf (sedit:get-format :slot-spec-list)
'(:indent :binding-list :args (:slot-spec) :inline nil))
(setf (sedit:get-format 'defclass)
'(:indent ((2) 1)
:args (:keyword nil nil :slot-spec-list nil)
:sublists (4)))
(setf (sedit:get-format 'defmethod)
'(:indent ((2))
:args (:keyword nil :lambda-list nil)
:sublists (3)))
(setf (sedit:get-format 'defgeneric) 'defun)
(setf (sedit:get-format 'generic-flet) 'flet)
(setf (sedit:get-format 'generic-labels) 'flet)
(setf (sedit:get-format 'call-next-method)
'(:indent (1) :args (:keyword nil)))
(setf (sedit:get-format 'symbol-macrolet) 'let)
(setf (sedit:get-format 'with-accessors)
'(:indent ((1) 1)
:args (:keyword :binding-list nil)
:sublists (2)
:miser :never))
(setf (sedit:get-format 'with-slots) 'with-accessors)
(setf (sedit:get-format 'make-instance)
'(:indent ((1))
:args (:keyword nil :slot-spec-list)))
(setf (sedit:get-format '*make-instance) 'make-instance)
;;; PrettyFileIndex stuff, the product of PI:NAME:<NAME>END_PIley Davis.
(defvar *pfi-class-type* '(class defclass pfi-class-namer))
(defvar *pfi-method-type* '(method defmethod pfi-method-namer)
"Handles method for prettyfileindex")
(defvar *pfi-index-accessors* nil
"t -> each slot accessor gets a listing in the index.")
(defvar *pfi-method-index* :group
":group, :separate, :both, or nil")
(defun pfi-add-class-type ()
(pushnew *pfi-class-type* il:*pfi-types*))
(defun pfi-add-method-type ()
(pushnew *pfi-method-type* il:*pfi-types*))
(defun pfi-class-namer (expression entry)
(let ((class-name (second expression)))
;; Following adds all slot readers/writers/accessors as separate entries in
;; the index. Probably a mistake.
(if *pfi-index-accessors*
(let ((slot-list (fourth expression))
(accessor-names nil))
(labels ((add-accessor (method-index name-index)
(push (case *pfi-method-index*
(:group method-index)
(:separate name-index)
((t :both) (list method-index name-index))
((nil) nil)
(otherwise (error "Illegal value for *pfi-method-index*: ~S"
*pfi-method-index*)))
accessor-names))
(add-reader (reader-name)
(add-accessor `(method (,reader-name (,class-name)))
`(,reader-name (,class-name))))
(add-writer (writer-name)
(add-accessor `(method ((setf ,writer-name) (t ,class-name)))
`((setf ,writer-name) (t ,class-name)))))
(dolist (slot-def slot-list)
(do* ((rest-slot-args (cdr slot-def) (cddr rest-slot-args))
(slot-arg (first rest-slot-args) (first rest-slot-args)))
((null rest-slot-args))
(case slot-arg
(:reader (add-reader (second rest-slot-args)))
(:writer (add-writer (second rest-slot-args)))
(:accessor (add-reader (second rest-slot-args))
(add-writer (second rest-slot-args)))
(otherwise nil))))
(cons `(class (,class-name)) accessor-names)))
class-name)))
(defun pfi-method-namer (expression entry)
(let ((method-name (second expression))
(specializers nil)
(qualifiers nil)
lambda-list)
(do* ((rest-qualifiers (cddr expression) (cdr rest-qualifiers))
(qualifier (first rest-qualifiers) (first rest-qualifiers)))
((listp qualifier) (setq lambda-list qualifier)
(setq qualifiers (reverse qualifiers)) qualifiers)
(push qualifier qualifiers))
(do* ((rest-lambda-list lambda-list (cdr rest-lambda-list))
(arg (first rest-lambda-list) (first rest-lambda-list)))
((or (member arg lambda-list-keywords) (null rest-lambda-list))
(setq specializers (reverse specializers)))
(push (if (listp arg) (second arg) t) specializers))
(let ((method-index `(method (,method-name ,@qualifiers ,specializers)))
(name-index `(,method-name ,@qualifiers ,specializers)))
(case *pfi-method-index*
(:group method-index)
(:separate name-index)
((t :both) (list method-index name-index))
((nil) nil)
(otherwise (error "Illegal value for *pfi-method-index*: ~S" *pfi-method-index*))))))
(defun pfi-install-clos ()
(pfi-add-method-type)
(pfi-add-class-type))
(eval-when (eval load)
(when (boundp (quote il:*pfi-types*))
(pfi-install-clos))
)
|
[
{
"context": "; DEALINGS IN THE SOFTWARE.\n;\n; Original author: Jared Davis <[email protected]>\n\n(in-package \"SET\")\n(includ",
"end": 1345,
"score": 0.9997488260269165,
"start": 1334,
"tag": "NAME",
"value": "Jared Davis"
},
{
"context": "N THE SOFTWARE.\n;\n; Original author: Jared Davis <[email protected]>\n\n(in-package \"SET\")\n(include-book \"delete\")\n(set",
"end": 1366,
"score": 0.999934732913971,
"start": 1347,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/std/osets/cardinality.lisp
|
mayankmanj/acl2
| 305 |
; Fully Ordered Finite Sets
; Copyright (C) 2003-2012 Kookamara LLC
;
; Contact:
;
; Kookamara LLC
; 11410 Windermere Meadows
; Austin, TX 78759, USA
; http://www.kookamara.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: Jared Davis <[email protected]>
(in-package "SET")
(include-book "delete")
(set-verify-guards-eagerness 2)
(defsection cardinality
:parents (std/osets)
:short "@(call cardinality) computes the number of elements in @('X')."
:long "<p>This is like @(see length), but respects the non-set convention and
always returns 0 for ill-formed sets.</p>"
(defun cardinality (X)
(declare (xargs :guard (setp X)
:verify-guards nil))
(mbe :logic (if (empty X)
0
(1+ (cardinality (tail X))))
:exec (length (the list X))))
(verify-guards cardinality
;; Normally we would never want to enable the primitives theory. However,
;; here we need to show that cardinality is equal to length, and for this
;; we need to be able to reason about tail and empty. Think of this as a
;; tiny extension of "fast.lisp"
:hints(("Goal" :in-theory (enable (:ruleset primitive-rules)))))
(defthm cardinality-type
(and (integerp (cardinality X))
(<= 0 (cardinality X)))
:rule-classes :type-prescription)
(defthm cardinality-zero-empty
(equal (equal (cardinality x) 0)
(empty x)))
(defthm cardinality-sfix-cancel
(equal (cardinality (sfix X)) (cardinality X)))
(encapsulate ()
(local (defthm cardinality-insert-empty
(implies (empty X)
(equal (cardinality (insert a X)) 1))
:hints(("Goal" :use (:instance cardinality (x (insert a nil)))))))
(defthm insert-cardinality
(equal (cardinality (insert a X))
(if (in a X)
(cardinality X)
(1+ (cardinality X))))))
(defthm delete-cardinality
(equal (cardinality (delete a X))
(if (in a X)
(1- (cardinality X))
(cardinality X))))
; Now that we have the delete function, we can prove an interesting
; theorem, namely that if (subset X Y) and |X| = |Y|, then X = Y. In
; order to do this, we need to induct by deleting elements from both
; X and Y. This is a little ugly, but along the way we will show the
; nice theorem, subset-cardinality.
(local (defun double-delete-induction (X Y)
(declare (xargs :guard (and (setp X) (setp Y))))
(if (or (empty X) (empty Y))
(list X Y)
(double-delete-induction (delete (head X) X)
(delete (head X) Y)))))
(local (defthmd subset-double-delete
(implies (subset X Y)
(subset (delete a X) (delete a Y)))
:hints(("Goal" :in-theory (disable delete-nonmember-cancel
in-tail-or-head)))))
(encapsulate
()
(local (defthm subset-cardinality-lemma
(implies (and (not (or (empty x) (empty y)))
(implies (subset (delete (head x) x)
(delete (head x) y))
(<= (cardinality (delete (head x) x))
(cardinality (delete (head x) y)))))
(implies (subset x y)
(<= (cardinality x) (cardinality y))))
:hints(("goal" :use ((:instance subset-double-delete
(a (head x))
(x x)
(y y)))))))
(defthm subset-cardinality
(implies (subset X Y)
(<= (cardinality X) (cardinality Y)))
:hints(("Goal" :induct (double-delete-induction X Y)))
:rule-classes (:rewrite :linear)))
(defthmd equal-cardinality-subset-is-equality
(implies (and (setp X)
(setp Y)
(subset X Y)
(equal (cardinality X) (cardinality Y)))
(equal (equal X Y) t))
:hints(("Goal" :induct (double-delete-induction X Y))
("Subgoal *1/2"
:use ((:instance subset-double-delete
(a (head X))
(X X)
(Y Y))
(:instance (:theorem
(implies (equal X Y)
(equal (insert a X) (insert a Y))))
(a (head X))
(X (tail X))
(Y (delete (head X) Y)))))))
(defthm proper-subset-cardinality
(implies (and (subset X Y)
(not (subset Y X)))
(< (cardinality X) (cardinality Y)))
:rule-classes (:rewrite :linear)
:hints(("Goal"
:in-theory (disable pick-a-point-subset-strategy)
:use ((:instance equal-cardinality-subset-is-equality
(X (sfix x))
(Y (sfix y))))))))
|
12776
|
; Fully Ordered Finite Sets
; Copyright (C) 2003-2012 Kookamara LLC
;
; Contact:
;
; Kookamara LLC
; 11410 Windermere Meadows
; Austin, TX 78759, USA
; http://www.kookamara.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: <NAME> <<EMAIL>>
(in-package "SET")
(include-book "delete")
(set-verify-guards-eagerness 2)
(defsection cardinality
:parents (std/osets)
:short "@(call cardinality) computes the number of elements in @('X')."
:long "<p>This is like @(see length), but respects the non-set convention and
always returns 0 for ill-formed sets.</p>"
(defun cardinality (X)
(declare (xargs :guard (setp X)
:verify-guards nil))
(mbe :logic (if (empty X)
0
(1+ (cardinality (tail X))))
:exec (length (the list X))))
(verify-guards cardinality
;; Normally we would never want to enable the primitives theory. However,
;; here we need to show that cardinality is equal to length, and for this
;; we need to be able to reason about tail and empty. Think of this as a
;; tiny extension of "fast.lisp"
:hints(("Goal" :in-theory (enable (:ruleset primitive-rules)))))
(defthm cardinality-type
(and (integerp (cardinality X))
(<= 0 (cardinality X)))
:rule-classes :type-prescription)
(defthm cardinality-zero-empty
(equal (equal (cardinality x) 0)
(empty x)))
(defthm cardinality-sfix-cancel
(equal (cardinality (sfix X)) (cardinality X)))
(encapsulate ()
(local (defthm cardinality-insert-empty
(implies (empty X)
(equal (cardinality (insert a X)) 1))
:hints(("Goal" :use (:instance cardinality (x (insert a nil)))))))
(defthm insert-cardinality
(equal (cardinality (insert a X))
(if (in a X)
(cardinality X)
(1+ (cardinality X))))))
(defthm delete-cardinality
(equal (cardinality (delete a X))
(if (in a X)
(1- (cardinality X))
(cardinality X))))
; Now that we have the delete function, we can prove an interesting
; theorem, namely that if (subset X Y) and |X| = |Y|, then X = Y. In
; order to do this, we need to induct by deleting elements from both
; X and Y. This is a little ugly, but along the way we will show the
; nice theorem, subset-cardinality.
(local (defun double-delete-induction (X Y)
(declare (xargs :guard (and (setp X) (setp Y))))
(if (or (empty X) (empty Y))
(list X Y)
(double-delete-induction (delete (head X) X)
(delete (head X) Y)))))
(local (defthmd subset-double-delete
(implies (subset X Y)
(subset (delete a X) (delete a Y)))
:hints(("Goal" :in-theory (disable delete-nonmember-cancel
in-tail-or-head)))))
(encapsulate
()
(local (defthm subset-cardinality-lemma
(implies (and (not (or (empty x) (empty y)))
(implies (subset (delete (head x) x)
(delete (head x) y))
(<= (cardinality (delete (head x) x))
(cardinality (delete (head x) y)))))
(implies (subset x y)
(<= (cardinality x) (cardinality y))))
:hints(("goal" :use ((:instance subset-double-delete
(a (head x))
(x x)
(y y)))))))
(defthm subset-cardinality
(implies (subset X Y)
(<= (cardinality X) (cardinality Y)))
:hints(("Goal" :induct (double-delete-induction X Y)))
:rule-classes (:rewrite :linear)))
(defthmd equal-cardinality-subset-is-equality
(implies (and (setp X)
(setp Y)
(subset X Y)
(equal (cardinality X) (cardinality Y)))
(equal (equal X Y) t))
:hints(("Goal" :induct (double-delete-induction X Y))
("Subgoal *1/2"
:use ((:instance subset-double-delete
(a (head X))
(X X)
(Y Y))
(:instance (:theorem
(implies (equal X Y)
(equal (insert a X) (insert a Y))))
(a (head X))
(X (tail X))
(Y (delete (head X) Y)))))))
(defthm proper-subset-cardinality
(implies (and (subset X Y)
(not (subset Y X)))
(< (cardinality X) (cardinality Y)))
:rule-classes (:rewrite :linear)
:hints(("Goal"
:in-theory (disable pick-a-point-subset-strategy)
:use ((:instance equal-cardinality-subset-is-equality
(X (sfix x))
(Y (sfix y))))))))
| true |
; Fully Ordered Finite Sets
; Copyright (C) 2003-2012 Kookamara LLC
;
; Contact:
;
; Kookamara LLC
; 11410 Windermere Meadows
; Austin, TX 78759, USA
; http://www.kookamara.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
(in-package "SET")
(include-book "delete")
(set-verify-guards-eagerness 2)
(defsection cardinality
:parents (std/osets)
:short "@(call cardinality) computes the number of elements in @('X')."
:long "<p>This is like @(see length), but respects the non-set convention and
always returns 0 for ill-formed sets.</p>"
(defun cardinality (X)
(declare (xargs :guard (setp X)
:verify-guards nil))
(mbe :logic (if (empty X)
0
(1+ (cardinality (tail X))))
:exec (length (the list X))))
(verify-guards cardinality
;; Normally we would never want to enable the primitives theory. However,
;; here we need to show that cardinality is equal to length, and for this
;; we need to be able to reason about tail and empty. Think of this as a
;; tiny extension of "fast.lisp"
:hints(("Goal" :in-theory (enable (:ruleset primitive-rules)))))
(defthm cardinality-type
(and (integerp (cardinality X))
(<= 0 (cardinality X)))
:rule-classes :type-prescription)
(defthm cardinality-zero-empty
(equal (equal (cardinality x) 0)
(empty x)))
(defthm cardinality-sfix-cancel
(equal (cardinality (sfix X)) (cardinality X)))
(encapsulate ()
(local (defthm cardinality-insert-empty
(implies (empty X)
(equal (cardinality (insert a X)) 1))
:hints(("Goal" :use (:instance cardinality (x (insert a nil)))))))
(defthm insert-cardinality
(equal (cardinality (insert a X))
(if (in a X)
(cardinality X)
(1+ (cardinality X))))))
(defthm delete-cardinality
(equal (cardinality (delete a X))
(if (in a X)
(1- (cardinality X))
(cardinality X))))
; Now that we have the delete function, we can prove an interesting
; theorem, namely that if (subset X Y) and |X| = |Y|, then X = Y. In
; order to do this, we need to induct by deleting elements from both
; X and Y. This is a little ugly, but along the way we will show the
; nice theorem, subset-cardinality.
(local (defun double-delete-induction (X Y)
(declare (xargs :guard (and (setp X) (setp Y))))
(if (or (empty X) (empty Y))
(list X Y)
(double-delete-induction (delete (head X) X)
(delete (head X) Y)))))
(local (defthmd subset-double-delete
(implies (subset X Y)
(subset (delete a X) (delete a Y)))
:hints(("Goal" :in-theory (disable delete-nonmember-cancel
in-tail-or-head)))))
(encapsulate
()
(local (defthm subset-cardinality-lemma
(implies (and (not (or (empty x) (empty y)))
(implies (subset (delete (head x) x)
(delete (head x) y))
(<= (cardinality (delete (head x) x))
(cardinality (delete (head x) y)))))
(implies (subset x y)
(<= (cardinality x) (cardinality y))))
:hints(("goal" :use ((:instance subset-double-delete
(a (head x))
(x x)
(y y)))))))
(defthm subset-cardinality
(implies (subset X Y)
(<= (cardinality X) (cardinality Y)))
:hints(("Goal" :induct (double-delete-induction X Y)))
:rule-classes (:rewrite :linear)))
(defthmd equal-cardinality-subset-is-equality
(implies (and (setp X)
(setp Y)
(subset X Y)
(equal (cardinality X) (cardinality Y)))
(equal (equal X Y) t))
:hints(("Goal" :induct (double-delete-induction X Y))
("Subgoal *1/2"
:use ((:instance subset-double-delete
(a (head X))
(X X)
(Y Y))
(:instance (:theorem
(implies (equal X Y)
(equal (insert a X) (insert a Y))))
(a (head X))
(X (tail X))
(Y (delete (head X) Y)))))))
(defthm proper-subset-cardinality
(implies (and (subset X Y)
(not (subset Y X)))
(< (cardinality X) (cardinality Y)))
:rule-classes (:rewrite :linear)
:hints(("Goal"
:in-theory (disable pick-a-point-subset-strategy)
:use ((:instance equal-cardinality-subset-is-equality
(X (sfix x))
(Y (sfix y))))))))
|
[
{
"context": "2013 Advanced Mirco Devices, Inc.\n;\n; Contact:\n; David Russinoff\n; 1106 W 9th St., Austin, TX 78703\n; http://w",
"end": 162,
"score": 0.9998922348022461,
"start": 147,
"tag": "NAME",
"value": "David Russinoff"
},
{
"context": "cense file books/rtl/rel9/license.txt.\n;\n; Author: David M. Russinoff ([email protected])\n\n(in-package \"RTL\")\n\n;This ",
"end": 310,
"score": 0.9998968839645386,
"start": 292,
"tag": "NAME",
"value": "David M. Russinoff"
},
{
"context": "rel9/license.txt.\n;\n; Author: David M. Russinoff ([email protected])\n\n(in-package \"RTL\")\n\n;This is different from the",
"end": 331,
"score": 0.999932587146759,
"start": 312,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "not (odd (* 2 x)))))\n\n\n;do we want this enabled?\n;Eric needed this for an RTL proof, but perhaps we shou",
"end": 3436,
"score": 0.9977837800979614,
"start": 3432,
"tag": "NAME",
"value": "Eric"
}
] |
books/rtl/rel11/rel9-rtl-pkg/arithmetic/even-odd2.lisp
|
mayankmanj/acl2
| 305 |
; RTL - A Formal Theory of Register-Transfer Logic and Computer Arithmetic
; Copyright (C) 1995-2013 Advanced Mirco Devices, Inc.
;
; Contact:
; David Russinoff
; 1106 W 9th St., Austin, TX 78703
; http://www.russsinoff.com/
;
; See license file books/rtl/rel9/license.txt.
;
; Author: David M. Russinoff ([email protected])
(in-package "RTL")
;This is different from the book even-odd. (We define new functions EVEN and ODD here.)
;This book contains only the results I want to export. The proofs are in even-odd2-proofs.lisp
;I could take pains to define functions that agree with evenp and oddp for all inputs (complex-rationalps are
;a little weird). But for now, I'll just focus on the integers.
;Perhaps see also the function REVEN in x-2xx.lisp
(include-book "ground-zero")
(local (include-book "even-odd2-proofs"))
;just a helper function
(defund even-aux (x)
(if (zp x)
t
(if (eql 1 x)
nil
(even-aux (+ -2 x)))))
;A recursive recognizer for even integers.
;Note that EVEN is not the same as the built in function EVENP
;handle complex numbers?
(defund even (x)
(if (not (integerp x))
nil
(if (< x 0)
(even-aux (- x))
(even-aux x))))
;A recognizer for odd integers.
;Most theorems about ODD follow from theorems about EVEN.
(defund odd (x)
(and (integerp x)
(not (even x))))
;keep disabled?
(defthmd even-is-evenp
(implies (integerp x)
(equal (even x) (evenp x))))
(defthm even-minus
(implies (case-split (acl2-numberp x))
(equal (even (* -1 x))
(even x))))
;not currently a rewrite rule
(defthm even-means-integerp
(implies (even x)
(integerp x))
:rule-classes (;:compound-recognizer
:forward-chaining))
;not currently a rewrite rule
(defthm odd-means-integerp
(implies (odd x)
(integerp x))
:rule-classes (;:compound-recognizer
:forward-chaining))
(defthm even-sum-rewrite-1
(implies (and (even x)
(case-split (acl2-numberp y))
)
(and (equal (even (+ x y))
(even y))
(equal (even (+ y x))
(even y)))))
(defthm even-sum-rewrite-2
(implies (odd x)
(and (equal (even (+ x y))
(odd y))
(equal (even (+ y x))
(odd y)))))
(defthm odd-sum-rewrite-1
(implies (even x)
(and (equal (odd (+ x y))
(odd y))
(equal (odd (+ y x))
(odd y)))))
(defthm odd-sum-rewrite-2
(implies (and (odd x)
(case-split (acl2-numberp y))
)
(and (equal (odd (+ x y))
(even y))
(equal (odd (+ y x))
(even y)))))
;avoid loops
;wait, why would even ever be around?
(theory-invariant (incompatible (:rewrite even-reduce) (:definition even-aux)))
;yuck. generalize?
(defthm even-reduce
(implies (case-split (integerp n))
(equal (even (+ -1 n))
(not (even n)))))
(defthm odd-reduce
(implies (case-split (integerp n))
(equal (odd (+ -1 n))
(not (odd n)))))
(defthm even-double
(implies (integerp x)
(even (* 2 x))))
(defthm odd-double
(implies (integerp x)
(not (odd (* 2 x)))))
;do we want this enabled?
;Eric needed this for an RTL proof, but perhaps we should think more about how to handle this.
(defthm even-means-half-is-integer
(implies (even x)
(integerp (* 1/2 x))))
#|
there are plenty more nice even-odd theorems
(defthm even-sum-rewrite
(implies (and (integerp x)
(integerp y))
(equal (even (+ x y))
(or (and (even x) (even y))
(and (odd x) (odd y)))))
:hints (("Goal" :in-theory (enable odd))))
plus rules to rewrite oddp and evenp
(defthm oddp-sum
(implies (and (integerp x)
(integerp y))
(equal (oddp (+ x y))
(or (and (oddp x) (evenp y))
(and (evenp x) (oddp y))))))
;move? ;or just prove rules like EVEN-SUM-REWRITE-1, etc. about even-aux
(defthm even-aux-reduce-by-4
(implies (and (case-split (integerp n))
(case-split (<= 4 n)))
(equal (even-aux (+ -4 n))
(even-aux n)))
:hints (("Goal" :in-theory (e/d (even odd) (ODD-REDUCE EVEN-REDUCE EVEN-SUM-REWRITE-1
ODD-SUM-REWRITE-1
EVEN-SUM-REWRITE-2
ODD-SUM-REWRITE-2))
:use ((:instance even-reduce (n n))
(:instance even-reduce (n (+ -1 n)))
(:instance even-reduce (n (+ -2 n)))
(:instance even-reduce (n (+ -3 n)))))))
|#
|
7608
|
; RTL - A Formal Theory of Register-Transfer Logic and Computer Arithmetic
; Copyright (C) 1995-2013 Advanced Mirco Devices, Inc.
;
; Contact:
; <NAME>
; 1106 W 9th St., Austin, TX 78703
; http://www.russsinoff.com/
;
; See license file books/rtl/rel9/license.txt.
;
; Author: <NAME> (<EMAIL>)
(in-package "RTL")
;This is different from the book even-odd. (We define new functions EVEN and ODD here.)
;This book contains only the results I want to export. The proofs are in even-odd2-proofs.lisp
;I could take pains to define functions that agree with evenp and oddp for all inputs (complex-rationalps are
;a little weird). But for now, I'll just focus on the integers.
;Perhaps see also the function REVEN in x-2xx.lisp
(include-book "ground-zero")
(local (include-book "even-odd2-proofs"))
;just a helper function
(defund even-aux (x)
(if (zp x)
t
(if (eql 1 x)
nil
(even-aux (+ -2 x)))))
;A recursive recognizer for even integers.
;Note that EVEN is not the same as the built in function EVENP
;handle complex numbers?
(defund even (x)
(if (not (integerp x))
nil
(if (< x 0)
(even-aux (- x))
(even-aux x))))
;A recognizer for odd integers.
;Most theorems about ODD follow from theorems about EVEN.
(defund odd (x)
(and (integerp x)
(not (even x))))
;keep disabled?
(defthmd even-is-evenp
(implies (integerp x)
(equal (even x) (evenp x))))
(defthm even-minus
(implies (case-split (acl2-numberp x))
(equal (even (* -1 x))
(even x))))
;not currently a rewrite rule
(defthm even-means-integerp
(implies (even x)
(integerp x))
:rule-classes (;:compound-recognizer
:forward-chaining))
;not currently a rewrite rule
(defthm odd-means-integerp
(implies (odd x)
(integerp x))
:rule-classes (;:compound-recognizer
:forward-chaining))
(defthm even-sum-rewrite-1
(implies (and (even x)
(case-split (acl2-numberp y))
)
(and (equal (even (+ x y))
(even y))
(equal (even (+ y x))
(even y)))))
(defthm even-sum-rewrite-2
(implies (odd x)
(and (equal (even (+ x y))
(odd y))
(equal (even (+ y x))
(odd y)))))
(defthm odd-sum-rewrite-1
(implies (even x)
(and (equal (odd (+ x y))
(odd y))
(equal (odd (+ y x))
(odd y)))))
(defthm odd-sum-rewrite-2
(implies (and (odd x)
(case-split (acl2-numberp y))
)
(and (equal (odd (+ x y))
(even y))
(equal (odd (+ y x))
(even y)))))
;avoid loops
;wait, why would even ever be around?
(theory-invariant (incompatible (:rewrite even-reduce) (:definition even-aux)))
;yuck. generalize?
(defthm even-reduce
(implies (case-split (integerp n))
(equal (even (+ -1 n))
(not (even n)))))
(defthm odd-reduce
(implies (case-split (integerp n))
(equal (odd (+ -1 n))
(not (odd n)))))
(defthm even-double
(implies (integerp x)
(even (* 2 x))))
(defthm odd-double
(implies (integerp x)
(not (odd (* 2 x)))))
;do we want this enabled?
;<NAME> needed this for an RTL proof, but perhaps we should think more about how to handle this.
(defthm even-means-half-is-integer
(implies (even x)
(integerp (* 1/2 x))))
#|
there are plenty more nice even-odd theorems
(defthm even-sum-rewrite
(implies (and (integerp x)
(integerp y))
(equal (even (+ x y))
(or (and (even x) (even y))
(and (odd x) (odd y)))))
:hints (("Goal" :in-theory (enable odd))))
plus rules to rewrite oddp and evenp
(defthm oddp-sum
(implies (and (integerp x)
(integerp y))
(equal (oddp (+ x y))
(or (and (oddp x) (evenp y))
(and (evenp x) (oddp y))))))
;move? ;or just prove rules like EVEN-SUM-REWRITE-1, etc. about even-aux
(defthm even-aux-reduce-by-4
(implies (and (case-split (integerp n))
(case-split (<= 4 n)))
(equal (even-aux (+ -4 n))
(even-aux n)))
:hints (("Goal" :in-theory (e/d (even odd) (ODD-REDUCE EVEN-REDUCE EVEN-SUM-REWRITE-1
ODD-SUM-REWRITE-1
EVEN-SUM-REWRITE-2
ODD-SUM-REWRITE-2))
:use ((:instance even-reduce (n n))
(:instance even-reduce (n (+ -1 n)))
(:instance even-reduce (n (+ -2 n)))
(:instance even-reduce (n (+ -3 n)))))))
|#
| true |
; RTL - A Formal Theory of Register-Transfer Logic and Computer Arithmetic
; Copyright (C) 1995-2013 Advanced Mirco Devices, Inc.
;
; Contact:
; PI:NAME:<NAME>END_PI
; 1106 W 9th St., Austin, TX 78703
; http://www.russsinoff.com/
;
; See license file books/rtl/rel9/license.txt.
;
; Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
(in-package "RTL")
;This is different from the book even-odd. (We define new functions EVEN and ODD here.)
;This book contains only the results I want to export. The proofs are in even-odd2-proofs.lisp
;I could take pains to define functions that agree with evenp and oddp for all inputs (complex-rationalps are
;a little weird). But for now, I'll just focus on the integers.
;Perhaps see also the function REVEN in x-2xx.lisp
(include-book "ground-zero")
(local (include-book "even-odd2-proofs"))
;just a helper function
(defund even-aux (x)
(if (zp x)
t
(if (eql 1 x)
nil
(even-aux (+ -2 x)))))
;A recursive recognizer for even integers.
;Note that EVEN is not the same as the built in function EVENP
;handle complex numbers?
(defund even (x)
(if (not (integerp x))
nil
(if (< x 0)
(even-aux (- x))
(even-aux x))))
;A recognizer for odd integers.
;Most theorems about ODD follow from theorems about EVEN.
(defund odd (x)
(and (integerp x)
(not (even x))))
;keep disabled?
(defthmd even-is-evenp
(implies (integerp x)
(equal (even x) (evenp x))))
(defthm even-minus
(implies (case-split (acl2-numberp x))
(equal (even (* -1 x))
(even x))))
;not currently a rewrite rule
(defthm even-means-integerp
(implies (even x)
(integerp x))
:rule-classes (;:compound-recognizer
:forward-chaining))
;not currently a rewrite rule
(defthm odd-means-integerp
(implies (odd x)
(integerp x))
:rule-classes (;:compound-recognizer
:forward-chaining))
(defthm even-sum-rewrite-1
(implies (and (even x)
(case-split (acl2-numberp y))
)
(and (equal (even (+ x y))
(even y))
(equal (even (+ y x))
(even y)))))
(defthm even-sum-rewrite-2
(implies (odd x)
(and (equal (even (+ x y))
(odd y))
(equal (even (+ y x))
(odd y)))))
(defthm odd-sum-rewrite-1
(implies (even x)
(and (equal (odd (+ x y))
(odd y))
(equal (odd (+ y x))
(odd y)))))
(defthm odd-sum-rewrite-2
(implies (and (odd x)
(case-split (acl2-numberp y))
)
(and (equal (odd (+ x y))
(even y))
(equal (odd (+ y x))
(even y)))))
;avoid loops
;wait, why would even ever be around?
(theory-invariant (incompatible (:rewrite even-reduce) (:definition even-aux)))
;yuck. generalize?
(defthm even-reduce
(implies (case-split (integerp n))
(equal (even (+ -1 n))
(not (even n)))))
(defthm odd-reduce
(implies (case-split (integerp n))
(equal (odd (+ -1 n))
(not (odd n)))))
(defthm even-double
(implies (integerp x)
(even (* 2 x))))
(defthm odd-double
(implies (integerp x)
(not (odd (* 2 x)))))
;do we want this enabled?
;PI:NAME:<NAME>END_PI needed this for an RTL proof, but perhaps we should think more about how to handle this.
(defthm even-means-half-is-integer
(implies (even x)
(integerp (* 1/2 x))))
#|
there are plenty more nice even-odd theorems
(defthm even-sum-rewrite
(implies (and (integerp x)
(integerp y))
(equal (even (+ x y))
(or (and (even x) (even y))
(and (odd x) (odd y)))))
:hints (("Goal" :in-theory (enable odd))))
plus rules to rewrite oddp and evenp
(defthm oddp-sum
(implies (and (integerp x)
(integerp y))
(equal (oddp (+ x y))
(or (and (oddp x) (evenp y))
(and (evenp x) (oddp y))))))
;move? ;or just prove rules like EVEN-SUM-REWRITE-1, etc. about even-aux
(defthm even-aux-reduce-by-4
(implies (and (case-split (integerp n))
(case-split (<= 4 n)))
(equal (even-aux (+ -4 n))
(even-aux n)))
:hints (("Goal" :in-theory (e/d (even odd) (ODD-REDUCE EVEN-REDUCE EVEN-SUM-REWRITE-1
ODD-SUM-REWRITE-1
EVEN-SUM-REWRITE-2
ODD-SUM-REWRITE-2))
:use ((:instance even-reduce (n n))
(:instance even-reduce (n (+ -1 n)))
(:instance even-reduce (n (+ -2 n)))
(:instance even-reduce (n (+ -3 n)))))))
|#
|
[
{
"context": "Lisp; Package: CCL -*-\n;;;\n;;; Copyright 1994-2009 Clozure Associates\n;;;\n;;; Licensed under the Apache License, Versio",
"end": 82,
"score": 0.9979177713394165,
"start": 64,
"tag": "NAME",
"value": "Clozure Associates"
}
] |
level-0/PPC/ppc-array.lisp
|
digikar99/ccl
| 732 |
;;;-*- Mode: Lisp; Package: CCL -*-
;;;
;;; Copyright 1994-2009 Clozure Associates
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
(in-package "CCL")
(eval-when (:compile-toplevel :execute)
#+ppc32-target
(require "PPC32-ARCH")
#+ppc64-target
(require "PPC64-ARCH")
(require "PPC-LAPMACROS"))
;;; Users of this shouldn't make assumptions about return value.
#+ppc32-target
(eval-when (:compile-toplevel :execute)
;;; Assumptions made by %init-misc
(assert (and (< ppc32::max-32-bit-ivector-subtag
ppc32::max-8-bit-ivector-subtag
ppc32::max-16-bit-ivector-subtag)
(eql ppc32::max-32-bit-ivector-subtag ppc32::subtag-simple-base-string)
(eql ppc32::max-16-bit-ivector-subtag ppc32::subtag-s16-vector)
(eql ppc32::max-8-bit-ivector-subtag 207))))
#+ppc32-target
(defppclapfunction %init-misc ((val arg_y)
(miscobj arg_z))
(getvheader imm0 miscobj)
(header-size imm3 imm0)
(cmpwi cr3 imm3 0)
(extract-fulltag imm1 imm0)
(cmpwi cr0 imm1 ppc32::fulltag-nodeheader)
(extract-lowbyte imm2 imm0)
(beqlr cr3) ; Silly 0-length case
(li imm4 ppc32::misc-data-offset)
(bne cr0 @imm)
;; Node vector. Don't need to memoize, since initial value is
;; older than vector.
@node-loop
(cmpwi cr0 imm3 1)
(subi imm3 imm3 1)
(stwx val miscobj imm4)
(la imm4 4 imm4)
(bne cr0 @node-loop)
(blr)
@imm
(cmpwi cr0 imm2 ppc32::subtag-double-float-vector)
(cmpwi cr1 imm2 ppc32::max-32-bit-ivector-subtag)
(cmpwi cr2 imm2 ppc32::max-8-bit-ivector-subtag)
(cmpwi cr3 imm2 ppc32::max-16-bit-ivector-subtag)
(extract-typecode imm0 val :CR6) ; don't clobber CR0
(cmpwi cr7 imm0 ppc32::tag-fixnum)
(beq cr0 @dfloat)
(ble cr1 @32)
(ble cr2 @8)
(ble cr3 @16)
(cmpwi cr0 imm2 ppc32::subtag-bit-vector)
(cmpwi cr1 imm2 ppc32::subtag-complex-double-float-vector)
(beq cr0 @bit)
(beq cr1 @complex-double-float)
;; Complex single-float vector
(cmpwi imm0 ppc32::subtag-complex-single-float)
(bne @bad)
(lfs fp0 ppc32::complex-single-float.realpart val)
(lfs fp1 ppc32::complex-single-float.imagpart val)
(li imm4 ppc32::complex-single-float.realpart)
@complex-single-float-loop
(cmpwi cr0 imm3 1)
(subi imm3 imm3 1)
(stfsx fp0 miscobj imm4)
(la imm4 4 imm4)
(stfsx fp1 miscobj imm4)
(la imm4 4 imm4)
(bne cr0 @complex-single-float-loop)
(blr)
@complex-double-float
(cmpwi imm0 ppc32::subtag-complex-double-float)
(bne @bad)
(lfd fp0 ppc32::complex-double-float.realpart val)
(lfd fp1 ppc32::complex-double-float.imagpart val)
(li imm4 ppc32::complex-double-float.realpart)
@complex-double-float-loop
(cmpwi cr0 imm3 1)
(subi imm3 imm3 1)
(stfdx fp0 miscobj imm4)
(la imm4 8 imm4)
(stfdx fp1 miscobj imm4)
(la imm4 8 imm4)
(bne cr0 @complex-double-float-loop)
(blr)
@bit
; Bit vector.
(cmplwi cr0 val '1)
(la imm3 31 imm3)
(srwi imm3 imm3 5)
(unbox-fixnum imm0 val)
(neg imm0 imm0)
(ble+ cr0 @set-32)
@bad
(li arg_x '#.$xnotelt)
(save-lisp-context)
(set-nargs 3)
(call-symbol %err-disp)
@dfloat
(cmpwi cr0 imm0 ppc32::subtag-double-float)
(li imm4 ppc32::misc-dfloat-offset)
(bne- cr0 @bad)
(lfd fp0 ppc32::double-float.value val)
@dfloat-loop
(cmpwi cr0 imm3 1)
(subi imm3 imm3 1)
(stfdx fp0 miscobj imm4)
(la imm4 8 imm4)
(bne cr0 @dfloat-loop)
(blr)
@32
(cmpwi cr4 imm2 ppc32::subtag-s32-vector)
(cmpwi cr0 imm2 ppc32::subtag-single-float-vector)
(cmpwi cr2 imm0 ppc32::subtag-bignum)
(cmpwi cr3 imm2 ppc32::subtag-fixnum-vector)
(beq cr1 @char32) ; ppc32::max-32-bit-ivector-subtag
(beq cr4 @s32)
(beq cr3 @fixnum)
(bne cr0 @u32)
;@sfloat
(cmpwi cr0 imm0 ppc32::subtag-single-float)
(bne- cr0 @bad)
(lwz imm0 ppc32::single-float.value val)
(b @set-32)
@fixnum
(unbox-fixnum imm0 val)
(beq+ cr7 @set-32)
(b @bad)
@char32
(unbox-base-char imm0 val cr0)
(b @set-32)
@s32
(unbox-fixnum imm0 val)
(beq+ cr7 @set-32)
(bne- cr2 @bad)
(getvheader imm0 val)
(cmpwi cr0 imm0 (logior (ash 1 ppc32::num-subtag-bits) ppc32::subtag-bignum))
(lwz imm0 ppc32::misc-data-offset val)
(beq+ cr0 @set-32)
(b @bad)
@u32
(extract-unsigned-byte-bits. imm0 val 30)
(unbox-fixnum imm0 val)
(beq cr0 @set-32)
(bne- cr2 @bad)
; a one-digit bignum is ok if that digit is positive.
; a two-digit bignum is ok if the sign-digit is 0.
(getvheader imm0 val)
(cmpwi cr2 imm0 (logior (ash 2 ppc32::num-subtag-bits) ppc32::subtag-bignum))
(lwz imm0 ppc32::misc-data-offset val)
(cmpwi cr3 imm0 0)
(bgt- cr2 @bad) ; more than two digits.
(beq cr2 @two-digits)
(bgt+ cr3 @set-32)
(b @bad)
@two-digits
(lwz imm1 (+ 4 ppc32::misc-data-offset) val)
(cmpwi cr0 imm1 0)
(bne- cr0 @bad)
(b @set-32)
@16
(cmpwi cr0 imm2 ppc32::subtag-u16-vector)
(la imm3 1 imm3)
(srwi imm3 imm3 1)
(beq cr3 @s16) ; ppc32::max-16-bit-ivector-subtag
(extract-unsigned-byte-bits. imm0 val 16)
(unbox-fixnum imm0 val)
(beq+ cr0 @set-16)
(b @bad)
@s16
(slwi imm0 val (- 32 (+ 16 ppc32::fixnumshift)))
(srawi imm0 imm0 (- 32 (+ 16 ppc32::fixnumshift)))
(cmpw cr0 imm0 val)
(unbox-fixnum imm0 val)
(bne- cr7 @bad)
(beq+ cr0 @set-16)
(b @bad)
@8
(cmpwi cr0 imm2 ppc32::subtag-s8-vector)
(la imm3 3 imm3)
(srwi imm3 imm3 2)
(beq cr0 @s8)
(extract-unsigned-byte-bits. imm0 val 8)
(unbox-fixnum imm0 val)
(beq+ cr0 @set-8)
(b @bad)
@s8
(slwi imm0 val (- 32 (+ 8 ppc32::fixnumshift)))
(srawi imm0 imm0 (- 32 (+ 8 ppc32::fixnumshift)))
(cmpw cr0 imm0 val)
(unbox-fixnum imm0 val)
(bne- cr7 @bad)
(beq+ cr0 @set-8)
(b @bad)
@char8
(unbox-base-char imm0 val cr0) ; this type checks val
@set-8 ; propagate low 8 bits into low 16
(rlwimi imm0 imm0 8 (- 32 16) (- 31 8))
@set-16 ; propagate low 16 bits into high 16
(rlwimi imm0 imm0 16 0 (- 31 16))
@set-32
(cmpwi cr0 imm3 1)
(subi imm3 imm3 1)
(stwx imm0 miscobj imm4)
(la imm4 4 imm4)
(bne cr0 @set-32)
(blr))
#+ppc64-target
(defppclapfunction %init-misc ((val arg_y)
(miscobj arg_z))
(getvheader imm0 miscobj)
;(extract-lowtag imm2 imm0)
(clrldi imm2 imm0 (- 64 ppc64::nlowtagbits))
(header-size imm3 imm0)
(cmpdi cr3 imm3 0)
(extract-fulltag imm1 imm0)
(cmpdi cr0 imm2 ppc64::lowtag-nodeheader)
(extract-lowbyte imm2 imm0)
(beqlr cr3) ; Silly 0-length case
(li imm4 ppc64::misc-data-offset)
(bne cr0 @imm)
;; Node vector. Don't need to memoize, since initial value is
;; older than vector.
@node-loop
(cmpdi cr0 imm3 1)
(subi imm3 imm3 1)
(stdx val miscobj imm4)
(la imm4 ppc64::node-size imm4)
(bne cr0 @node-loop)
(blr)
@imm
(extract-typecode imm0 val)
(cmpdi cr0 imm1 ppc64::ivector-class-64-bit)
(cmpdi cr1 imm1 ppc64::ivector-class-32-bit)
(cmpdi cr2 imm1 ppc64::ivector-class-8-bit)
(cmpdi cr7 imm0 ppc64::tag-fixnum)
(cmpdi cr5 imm0 ppc64::subtag-bignum)
(cmpdi cr6 imm2 ppc64::subtag-complex-double-float-vector)
(beq cr0 @64)
(beq cr1 @32)
(beq cr2 @8)
(beq cr6 @complex-double-float)
;; u16, s16, or bit-vector. Val must be a fixnum.
(cmpdi cr0 imm2 ppc64::subtag-u16-vector)
(cmpdi cr1 imm2 ppc64::subtag-s16-vector)
(bne cr7 @bad) ; not a fixnum
(beq cr0 @u16)
(beq cr1 @s16)
; Bit vector.
(cmpldi cr0 val '1)
(la imm3 63 imm3)
(srdi imm3 imm3 6)
(unbox-fixnum imm0 val)
(neg imm0 imm0)
(ble+ cr0 @set-64)
@bad
(li arg_x '#.$xnotelt)
(save-lisp-context)
(set-nargs 3)
(call-symbol %err-disp)
@complex-double-float
(cmpdi imm0 ppc64::subtag-complex-double-float)
(bne @bad)
(lfd fp0 ppc64::complex-double-float.realpart val)
(lfd fp1 ppc64::complex-double-float.imagpart val)
(li imm4 ppc64::complex-double-float.realpart)
@complex-double-float-loop
(cmpdi cr0 imm3 1)
(subi imm3 imm3 1)
(stfdx fp0 miscobj imm4)
(la imm4 8 imm4)
(stfdx fp1 miscobj imm4)
(la imm4 8 imm4)
(bne cr0 @complex-double-float-loop)
(blr)
@64
(cmpdi cr4 imm2 ppc64::subtag-complex-single-float-vector)
(cmpdi cr3 imm2 ppc64::subtag-fixnum-vector)
(cmpdi cr1 imm2 ppc64::subtag-double-float-vector)
(cmpdi cr2 imm2 ppc64::subtag-s64-vector)
(beq cr4 @complex-single-float)
(beq cr3 @fixnum)
(beq cr1 @dfloat)
(bne cr2 @u64)
;; s64
(unbox-fixnum imm0 val)
(beq cr7 @set-64) ; all fixnums are (SIGNED-BYTE 64)
(bne cr5 @bad) ; as are 2-digit bignums
(getvheader imm1 val)
(ld imm0 ppc64::misc-data-offset val)
(cmpdi imm1 ppc64::two-digit-bignum-header)
(rotldi imm0 imm0 32)
(beq @set-64)
(b @bad)
@complex-single-float
(cmpdi imm0 ppc64::subtag-complex-single-float)
(bne @bad)
(ld imm0 ppc64::complex-single-float.realpart val)
(b @set-64)
@fixnum
(unbox-fixnum imm0 val)
(beq cr7 @set-64) ; all fixnums are (SIGNED-BYTE 64)
(b @bad) ; as are 2-digit bignums
;; u64 if fixnum and positive, 2-digit bignum and positive, or
;; 3-digit bignum with most-significant digit 0.
@u64
(cmpdi cr2 val 0)
(unbox-fixnum imm0 val)
(bne cr7 @u64-maybe-bignum)
(bge cr2 @set-64)
(b @bad)
@u64-maybe-bignum
(bne cr5 @bad)
(ld imm0 ppc64::misc-data-offset val)
(getvheader imm1 val)
(rotldi imm0 imm0 32)
(cmpdi cr2 imm1 ppc64::two-digit-bignum-header)
(cmpdi cr3 imm1 ppc64::three-digit-bignum-header)
(cmpdi cr0 imm0 0)
(beq cr2 @u64-two-digit)
(bne cr3 @bad)
(lwz imm1 (+ 8 ppc64::misc-data-offset) val)
(cmpwi imm1 0)
(beq @set-64)
(b @bad)
@u64-two-digit
(bgt cr0 @set-64)
(b @bad)
@dfloat
(cmpdi cr0 imm0 ppc64::subtag-double-float)
(bne- cr0 @bad)
(ld imm0 ppc64::double-float.value val)
(b @set-64)
@32
(cmpdi cr3 imm2 ppc64::subtag-simple-base-string)
(cmpdi cr2 imm2 ppc64::subtag-s32-vector)
(cmpdi cr0 imm2 ppc64::subtag-single-float-vector)
(beq cr3 @char32)
(beq cr2 @s32)
(bne cr0 @u32)
;@sfloat
(cmpdi cr0 imm0 ppc64::subtag-single-float)
(srdi imm0 val 32)
(bne- cr0 @bad)
(b @set-32)
@s32
;; Must be a fixnum (and a (SIGNED-BYTE 32)).
(bne cr7 @bad)
(unbox-fixnum imm0 val)
(sldi imm1 imm0 32)
(sradi imm1 imm1 32)
(cmpd imm1 imm0)
(bne @bad)
(b @set-32)
@char32
(unbox-base-char imm0 val cr0) ; this type checks val
(b @set-32)
@u32
;; Also has to be a fixnum (and an (UNSIGNED-BYTE 32)).
(unbox-fixnum imm0 val)
(clrrdi. imm1 imm0 32) ; ~Z if any high bits set
(bne cr7 @bad)
(bne cr0 @bad)
(b @set-32)
@u16
(unbox-fixnum imm0 val)
(clrrdi. imm1 imm0 16)
(bne cr7 @bad)
(bne cr0 @bad)
(b @set-16)
@s16
(sldi imm0 val (- 64 (+ 16 ppc64::fixnumshift)))
(sradi imm0 imm0 (- 64 (+ 16 ppc64::fixnumshift)))
(cmpw cr0 imm0 val)
(unbox-fixnum imm0 val)
(bne- cr7 @bad)
(beq+ cr0 @set-16)
(b @bad)
@8
(cmpdi cr0 imm2 ppc64::subtag-s8-vector)
(beq cr0 @s8)
(extract-unsigned-byte-bits. imm0 val 8)
(unbox-fixnum imm0 val)
(beq+ cr0 @set-8)
(b @bad)
@s8
(sldi imm0 val (- 64 (+ 8 ppc64::fixnumshift)))
(sradi imm0 imm0 (- 64 (+ 8 ppc64::fixnumshift)))
(cmpd cr0 imm0 val)
(unbox-fixnum imm0 val)
(bne- cr7 @bad)
(beq+ cr0 @set-8)
(b @bad)
@char8
(unbox-base-char imm0 val cr0) ; this type checks val
@set-8 ; propagate low 8 bits into low 16
(la imm3 1 imm3)
(rlwimi imm0 imm0 8 (- 32 16) (- 31 8))
(srdi imm3 imm3 1)
@set-16 ; propagate low 16 bits into high 16
(la imm3 1 imm3)
(rlwimi imm0 imm0 16 0 (- 31 16))
(srdi imm3 imm3 1)
@set-32 ; propagate low 32 bits into high 32
(la imm3 1 imm3)
(rldimi imm0 imm0 32 0)
(srdi imm3 imm3 1)
@set-64
(cmpdi cr0 imm3 1)
(subi imm3 imm3 1)
(stdx imm0 miscobj imm4)
(la imm4 8 imm4)
(bne cr0 @set-64)
(blr))
;;; Make a new vector of size newsize whose subtag matches that of oldv-arg.
;;; Blast the contents of the old vector into the new one as quickly as
;;; possible; leave remaining elements of new vector undefined (0).
;;; Return new-vector.
#+ppc32-target
(defppclapfunction %extend-vector ((start-arg arg_x) (oldv-arg arg_y) (newsize arg_z))
(let ((oldv save0)
(oldsize save1)
(oldsubtag save2)
(start-offset save3))
(save-lisp-context)
(:regsave save3 0)
(vpush save0)
(vpush save1)
(vpush save2)
(vpush save3)
(mr oldv oldv-arg)
(mr start-offset start-arg)
(getvheader imm0 oldv)
(header-length oldsize imm0)
(header-subtag[fixnum] oldsubtag imm0)
(mr arg_y newsize)
(mr arg_z oldsubtag)
(bla .SPmisc-alloc)
(extrwi imm0 oldsubtag ppc32::ntagbits (- 32 (+ ppc32::fixnumshift ppc32::ntagbits)))
(cmpwi cr0 oldsize 0)
(cmpwi cr1 imm0 ppc32::fulltag-nodeheader)
(cmpwi cr2 oldsubtag '#.ppc32::max-32-bit-ivector-subtag)
(la imm1 ppc32::misc-data-offset start-offset)
(li imm3 ppc32::misc-data-offset)
(beq cr0 @done)
(bne cr1 @imm)
;; copy nodes. New vector is "new", so no memoization required.
@node-loop
(cmpwi cr0 oldsize '1)
(lwzx temp0 oldv imm1)
(addi imm1 imm1 4)
(subi oldsize oldsize '1)
(stwx temp0 arg_z imm3)
(addi imm3 imm3 4)
(bne cr0 @node-loop)
;;Restore registers. New vector's been in arg_z all this time.
@done
(lwz save3 0 vsp)
(lwz save2 4 vsp)
(lwz save1 8 vsp)
(lwz save0 12 vsp)
(restore-full-lisp-context)
(blr)
@imm
(unbox-fixnum imm2 oldsize)
(unbox-fixnum imm3 start-offset)
(li imm1 ppc32::misc-data-offset)
(la imm4 ppc32::misc-data-offset start-offset)
(cmpwi cr1 oldsubtag '#.ppc32::max-8-bit-ivector-subtag)
(cmpwi cr0 oldsubtag '#.ppc32::max-16-bit-ivector-subtag)
(ble cr2 @fullword-loop)
(cmpwi cr2 oldsubtag '#.ppc32::subtag-bit-vector)
(ble cr1 @8-bit)
(ble cr0 @16-bit)
(beq cr2 @1-bit)
;; 64-bit (double-float) vectors. There's a different
;; initial offset, but we're always word-aligned, so that
;; part's easy.
(li imm1 ppc32::misc-dfloat-offset) ; scaled destination pointer
(slwi imm2 imm2 1) ; twice as many fullwords
(slwi imm3 imm3 3) ; convert dword count to byte offset
(la imm4 ppc32::misc-dfloat-offset imm3) ; scaled source pointer
(b @fullword-loop)
;; The bitvector case is hard if START-OFFSET isn't on an 8-bit boundary,
;; and can be turned into the 8-bit case otherwise.
;; The 8-bit case is hard if START-OFFSET isn't on a 16-bit boundary,
;; and can be turned into the 16-bit case otherwise.
;; The 16-bit case is hard if START-OFFSET isn't on a 32-bit boundary,
;; and can be turned into the 32-bit case otherwise.
;; Hmm.
@1-bit
(clrlwi. imm0 imm3 (- 32 3))
(bne- cr0 @hard-1-bit)
(srwi imm3 imm3 3) ; bit offset to byte offset
(addi imm2 imm2 7)
(srwi imm2 imm2 3) ; bit count to byte count
@8-bit
; If the byte offset's even, copy half as many halfwords
(clrlwi. imm0 imm3 (- 32 1))
(bne- cr0 @hard-8-bit)
(addi imm2 imm2 1)
(srwi imm2 imm2 1) ; byte count to halfword count
(srwi imm3 imm3 1) ; byte offset to halfword offset
@16-bit
; If the halfword offset's even, copy half as many fullwords
(clrlwi. imm0 imm3 (- 32 1))
(bne- cr0 @hard-16-bit)
(addi imm2 imm2 1)
(srwi imm2 imm2 1) ; halfword count to fullword count
(li imm1 ppc32::misc-data-offset)
@fullword-loop
(cmpwi cr0 imm2 1)
(lwzx imm0 oldv imm4)
(addi imm4 imm4 4)
(subi imm2 imm2 1)
(stwx imm0 arg_z imm1)
(addi imm1 imm1 4)
(bne cr0 @fullword-loop)
(b @done)
;;; This can just do a uvref/uvset loop. Cases that can
;;; cons (x32, double-float) have already been dealt with.
@hard-1-bit
@hard-8-bit
@hard-16-bit
(let ((newv save4)
(outi save5)
(oldlen save6))
(vpush save4)
(vpush save5)
(vpush save6)
(mr newv arg_z)
(sub oldlen oldsize start-offset)
(li outi 0)
@hard-loop
(mr arg_y oldv)
(mr arg_z start-offset)
(bla .SPmisc-ref)
(mr arg_x newv)
(mr arg_y outi)
(bla .SPmisc-set)
(la outi '1 outi)
(cmpw cr0 outi oldlen)
(la start-offset '1 start-offset)
(bne @hard-loop)
(mr arg_z newv)
(vpop save6)
(vpop save5)
(vpop save4)
(b @done))))
#+ppc64-target
(defppclapfunction %extend-vector ((start-arg arg_x) (oldv-arg arg_y) (newsize arg_z))
(let ((oldv save0)
(oldsize save1)
(oldsubtag save2)
(start-offset save3))
(save-lisp-context)
(:regsave save3 0)
(vpush save0)
(vpush save1)
(vpush save2)
(vpush save3)
(mr oldv oldv-arg)
(mr start-offset start-arg)
(getvheader imm0 oldv)
(header-length oldsize imm0)
(header-subtag[fixnum] oldsubtag imm0)
(mr arg_y newsize)
(mr arg_z oldsubtag)
(bla .SPmisc-alloc)
(unbox-fixnum imm0 oldsubtag)
(extract-lowtag imm1 imm0)
(extract-fulltag imm2 imm0)
(cmpdi cr0 oldsize 0)
(cmpdi cr1 imm1 ppc64::lowtag-nodeheader)
(cmpdi cr2 imm2 ppc64::ivector-class-8-bit)
(cmpdi cr3 imm2 ppc64::ivector-class-32-bit)
(cmpdi cr4 imm2 ppc64::ivector-class-64-bit)
(cmpdi cr5 imm0 ppc64::subtag-bit-vector)
(li imm3 ppc64::misc-data-offset)
(beq cr0 @done)
(bne cr1 @imm)
(la imm1 ppc64::misc-data-offset start-offset)
;; copy nodes. New vector is "new", so no memoization required.
@node-loop
(cmpdi cr0 oldsize '1)
(ldx temp0 oldv imm1)
(addi imm1 imm1 8)
(subi oldsize oldsize '1)
(stdx temp0 arg_z imm3)
(addi imm3 imm3 8)
(bne cr0 @node-loop)
;;Restore registers. New vector's been in arg_z all this time.
@done
(ld save3 0 vsp)
(ld save2 8 vsp)
(ld save1 16 vsp)
(ld save0 24 vsp)
(restore-full-lisp-context)
(blr)
@imm
(beq cr2 @8-bit)
(beq cr3 @32-bit)
(beq cr4 @64-bit)
(beq cr5 @1-bit)
;;; The bit-vector case is ignored, but we should probably
;;; try to handle (VECTOR (COMPLEX DOUBLE-FLOAT)).
(srdi imm1 start-offset 2)
(la imm1 ppc64::misc-data-offset imm1)
@16-loop
(cmpdi cr0 oldsize '1)
(lhzx imm4 oldv imm1)
(addi imm1 imm1 2)
(subi oldsize oldsize '1)
(sthx imm4 arg_z imm3)
(addi imm3 imm3 2)
(bne cr0 @16-loop)
(b @done)
@8-bit
(srdi imm1 start-offset 3)
(la imm1 ppc64::misc-data-offset imm1)
@8-loop
(cmpdi cr0 oldsize '1)
(lbzx imm4 oldv imm1)
(addi imm1 imm1 1)
(subi oldsize oldsize '1)
(stbx imm4 arg_z imm3)
(addi imm3 imm3 1)
(bne cr0 @8-loop)
(b @done)
@32-bit
(srdi imm1 start-offset 1)
(la imm1 ppc64::misc-data-offset imm1)
@32-loop
(cmpdi cr0 oldsize '1)
(lwzx imm4 oldv imm1)
(addi imm1 imm1 4)
(subi oldsize oldsize '1)
(stwx imm4 arg_z imm3)
(addi imm3 imm3 4)
(bne cr0 @32-loop)
(b @done)
@64-bit
(la imm1 ppc64::misc-data-offset start-offset)
@64-loop
(cmpdi cr0 oldsize '1)
(ldx imm4 oldv imm1)
(addi imm1 imm1 8)
(subi oldsize oldsize '1)
(stdx imm4 arg_z imm3)
(addi imm3 imm3 8)
(bne cr0 @64-loop)
(b @done)
@1-bit
(let ((newv save4)
(outi save5)
(oldlen save6))
(vpush save4)
(vpush save5)
(vpush save6)
(mr newv arg_z)
(sub oldlen oldsize start-offset)
(li outi 0)
@hard-loop
(mr arg_y oldv)
(mr arg_z start-offset)
(bla .SPmisc-ref)
(mr arg_x newv)
(mr arg_y outi)
(bla .SPmisc-set)
(la outi '1 outi)
(cmpd cr0 outi oldlen)
(la start-offset '1 start-offset)
(bne @hard-loop)
(mr arg_z newv)
(vpop save6)
(vpop save5)
(vpop save4)
(b @done))))
;;; argument is a vector header or an array header. Or else.
(defppclapfunction %array-header-data-and-offset ((a arg_z))
(let ((offset arg_y)
(disp arg_x)
(temp temp0))
(li offset 0)
(mr temp a)
@loop
(ldr a target::arrayH.data-vector temp)
(lbz imm0 target::misc-subtag-offset a)
(cmpri cr0 imm0 target::subtag-vectorH)
(cmpri cr1 imm0 target::subtag-arrayH)
(ldr disp target::arrayH.displacement temp)
(mr temp a)
(add offset offset disp)
(beq cr0 @loop)
(beq cr1 @loop)
(vpush a)
(vpush offset)
(set-nargs 2)
(la temp0 (* 2 (ash 1 target::word-shift)) vsp)
(ba .SPvalues)))
;;; If the bit-arrays are all simple-bit-vectorp, we can do the operations
;;; 32 bits at a time. (other case have to worry about alignment/displacement.)
#+ppc32-target
(defppclapfunction %simple-bit-boole ((op 0) (b1 arg_x) (b2 arg_y) (result arg_z))
(la imm0 4 vsp)
(save-lisp-context imm0)
(vector-size imm4 result imm4)
(srwi. imm3 imm4 5)
(clrlwi imm4 imm4 27)
(bl @get-dispatch)
(cmpwi cr1 imm4 0)
(mflr loc-pc)
(lwz temp0 op vsp)
(add loc-pc loc-pc temp0)
(add loc-pc loc-pc temp0)
(mtctr loc-pc)
(li imm0 ppc32::misc-data-offset)
(b @testw)
@nextw
(cmpwi cr0 imm3 1)
(subi imm3 imm3 1)
(lwzx imm1 b1 imm0)
(lwzx imm2 b2 imm0)
(bctrl)
(stwx imm1 result imm0)
(addi imm0 imm0 4)
@testw
(bne cr0 @nextw)
(beq cr1 @done)
;; Not sure if we need to make this much fuss about the partial word
;; in this simple case, but what the hell.
(lwzx imm1 b1 imm0)
(lwzx imm2 b2 imm0)
(bctrl)
(lwzx imm2 result imm0)
(slw imm2 imm2 imm4)
(srw imm2 imm2 imm4)
(subfic imm4 imm4 32)
(srw imm1 imm1 imm4)
(slw imm1 imm1 imm4)
(or imm1 imm1 imm2)
(stwx imm1 result imm0)
@done
(restore-full-lisp-context)
(blr)
@get-dispatch
(blrl)
@disptach
(li imm1 0) ; boole-clr
(blr)
(li imm1 -1) ; boole-set
(blr)
(blr) ; boole-1
(blr)
(mr imm1 imm2) ; boole-2
(blr)
(not imm1 imm1) ; boole-c1
(blr)
(not imm1 imm2) ; boole-c2
(blr)
(and imm1 imm1 imm2) ; boole-and
(blr)
(or imm1 imm1 imm2) ; boole-ior
(blr)
(xor imm1 imm1 imm2) ; boole-xor
(blr)
(eqv imm1 imm1 imm2) ; boole-eqv
(blr)
(nand imm1 imm1 imm2) ; boole-nand
(blr)
(nor imm1 imm1 imm2) ; boole-nor
(blr)
(andc imm1 imm2 imm1) ; boole-andc1
(blr)
(andc imm1 imm1 imm2) ; boole-andc2
(blr)
(orc imm1 imm2 imm1) ; boole-orc1
(blr)
(orc imm1 imm1 imm2) ; boole-orc2
(blr))
#+ppc64-target
(defppclapfunction %simple-bit-boole ((op 0) (b1 arg_x) (b2 arg_y) (result arg_z))
(la imm0 8 vsp)
(save-lisp-context imm0)
(vector-size imm4 result imm4)
(srdi. imm3 imm4 6)
(clrldi imm4 imm4 (- 64 6))
(bl @get-dispatch)
(cmpdi cr1 imm4 0) ; at most low 6 bits set in imm4
(mflr loc-pc)
(ld temp0 op vsp)
(add loc-pc loc-pc temp0)
(mtctr loc-pc)
(li imm0 ppc64::misc-data-offset)
(b @testd)
@nextd
(cmpdi cr0 imm3 1)
(subi imm3 imm3 1)
(ldx imm1 b1 imm0)
(ldx imm2 b2 imm0)
(bctrl)
(stdx imm1 result imm0)
(addi imm0 imm0 8)
@testd
(bne cr0 @nextd)
(beq cr1 @done)
;; Not sure if we need to make this much fuss about the partial word
;; in this simple case, but what the hell.
(ldx imm1 b1 imm0)
(ldx imm2 b2 imm0)
(bctrl)
(ldx imm2 result imm0)
(sld imm2 imm2 imm4)
(srd imm2 imm2 imm4)
(subfic imm4 imm4 64)
(srd imm1 imm1 imm4)
(sld imm1 imm1 imm4)
(or imm1 imm1 imm2)
(stdx imm1 result imm0)
@done
(restore-full-lisp-context)
(blr)
@get-dispatch
(blrl)
@disptach
(li imm1 0) ; boole-clr
(blr)
(li imm1 -1) ; boole-set
(blr)
(blr) ; boole-1
(blr)
(mr imm1 imm2) ; boole-2
(blr)
(not imm1 imm1) ; boole-c1
(blr)
(not imm1 imm2) ; boole-c2
(blr)
(and imm1 imm1 imm2) ; boole-and
(blr)
(or imm1 imm1 imm2) ; boole-ior
(blr)
(xor imm1 imm1 imm2) ; boole-xor
(blr)
(eqv imm1 imm1 imm2) ; boole-eqv
(blr)
(nand imm1 imm1 imm2) ; boole-nand
(blr)
(nor imm1 imm1 imm2) ; boole-nor
(blr)
(andc imm1 imm2 imm1) ; boole-andc1
(blr)
(andc imm1 imm1 imm2) ; boole-andc2
(blr)
(orc imm1 imm2 imm1) ; boole-orc1
(blr)
(orc imm1 imm1 imm2) ; boole-orc2
(blr))
(defppclapfunction %aref2 ((array arg_x) (i arg_y) (j arg_z))
(check-nargs 3)
(ba .SParef2))
(defppclapfunction %aref3 ((array 0) (i arg_x) (j arg_y) (k arg_z))
(check-nargs 4)
(vpop temp0)
(ba .SParef3))
(defppclapfunction %aset2 ((array 0) (i arg_x) (j arg_y) (newval arg_z))
(check-nargs 4)
(vpop temp0)
(ba .SPaset2))
(defppclapfunction %aset3 ((array #.target::node-size) (i 0) (j arg_x) (k arg_y) (newval arg_z))
(check-nargs 5)
(vpop temp0)
(vpop temp1)
(ba .SPaset3))
|
47690
|
;;;-*- Mode: Lisp; Package: CCL -*-
;;;
;;; Copyright 1994-2009 <NAME>
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
(in-package "CCL")
(eval-when (:compile-toplevel :execute)
#+ppc32-target
(require "PPC32-ARCH")
#+ppc64-target
(require "PPC64-ARCH")
(require "PPC-LAPMACROS"))
;;; Users of this shouldn't make assumptions about return value.
#+ppc32-target
(eval-when (:compile-toplevel :execute)
;;; Assumptions made by %init-misc
(assert (and (< ppc32::max-32-bit-ivector-subtag
ppc32::max-8-bit-ivector-subtag
ppc32::max-16-bit-ivector-subtag)
(eql ppc32::max-32-bit-ivector-subtag ppc32::subtag-simple-base-string)
(eql ppc32::max-16-bit-ivector-subtag ppc32::subtag-s16-vector)
(eql ppc32::max-8-bit-ivector-subtag 207))))
#+ppc32-target
(defppclapfunction %init-misc ((val arg_y)
(miscobj arg_z))
(getvheader imm0 miscobj)
(header-size imm3 imm0)
(cmpwi cr3 imm3 0)
(extract-fulltag imm1 imm0)
(cmpwi cr0 imm1 ppc32::fulltag-nodeheader)
(extract-lowbyte imm2 imm0)
(beqlr cr3) ; Silly 0-length case
(li imm4 ppc32::misc-data-offset)
(bne cr0 @imm)
;; Node vector. Don't need to memoize, since initial value is
;; older than vector.
@node-loop
(cmpwi cr0 imm3 1)
(subi imm3 imm3 1)
(stwx val miscobj imm4)
(la imm4 4 imm4)
(bne cr0 @node-loop)
(blr)
@imm
(cmpwi cr0 imm2 ppc32::subtag-double-float-vector)
(cmpwi cr1 imm2 ppc32::max-32-bit-ivector-subtag)
(cmpwi cr2 imm2 ppc32::max-8-bit-ivector-subtag)
(cmpwi cr3 imm2 ppc32::max-16-bit-ivector-subtag)
(extract-typecode imm0 val :CR6) ; don't clobber CR0
(cmpwi cr7 imm0 ppc32::tag-fixnum)
(beq cr0 @dfloat)
(ble cr1 @32)
(ble cr2 @8)
(ble cr3 @16)
(cmpwi cr0 imm2 ppc32::subtag-bit-vector)
(cmpwi cr1 imm2 ppc32::subtag-complex-double-float-vector)
(beq cr0 @bit)
(beq cr1 @complex-double-float)
;; Complex single-float vector
(cmpwi imm0 ppc32::subtag-complex-single-float)
(bne @bad)
(lfs fp0 ppc32::complex-single-float.realpart val)
(lfs fp1 ppc32::complex-single-float.imagpart val)
(li imm4 ppc32::complex-single-float.realpart)
@complex-single-float-loop
(cmpwi cr0 imm3 1)
(subi imm3 imm3 1)
(stfsx fp0 miscobj imm4)
(la imm4 4 imm4)
(stfsx fp1 miscobj imm4)
(la imm4 4 imm4)
(bne cr0 @complex-single-float-loop)
(blr)
@complex-double-float
(cmpwi imm0 ppc32::subtag-complex-double-float)
(bne @bad)
(lfd fp0 ppc32::complex-double-float.realpart val)
(lfd fp1 ppc32::complex-double-float.imagpart val)
(li imm4 ppc32::complex-double-float.realpart)
@complex-double-float-loop
(cmpwi cr0 imm3 1)
(subi imm3 imm3 1)
(stfdx fp0 miscobj imm4)
(la imm4 8 imm4)
(stfdx fp1 miscobj imm4)
(la imm4 8 imm4)
(bne cr0 @complex-double-float-loop)
(blr)
@bit
; Bit vector.
(cmplwi cr0 val '1)
(la imm3 31 imm3)
(srwi imm3 imm3 5)
(unbox-fixnum imm0 val)
(neg imm0 imm0)
(ble+ cr0 @set-32)
@bad
(li arg_x '#.$xnotelt)
(save-lisp-context)
(set-nargs 3)
(call-symbol %err-disp)
@dfloat
(cmpwi cr0 imm0 ppc32::subtag-double-float)
(li imm4 ppc32::misc-dfloat-offset)
(bne- cr0 @bad)
(lfd fp0 ppc32::double-float.value val)
@dfloat-loop
(cmpwi cr0 imm3 1)
(subi imm3 imm3 1)
(stfdx fp0 miscobj imm4)
(la imm4 8 imm4)
(bne cr0 @dfloat-loop)
(blr)
@32
(cmpwi cr4 imm2 ppc32::subtag-s32-vector)
(cmpwi cr0 imm2 ppc32::subtag-single-float-vector)
(cmpwi cr2 imm0 ppc32::subtag-bignum)
(cmpwi cr3 imm2 ppc32::subtag-fixnum-vector)
(beq cr1 @char32) ; ppc32::max-32-bit-ivector-subtag
(beq cr4 @s32)
(beq cr3 @fixnum)
(bne cr0 @u32)
;@sfloat
(cmpwi cr0 imm0 ppc32::subtag-single-float)
(bne- cr0 @bad)
(lwz imm0 ppc32::single-float.value val)
(b @set-32)
@fixnum
(unbox-fixnum imm0 val)
(beq+ cr7 @set-32)
(b @bad)
@char32
(unbox-base-char imm0 val cr0)
(b @set-32)
@s32
(unbox-fixnum imm0 val)
(beq+ cr7 @set-32)
(bne- cr2 @bad)
(getvheader imm0 val)
(cmpwi cr0 imm0 (logior (ash 1 ppc32::num-subtag-bits) ppc32::subtag-bignum))
(lwz imm0 ppc32::misc-data-offset val)
(beq+ cr0 @set-32)
(b @bad)
@u32
(extract-unsigned-byte-bits. imm0 val 30)
(unbox-fixnum imm0 val)
(beq cr0 @set-32)
(bne- cr2 @bad)
; a one-digit bignum is ok if that digit is positive.
; a two-digit bignum is ok if the sign-digit is 0.
(getvheader imm0 val)
(cmpwi cr2 imm0 (logior (ash 2 ppc32::num-subtag-bits) ppc32::subtag-bignum))
(lwz imm0 ppc32::misc-data-offset val)
(cmpwi cr3 imm0 0)
(bgt- cr2 @bad) ; more than two digits.
(beq cr2 @two-digits)
(bgt+ cr3 @set-32)
(b @bad)
@two-digits
(lwz imm1 (+ 4 ppc32::misc-data-offset) val)
(cmpwi cr0 imm1 0)
(bne- cr0 @bad)
(b @set-32)
@16
(cmpwi cr0 imm2 ppc32::subtag-u16-vector)
(la imm3 1 imm3)
(srwi imm3 imm3 1)
(beq cr3 @s16) ; ppc32::max-16-bit-ivector-subtag
(extract-unsigned-byte-bits. imm0 val 16)
(unbox-fixnum imm0 val)
(beq+ cr0 @set-16)
(b @bad)
@s16
(slwi imm0 val (- 32 (+ 16 ppc32::fixnumshift)))
(srawi imm0 imm0 (- 32 (+ 16 ppc32::fixnumshift)))
(cmpw cr0 imm0 val)
(unbox-fixnum imm0 val)
(bne- cr7 @bad)
(beq+ cr0 @set-16)
(b @bad)
@8
(cmpwi cr0 imm2 ppc32::subtag-s8-vector)
(la imm3 3 imm3)
(srwi imm3 imm3 2)
(beq cr0 @s8)
(extract-unsigned-byte-bits. imm0 val 8)
(unbox-fixnum imm0 val)
(beq+ cr0 @set-8)
(b @bad)
@s8
(slwi imm0 val (- 32 (+ 8 ppc32::fixnumshift)))
(srawi imm0 imm0 (- 32 (+ 8 ppc32::fixnumshift)))
(cmpw cr0 imm0 val)
(unbox-fixnum imm0 val)
(bne- cr7 @bad)
(beq+ cr0 @set-8)
(b @bad)
@char8
(unbox-base-char imm0 val cr0) ; this type checks val
@set-8 ; propagate low 8 bits into low 16
(rlwimi imm0 imm0 8 (- 32 16) (- 31 8))
@set-16 ; propagate low 16 bits into high 16
(rlwimi imm0 imm0 16 0 (- 31 16))
@set-32
(cmpwi cr0 imm3 1)
(subi imm3 imm3 1)
(stwx imm0 miscobj imm4)
(la imm4 4 imm4)
(bne cr0 @set-32)
(blr))
#+ppc64-target
(defppclapfunction %init-misc ((val arg_y)
(miscobj arg_z))
(getvheader imm0 miscobj)
;(extract-lowtag imm2 imm0)
(clrldi imm2 imm0 (- 64 ppc64::nlowtagbits))
(header-size imm3 imm0)
(cmpdi cr3 imm3 0)
(extract-fulltag imm1 imm0)
(cmpdi cr0 imm2 ppc64::lowtag-nodeheader)
(extract-lowbyte imm2 imm0)
(beqlr cr3) ; Silly 0-length case
(li imm4 ppc64::misc-data-offset)
(bne cr0 @imm)
;; Node vector. Don't need to memoize, since initial value is
;; older than vector.
@node-loop
(cmpdi cr0 imm3 1)
(subi imm3 imm3 1)
(stdx val miscobj imm4)
(la imm4 ppc64::node-size imm4)
(bne cr0 @node-loop)
(blr)
@imm
(extract-typecode imm0 val)
(cmpdi cr0 imm1 ppc64::ivector-class-64-bit)
(cmpdi cr1 imm1 ppc64::ivector-class-32-bit)
(cmpdi cr2 imm1 ppc64::ivector-class-8-bit)
(cmpdi cr7 imm0 ppc64::tag-fixnum)
(cmpdi cr5 imm0 ppc64::subtag-bignum)
(cmpdi cr6 imm2 ppc64::subtag-complex-double-float-vector)
(beq cr0 @64)
(beq cr1 @32)
(beq cr2 @8)
(beq cr6 @complex-double-float)
;; u16, s16, or bit-vector. Val must be a fixnum.
(cmpdi cr0 imm2 ppc64::subtag-u16-vector)
(cmpdi cr1 imm2 ppc64::subtag-s16-vector)
(bne cr7 @bad) ; not a fixnum
(beq cr0 @u16)
(beq cr1 @s16)
; Bit vector.
(cmpldi cr0 val '1)
(la imm3 63 imm3)
(srdi imm3 imm3 6)
(unbox-fixnum imm0 val)
(neg imm0 imm0)
(ble+ cr0 @set-64)
@bad
(li arg_x '#.$xnotelt)
(save-lisp-context)
(set-nargs 3)
(call-symbol %err-disp)
@complex-double-float
(cmpdi imm0 ppc64::subtag-complex-double-float)
(bne @bad)
(lfd fp0 ppc64::complex-double-float.realpart val)
(lfd fp1 ppc64::complex-double-float.imagpart val)
(li imm4 ppc64::complex-double-float.realpart)
@complex-double-float-loop
(cmpdi cr0 imm3 1)
(subi imm3 imm3 1)
(stfdx fp0 miscobj imm4)
(la imm4 8 imm4)
(stfdx fp1 miscobj imm4)
(la imm4 8 imm4)
(bne cr0 @complex-double-float-loop)
(blr)
@64
(cmpdi cr4 imm2 ppc64::subtag-complex-single-float-vector)
(cmpdi cr3 imm2 ppc64::subtag-fixnum-vector)
(cmpdi cr1 imm2 ppc64::subtag-double-float-vector)
(cmpdi cr2 imm2 ppc64::subtag-s64-vector)
(beq cr4 @complex-single-float)
(beq cr3 @fixnum)
(beq cr1 @dfloat)
(bne cr2 @u64)
;; s64
(unbox-fixnum imm0 val)
(beq cr7 @set-64) ; all fixnums are (SIGNED-BYTE 64)
(bne cr5 @bad) ; as are 2-digit bignums
(getvheader imm1 val)
(ld imm0 ppc64::misc-data-offset val)
(cmpdi imm1 ppc64::two-digit-bignum-header)
(rotldi imm0 imm0 32)
(beq @set-64)
(b @bad)
@complex-single-float
(cmpdi imm0 ppc64::subtag-complex-single-float)
(bne @bad)
(ld imm0 ppc64::complex-single-float.realpart val)
(b @set-64)
@fixnum
(unbox-fixnum imm0 val)
(beq cr7 @set-64) ; all fixnums are (SIGNED-BYTE 64)
(b @bad) ; as are 2-digit bignums
;; u64 if fixnum and positive, 2-digit bignum and positive, or
;; 3-digit bignum with most-significant digit 0.
@u64
(cmpdi cr2 val 0)
(unbox-fixnum imm0 val)
(bne cr7 @u64-maybe-bignum)
(bge cr2 @set-64)
(b @bad)
@u64-maybe-bignum
(bne cr5 @bad)
(ld imm0 ppc64::misc-data-offset val)
(getvheader imm1 val)
(rotldi imm0 imm0 32)
(cmpdi cr2 imm1 ppc64::two-digit-bignum-header)
(cmpdi cr3 imm1 ppc64::three-digit-bignum-header)
(cmpdi cr0 imm0 0)
(beq cr2 @u64-two-digit)
(bne cr3 @bad)
(lwz imm1 (+ 8 ppc64::misc-data-offset) val)
(cmpwi imm1 0)
(beq @set-64)
(b @bad)
@u64-two-digit
(bgt cr0 @set-64)
(b @bad)
@dfloat
(cmpdi cr0 imm0 ppc64::subtag-double-float)
(bne- cr0 @bad)
(ld imm0 ppc64::double-float.value val)
(b @set-64)
@32
(cmpdi cr3 imm2 ppc64::subtag-simple-base-string)
(cmpdi cr2 imm2 ppc64::subtag-s32-vector)
(cmpdi cr0 imm2 ppc64::subtag-single-float-vector)
(beq cr3 @char32)
(beq cr2 @s32)
(bne cr0 @u32)
;@sfloat
(cmpdi cr0 imm0 ppc64::subtag-single-float)
(srdi imm0 val 32)
(bne- cr0 @bad)
(b @set-32)
@s32
;; Must be a fixnum (and a (SIGNED-BYTE 32)).
(bne cr7 @bad)
(unbox-fixnum imm0 val)
(sldi imm1 imm0 32)
(sradi imm1 imm1 32)
(cmpd imm1 imm0)
(bne @bad)
(b @set-32)
@char32
(unbox-base-char imm0 val cr0) ; this type checks val
(b @set-32)
@u32
;; Also has to be a fixnum (and an (UNSIGNED-BYTE 32)).
(unbox-fixnum imm0 val)
(clrrdi. imm1 imm0 32) ; ~Z if any high bits set
(bne cr7 @bad)
(bne cr0 @bad)
(b @set-32)
@u16
(unbox-fixnum imm0 val)
(clrrdi. imm1 imm0 16)
(bne cr7 @bad)
(bne cr0 @bad)
(b @set-16)
@s16
(sldi imm0 val (- 64 (+ 16 ppc64::fixnumshift)))
(sradi imm0 imm0 (- 64 (+ 16 ppc64::fixnumshift)))
(cmpw cr0 imm0 val)
(unbox-fixnum imm0 val)
(bne- cr7 @bad)
(beq+ cr0 @set-16)
(b @bad)
@8
(cmpdi cr0 imm2 ppc64::subtag-s8-vector)
(beq cr0 @s8)
(extract-unsigned-byte-bits. imm0 val 8)
(unbox-fixnum imm0 val)
(beq+ cr0 @set-8)
(b @bad)
@s8
(sldi imm0 val (- 64 (+ 8 ppc64::fixnumshift)))
(sradi imm0 imm0 (- 64 (+ 8 ppc64::fixnumshift)))
(cmpd cr0 imm0 val)
(unbox-fixnum imm0 val)
(bne- cr7 @bad)
(beq+ cr0 @set-8)
(b @bad)
@char8
(unbox-base-char imm0 val cr0) ; this type checks val
@set-8 ; propagate low 8 bits into low 16
(la imm3 1 imm3)
(rlwimi imm0 imm0 8 (- 32 16) (- 31 8))
(srdi imm3 imm3 1)
@set-16 ; propagate low 16 bits into high 16
(la imm3 1 imm3)
(rlwimi imm0 imm0 16 0 (- 31 16))
(srdi imm3 imm3 1)
@set-32 ; propagate low 32 bits into high 32
(la imm3 1 imm3)
(rldimi imm0 imm0 32 0)
(srdi imm3 imm3 1)
@set-64
(cmpdi cr0 imm3 1)
(subi imm3 imm3 1)
(stdx imm0 miscobj imm4)
(la imm4 8 imm4)
(bne cr0 @set-64)
(blr))
;;; Make a new vector of size newsize whose subtag matches that of oldv-arg.
;;; Blast the contents of the old vector into the new one as quickly as
;;; possible; leave remaining elements of new vector undefined (0).
;;; Return new-vector.
#+ppc32-target
(defppclapfunction %extend-vector ((start-arg arg_x) (oldv-arg arg_y) (newsize arg_z))
(let ((oldv save0)
(oldsize save1)
(oldsubtag save2)
(start-offset save3))
(save-lisp-context)
(:regsave save3 0)
(vpush save0)
(vpush save1)
(vpush save2)
(vpush save3)
(mr oldv oldv-arg)
(mr start-offset start-arg)
(getvheader imm0 oldv)
(header-length oldsize imm0)
(header-subtag[fixnum] oldsubtag imm0)
(mr arg_y newsize)
(mr arg_z oldsubtag)
(bla .SPmisc-alloc)
(extrwi imm0 oldsubtag ppc32::ntagbits (- 32 (+ ppc32::fixnumshift ppc32::ntagbits)))
(cmpwi cr0 oldsize 0)
(cmpwi cr1 imm0 ppc32::fulltag-nodeheader)
(cmpwi cr2 oldsubtag '#.ppc32::max-32-bit-ivector-subtag)
(la imm1 ppc32::misc-data-offset start-offset)
(li imm3 ppc32::misc-data-offset)
(beq cr0 @done)
(bne cr1 @imm)
;; copy nodes. New vector is "new", so no memoization required.
@node-loop
(cmpwi cr0 oldsize '1)
(lwzx temp0 oldv imm1)
(addi imm1 imm1 4)
(subi oldsize oldsize '1)
(stwx temp0 arg_z imm3)
(addi imm3 imm3 4)
(bne cr0 @node-loop)
;;Restore registers. New vector's been in arg_z all this time.
@done
(lwz save3 0 vsp)
(lwz save2 4 vsp)
(lwz save1 8 vsp)
(lwz save0 12 vsp)
(restore-full-lisp-context)
(blr)
@imm
(unbox-fixnum imm2 oldsize)
(unbox-fixnum imm3 start-offset)
(li imm1 ppc32::misc-data-offset)
(la imm4 ppc32::misc-data-offset start-offset)
(cmpwi cr1 oldsubtag '#.ppc32::max-8-bit-ivector-subtag)
(cmpwi cr0 oldsubtag '#.ppc32::max-16-bit-ivector-subtag)
(ble cr2 @fullword-loop)
(cmpwi cr2 oldsubtag '#.ppc32::subtag-bit-vector)
(ble cr1 @8-bit)
(ble cr0 @16-bit)
(beq cr2 @1-bit)
;; 64-bit (double-float) vectors. There's a different
;; initial offset, but we're always word-aligned, so that
;; part's easy.
(li imm1 ppc32::misc-dfloat-offset) ; scaled destination pointer
(slwi imm2 imm2 1) ; twice as many fullwords
(slwi imm3 imm3 3) ; convert dword count to byte offset
(la imm4 ppc32::misc-dfloat-offset imm3) ; scaled source pointer
(b @fullword-loop)
;; The bitvector case is hard if START-OFFSET isn't on an 8-bit boundary,
;; and can be turned into the 8-bit case otherwise.
;; The 8-bit case is hard if START-OFFSET isn't on a 16-bit boundary,
;; and can be turned into the 16-bit case otherwise.
;; The 16-bit case is hard if START-OFFSET isn't on a 32-bit boundary,
;; and can be turned into the 32-bit case otherwise.
;; Hmm.
@1-bit
(clrlwi. imm0 imm3 (- 32 3))
(bne- cr0 @hard-1-bit)
(srwi imm3 imm3 3) ; bit offset to byte offset
(addi imm2 imm2 7)
(srwi imm2 imm2 3) ; bit count to byte count
@8-bit
; If the byte offset's even, copy half as many halfwords
(clrlwi. imm0 imm3 (- 32 1))
(bne- cr0 @hard-8-bit)
(addi imm2 imm2 1)
(srwi imm2 imm2 1) ; byte count to halfword count
(srwi imm3 imm3 1) ; byte offset to halfword offset
@16-bit
; If the halfword offset's even, copy half as many fullwords
(clrlwi. imm0 imm3 (- 32 1))
(bne- cr0 @hard-16-bit)
(addi imm2 imm2 1)
(srwi imm2 imm2 1) ; halfword count to fullword count
(li imm1 ppc32::misc-data-offset)
@fullword-loop
(cmpwi cr0 imm2 1)
(lwzx imm0 oldv imm4)
(addi imm4 imm4 4)
(subi imm2 imm2 1)
(stwx imm0 arg_z imm1)
(addi imm1 imm1 4)
(bne cr0 @fullword-loop)
(b @done)
;;; This can just do a uvref/uvset loop. Cases that can
;;; cons (x32, double-float) have already been dealt with.
@hard-1-bit
@hard-8-bit
@hard-16-bit
(let ((newv save4)
(outi save5)
(oldlen save6))
(vpush save4)
(vpush save5)
(vpush save6)
(mr newv arg_z)
(sub oldlen oldsize start-offset)
(li outi 0)
@hard-loop
(mr arg_y oldv)
(mr arg_z start-offset)
(bla .SPmisc-ref)
(mr arg_x newv)
(mr arg_y outi)
(bla .SPmisc-set)
(la outi '1 outi)
(cmpw cr0 outi oldlen)
(la start-offset '1 start-offset)
(bne @hard-loop)
(mr arg_z newv)
(vpop save6)
(vpop save5)
(vpop save4)
(b @done))))
#+ppc64-target
(defppclapfunction %extend-vector ((start-arg arg_x) (oldv-arg arg_y) (newsize arg_z))
(let ((oldv save0)
(oldsize save1)
(oldsubtag save2)
(start-offset save3))
(save-lisp-context)
(:regsave save3 0)
(vpush save0)
(vpush save1)
(vpush save2)
(vpush save3)
(mr oldv oldv-arg)
(mr start-offset start-arg)
(getvheader imm0 oldv)
(header-length oldsize imm0)
(header-subtag[fixnum] oldsubtag imm0)
(mr arg_y newsize)
(mr arg_z oldsubtag)
(bla .SPmisc-alloc)
(unbox-fixnum imm0 oldsubtag)
(extract-lowtag imm1 imm0)
(extract-fulltag imm2 imm0)
(cmpdi cr0 oldsize 0)
(cmpdi cr1 imm1 ppc64::lowtag-nodeheader)
(cmpdi cr2 imm2 ppc64::ivector-class-8-bit)
(cmpdi cr3 imm2 ppc64::ivector-class-32-bit)
(cmpdi cr4 imm2 ppc64::ivector-class-64-bit)
(cmpdi cr5 imm0 ppc64::subtag-bit-vector)
(li imm3 ppc64::misc-data-offset)
(beq cr0 @done)
(bne cr1 @imm)
(la imm1 ppc64::misc-data-offset start-offset)
;; copy nodes. New vector is "new", so no memoization required.
@node-loop
(cmpdi cr0 oldsize '1)
(ldx temp0 oldv imm1)
(addi imm1 imm1 8)
(subi oldsize oldsize '1)
(stdx temp0 arg_z imm3)
(addi imm3 imm3 8)
(bne cr0 @node-loop)
;;Restore registers. New vector's been in arg_z all this time.
@done
(ld save3 0 vsp)
(ld save2 8 vsp)
(ld save1 16 vsp)
(ld save0 24 vsp)
(restore-full-lisp-context)
(blr)
@imm
(beq cr2 @8-bit)
(beq cr3 @32-bit)
(beq cr4 @64-bit)
(beq cr5 @1-bit)
;;; The bit-vector case is ignored, but we should probably
;;; try to handle (VECTOR (COMPLEX DOUBLE-FLOAT)).
(srdi imm1 start-offset 2)
(la imm1 ppc64::misc-data-offset imm1)
@16-loop
(cmpdi cr0 oldsize '1)
(lhzx imm4 oldv imm1)
(addi imm1 imm1 2)
(subi oldsize oldsize '1)
(sthx imm4 arg_z imm3)
(addi imm3 imm3 2)
(bne cr0 @16-loop)
(b @done)
@8-bit
(srdi imm1 start-offset 3)
(la imm1 ppc64::misc-data-offset imm1)
@8-loop
(cmpdi cr0 oldsize '1)
(lbzx imm4 oldv imm1)
(addi imm1 imm1 1)
(subi oldsize oldsize '1)
(stbx imm4 arg_z imm3)
(addi imm3 imm3 1)
(bne cr0 @8-loop)
(b @done)
@32-bit
(srdi imm1 start-offset 1)
(la imm1 ppc64::misc-data-offset imm1)
@32-loop
(cmpdi cr0 oldsize '1)
(lwzx imm4 oldv imm1)
(addi imm1 imm1 4)
(subi oldsize oldsize '1)
(stwx imm4 arg_z imm3)
(addi imm3 imm3 4)
(bne cr0 @32-loop)
(b @done)
@64-bit
(la imm1 ppc64::misc-data-offset start-offset)
@64-loop
(cmpdi cr0 oldsize '1)
(ldx imm4 oldv imm1)
(addi imm1 imm1 8)
(subi oldsize oldsize '1)
(stdx imm4 arg_z imm3)
(addi imm3 imm3 8)
(bne cr0 @64-loop)
(b @done)
@1-bit
(let ((newv save4)
(outi save5)
(oldlen save6))
(vpush save4)
(vpush save5)
(vpush save6)
(mr newv arg_z)
(sub oldlen oldsize start-offset)
(li outi 0)
@hard-loop
(mr arg_y oldv)
(mr arg_z start-offset)
(bla .SPmisc-ref)
(mr arg_x newv)
(mr arg_y outi)
(bla .SPmisc-set)
(la outi '1 outi)
(cmpd cr0 outi oldlen)
(la start-offset '1 start-offset)
(bne @hard-loop)
(mr arg_z newv)
(vpop save6)
(vpop save5)
(vpop save4)
(b @done))))
;;; argument is a vector header or an array header. Or else.
(defppclapfunction %array-header-data-and-offset ((a arg_z))
(let ((offset arg_y)
(disp arg_x)
(temp temp0))
(li offset 0)
(mr temp a)
@loop
(ldr a target::arrayH.data-vector temp)
(lbz imm0 target::misc-subtag-offset a)
(cmpri cr0 imm0 target::subtag-vectorH)
(cmpri cr1 imm0 target::subtag-arrayH)
(ldr disp target::arrayH.displacement temp)
(mr temp a)
(add offset offset disp)
(beq cr0 @loop)
(beq cr1 @loop)
(vpush a)
(vpush offset)
(set-nargs 2)
(la temp0 (* 2 (ash 1 target::word-shift)) vsp)
(ba .SPvalues)))
;;; If the bit-arrays are all simple-bit-vectorp, we can do the operations
;;; 32 bits at a time. (other case have to worry about alignment/displacement.)
#+ppc32-target
(defppclapfunction %simple-bit-boole ((op 0) (b1 arg_x) (b2 arg_y) (result arg_z))
(la imm0 4 vsp)
(save-lisp-context imm0)
(vector-size imm4 result imm4)
(srwi. imm3 imm4 5)
(clrlwi imm4 imm4 27)
(bl @get-dispatch)
(cmpwi cr1 imm4 0)
(mflr loc-pc)
(lwz temp0 op vsp)
(add loc-pc loc-pc temp0)
(add loc-pc loc-pc temp0)
(mtctr loc-pc)
(li imm0 ppc32::misc-data-offset)
(b @testw)
@nextw
(cmpwi cr0 imm3 1)
(subi imm3 imm3 1)
(lwzx imm1 b1 imm0)
(lwzx imm2 b2 imm0)
(bctrl)
(stwx imm1 result imm0)
(addi imm0 imm0 4)
@testw
(bne cr0 @nextw)
(beq cr1 @done)
;; Not sure if we need to make this much fuss about the partial word
;; in this simple case, but what the hell.
(lwzx imm1 b1 imm0)
(lwzx imm2 b2 imm0)
(bctrl)
(lwzx imm2 result imm0)
(slw imm2 imm2 imm4)
(srw imm2 imm2 imm4)
(subfic imm4 imm4 32)
(srw imm1 imm1 imm4)
(slw imm1 imm1 imm4)
(or imm1 imm1 imm2)
(stwx imm1 result imm0)
@done
(restore-full-lisp-context)
(blr)
@get-dispatch
(blrl)
@disptach
(li imm1 0) ; boole-clr
(blr)
(li imm1 -1) ; boole-set
(blr)
(blr) ; boole-1
(blr)
(mr imm1 imm2) ; boole-2
(blr)
(not imm1 imm1) ; boole-c1
(blr)
(not imm1 imm2) ; boole-c2
(blr)
(and imm1 imm1 imm2) ; boole-and
(blr)
(or imm1 imm1 imm2) ; boole-ior
(blr)
(xor imm1 imm1 imm2) ; boole-xor
(blr)
(eqv imm1 imm1 imm2) ; boole-eqv
(blr)
(nand imm1 imm1 imm2) ; boole-nand
(blr)
(nor imm1 imm1 imm2) ; boole-nor
(blr)
(andc imm1 imm2 imm1) ; boole-andc1
(blr)
(andc imm1 imm1 imm2) ; boole-andc2
(blr)
(orc imm1 imm2 imm1) ; boole-orc1
(blr)
(orc imm1 imm1 imm2) ; boole-orc2
(blr))
#+ppc64-target
(defppclapfunction %simple-bit-boole ((op 0) (b1 arg_x) (b2 arg_y) (result arg_z))
(la imm0 8 vsp)
(save-lisp-context imm0)
(vector-size imm4 result imm4)
(srdi. imm3 imm4 6)
(clrldi imm4 imm4 (- 64 6))
(bl @get-dispatch)
(cmpdi cr1 imm4 0) ; at most low 6 bits set in imm4
(mflr loc-pc)
(ld temp0 op vsp)
(add loc-pc loc-pc temp0)
(mtctr loc-pc)
(li imm0 ppc64::misc-data-offset)
(b @testd)
@nextd
(cmpdi cr0 imm3 1)
(subi imm3 imm3 1)
(ldx imm1 b1 imm0)
(ldx imm2 b2 imm0)
(bctrl)
(stdx imm1 result imm0)
(addi imm0 imm0 8)
@testd
(bne cr0 @nextd)
(beq cr1 @done)
;; Not sure if we need to make this much fuss about the partial word
;; in this simple case, but what the hell.
(ldx imm1 b1 imm0)
(ldx imm2 b2 imm0)
(bctrl)
(ldx imm2 result imm0)
(sld imm2 imm2 imm4)
(srd imm2 imm2 imm4)
(subfic imm4 imm4 64)
(srd imm1 imm1 imm4)
(sld imm1 imm1 imm4)
(or imm1 imm1 imm2)
(stdx imm1 result imm0)
@done
(restore-full-lisp-context)
(blr)
@get-dispatch
(blrl)
@disptach
(li imm1 0) ; boole-clr
(blr)
(li imm1 -1) ; boole-set
(blr)
(blr) ; boole-1
(blr)
(mr imm1 imm2) ; boole-2
(blr)
(not imm1 imm1) ; boole-c1
(blr)
(not imm1 imm2) ; boole-c2
(blr)
(and imm1 imm1 imm2) ; boole-and
(blr)
(or imm1 imm1 imm2) ; boole-ior
(blr)
(xor imm1 imm1 imm2) ; boole-xor
(blr)
(eqv imm1 imm1 imm2) ; boole-eqv
(blr)
(nand imm1 imm1 imm2) ; boole-nand
(blr)
(nor imm1 imm1 imm2) ; boole-nor
(blr)
(andc imm1 imm2 imm1) ; boole-andc1
(blr)
(andc imm1 imm1 imm2) ; boole-andc2
(blr)
(orc imm1 imm2 imm1) ; boole-orc1
(blr)
(orc imm1 imm1 imm2) ; boole-orc2
(blr))
(defppclapfunction %aref2 ((array arg_x) (i arg_y) (j arg_z))
(check-nargs 3)
(ba .SParef2))
(defppclapfunction %aref3 ((array 0) (i arg_x) (j arg_y) (k arg_z))
(check-nargs 4)
(vpop temp0)
(ba .SParef3))
(defppclapfunction %aset2 ((array 0) (i arg_x) (j arg_y) (newval arg_z))
(check-nargs 4)
(vpop temp0)
(ba .SPaset2))
(defppclapfunction %aset3 ((array #.target::node-size) (i 0) (j arg_x) (k arg_y) (newval arg_z))
(check-nargs 5)
(vpop temp0)
(vpop temp1)
(ba .SPaset3))
| true |
;;;-*- Mode: Lisp; Package: CCL -*-
;;;
;;; Copyright 1994-2009 PI:NAME:<NAME>END_PI
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
(in-package "CCL")
(eval-when (:compile-toplevel :execute)
#+ppc32-target
(require "PPC32-ARCH")
#+ppc64-target
(require "PPC64-ARCH")
(require "PPC-LAPMACROS"))
;;; Users of this shouldn't make assumptions about return value.
#+ppc32-target
(eval-when (:compile-toplevel :execute)
;;; Assumptions made by %init-misc
(assert (and (< ppc32::max-32-bit-ivector-subtag
ppc32::max-8-bit-ivector-subtag
ppc32::max-16-bit-ivector-subtag)
(eql ppc32::max-32-bit-ivector-subtag ppc32::subtag-simple-base-string)
(eql ppc32::max-16-bit-ivector-subtag ppc32::subtag-s16-vector)
(eql ppc32::max-8-bit-ivector-subtag 207))))
#+ppc32-target
(defppclapfunction %init-misc ((val arg_y)
(miscobj arg_z))
(getvheader imm0 miscobj)
(header-size imm3 imm0)
(cmpwi cr3 imm3 0)
(extract-fulltag imm1 imm0)
(cmpwi cr0 imm1 ppc32::fulltag-nodeheader)
(extract-lowbyte imm2 imm0)
(beqlr cr3) ; Silly 0-length case
(li imm4 ppc32::misc-data-offset)
(bne cr0 @imm)
;; Node vector. Don't need to memoize, since initial value is
;; older than vector.
@node-loop
(cmpwi cr0 imm3 1)
(subi imm3 imm3 1)
(stwx val miscobj imm4)
(la imm4 4 imm4)
(bne cr0 @node-loop)
(blr)
@imm
(cmpwi cr0 imm2 ppc32::subtag-double-float-vector)
(cmpwi cr1 imm2 ppc32::max-32-bit-ivector-subtag)
(cmpwi cr2 imm2 ppc32::max-8-bit-ivector-subtag)
(cmpwi cr3 imm2 ppc32::max-16-bit-ivector-subtag)
(extract-typecode imm0 val :CR6) ; don't clobber CR0
(cmpwi cr7 imm0 ppc32::tag-fixnum)
(beq cr0 @dfloat)
(ble cr1 @32)
(ble cr2 @8)
(ble cr3 @16)
(cmpwi cr0 imm2 ppc32::subtag-bit-vector)
(cmpwi cr1 imm2 ppc32::subtag-complex-double-float-vector)
(beq cr0 @bit)
(beq cr1 @complex-double-float)
;; Complex single-float vector
(cmpwi imm0 ppc32::subtag-complex-single-float)
(bne @bad)
(lfs fp0 ppc32::complex-single-float.realpart val)
(lfs fp1 ppc32::complex-single-float.imagpart val)
(li imm4 ppc32::complex-single-float.realpart)
@complex-single-float-loop
(cmpwi cr0 imm3 1)
(subi imm3 imm3 1)
(stfsx fp0 miscobj imm4)
(la imm4 4 imm4)
(stfsx fp1 miscobj imm4)
(la imm4 4 imm4)
(bne cr0 @complex-single-float-loop)
(blr)
@complex-double-float
(cmpwi imm0 ppc32::subtag-complex-double-float)
(bne @bad)
(lfd fp0 ppc32::complex-double-float.realpart val)
(lfd fp1 ppc32::complex-double-float.imagpart val)
(li imm4 ppc32::complex-double-float.realpart)
@complex-double-float-loop
(cmpwi cr0 imm3 1)
(subi imm3 imm3 1)
(stfdx fp0 miscobj imm4)
(la imm4 8 imm4)
(stfdx fp1 miscobj imm4)
(la imm4 8 imm4)
(bne cr0 @complex-double-float-loop)
(blr)
@bit
; Bit vector.
(cmplwi cr0 val '1)
(la imm3 31 imm3)
(srwi imm3 imm3 5)
(unbox-fixnum imm0 val)
(neg imm0 imm0)
(ble+ cr0 @set-32)
@bad
(li arg_x '#.$xnotelt)
(save-lisp-context)
(set-nargs 3)
(call-symbol %err-disp)
@dfloat
(cmpwi cr0 imm0 ppc32::subtag-double-float)
(li imm4 ppc32::misc-dfloat-offset)
(bne- cr0 @bad)
(lfd fp0 ppc32::double-float.value val)
@dfloat-loop
(cmpwi cr0 imm3 1)
(subi imm3 imm3 1)
(stfdx fp0 miscobj imm4)
(la imm4 8 imm4)
(bne cr0 @dfloat-loop)
(blr)
@32
(cmpwi cr4 imm2 ppc32::subtag-s32-vector)
(cmpwi cr0 imm2 ppc32::subtag-single-float-vector)
(cmpwi cr2 imm0 ppc32::subtag-bignum)
(cmpwi cr3 imm2 ppc32::subtag-fixnum-vector)
(beq cr1 @char32) ; ppc32::max-32-bit-ivector-subtag
(beq cr4 @s32)
(beq cr3 @fixnum)
(bne cr0 @u32)
;@sfloat
(cmpwi cr0 imm0 ppc32::subtag-single-float)
(bne- cr0 @bad)
(lwz imm0 ppc32::single-float.value val)
(b @set-32)
@fixnum
(unbox-fixnum imm0 val)
(beq+ cr7 @set-32)
(b @bad)
@char32
(unbox-base-char imm0 val cr0)
(b @set-32)
@s32
(unbox-fixnum imm0 val)
(beq+ cr7 @set-32)
(bne- cr2 @bad)
(getvheader imm0 val)
(cmpwi cr0 imm0 (logior (ash 1 ppc32::num-subtag-bits) ppc32::subtag-bignum))
(lwz imm0 ppc32::misc-data-offset val)
(beq+ cr0 @set-32)
(b @bad)
@u32
(extract-unsigned-byte-bits. imm0 val 30)
(unbox-fixnum imm0 val)
(beq cr0 @set-32)
(bne- cr2 @bad)
; a one-digit bignum is ok if that digit is positive.
; a two-digit bignum is ok if the sign-digit is 0.
(getvheader imm0 val)
(cmpwi cr2 imm0 (logior (ash 2 ppc32::num-subtag-bits) ppc32::subtag-bignum))
(lwz imm0 ppc32::misc-data-offset val)
(cmpwi cr3 imm0 0)
(bgt- cr2 @bad) ; more than two digits.
(beq cr2 @two-digits)
(bgt+ cr3 @set-32)
(b @bad)
@two-digits
(lwz imm1 (+ 4 ppc32::misc-data-offset) val)
(cmpwi cr0 imm1 0)
(bne- cr0 @bad)
(b @set-32)
@16
(cmpwi cr0 imm2 ppc32::subtag-u16-vector)
(la imm3 1 imm3)
(srwi imm3 imm3 1)
(beq cr3 @s16) ; ppc32::max-16-bit-ivector-subtag
(extract-unsigned-byte-bits. imm0 val 16)
(unbox-fixnum imm0 val)
(beq+ cr0 @set-16)
(b @bad)
@s16
(slwi imm0 val (- 32 (+ 16 ppc32::fixnumshift)))
(srawi imm0 imm0 (- 32 (+ 16 ppc32::fixnumshift)))
(cmpw cr0 imm0 val)
(unbox-fixnum imm0 val)
(bne- cr7 @bad)
(beq+ cr0 @set-16)
(b @bad)
@8
(cmpwi cr0 imm2 ppc32::subtag-s8-vector)
(la imm3 3 imm3)
(srwi imm3 imm3 2)
(beq cr0 @s8)
(extract-unsigned-byte-bits. imm0 val 8)
(unbox-fixnum imm0 val)
(beq+ cr0 @set-8)
(b @bad)
@s8
(slwi imm0 val (- 32 (+ 8 ppc32::fixnumshift)))
(srawi imm0 imm0 (- 32 (+ 8 ppc32::fixnumshift)))
(cmpw cr0 imm0 val)
(unbox-fixnum imm0 val)
(bne- cr7 @bad)
(beq+ cr0 @set-8)
(b @bad)
@char8
(unbox-base-char imm0 val cr0) ; this type checks val
@set-8 ; propagate low 8 bits into low 16
(rlwimi imm0 imm0 8 (- 32 16) (- 31 8))
@set-16 ; propagate low 16 bits into high 16
(rlwimi imm0 imm0 16 0 (- 31 16))
@set-32
(cmpwi cr0 imm3 1)
(subi imm3 imm3 1)
(stwx imm0 miscobj imm4)
(la imm4 4 imm4)
(bne cr0 @set-32)
(blr))
#+ppc64-target
(defppclapfunction %init-misc ((val arg_y)
(miscobj arg_z))
(getvheader imm0 miscobj)
;(extract-lowtag imm2 imm0)
(clrldi imm2 imm0 (- 64 ppc64::nlowtagbits))
(header-size imm3 imm0)
(cmpdi cr3 imm3 0)
(extract-fulltag imm1 imm0)
(cmpdi cr0 imm2 ppc64::lowtag-nodeheader)
(extract-lowbyte imm2 imm0)
(beqlr cr3) ; Silly 0-length case
(li imm4 ppc64::misc-data-offset)
(bne cr0 @imm)
;; Node vector. Don't need to memoize, since initial value is
;; older than vector.
@node-loop
(cmpdi cr0 imm3 1)
(subi imm3 imm3 1)
(stdx val miscobj imm4)
(la imm4 ppc64::node-size imm4)
(bne cr0 @node-loop)
(blr)
@imm
(extract-typecode imm0 val)
(cmpdi cr0 imm1 ppc64::ivector-class-64-bit)
(cmpdi cr1 imm1 ppc64::ivector-class-32-bit)
(cmpdi cr2 imm1 ppc64::ivector-class-8-bit)
(cmpdi cr7 imm0 ppc64::tag-fixnum)
(cmpdi cr5 imm0 ppc64::subtag-bignum)
(cmpdi cr6 imm2 ppc64::subtag-complex-double-float-vector)
(beq cr0 @64)
(beq cr1 @32)
(beq cr2 @8)
(beq cr6 @complex-double-float)
;; u16, s16, or bit-vector. Val must be a fixnum.
(cmpdi cr0 imm2 ppc64::subtag-u16-vector)
(cmpdi cr1 imm2 ppc64::subtag-s16-vector)
(bne cr7 @bad) ; not a fixnum
(beq cr0 @u16)
(beq cr1 @s16)
; Bit vector.
(cmpldi cr0 val '1)
(la imm3 63 imm3)
(srdi imm3 imm3 6)
(unbox-fixnum imm0 val)
(neg imm0 imm0)
(ble+ cr0 @set-64)
@bad
(li arg_x '#.$xnotelt)
(save-lisp-context)
(set-nargs 3)
(call-symbol %err-disp)
@complex-double-float
(cmpdi imm0 ppc64::subtag-complex-double-float)
(bne @bad)
(lfd fp0 ppc64::complex-double-float.realpart val)
(lfd fp1 ppc64::complex-double-float.imagpart val)
(li imm4 ppc64::complex-double-float.realpart)
@complex-double-float-loop
(cmpdi cr0 imm3 1)
(subi imm3 imm3 1)
(stfdx fp0 miscobj imm4)
(la imm4 8 imm4)
(stfdx fp1 miscobj imm4)
(la imm4 8 imm4)
(bne cr0 @complex-double-float-loop)
(blr)
@64
(cmpdi cr4 imm2 ppc64::subtag-complex-single-float-vector)
(cmpdi cr3 imm2 ppc64::subtag-fixnum-vector)
(cmpdi cr1 imm2 ppc64::subtag-double-float-vector)
(cmpdi cr2 imm2 ppc64::subtag-s64-vector)
(beq cr4 @complex-single-float)
(beq cr3 @fixnum)
(beq cr1 @dfloat)
(bne cr2 @u64)
;; s64
(unbox-fixnum imm0 val)
(beq cr7 @set-64) ; all fixnums are (SIGNED-BYTE 64)
(bne cr5 @bad) ; as are 2-digit bignums
(getvheader imm1 val)
(ld imm0 ppc64::misc-data-offset val)
(cmpdi imm1 ppc64::two-digit-bignum-header)
(rotldi imm0 imm0 32)
(beq @set-64)
(b @bad)
@complex-single-float
(cmpdi imm0 ppc64::subtag-complex-single-float)
(bne @bad)
(ld imm0 ppc64::complex-single-float.realpart val)
(b @set-64)
@fixnum
(unbox-fixnum imm0 val)
(beq cr7 @set-64) ; all fixnums are (SIGNED-BYTE 64)
(b @bad) ; as are 2-digit bignums
;; u64 if fixnum and positive, 2-digit bignum and positive, or
;; 3-digit bignum with most-significant digit 0.
@u64
(cmpdi cr2 val 0)
(unbox-fixnum imm0 val)
(bne cr7 @u64-maybe-bignum)
(bge cr2 @set-64)
(b @bad)
@u64-maybe-bignum
(bne cr5 @bad)
(ld imm0 ppc64::misc-data-offset val)
(getvheader imm1 val)
(rotldi imm0 imm0 32)
(cmpdi cr2 imm1 ppc64::two-digit-bignum-header)
(cmpdi cr3 imm1 ppc64::three-digit-bignum-header)
(cmpdi cr0 imm0 0)
(beq cr2 @u64-two-digit)
(bne cr3 @bad)
(lwz imm1 (+ 8 ppc64::misc-data-offset) val)
(cmpwi imm1 0)
(beq @set-64)
(b @bad)
@u64-two-digit
(bgt cr0 @set-64)
(b @bad)
@dfloat
(cmpdi cr0 imm0 ppc64::subtag-double-float)
(bne- cr0 @bad)
(ld imm0 ppc64::double-float.value val)
(b @set-64)
@32
(cmpdi cr3 imm2 ppc64::subtag-simple-base-string)
(cmpdi cr2 imm2 ppc64::subtag-s32-vector)
(cmpdi cr0 imm2 ppc64::subtag-single-float-vector)
(beq cr3 @char32)
(beq cr2 @s32)
(bne cr0 @u32)
;@sfloat
(cmpdi cr0 imm0 ppc64::subtag-single-float)
(srdi imm0 val 32)
(bne- cr0 @bad)
(b @set-32)
@s32
;; Must be a fixnum (and a (SIGNED-BYTE 32)).
(bne cr7 @bad)
(unbox-fixnum imm0 val)
(sldi imm1 imm0 32)
(sradi imm1 imm1 32)
(cmpd imm1 imm0)
(bne @bad)
(b @set-32)
@char32
(unbox-base-char imm0 val cr0) ; this type checks val
(b @set-32)
@u32
;; Also has to be a fixnum (and an (UNSIGNED-BYTE 32)).
(unbox-fixnum imm0 val)
(clrrdi. imm1 imm0 32) ; ~Z if any high bits set
(bne cr7 @bad)
(bne cr0 @bad)
(b @set-32)
@u16
(unbox-fixnum imm0 val)
(clrrdi. imm1 imm0 16)
(bne cr7 @bad)
(bne cr0 @bad)
(b @set-16)
@s16
(sldi imm0 val (- 64 (+ 16 ppc64::fixnumshift)))
(sradi imm0 imm0 (- 64 (+ 16 ppc64::fixnumshift)))
(cmpw cr0 imm0 val)
(unbox-fixnum imm0 val)
(bne- cr7 @bad)
(beq+ cr0 @set-16)
(b @bad)
@8
(cmpdi cr0 imm2 ppc64::subtag-s8-vector)
(beq cr0 @s8)
(extract-unsigned-byte-bits. imm0 val 8)
(unbox-fixnum imm0 val)
(beq+ cr0 @set-8)
(b @bad)
@s8
(sldi imm0 val (- 64 (+ 8 ppc64::fixnumshift)))
(sradi imm0 imm0 (- 64 (+ 8 ppc64::fixnumshift)))
(cmpd cr0 imm0 val)
(unbox-fixnum imm0 val)
(bne- cr7 @bad)
(beq+ cr0 @set-8)
(b @bad)
@char8
(unbox-base-char imm0 val cr0) ; this type checks val
@set-8 ; propagate low 8 bits into low 16
(la imm3 1 imm3)
(rlwimi imm0 imm0 8 (- 32 16) (- 31 8))
(srdi imm3 imm3 1)
@set-16 ; propagate low 16 bits into high 16
(la imm3 1 imm3)
(rlwimi imm0 imm0 16 0 (- 31 16))
(srdi imm3 imm3 1)
@set-32 ; propagate low 32 bits into high 32
(la imm3 1 imm3)
(rldimi imm0 imm0 32 0)
(srdi imm3 imm3 1)
@set-64
(cmpdi cr0 imm3 1)
(subi imm3 imm3 1)
(stdx imm0 miscobj imm4)
(la imm4 8 imm4)
(bne cr0 @set-64)
(blr))
;;; Make a new vector of size newsize whose subtag matches that of oldv-arg.
;;; Blast the contents of the old vector into the new one as quickly as
;;; possible; leave remaining elements of new vector undefined (0).
;;; Return new-vector.
#+ppc32-target
(defppclapfunction %extend-vector ((start-arg arg_x) (oldv-arg arg_y) (newsize arg_z))
(let ((oldv save0)
(oldsize save1)
(oldsubtag save2)
(start-offset save3))
(save-lisp-context)
(:regsave save3 0)
(vpush save0)
(vpush save1)
(vpush save2)
(vpush save3)
(mr oldv oldv-arg)
(mr start-offset start-arg)
(getvheader imm0 oldv)
(header-length oldsize imm0)
(header-subtag[fixnum] oldsubtag imm0)
(mr arg_y newsize)
(mr arg_z oldsubtag)
(bla .SPmisc-alloc)
(extrwi imm0 oldsubtag ppc32::ntagbits (- 32 (+ ppc32::fixnumshift ppc32::ntagbits)))
(cmpwi cr0 oldsize 0)
(cmpwi cr1 imm0 ppc32::fulltag-nodeheader)
(cmpwi cr2 oldsubtag '#.ppc32::max-32-bit-ivector-subtag)
(la imm1 ppc32::misc-data-offset start-offset)
(li imm3 ppc32::misc-data-offset)
(beq cr0 @done)
(bne cr1 @imm)
;; copy nodes. New vector is "new", so no memoization required.
@node-loop
(cmpwi cr0 oldsize '1)
(lwzx temp0 oldv imm1)
(addi imm1 imm1 4)
(subi oldsize oldsize '1)
(stwx temp0 arg_z imm3)
(addi imm3 imm3 4)
(bne cr0 @node-loop)
;;Restore registers. New vector's been in arg_z all this time.
@done
(lwz save3 0 vsp)
(lwz save2 4 vsp)
(lwz save1 8 vsp)
(lwz save0 12 vsp)
(restore-full-lisp-context)
(blr)
@imm
(unbox-fixnum imm2 oldsize)
(unbox-fixnum imm3 start-offset)
(li imm1 ppc32::misc-data-offset)
(la imm4 ppc32::misc-data-offset start-offset)
(cmpwi cr1 oldsubtag '#.ppc32::max-8-bit-ivector-subtag)
(cmpwi cr0 oldsubtag '#.ppc32::max-16-bit-ivector-subtag)
(ble cr2 @fullword-loop)
(cmpwi cr2 oldsubtag '#.ppc32::subtag-bit-vector)
(ble cr1 @8-bit)
(ble cr0 @16-bit)
(beq cr2 @1-bit)
;; 64-bit (double-float) vectors. There's a different
;; initial offset, but we're always word-aligned, so that
;; part's easy.
(li imm1 ppc32::misc-dfloat-offset) ; scaled destination pointer
(slwi imm2 imm2 1) ; twice as many fullwords
(slwi imm3 imm3 3) ; convert dword count to byte offset
(la imm4 ppc32::misc-dfloat-offset imm3) ; scaled source pointer
(b @fullword-loop)
;; The bitvector case is hard if START-OFFSET isn't on an 8-bit boundary,
;; and can be turned into the 8-bit case otherwise.
;; The 8-bit case is hard if START-OFFSET isn't on a 16-bit boundary,
;; and can be turned into the 16-bit case otherwise.
;; The 16-bit case is hard if START-OFFSET isn't on a 32-bit boundary,
;; and can be turned into the 32-bit case otherwise.
;; Hmm.
@1-bit
(clrlwi. imm0 imm3 (- 32 3))
(bne- cr0 @hard-1-bit)
(srwi imm3 imm3 3) ; bit offset to byte offset
(addi imm2 imm2 7)
(srwi imm2 imm2 3) ; bit count to byte count
@8-bit
; If the byte offset's even, copy half as many halfwords
(clrlwi. imm0 imm3 (- 32 1))
(bne- cr0 @hard-8-bit)
(addi imm2 imm2 1)
(srwi imm2 imm2 1) ; byte count to halfword count
(srwi imm3 imm3 1) ; byte offset to halfword offset
@16-bit
; If the halfword offset's even, copy half as many fullwords
(clrlwi. imm0 imm3 (- 32 1))
(bne- cr0 @hard-16-bit)
(addi imm2 imm2 1)
(srwi imm2 imm2 1) ; halfword count to fullword count
(li imm1 ppc32::misc-data-offset)
@fullword-loop
(cmpwi cr0 imm2 1)
(lwzx imm0 oldv imm4)
(addi imm4 imm4 4)
(subi imm2 imm2 1)
(stwx imm0 arg_z imm1)
(addi imm1 imm1 4)
(bne cr0 @fullword-loop)
(b @done)
;;; This can just do a uvref/uvset loop. Cases that can
;;; cons (x32, double-float) have already been dealt with.
@hard-1-bit
@hard-8-bit
@hard-16-bit
(let ((newv save4)
(outi save5)
(oldlen save6))
(vpush save4)
(vpush save5)
(vpush save6)
(mr newv arg_z)
(sub oldlen oldsize start-offset)
(li outi 0)
@hard-loop
(mr arg_y oldv)
(mr arg_z start-offset)
(bla .SPmisc-ref)
(mr arg_x newv)
(mr arg_y outi)
(bla .SPmisc-set)
(la outi '1 outi)
(cmpw cr0 outi oldlen)
(la start-offset '1 start-offset)
(bne @hard-loop)
(mr arg_z newv)
(vpop save6)
(vpop save5)
(vpop save4)
(b @done))))
#+ppc64-target
(defppclapfunction %extend-vector ((start-arg arg_x) (oldv-arg arg_y) (newsize arg_z))
(let ((oldv save0)
(oldsize save1)
(oldsubtag save2)
(start-offset save3))
(save-lisp-context)
(:regsave save3 0)
(vpush save0)
(vpush save1)
(vpush save2)
(vpush save3)
(mr oldv oldv-arg)
(mr start-offset start-arg)
(getvheader imm0 oldv)
(header-length oldsize imm0)
(header-subtag[fixnum] oldsubtag imm0)
(mr arg_y newsize)
(mr arg_z oldsubtag)
(bla .SPmisc-alloc)
(unbox-fixnum imm0 oldsubtag)
(extract-lowtag imm1 imm0)
(extract-fulltag imm2 imm0)
(cmpdi cr0 oldsize 0)
(cmpdi cr1 imm1 ppc64::lowtag-nodeheader)
(cmpdi cr2 imm2 ppc64::ivector-class-8-bit)
(cmpdi cr3 imm2 ppc64::ivector-class-32-bit)
(cmpdi cr4 imm2 ppc64::ivector-class-64-bit)
(cmpdi cr5 imm0 ppc64::subtag-bit-vector)
(li imm3 ppc64::misc-data-offset)
(beq cr0 @done)
(bne cr1 @imm)
(la imm1 ppc64::misc-data-offset start-offset)
;; copy nodes. New vector is "new", so no memoization required.
@node-loop
(cmpdi cr0 oldsize '1)
(ldx temp0 oldv imm1)
(addi imm1 imm1 8)
(subi oldsize oldsize '1)
(stdx temp0 arg_z imm3)
(addi imm3 imm3 8)
(bne cr0 @node-loop)
;;Restore registers. New vector's been in arg_z all this time.
@done
(ld save3 0 vsp)
(ld save2 8 vsp)
(ld save1 16 vsp)
(ld save0 24 vsp)
(restore-full-lisp-context)
(blr)
@imm
(beq cr2 @8-bit)
(beq cr3 @32-bit)
(beq cr4 @64-bit)
(beq cr5 @1-bit)
;;; The bit-vector case is ignored, but we should probably
;;; try to handle (VECTOR (COMPLEX DOUBLE-FLOAT)).
(srdi imm1 start-offset 2)
(la imm1 ppc64::misc-data-offset imm1)
@16-loop
(cmpdi cr0 oldsize '1)
(lhzx imm4 oldv imm1)
(addi imm1 imm1 2)
(subi oldsize oldsize '1)
(sthx imm4 arg_z imm3)
(addi imm3 imm3 2)
(bne cr0 @16-loop)
(b @done)
@8-bit
(srdi imm1 start-offset 3)
(la imm1 ppc64::misc-data-offset imm1)
@8-loop
(cmpdi cr0 oldsize '1)
(lbzx imm4 oldv imm1)
(addi imm1 imm1 1)
(subi oldsize oldsize '1)
(stbx imm4 arg_z imm3)
(addi imm3 imm3 1)
(bne cr0 @8-loop)
(b @done)
@32-bit
(srdi imm1 start-offset 1)
(la imm1 ppc64::misc-data-offset imm1)
@32-loop
(cmpdi cr0 oldsize '1)
(lwzx imm4 oldv imm1)
(addi imm1 imm1 4)
(subi oldsize oldsize '1)
(stwx imm4 arg_z imm3)
(addi imm3 imm3 4)
(bne cr0 @32-loop)
(b @done)
@64-bit
(la imm1 ppc64::misc-data-offset start-offset)
@64-loop
(cmpdi cr0 oldsize '1)
(ldx imm4 oldv imm1)
(addi imm1 imm1 8)
(subi oldsize oldsize '1)
(stdx imm4 arg_z imm3)
(addi imm3 imm3 8)
(bne cr0 @64-loop)
(b @done)
@1-bit
(let ((newv save4)
(outi save5)
(oldlen save6))
(vpush save4)
(vpush save5)
(vpush save6)
(mr newv arg_z)
(sub oldlen oldsize start-offset)
(li outi 0)
@hard-loop
(mr arg_y oldv)
(mr arg_z start-offset)
(bla .SPmisc-ref)
(mr arg_x newv)
(mr arg_y outi)
(bla .SPmisc-set)
(la outi '1 outi)
(cmpd cr0 outi oldlen)
(la start-offset '1 start-offset)
(bne @hard-loop)
(mr arg_z newv)
(vpop save6)
(vpop save5)
(vpop save4)
(b @done))))
;;; argument is a vector header or an array header. Or else.
(defppclapfunction %array-header-data-and-offset ((a arg_z))
(let ((offset arg_y)
(disp arg_x)
(temp temp0))
(li offset 0)
(mr temp a)
@loop
(ldr a target::arrayH.data-vector temp)
(lbz imm0 target::misc-subtag-offset a)
(cmpri cr0 imm0 target::subtag-vectorH)
(cmpri cr1 imm0 target::subtag-arrayH)
(ldr disp target::arrayH.displacement temp)
(mr temp a)
(add offset offset disp)
(beq cr0 @loop)
(beq cr1 @loop)
(vpush a)
(vpush offset)
(set-nargs 2)
(la temp0 (* 2 (ash 1 target::word-shift)) vsp)
(ba .SPvalues)))
;;; If the bit-arrays are all simple-bit-vectorp, we can do the operations
;;; 32 bits at a time. (other case have to worry about alignment/displacement.)
#+ppc32-target
(defppclapfunction %simple-bit-boole ((op 0) (b1 arg_x) (b2 arg_y) (result arg_z))
(la imm0 4 vsp)
(save-lisp-context imm0)
(vector-size imm4 result imm4)
(srwi. imm3 imm4 5)
(clrlwi imm4 imm4 27)
(bl @get-dispatch)
(cmpwi cr1 imm4 0)
(mflr loc-pc)
(lwz temp0 op vsp)
(add loc-pc loc-pc temp0)
(add loc-pc loc-pc temp0)
(mtctr loc-pc)
(li imm0 ppc32::misc-data-offset)
(b @testw)
@nextw
(cmpwi cr0 imm3 1)
(subi imm3 imm3 1)
(lwzx imm1 b1 imm0)
(lwzx imm2 b2 imm0)
(bctrl)
(stwx imm1 result imm0)
(addi imm0 imm0 4)
@testw
(bne cr0 @nextw)
(beq cr1 @done)
;; Not sure if we need to make this much fuss about the partial word
;; in this simple case, but what the hell.
(lwzx imm1 b1 imm0)
(lwzx imm2 b2 imm0)
(bctrl)
(lwzx imm2 result imm0)
(slw imm2 imm2 imm4)
(srw imm2 imm2 imm4)
(subfic imm4 imm4 32)
(srw imm1 imm1 imm4)
(slw imm1 imm1 imm4)
(or imm1 imm1 imm2)
(stwx imm1 result imm0)
@done
(restore-full-lisp-context)
(blr)
@get-dispatch
(blrl)
@disptach
(li imm1 0) ; boole-clr
(blr)
(li imm1 -1) ; boole-set
(blr)
(blr) ; boole-1
(blr)
(mr imm1 imm2) ; boole-2
(blr)
(not imm1 imm1) ; boole-c1
(blr)
(not imm1 imm2) ; boole-c2
(blr)
(and imm1 imm1 imm2) ; boole-and
(blr)
(or imm1 imm1 imm2) ; boole-ior
(blr)
(xor imm1 imm1 imm2) ; boole-xor
(blr)
(eqv imm1 imm1 imm2) ; boole-eqv
(blr)
(nand imm1 imm1 imm2) ; boole-nand
(blr)
(nor imm1 imm1 imm2) ; boole-nor
(blr)
(andc imm1 imm2 imm1) ; boole-andc1
(blr)
(andc imm1 imm1 imm2) ; boole-andc2
(blr)
(orc imm1 imm2 imm1) ; boole-orc1
(blr)
(orc imm1 imm1 imm2) ; boole-orc2
(blr))
#+ppc64-target
(defppclapfunction %simple-bit-boole ((op 0) (b1 arg_x) (b2 arg_y) (result arg_z))
(la imm0 8 vsp)
(save-lisp-context imm0)
(vector-size imm4 result imm4)
(srdi. imm3 imm4 6)
(clrldi imm4 imm4 (- 64 6))
(bl @get-dispatch)
(cmpdi cr1 imm4 0) ; at most low 6 bits set in imm4
(mflr loc-pc)
(ld temp0 op vsp)
(add loc-pc loc-pc temp0)
(mtctr loc-pc)
(li imm0 ppc64::misc-data-offset)
(b @testd)
@nextd
(cmpdi cr0 imm3 1)
(subi imm3 imm3 1)
(ldx imm1 b1 imm0)
(ldx imm2 b2 imm0)
(bctrl)
(stdx imm1 result imm0)
(addi imm0 imm0 8)
@testd
(bne cr0 @nextd)
(beq cr1 @done)
;; Not sure if we need to make this much fuss about the partial word
;; in this simple case, but what the hell.
(ldx imm1 b1 imm0)
(ldx imm2 b2 imm0)
(bctrl)
(ldx imm2 result imm0)
(sld imm2 imm2 imm4)
(srd imm2 imm2 imm4)
(subfic imm4 imm4 64)
(srd imm1 imm1 imm4)
(sld imm1 imm1 imm4)
(or imm1 imm1 imm2)
(stdx imm1 result imm0)
@done
(restore-full-lisp-context)
(blr)
@get-dispatch
(blrl)
@disptach
(li imm1 0) ; boole-clr
(blr)
(li imm1 -1) ; boole-set
(blr)
(blr) ; boole-1
(blr)
(mr imm1 imm2) ; boole-2
(blr)
(not imm1 imm1) ; boole-c1
(blr)
(not imm1 imm2) ; boole-c2
(blr)
(and imm1 imm1 imm2) ; boole-and
(blr)
(or imm1 imm1 imm2) ; boole-ior
(blr)
(xor imm1 imm1 imm2) ; boole-xor
(blr)
(eqv imm1 imm1 imm2) ; boole-eqv
(blr)
(nand imm1 imm1 imm2) ; boole-nand
(blr)
(nor imm1 imm1 imm2) ; boole-nor
(blr)
(andc imm1 imm2 imm1) ; boole-andc1
(blr)
(andc imm1 imm1 imm2) ; boole-andc2
(blr)
(orc imm1 imm2 imm1) ; boole-orc1
(blr)
(orc imm1 imm1 imm2) ; boole-orc2
(blr))
(defppclapfunction %aref2 ((array arg_x) (i arg_y) (j arg_z))
(check-nargs 3)
(ba .SParef2))
(defppclapfunction %aref3 ((array 0) (i arg_x) (j arg_y) (k arg_z))
(check-nargs 4)
(vpop temp0)
(ba .SParef3))
(defppclapfunction %aset2 ((array 0) (i arg_x) (j arg_y) (newval arg_z))
(check-nargs 4)
(vpop temp0)
(ba .SPaset2))
(defppclapfunction %aset3 ((array #.target::node-size) (i 0) (j arg_x) (k arg_y) (newval arg_z))
(check-nargs 5)
(vpop temp0)
(vpop temp1)
(ba .SPaset3))
|
[
{
"context": "\n(defsystem lack-util\n :version \"0.1\"\n :author \"Eitaro Fukamachi\"\n :license \"LLGPL\"\n :depends-on (:ironclad)\n :",
"end": 163,
"score": 0.9998773336410522,
"start": 147,
"tag": "NAME",
"value": "Eitaro Fukamachi"
}
] |
bundle-libs/software/lack-20190521-git/lack-util.asd
|
dbym4820/photon
| 4 |
(in-package :cl-user)
(defpackage :lack-util-asd
(:use :cl :asdf))
(in-package :lack-util-asd)
(defsystem lack-util
:version "0.1"
:author "Eitaro Fukamachi"
:license "LLGPL"
:depends-on (:ironclad)
:components ((:file "src/util"))
:in-order-to ((test-op (test-op t-lack-util))))
|
90946
|
(in-package :cl-user)
(defpackage :lack-util-asd
(:use :cl :asdf))
(in-package :lack-util-asd)
(defsystem lack-util
:version "0.1"
:author "<NAME>"
:license "LLGPL"
:depends-on (:ironclad)
:components ((:file "src/util"))
:in-order-to ((test-op (test-op t-lack-util))))
| true |
(in-package :cl-user)
(defpackage :lack-util-asd
(:use :cl :asdf))
(in-package :lack-util-asd)
(defsystem lack-util
:version "0.1"
:author "PI:NAME:<NAME>END_PI"
:license "LLGPL"
:depends-on (:ironclad)
:components ((:file "src/util"))
:in-order-to ((test-op (test-op t-lack-util))))
|
[
{
"context": "he LICENSE file distributed with ACL2.\n;\n; Author: Alessandro Coglio ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 191,
"score": 0.9998753070831299,
"start": 174,
"tag": "NAME",
"value": "Alessandro Coglio"
},
{
"context": "ributed with ACL2.\n;\n; Author: Alessandro Coglio ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 211,
"score": 0.999930202960968,
"start": 193,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/kestrel/java/language/primitive-conversions.lisp
|
mayankmanj/acl2
| 305 |
; Java Library
;
; Copyright (C) 2020 Kestrel Institute (http://www.kestrel.edu)
;
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;
; Author: Alessandro Coglio ([email protected])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "JAVA")
(include-book "primitive-values")
(include-book "primitive-function-macros")
(include-book "kestrel/fty/sbyte8-ihs-theorems" :dir :system)
(include-book "kestrel/fty/sbyte16-ihs-theorems" :dir :system)
(include-book "kestrel/fty/sbyte32-ihs-theorems" :dir :system)
(include-book "kestrel/fty/ubyte16-ihs-theorems" :dir :system)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local (in-theory (disable logext loghead)))
(defrulel sbyte16p-when-sbyte8p
(implies (sbyte8p x)
(sbyte16p x))
:enable (sbyte8p sbyte16p))
(defrulel sbyte32p-when-sbyte16p
(implies (sbyte16p x)
(sbyte32p x))
:enable (sbyte16p sbyte32p))
(defrulel sbyte64p-when-sbyte32p
(implies (sbyte32p x)
(sbyte64p x))
:enable (sbyte32p sbyte64p))
(defrulel sbyte32p-when-ubyte16p
(implies (ubyte16p x)
(sbyte32p x))
:enable (ubyte16p sbyte32p))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc+ primitive-conversions
:parents (semantics)
:short "Java primitive conversions [JLS:5.1.2-4]."
:long
(xdoc::topstring
(xdoc::p
"We formalize the Java primitive conversions between integral types.
We also provide abstract notions of
the Java primitive conversions that involve floating-point values,
as a placeholder for a more precise formalization of them."))
:order-subtopics t
:default-parent t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc+ primitive-widening-conversions
:parents (primitive-conversions)
:short "Java primitive widening conversions [JLS:5.1.2]."
:order-subtopics t
:default-parent t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary byte-to-short
:in-type (primitive-type-byte)
:out-type (primitive-type-short)
:operation x
:short "Widening conversion from @('byte') to @('short') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary byte-to-int
:in-type (primitive-type-byte)
:out-type (primitive-type-int)
:operation x
:short "Widening conversion from @('byte') to @('int') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary byte-to-long
:in-type (primitive-type-byte)
:out-type (primitive-type-long)
:operation x
:short "Widening conversion from @('byte') to @('long') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary byte-to-float
:in-type (primitive-type-byte)
:out-type (primitive-type-float)
:operation (byte-to-float-abs x)
:short "Widening conversion from @('byte') to @('float') [JLS:5.1.2].")
(in-theory (disable (:e byte-to-float)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary byte-to-double
:in-type (primitive-type-byte)
:out-type (primitive-type-double)
:operation (byte-to-double-abs x)
:short "Widening conversion from @('byte') to @('double') [JLS:5.1.2].")
(in-theory (disable (:e byte-to-double)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary short-to-int
:in-type (primitive-type-short)
:out-type (primitive-type-int)
:operation x
:short "Widening conversion from @('short') to @('int') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary short-to-long
:in-type (primitive-type-short)
:out-type (primitive-type-long)
:operation x
:short "Widening conversion from @('short') to @('long') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary short-to-float
:in-type (primitive-type-short)
:out-type (primitive-type-float)
:operation (short-to-float-abs x)
:short "Widening conversion from @('short') to @('float') [JLS:5.1.2].")
(in-theory (disable (:e short-to-float)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary short-to-double
:in-type (primitive-type-short)
:out-type (primitive-type-double)
:operation (short-to-double-abs x)
:short "Widening conversion from @('short') to @('double') [JLS:5.1.2].")
(in-theory (disable (:e short-to-double)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary char-to-int
:in-type (primitive-type-char)
:out-type (primitive-type-int)
:operation x
:short "Widening conversion from @('char') to @('int') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary char-to-long
:in-type (primitive-type-char)
:out-type (primitive-type-long)
:operation x
:short "Widening conversion from @('char') to @('long') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary char-to-float
:in-type (primitive-type-char)
:out-type (primitive-type-float)
:operation (char-to-float-abs x)
:short "Widening conversion from @('char') to @('float') [JLS:5.1.2].")
(in-theory (disable (:e char-to-float)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary char-to-double
:in-type (primitive-type-char)
:out-type (primitive-type-double)
:operation (char-to-double-abs x)
:short "Widening conversion from @('char') to @('double') [JLS:5.1.2].")
(in-theory (disable (:e char-to-double)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary int-to-long
:in-type (primitive-type-int)
:out-type (primitive-type-long)
:operation x
:short "Widening conversion from @('int') to @('long') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary int-to-float
:in-type (primitive-type-int)
:out-type (primitive-type-float)
:operation (int-to-float-abs x)
:short "Widening conversion from @('int') to @('float') [JLS:5.1.2].")
(in-theory (disable (:e int-to-float)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary int-to-double
:in-type (primitive-type-int)
:out-type (primitive-type-double)
:operation (int-to-double-abs x)
:short "Widening conversion from @('int') to @('double') [JLS:5.1.2].")
(in-theory (disable (:e int-to-double)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary long-to-float
:in-type (primitive-type-long)
:out-type (primitive-type-float)
:operation (long-to-float-abs x)
:short "Widening conversion from @('long') to @('float') [JLS:5.1.2].")
(in-theory (disable (:e long-to-float)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary long-to-double
:in-type (primitive-type-long)
:out-type (primitive-type-double)
:operation (long-to-double-abs x)
:short "Widening conversion from @('long') to @('double') [JLS:5.1.2].")
(in-theory (disable (:e long-to-double)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary float-to-double
:in-type (primitive-type-float)
:out-type (primitive-type-double)
:operation (float-to-double-abs x)
:short "Widening conversion from @('float') to @('double') [JLS:5.1.2].")
(in-theory (disable (:e float-to-double)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc+ primitive-narrowing-conversions
:parents (primitive-conversions)
:short "Java primitive narrowing conversions [JLS:5.1.3]."
:order-subtopics t
:default-parent t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary short-to-byte
:in-type (primitive-type-short)
:out-type (primitive-type-byte)
:operation (logext 8 x)
:short "Narrowing conversion from @('short') to @('byte') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary short-to-char
:in-type (primitive-type-short)
:out-type (primitive-type-char)
:operation (loghead 16 x)
:short "Narrowing conversion from @('short') to @('char') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary char-to-byte
:in-type (primitive-type-char)
:out-type (primitive-type-byte)
:operation (logext 8 x)
:short "Narrowing conversion from @('char') to @('byte') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary char-to-short
:in-type (primitive-type-char)
:out-type (primitive-type-short)
:operation (logext 16 x)
:short "Narrowing conversion from @('char') to @('short') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary int-to-byte
:in-type (primitive-type-int)
:out-type (primitive-type-byte)
:operation (logext 8 x)
:short "Narrowing conversion from @('int') to @('byte') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary int-to-short
:in-type (primitive-type-int)
:out-type (primitive-type-short)
:operation (logext 16 x)
:short "Narrowing conversion from @('int') to @('short') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary int-to-char
:in-type (primitive-type-int)
:out-type (primitive-type-char)
:operation (loghead 16 x)
:short "Narrowing conversion from @('int') to @('char') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary long-to-byte
:in-type (primitive-type-long)
:out-type (primitive-type-byte)
:operation (logext 8 x)
:short "Narrowing conversion from @('long') to @('byte') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary long-to-short
:in-type (primitive-type-long)
:out-type (primitive-type-short)
:operation (logext 16 x)
:short "Narrowing conversion from @('long') to @('short') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary long-to-char
:in-type (primitive-type-long)
:out-type (primitive-type-char)
:operation (loghead 16 x)
:short "Narrowing conversion from @('long') to @('char') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary long-to-int
:in-type (primitive-type-long)
:out-type (primitive-type-int)
:operation (logext 32 x)
:short "Narrowing conversion from @('long') to @('int') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary float-to-byte
:in-type (primitive-type-float)
:out-type (primitive-type-byte)
:operation (float-to-byte-abs x)
:short "Narrowing conversion from @('float') to @('byte') [JLS:5.1.3].")
(in-theory (disable (:e float-to-byte)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary float-to-short
:in-type (primitive-type-float)
:out-type (primitive-type-short)
:operation (float-to-short-abs x)
:short "Narrowing conversion from @('float') to @('short') [JLS:5.1.3].")
(in-theory (disable (:e float-to-short)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary float-to-char
:in-type (primitive-type-float)
:out-type (primitive-type-char)
:operation (float-to-char-abs x)
:short "Narrowing conversion from @('float') to @('char') [JLS:5.1.3].")
(in-theory (disable (:e float-to-char)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary float-to-int
:in-type (primitive-type-float)
:out-type (primitive-type-int)
:operation (float-to-int-abs x)
:short "Narrowing conversion from @('float') to @('int') [JLS:5.1.3].")
(in-theory (disable (:e float-to-int)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary float-to-long
:in-type (primitive-type-float)
:out-type (primitive-type-long)
:operation (float-to-long-abs x)
:short "Narrowing conversion from @('float') to @('long') [JLS:5.1.3].")
(in-theory (disable (:e float-to-long)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary double-to-byte
:in-type (primitive-type-double)
:out-type (primitive-type-byte)
:operation (double-to-byte-abs x)
:short "Narrowing conversion from @('double') to @('byte') [JLS:5.1.3].")
(in-theory (disable (:e double-to-byte)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary double-to-short
:in-type (primitive-type-double)
:out-type (primitive-type-short)
:operation (double-to-short-abs x)
:short "Narrowing conversion from @('double') to @('short') [JLS:5.1.3].")
(in-theory (disable (:e double-to-short)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary double-to-char
:in-type (primitive-type-double)
:out-type (primitive-type-char)
:operation (double-to-char-abs x)
:short "Narrowing conversion from @('double') to @('char') [JLS:5.1.3].")
(in-theory (disable (:e double-to-char)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary double-to-int
:in-type (primitive-type-double)
:out-type (primitive-type-int)
:operation (double-to-int-abs x)
:short "Narrowing conversion from @('double') to @('int') [JLS:5.1.3].")
(in-theory (disable (:e double-to-int)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary double-to-long
:in-type (primitive-type-double)
:out-type (primitive-type-long)
:operation (double-to-long-abs x)
:short "Narrowing conversion from @('double') to @('long') [JLS:5.1.3].")
(in-theory (disable (:e double-to-long)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary double-to-float
:in-type (primitive-type-double)
:out-type (primitive-type-float)
:operation (double-to-float-abs x)
:short "Narrowing conversion from @('double') to @('float') [JLS:5.1.3].")
(in-theory (disable (:e double-to-float)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc+ primitive-widening-narrowing-conversions
:parents (primitive-conversions)
:short "Java primitive widening and narrowing conversions [JLS:5.1.4]."
:order-subtopics t
:default-parent t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary byte-to-char
:in-type (primitive-type-byte)
:out-type (primitive-type-char)
:operation (loghead 16 x)
:short "Widening and narrowing conversion
from @('byte') to @('char') [JLS:5.1.4].")
|
96125
|
; Java Library
;
; Copyright (C) 2020 Kestrel Institute (http://www.kestrel.edu)
;
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;
; Author: <NAME> (<EMAIL>)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "JAVA")
(include-book "primitive-values")
(include-book "primitive-function-macros")
(include-book "kestrel/fty/sbyte8-ihs-theorems" :dir :system)
(include-book "kestrel/fty/sbyte16-ihs-theorems" :dir :system)
(include-book "kestrel/fty/sbyte32-ihs-theorems" :dir :system)
(include-book "kestrel/fty/ubyte16-ihs-theorems" :dir :system)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local (in-theory (disable logext loghead)))
(defrulel sbyte16p-when-sbyte8p
(implies (sbyte8p x)
(sbyte16p x))
:enable (sbyte8p sbyte16p))
(defrulel sbyte32p-when-sbyte16p
(implies (sbyte16p x)
(sbyte32p x))
:enable (sbyte16p sbyte32p))
(defrulel sbyte64p-when-sbyte32p
(implies (sbyte32p x)
(sbyte64p x))
:enable (sbyte32p sbyte64p))
(defrulel sbyte32p-when-ubyte16p
(implies (ubyte16p x)
(sbyte32p x))
:enable (ubyte16p sbyte32p))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc+ primitive-conversions
:parents (semantics)
:short "Java primitive conversions [JLS:5.1.2-4]."
:long
(xdoc::topstring
(xdoc::p
"We formalize the Java primitive conversions between integral types.
We also provide abstract notions of
the Java primitive conversions that involve floating-point values,
as a placeholder for a more precise formalization of them."))
:order-subtopics t
:default-parent t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc+ primitive-widening-conversions
:parents (primitive-conversions)
:short "Java primitive widening conversions [JLS:5.1.2]."
:order-subtopics t
:default-parent t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary byte-to-short
:in-type (primitive-type-byte)
:out-type (primitive-type-short)
:operation x
:short "Widening conversion from @('byte') to @('short') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary byte-to-int
:in-type (primitive-type-byte)
:out-type (primitive-type-int)
:operation x
:short "Widening conversion from @('byte') to @('int') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary byte-to-long
:in-type (primitive-type-byte)
:out-type (primitive-type-long)
:operation x
:short "Widening conversion from @('byte') to @('long') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary byte-to-float
:in-type (primitive-type-byte)
:out-type (primitive-type-float)
:operation (byte-to-float-abs x)
:short "Widening conversion from @('byte') to @('float') [JLS:5.1.2].")
(in-theory (disable (:e byte-to-float)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary byte-to-double
:in-type (primitive-type-byte)
:out-type (primitive-type-double)
:operation (byte-to-double-abs x)
:short "Widening conversion from @('byte') to @('double') [JLS:5.1.2].")
(in-theory (disable (:e byte-to-double)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary short-to-int
:in-type (primitive-type-short)
:out-type (primitive-type-int)
:operation x
:short "Widening conversion from @('short') to @('int') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary short-to-long
:in-type (primitive-type-short)
:out-type (primitive-type-long)
:operation x
:short "Widening conversion from @('short') to @('long') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary short-to-float
:in-type (primitive-type-short)
:out-type (primitive-type-float)
:operation (short-to-float-abs x)
:short "Widening conversion from @('short') to @('float') [JLS:5.1.2].")
(in-theory (disable (:e short-to-float)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary short-to-double
:in-type (primitive-type-short)
:out-type (primitive-type-double)
:operation (short-to-double-abs x)
:short "Widening conversion from @('short') to @('double') [JLS:5.1.2].")
(in-theory (disable (:e short-to-double)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary char-to-int
:in-type (primitive-type-char)
:out-type (primitive-type-int)
:operation x
:short "Widening conversion from @('char') to @('int') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary char-to-long
:in-type (primitive-type-char)
:out-type (primitive-type-long)
:operation x
:short "Widening conversion from @('char') to @('long') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary char-to-float
:in-type (primitive-type-char)
:out-type (primitive-type-float)
:operation (char-to-float-abs x)
:short "Widening conversion from @('char') to @('float') [JLS:5.1.2].")
(in-theory (disable (:e char-to-float)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary char-to-double
:in-type (primitive-type-char)
:out-type (primitive-type-double)
:operation (char-to-double-abs x)
:short "Widening conversion from @('char') to @('double') [JLS:5.1.2].")
(in-theory (disable (:e char-to-double)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary int-to-long
:in-type (primitive-type-int)
:out-type (primitive-type-long)
:operation x
:short "Widening conversion from @('int') to @('long') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary int-to-float
:in-type (primitive-type-int)
:out-type (primitive-type-float)
:operation (int-to-float-abs x)
:short "Widening conversion from @('int') to @('float') [JLS:5.1.2].")
(in-theory (disable (:e int-to-float)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary int-to-double
:in-type (primitive-type-int)
:out-type (primitive-type-double)
:operation (int-to-double-abs x)
:short "Widening conversion from @('int') to @('double') [JLS:5.1.2].")
(in-theory (disable (:e int-to-double)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary long-to-float
:in-type (primitive-type-long)
:out-type (primitive-type-float)
:operation (long-to-float-abs x)
:short "Widening conversion from @('long') to @('float') [JLS:5.1.2].")
(in-theory (disable (:e long-to-float)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary long-to-double
:in-type (primitive-type-long)
:out-type (primitive-type-double)
:operation (long-to-double-abs x)
:short "Widening conversion from @('long') to @('double') [JLS:5.1.2].")
(in-theory (disable (:e long-to-double)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary float-to-double
:in-type (primitive-type-float)
:out-type (primitive-type-double)
:operation (float-to-double-abs x)
:short "Widening conversion from @('float') to @('double') [JLS:5.1.2].")
(in-theory (disable (:e float-to-double)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc+ primitive-narrowing-conversions
:parents (primitive-conversions)
:short "Java primitive narrowing conversions [JLS:5.1.3]."
:order-subtopics t
:default-parent t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary short-to-byte
:in-type (primitive-type-short)
:out-type (primitive-type-byte)
:operation (logext 8 x)
:short "Narrowing conversion from @('short') to @('byte') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary short-to-char
:in-type (primitive-type-short)
:out-type (primitive-type-char)
:operation (loghead 16 x)
:short "Narrowing conversion from @('short') to @('char') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary char-to-byte
:in-type (primitive-type-char)
:out-type (primitive-type-byte)
:operation (logext 8 x)
:short "Narrowing conversion from @('char') to @('byte') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary char-to-short
:in-type (primitive-type-char)
:out-type (primitive-type-short)
:operation (logext 16 x)
:short "Narrowing conversion from @('char') to @('short') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary int-to-byte
:in-type (primitive-type-int)
:out-type (primitive-type-byte)
:operation (logext 8 x)
:short "Narrowing conversion from @('int') to @('byte') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary int-to-short
:in-type (primitive-type-int)
:out-type (primitive-type-short)
:operation (logext 16 x)
:short "Narrowing conversion from @('int') to @('short') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary int-to-char
:in-type (primitive-type-int)
:out-type (primitive-type-char)
:operation (loghead 16 x)
:short "Narrowing conversion from @('int') to @('char') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary long-to-byte
:in-type (primitive-type-long)
:out-type (primitive-type-byte)
:operation (logext 8 x)
:short "Narrowing conversion from @('long') to @('byte') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary long-to-short
:in-type (primitive-type-long)
:out-type (primitive-type-short)
:operation (logext 16 x)
:short "Narrowing conversion from @('long') to @('short') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary long-to-char
:in-type (primitive-type-long)
:out-type (primitive-type-char)
:operation (loghead 16 x)
:short "Narrowing conversion from @('long') to @('char') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary long-to-int
:in-type (primitive-type-long)
:out-type (primitive-type-int)
:operation (logext 32 x)
:short "Narrowing conversion from @('long') to @('int') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary float-to-byte
:in-type (primitive-type-float)
:out-type (primitive-type-byte)
:operation (float-to-byte-abs x)
:short "Narrowing conversion from @('float') to @('byte') [JLS:5.1.3].")
(in-theory (disable (:e float-to-byte)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary float-to-short
:in-type (primitive-type-float)
:out-type (primitive-type-short)
:operation (float-to-short-abs x)
:short "Narrowing conversion from @('float') to @('short') [JLS:5.1.3].")
(in-theory (disable (:e float-to-short)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary float-to-char
:in-type (primitive-type-float)
:out-type (primitive-type-char)
:operation (float-to-char-abs x)
:short "Narrowing conversion from @('float') to @('char') [JLS:5.1.3].")
(in-theory (disable (:e float-to-char)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary float-to-int
:in-type (primitive-type-float)
:out-type (primitive-type-int)
:operation (float-to-int-abs x)
:short "Narrowing conversion from @('float') to @('int') [JLS:5.1.3].")
(in-theory (disable (:e float-to-int)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary float-to-long
:in-type (primitive-type-float)
:out-type (primitive-type-long)
:operation (float-to-long-abs x)
:short "Narrowing conversion from @('float') to @('long') [JLS:5.1.3].")
(in-theory (disable (:e float-to-long)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary double-to-byte
:in-type (primitive-type-double)
:out-type (primitive-type-byte)
:operation (double-to-byte-abs x)
:short "Narrowing conversion from @('double') to @('byte') [JLS:5.1.3].")
(in-theory (disable (:e double-to-byte)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary double-to-short
:in-type (primitive-type-double)
:out-type (primitive-type-short)
:operation (double-to-short-abs x)
:short "Narrowing conversion from @('double') to @('short') [JLS:5.1.3].")
(in-theory (disable (:e double-to-short)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary double-to-char
:in-type (primitive-type-double)
:out-type (primitive-type-char)
:operation (double-to-char-abs x)
:short "Narrowing conversion from @('double') to @('char') [JLS:5.1.3].")
(in-theory (disable (:e double-to-char)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary double-to-int
:in-type (primitive-type-double)
:out-type (primitive-type-int)
:operation (double-to-int-abs x)
:short "Narrowing conversion from @('double') to @('int') [JLS:5.1.3].")
(in-theory (disable (:e double-to-int)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary double-to-long
:in-type (primitive-type-double)
:out-type (primitive-type-long)
:operation (double-to-long-abs x)
:short "Narrowing conversion from @('double') to @('long') [JLS:5.1.3].")
(in-theory (disable (:e double-to-long)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary double-to-float
:in-type (primitive-type-double)
:out-type (primitive-type-float)
:operation (double-to-float-abs x)
:short "Narrowing conversion from @('double') to @('float') [JLS:5.1.3].")
(in-theory (disable (:e double-to-float)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc+ primitive-widening-narrowing-conversions
:parents (primitive-conversions)
:short "Java primitive widening and narrowing conversions [JLS:5.1.4]."
:order-subtopics t
:default-parent t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary byte-to-char
:in-type (primitive-type-byte)
:out-type (primitive-type-char)
:operation (loghead 16 x)
:short "Widening and narrowing conversion
from @('byte') to @('char') [JLS:5.1.4].")
| true |
; Java Library
;
; Copyright (C) 2020 Kestrel Institute (http://www.kestrel.edu)
;
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;
; Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "JAVA")
(include-book "primitive-values")
(include-book "primitive-function-macros")
(include-book "kestrel/fty/sbyte8-ihs-theorems" :dir :system)
(include-book "kestrel/fty/sbyte16-ihs-theorems" :dir :system)
(include-book "kestrel/fty/sbyte32-ihs-theorems" :dir :system)
(include-book "kestrel/fty/ubyte16-ihs-theorems" :dir :system)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local (in-theory (disable logext loghead)))
(defrulel sbyte16p-when-sbyte8p
(implies (sbyte8p x)
(sbyte16p x))
:enable (sbyte8p sbyte16p))
(defrulel sbyte32p-when-sbyte16p
(implies (sbyte16p x)
(sbyte32p x))
:enable (sbyte16p sbyte32p))
(defrulel sbyte64p-when-sbyte32p
(implies (sbyte32p x)
(sbyte64p x))
:enable (sbyte32p sbyte64p))
(defrulel sbyte32p-when-ubyte16p
(implies (ubyte16p x)
(sbyte32p x))
:enable (ubyte16p sbyte32p))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc+ primitive-conversions
:parents (semantics)
:short "Java primitive conversions [JLS:5.1.2-4]."
:long
(xdoc::topstring
(xdoc::p
"We formalize the Java primitive conversions between integral types.
We also provide abstract notions of
the Java primitive conversions that involve floating-point values,
as a placeholder for a more precise formalization of them."))
:order-subtopics t
:default-parent t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc+ primitive-widening-conversions
:parents (primitive-conversions)
:short "Java primitive widening conversions [JLS:5.1.2]."
:order-subtopics t
:default-parent t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary byte-to-short
:in-type (primitive-type-byte)
:out-type (primitive-type-short)
:operation x
:short "Widening conversion from @('byte') to @('short') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary byte-to-int
:in-type (primitive-type-byte)
:out-type (primitive-type-int)
:operation x
:short "Widening conversion from @('byte') to @('int') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary byte-to-long
:in-type (primitive-type-byte)
:out-type (primitive-type-long)
:operation x
:short "Widening conversion from @('byte') to @('long') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary byte-to-float
:in-type (primitive-type-byte)
:out-type (primitive-type-float)
:operation (byte-to-float-abs x)
:short "Widening conversion from @('byte') to @('float') [JLS:5.1.2].")
(in-theory (disable (:e byte-to-float)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary byte-to-double
:in-type (primitive-type-byte)
:out-type (primitive-type-double)
:operation (byte-to-double-abs x)
:short "Widening conversion from @('byte') to @('double') [JLS:5.1.2].")
(in-theory (disable (:e byte-to-double)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary short-to-int
:in-type (primitive-type-short)
:out-type (primitive-type-int)
:operation x
:short "Widening conversion from @('short') to @('int') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary short-to-long
:in-type (primitive-type-short)
:out-type (primitive-type-long)
:operation x
:short "Widening conversion from @('short') to @('long') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary short-to-float
:in-type (primitive-type-short)
:out-type (primitive-type-float)
:operation (short-to-float-abs x)
:short "Widening conversion from @('short') to @('float') [JLS:5.1.2].")
(in-theory (disable (:e short-to-float)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary short-to-double
:in-type (primitive-type-short)
:out-type (primitive-type-double)
:operation (short-to-double-abs x)
:short "Widening conversion from @('short') to @('double') [JLS:5.1.2].")
(in-theory (disable (:e short-to-double)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary char-to-int
:in-type (primitive-type-char)
:out-type (primitive-type-int)
:operation x
:short "Widening conversion from @('char') to @('int') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary char-to-long
:in-type (primitive-type-char)
:out-type (primitive-type-long)
:operation x
:short "Widening conversion from @('char') to @('long') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary char-to-float
:in-type (primitive-type-char)
:out-type (primitive-type-float)
:operation (char-to-float-abs x)
:short "Widening conversion from @('char') to @('float') [JLS:5.1.2].")
(in-theory (disable (:e char-to-float)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary char-to-double
:in-type (primitive-type-char)
:out-type (primitive-type-double)
:operation (char-to-double-abs x)
:short "Widening conversion from @('char') to @('double') [JLS:5.1.2].")
(in-theory (disable (:e char-to-double)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary int-to-long
:in-type (primitive-type-int)
:out-type (primitive-type-long)
:operation x
:short "Widening conversion from @('int') to @('long') [JLS:5.1.2].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary int-to-float
:in-type (primitive-type-int)
:out-type (primitive-type-float)
:operation (int-to-float-abs x)
:short "Widening conversion from @('int') to @('float') [JLS:5.1.2].")
(in-theory (disable (:e int-to-float)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary int-to-double
:in-type (primitive-type-int)
:out-type (primitive-type-double)
:operation (int-to-double-abs x)
:short "Widening conversion from @('int') to @('double') [JLS:5.1.2].")
(in-theory (disable (:e int-to-double)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary long-to-float
:in-type (primitive-type-long)
:out-type (primitive-type-float)
:operation (long-to-float-abs x)
:short "Widening conversion from @('long') to @('float') [JLS:5.1.2].")
(in-theory (disable (:e long-to-float)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary long-to-double
:in-type (primitive-type-long)
:out-type (primitive-type-double)
:operation (long-to-double-abs x)
:short "Widening conversion from @('long') to @('double') [JLS:5.1.2].")
(in-theory (disable (:e long-to-double)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary float-to-double
:in-type (primitive-type-float)
:out-type (primitive-type-double)
:operation (float-to-double-abs x)
:short "Widening conversion from @('float') to @('double') [JLS:5.1.2].")
(in-theory (disable (:e float-to-double)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc+ primitive-narrowing-conversions
:parents (primitive-conversions)
:short "Java primitive narrowing conversions [JLS:5.1.3]."
:order-subtopics t
:default-parent t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary short-to-byte
:in-type (primitive-type-short)
:out-type (primitive-type-byte)
:operation (logext 8 x)
:short "Narrowing conversion from @('short') to @('byte') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary short-to-char
:in-type (primitive-type-short)
:out-type (primitive-type-char)
:operation (loghead 16 x)
:short "Narrowing conversion from @('short') to @('char') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary char-to-byte
:in-type (primitive-type-char)
:out-type (primitive-type-byte)
:operation (logext 8 x)
:short "Narrowing conversion from @('char') to @('byte') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary char-to-short
:in-type (primitive-type-char)
:out-type (primitive-type-short)
:operation (logext 16 x)
:short "Narrowing conversion from @('char') to @('short') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary int-to-byte
:in-type (primitive-type-int)
:out-type (primitive-type-byte)
:operation (logext 8 x)
:short "Narrowing conversion from @('int') to @('byte') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary int-to-short
:in-type (primitive-type-int)
:out-type (primitive-type-short)
:operation (logext 16 x)
:short "Narrowing conversion from @('int') to @('short') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary int-to-char
:in-type (primitive-type-int)
:out-type (primitive-type-char)
:operation (loghead 16 x)
:short "Narrowing conversion from @('int') to @('char') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary long-to-byte
:in-type (primitive-type-long)
:out-type (primitive-type-byte)
:operation (logext 8 x)
:short "Narrowing conversion from @('long') to @('byte') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary long-to-short
:in-type (primitive-type-long)
:out-type (primitive-type-short)
:operation (logext 16 x)
:short "Narrowing conversion from @('long') to @('short') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary long-to-char
:in-type (primitive-type-long)
:out-type (primitive-type-char)
:operation (loghead 16 x)
:short "Narrowing conversion from @('long') to @('char') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary long-to-int
:in-type (primitive-type-long)
:out-type (primitive-type-int)
:operation (logext 32 x)
:short "Narrowing conversion from @('long') to @('int') [JLS:5.1.3].")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary float-to-byte
:in-type (primitive-type-float)
:out-type (primitive-type-byte)
:operation (float-to-byte-abs x)
:short "Narrowing conversion from @('float') to @('byte') [JLS:5.1.3].")
(in-theory (disable (:e float-to-byte)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary float-to-short
:in-type (primitive-type-float)
:out-type (primitive-type-short)
:operation (float-to-short-abs x)
:short "Narrowing conversion from @('float') to @('short') [JLS:5.1.3].")
(in-theory (disable (:e float-to-short)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary float-to-char
:in-type (primitive-type-float)
:out-type (primitive-type-char)
:operation (float-to-char-abs x)
:short "Narrowing conversion from @('float') to @('char') [JLS:5.1.3].")
(in-theory (disable (:e float-to-char)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary float-to-int
:in-type (primitive-type-float)
:out-type (primitive-type-int)
:operation (float-to-int-abs x)
:short "Narrowing conversion from @('float') to @('int') [JLS:5.1.3].")
(in-theory (disable (:e float-to-int)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary float-to-long
:in-type (primitive-type-float)
:out-type (primitive-type-long)
:operation (float-to-long-abs x)
:short "Narrowing conversion from @('float') to @('long') [JLS:5.1.3].")
(in-theory (disable (:e float-to-long)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary double-to-byte
:in-type (primitive-type-double)
:out-type (primitive-type-byte)
:operation (double-to-byte-abs x)
:short "Narrowing conversion from @('double') to @('byte') [JLS:5.1.3].")
(in-theory (disable (:e double-to-byte)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary double-to-short
:in-type (primitive-type-double)
:out-type (primitive-type-short)
:operation (double-to-short-abs x)
:short "Narrowing conversion from @('double') to @('short') [JLS:5.1.3].")
(in-theory (disable (:e double-to-short)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary double-to-char
:in-type (primitive-type-double)
:out-type (primitive-type-char)
:operation (double-to-char-abs x)
:short "Narrowing conversion from @('double') to @('char') [JLS:5.1.3].")
(in-theory (disable (:e double-to-char)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary double-to-int
:in-type (primitive-type-double)
:out-type (primitive-type-int)
:operation (double-to-int-abs x)
:short "Narrowing conversion from @('double') to @('int') [JLS:5.1.3].")
(in-theory (disable (:e double-to-int)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary double-to-long
:in-type (primitive-type-double)
:out-type (primitive-type-long)
:operation (double-to-long-abs x)
:short "Narrowing conversion from @('double') to @('long') [JLS:5.1.3].")
(in-theory (disable (:e double-to-long)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary double-to-float
:in-type (primitive-type-double)
:out-type (primitive-type-float)
:operation (double-to-float-abs x)
:short "Narrowing conversion from @('double') to @('float') [JLS:5.1.3].")
(in-theory (disable (:e double-to-float)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc+ primitive-widening-narrowing-conversions
:parents (primitive-conversions)
:short "Java primitive widening and narrowing conversions [JLS:5.1.4]."
:order-subtopics t
:default-parent t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def-primitive-unary byte-to-char
:in-type (primitive-type-byte)
:out-type (primitive-type-char)
:operation (loghead 16 x)
:short "Widening and narrowing conversion
from @('byte') to @('char') [JLS:5.1.4].")
|
[
{
"context": "e LICENSE file distributed with ACL2.\n;\n; Authors: Alessandro Coglio ([email protected])\n; Eric McCarthy (mc",
"end": 222,
"score": 0.9998757839202881,
"start": 205,
"tag": "NAME",
"value": "Alessandro Coglio"
},
{
"context": "ibuted with ACL2.\n;\n; Authors: Alessandro Coglio ([email protected])\n; Eric McCarthy ([email protected])\n",
"end": 242,
"score": 0.9999268651008606,
"start": 224,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " Alessandro Coglio ([email protected])\n; Eric McCarthy ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 268,
"score": 0.9998669624328613,
"start": 255,
"tag": "NAME",
"value": "Eric McCarthy"
},
{
"context": "io ([email protected])\n; Eric McCarthy ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 290,
"score": 0.999927818775177,
"start": 270,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/kestrel/fty/deflist-of-len.lisp
|
kwancarl/acl2
| 0 |
; FTY -- Fixed-Length List Fixtype Generator
;
; Copyright (C) 2020 Kestrel Institute (http://www.kestrel.edu)
;
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;
; Authors: Alessandro Coglio ([email protected])
; Eric McCarthy ([email protected])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "FTY")
(include-book "centaur/fty/top" :dir :system)
(include-book "std/util/defrule" :dir :system)
(include-book "xdoc/defxdoc-plus" :dir :system)
(local (include-book "std/lists/take" :dir :system))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc deflist-of-len
:parents (fty-extensions fty deflist)
:short "Introduce a <see topic='@(url fty)'>fixtype</see> of
lists of a specified length."
:long
(xdoc::topstring
(xdoc::h3 "Introduction")
(xdoc::p
"@(tsee deflist) introduces fixtypes of lists of arbitrary lengths.
Given such a fixtype, the macro @('deflist-of-len') introduces
a fixtype of those lists that have a specified length,
along with some theorems that relate
the recognizers, fixers, and equivalences of the two fixtypes.")
(xdoc::p
"The lists may be true or dotted, depending on
the @(':true-listp') option used in @(tsee deflist).
The macro @('deflist-of-len') preserves that option.")
(xdoc::p
"Future versions of this macro could support
richer constraints on list length than equality with a certain value,
e.g. introduce fixtypes of lists of lengths below a certain value.")
(xdoc::h3 "General Form")
(xdoc::codeblock
"(deflist-of-len type"
" :list-type ..."
" :length ..."
" :pred ..."
" :fix ..."
" :equiv ..."
" :parents ..."
" :short ..."
" :long ..."
" )")
(xdoc::h3 "Inputs")
(xdoc::desc
"@('type')"
(xdoc::p
"A symbol that specifies the name of the fixtype."))
(xdoc::desc
"@(':list-type')"
(xdoc::p
"A symbol that names a fixtype previously introduced via @(tsee deflist).
This is the fixtype of the lists of arbitrary lengths,
which are a superset of the lists of the generated fixtype.")
(xdoc::p
"The recognizer, fixer, and equivalence of the list fixtype
must be all guard-verified.
Let @('list-pred'), @('list-fix') and @('list-equiv')
be their names.")
(xdoc::p
"This input must be supplied; there is no default."))
(xdoc::desc
"@(':length')"
(xdoc::p
"A non-negative integer that specifies the length of the lists.")
(xdoc::p
"This input must be supplied; there is no default."))
(xdoc::desc
"@(':pred')"
(xdoc::p
"A symbol that specifies the name of the recognizer for @('type').
If this is @('nil') (the default),
the name of the recognizer is @('type') followed by @('-p')."))
(xdoc::desc
"@(':fix')"
(xdoc::p
"A symbol that specifies the name of the fixer for @('type').
If this is @('nil') (the default),
the name of the fixer is @('type') followed by @('-fix')."))
(xdoc::desc
"@(':equiv')"
(xdoc::p
"A symbol that specifies the name of the equivalence for @('type').
If this is @('nil') (the default),
the name of the equivalence is @('type') followed by @('-equiv')."))
(xdoc::desc
(list
"@(':parents')"
"@(':short')"
"@(':long')")
(xdoc::p
"These, if present, are added to
the XDOC topic generated for the fixtype."))
(xdoc::h3 "Generated Events")
(xdoc::desc
"@('pred')"
(xdoc::p
"The recognizer for the fixtype, guard-verified."))
(xdoc::desc
"@('booleanp-of-pred')"
(xdoc::p
"A rewrite rule saying that @('pred') is boolean-valued."))
(xdoc::desc
(list
"@('list-pred-when-pred-rewrite')"
"@('list-pred-when-pred-forward')")
(xdoc::p
"A rewrite rule and a forward chaining rule
saying that a value satisfies @('list-pred')
when it satisfies @('pred')."))
(xdoc::desc
"@('len-when-pred-tau')"
(xdoc::p
"A tau system rule saying that if a value satisfies @('pred')
then its length is the one specified by @(':length')."))
(xdoc::desc
"@('fix')"
(xdoc::p
"The fixer for the fixtype, guard-verified.")
(xdoc::p
"It fixes values outside of @('pred') by applying
first @(tsee take) with the number specified by @(':length')
and then @('list-fix') to the result."))
(xdoc::desc
"@('pred-of-fix')"
(xdoc::p
"A rewrite rule saying that @('fix') always returns
a value that satisfies @('pred')."))
(xdoc::desc
"@('fix-when-pred')"
(xdoc::p
"A rewrite rule saying that @('fix') disappears
when its argument satisfies @('pred')."))
(xdoc::desc
(list
"@('type')"
"@('equiv')")
(xdoc::p
"The fixtype, via a call of @(tsee fty::deffixtype)
that also introduces the equivalence @('equiv')."))
(xdoc::p
"The above items are generated with XDOC documentation.")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(acl2::defxdoc+ deflist-of-len-implementation
:parents (deflist-of-len)
:short "Implementation of @(tsee deflist-of-len)."
:order-subtopics t
:default-parent t)
(defruled deflist-of-len-support-lemma
:short "Support lemma for generated fixing theorem."
:long
(xdoc::topstring
(xdoc::p
"In the events generated by @(tsee deflist-of-len),
proving that the fixer returns a value that satisifes the recognizer
involves showing that @(tsee take) returns a list of length
equal to the first argument of @(tsee take).
This is not readily provable from the built-in definition of @(tsee take),
but it is proved in @(see acl2::std/lists/take).
To avoid implicitly including that file
when including this file for @(tsee deflist-of-len),
we locally include that file and provide the theorem here,
so that it can be used in the generated theorem."))
(equal (len (take n x)) (nfix n)))
(define deflist-of-len-fn (type
list-type
length
pred
fix
equiv
parents
short
long
(wrld plist-worldp))
:returns (event "A @(tsee acl2::maybe-pseudo-event-formp).")
:mode :program
:short "Events generated by @(tsee deflist-of-len)."
:long
(xdoc::topstring-p
"For now we only perform partial validation of the inputs.
Future implementations may perform a more thorough validation.")
(b* (;; validate the TYPE input:
((unless (symbolp type))
(raise "The TYPE input must be a symbol, ~
but it is ~x0 instead." type))
;; validate the :LIST-TYPE input:
((unless (symbolp list-type))
(raise "The :LIST-TYPE input must be a symbol, ~
but it is ~x0 instead." list-type))
(fty-table (get-fixtypes-alist wrld))
(fty-info (find-fixtype list-type fty-table))
((unless fty-info)
(raise "The :LIST-TYPE input ~x0 must name a fixtype, ~
but it does not." list-type))
;; retrieve the recognizer and fixer of the existing list type:
(list-pred (fixtype->pred fty-info))
(list-fix (fixtype->fix fty-info))
;; validate the :LENGTH input:
((unless (natp length))
(raise "The :LENGTH input must be a non-negative integer, ~
but it is ~x0 instead." length))
;; validate the :PRED input:
((unless (symbolp pred))
(raise "The :PRED input must be a symbol, ~
but it is ~x0 instead." pred))
;; validate the :FIX input:
((unless (symbolp fix))
(raise "The :FIX input must be a symbol, ~
but it is ~x0 instead." fix))
;; validate the :EQUIV input:
((unless (symbolp equiv))
(raise "The :EQUIV input must be a symbol, ~
but it is ~x0 instead." equiv))
;; package for the generated theorem and variable names:
(pkg (symbol-package-name type))
(pkg (if (equal pkg *main-lisp-package-name*) "ACL2" pkg))
(pkg-witness (pkg-witness pkg))
;; names of the generated functions:
(pred (or pred (acl2::add-suffix-to-fn type "-P")))
(fix (or fix (acl2::add-suffix-to-fn type "-FIX")))
(equiv (or equiv (acl2::add-suffix-to-fn type "-EQUIV")))
;; names of the generated theorems:
(booleanp-of-pred (acl2::packn-pos (list 'booleanp-of- pred)
pkg-witness))
(list-pred-when-pred-rewrite (acl2::packn-pos (list list-pred
'-when-
pred
'-rewrite)
pkg-witness))
(list-pred-when-pred-forward (acl2::packn-pos (list list-pred
'-when-
pred
'-forward)
pkg-witness))
(len-when-pred-tau (acl2::packn-pos (list 'len-when- pred '-tau)
pkg-witness))
(pred-of-fix (acl2::packn-pos (list pred '-of- fix)
pkg-witness))
(fix-when-pred (acl2::packn-pos (list fix '-when- pred)
pkg-witness))
;; variable to use in the generated functions and theorems:
(x (intern-in-package-of-symbol "X" pkg-witness))
;; reference to the fixtype for the generated XDOC documentation:
(type-ref (concatenate 'string
"@(tsee "
(acl2::string-downcase (symbol-package-name type))
"::"
(acl2::string-downcase (symbol-name type))
")"))
;; generated events:
(pred-event
`(define ,pred (,x)
:parents (,type)
:short ,(concatenate 'string "Recognizer for " type-ref ".")
(and (,list-pred ,x)
(equal (len ,x) ,length))
:no-function t
///
(defrule ,booleanp-of-pred
(booleanp (,pred ,x)))
(defrule ,list-pred-when-pred-rewrite
(implies (,pred ,x)
(,list-pred ,x)))
(defrule ,list-pred-when-pred-forward
(implies (,pred ,x)
(,list-pred ,x))
:rule-classes :forward-chaining)
(defrule ,len-when-pred-tau
(implies (,pred ,x)
(equal (len ,x) ,length))
:rule-classes :tau-system)))
(fix-event
`(define ,fix ((,x ,pred))
:parents (,type)
:short ,(concatenate 'string "Fixer for " type-ref ".")
(mbe :logic (if (,pred ,x)
,x
(,list-fix (take ,length ,x)))
:exec ,x)
:no-function t
///
(defrule ,pred-of-fix
(,pred (,fix ,x))
:enable (,pred deflist-of-len-support-lemma)
:disable take)
(defrule ,fix-when-pred
(implies (,pred ,x)
(equal (,fix ,x) ,x)))))
(type-event
`(defsection ,type
,@(and parents (list :parents parents))
,@(and short (list :short short))
,@(and long (list :long long))
(fty::deffixtype ,type
:pred ,pred
:fix ,fix
:equiv ,equiv
:define t
:forward t))))
;; top-level event:
`(encapsulate
()
(logic)
,pred-event
,fix-event
,type-event)))
(defsection deflist-of-len-macro-definition
:short "Definition of the @(tsee deflist-of-len) macro."
:long "@(def deflist-of-len)"
(defmacro deflist-of-len (type
&key
list-type
length
pred
fix
equiv
parents
short
long)
`(make-event (deflist-of-len-fn
',type
',list-type
',length
',pred
',fix
',equiv
',parents
,short
,long
(w state)))))
|
26252
|
; FTY -- Fixed-Length List Fixtype Generator
;
; Copyright (C) 2020 Kestrel Institute (http://www.kestrel.edu)
;
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;
; Authors: <NAME> (<EMAIL>)
; <NAME> (<EMAIL>)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "FTY")
(include-book "centaur/fty/top" :dir :system)
(include-book "std/util/defrule" :dir :system)
(include-book "xdoc/defxdoc-plus" :dir :system)
(local (include-book "std/lists/take" :dir :system))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc deflist-of-len
:parents (fty-extensions fty deflist)
:short "Introduce a <see topic='@(url fty)'>fixtype</see> of
lists of a specified length."
:long
(xdoc::topstring
(xdoc::h3 "Introduction")
(xdoc::p
"@(tsee deflist) introduces fixtypes of lists of arbitrary lengths.
Given such a fixtype, the macro @('deflist-of-len') introduces
a fixtype of those lists that have a specified length,
along with some theorems that relate
the recognizers, fixers, and equivalences of the two fixtypes.")
(xdoc::p
"The lists may be true or dotted, depending on
the @(':true-listp') option used in @(tsee deflist).
The macro @('deflist-of-len') preserves that option.")
(xdoc::p
"Future versions of this macro could support
richer constraints on list length than equality with a certain value,
e.g. introduce fixtypes of lists of lengths below a certain value.")
(xdoc::h3 "General Form")
(xdoc::codeblock
"(deflist-of-len type"
" :list-type ..."
" :length ..."
" :pred ..."
" :fix ..."
" :equiv ..."
" :parents ..."
" :short ..."
" :long ..."
" )")
(xdoc::h3 "Inputs")
(xdoc::desc
"@('type')"
(xdoc::p
"A symbol that specifies the name of the fixtype."))
(xdoc::desc
"@(':list-type')"
(xdoc::p
"A symbol that names a fixtype previously introduced via @(tsee deflist).
This is the fixtype of the lists of arbitrary lengths,
which are a superset of the lists of the generated fixtype.")
(xdoc::p
"The recognizer, fixer, and equivalence of the list fixtype
must be all guard-verified.
Let @('list-pred'), @('list-fix') and @('list-equiv')
be their names.")
(xdoc::p
"This input must be supplied; there is no default."))
(xdoc::desc
"@(':length')"
(xdoc::p
"A non-negative integer that specifies the length of the lists.")
(xdoc::p
"This input must be supplied; there is no default."))
(xdoc::desc
"@(':pred')"
(xdoc::p
"A symbol that specifies the name of the recognizer for @('type').
If this is @('nil') (the default),
the name of the recognizer is @('type') followed by @('-p')."))
(xdoc::desc
"@(':fix')"
(xdoc::p
"A symbol that specifies the name of the fixer for @('type').
If this is @('nil') (the default),
the name of the fixer is @('type') followed by @('-fix')."))
(xdoc::desc
"@(':equiv')"
(xdoc::p
"A symbol that specifies the name of the equivalence for @('type').
If this is @('nil') (the default),
the name of the equivalence is @('type') followed by @('-equiv')."))
(xdoc::desc
(list
"@(':parents')"
"@(':short')"
"@(':long')")
(xdoc::p
"These, if present, are added to
the XDOC topic generated for the fixtype."))
(xdoc::h3 "Generated Events")
(xdoc::desc
"@('pred')"
(xdoc::p
"The recognizer for the fixtype, guard-verified."))
(xdoc::desc
"@('booleanp-of-pred')"
(xdoc::p
"A rewrite rule saying that @('pred') is boolean-valued."))
(xdoc::desc
(list
"@('list-pred-when-pred-rewrite')"
"@('list-pred-when-pred-forward')")
(xdoc::p
"A rewrite rule and a forward chaining rule
saying that a value satisfies @('list-pred')
when it satisfies @('pred')."))
(xdoc::desc
"@('len-when-pred-tau')"
(xdoc::p
"A tau system rule saying that if a value satisfies @('pred')
then its length is the one specified by @(':length')."))
(xdoc::desc
"@('fix')"
(xdoc::p
"The fixer for the fixtype, guard-verified.")
(xdoc::p
"It fixes values outside of @('pred') by applying
first @(tsee take) with the number specified by @(':length')
and then @('list-fix') to the result."))
(xdoc::desc
"@('pred-of-fix')"
(xdoc::p
"A rewrite rule saying that @('fix') always returns
a value that satisfies @('pred')."))
(xdoc::desc
"@('fix-when-pred')"
(xdoc::p
"A rewrite rule saying that @('fix') disappears
when its argument satisfies @('pred')."))
(xdoc::desc
(list
"@('type')"
"@('equiv')")
(xdoc::p
"The fixtype, via a call of @(tsee fty::deffixtype)
that also introduces the equivalence @('equiv')."))
(xdoc::p
"The above items are generated with XDOC documentation.")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(acl2::defxdoc+ deflist-of-len-implementation
:parents (deflist-of-len)
:short "Implementation of @(tsee deflist-of-len)."
:order-subtopics t
:default-parent t)
(defruled deflist-of-len-support-lemma
:short "Support lemma for generated fixing theorem."
:long
(xdoc::topstring
(xdoc::p
"In the events generated by @(tsee deflist-of-len),
proving that the fixer returns a value that satisifes the recognizer
involves showing that @(tsee take) returns a list of length
equal to the first argument of @(tsee take).
This is not readily provable from the built-in definition of @(tsee take),
but it is proved in @(see acl2::std/lists/take).
To avoid implicitly including that file
when including this file for @(tsee deflist-of-len),
we locally include that file and provide the theorem here,
so that it can be used in the generated theorem."))
(equal (len (take n x)) (nfix n)))
(define deflist-of-len-fn (type
list-type
length
pred
fix
equiv
parents
short
long
(wrld plist-worldp))
:returns (event "A @(tsee acl2::maybe-pseudo-event-formp).")
:mode :program
:short "Events generated by @(tsee deflist-of-len)."
:long
(xdoc::topstring-p
"For now we only perform partial validation of the inputs.
Future implementations may perform a more thorough validation.")
(b* (;; validate the TYPE input:
((unless (symbolp type))
(raise "The TYPE input must be a symbol, ~
but it is ~x0 instead." type))
;; validate the :LIST-TYPE input:
((unless (symbolp list-type))
(raise "The :LIST-TYPE input must be a symbol, ~
but it is ~x0 instead." list-type))
(fty-table (get-fixtypes-alist wrld))
(fty-info (find-fixtype list-type fty-table))
((unless fty-info)
(raise "The :LIST-TYPE input ~x0 must name a fixtype, ~
but it does not." list-type))
;; retrieve the recognizer and fixer of the existing list type:
(list-pred (fixtype->pred fty-info))
(list-fix (fixtype->fix fty-info))
;; validate the :LENGTH input:
((unless (natp length))
(raise "The :LENGTH input must be a non-negative integer, ~
but it is ~x0 instead." length))
;; validate the :PRED input:
((unless (symbolp pred))
(raise "The :PRED input must be a symbol, ~
but it is ~x0 instead." pred))
;; validate the :FIX input:
((unless (symbolp fix))
(raise "The :FIX input must be a symbol, ~
but it is ~x0 instead." fix))
;; validate the :EQUIV input:
((unless (symbolp equiv))
(raise "The :EQUIV input must be a symbol, ~
but it is ~x0 instead." equiv))
;; package for the generated theorem and variable names:
(pkg (symbol-package-name type))
(pkg (if (equal pkg *main-lisp-package-name*) "ACL2" pkg))
(pkg-witness (pkg-witness pkg))
;; names of the generated functions:
(pred (or pred (acl2::add-suffix-to-fn type "-P")))
(fix (or fix (acl2::add-suffix-to-fn type "-FIX")))
(equiv (or equiv (acl2::add-suffix-to-fn type "-EQUIV")))
;; names of the generated theorems:
(booleanp-of-pred (acl2::packn-pos (list 'booleanp-of- pred)
pkg-witness))
(list-pred-when-pred-rewrite (acl2::packn-pos (list list-pred
'-when-
pred
'-rewrite)
pkg-witness))
(list-pred-when-pred-forward (acl2::packn-pos (list list-pred
'-when-
pred
'-forward)
pkg-witness))
(len-when-pred-tau (acl2::packn-pos (list 'len-when- pred '-tau)
pkg-witness))
(pred-of-fix (acl2::packn-pos (list pred '-of- fix)
pkg-witness))
(fix-when-pred (acl2::packn-pos (list fix '-when- pred)
pkg-witness))
;; variable to use in the generated functions and theorems:
(x (intern-in-package-of-symbol "X" pkg-witness))
;; reference to the fixtype for the generated XDOC documentation:
(type-ref (concatenate 'string
"@(tsee "
(acl2::string-downcase (symbol-package-name type))
"::"
(acl2::string-downcase (symbol-name type))
")"))
;; generated events:
(pred-event
`(define ,pred (,x)
:parents (,type)
:short ,(concatenate 'string "Recognizer for " type-ref ".")
(and (,list-pred ,x)
(equal (len ,x) ,length))
:no-function t
///
(defrule ,booleanp-of-pred
(booleanp (,pred ,x)))
(defrule ,list-pred-when-pred-rewrite
(implies (,pred ,x)
(,list-pred ,x)))
(defrule ,list-pred-when-pred-forward
(implies (,pred ,x)
(,list-pred ,x))
:rule-classes :forward-chaining)
(defrule ,len-when-pred-tau
(implies (,pred ,x)
(equal (len ,x) ,length))
:rule-classes :tau-system)))
(fix-event
`(define ,fix ((,x ,pred))
:parents (,type)
:short ,(concatenate 'string "Fixer for " type-ref ".")
(mbe :logic (if (,pred ,x)
,x
(,list-fix (take ,length ,x)))
:exec ,x)
:no-function t
///
(defrule ,pred-of-fix
(,pred (,fix ,x))
:enable (,pred deflist-of-len-support-lemma)
:disable take)
(defrule ,fix-when-pred
(implies (,pred ,x)
(equal (,fix ,x) ,x)))))
(type-event
`(defsection ,type
,@(and parents (list :parents parents))
,@(and short (list :short short))
,@(and long (list :long long))
(fty::deffixtype ,type
:pred ,pred
:fix ,fix
:equiv ,equiv
:define t
:forward t))))
;; top-level event:
`(encapsulate
()
(logic)
,pred-event
,fix-event
,type-event)))
(defsection deflist-of-len-macro-definition
:short "Definition of the @(tsee deflist-of-len) macro."
:long "@(def deflist-of-len)"
(defmacro deflist-of-len (type
&key
list-type
length
pred
fix
equiv
parents
short
long)
`(make-event (deflist-of-len-fn
',type
',list-type
',length
',pred
',fix
',equiv
',parents
,short
,long
(w state)))))
| true |
; FTY -- Fixed-Length List Fixtype Generator
;
; Copyright (C) 2020 Kestrel Institute (http://www.kestrel.edu)
;
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;
; Authors: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
; PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "FTY")
(include-book "centaur/fty/top" :dir :system)
(include-book "std/util/defrule" :dir :system)
(include-book "xdoc/defxdoc-plus" :dir :system)
(local (include-book "std/lists/take" :dir :system))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc deflist-of-len
:parents (fty-extensions fty deflist)
:short "Introduce a <see topic='@(url fty)'>fixtype</see> of
lists of a specified length."
:long
(xdoc::topstring
(xdoc::h3 "Introduction")
(xdoc::p
"@(tsee deflist) introduces fixtypes of lists of arbitrary lengths.
Given such a fixtype, the macro @('deflist-of-len') introduces
a fixtype of those lists that have a specified length,
along with some theorems that relate
the recognizers, fixers, and equivalences of the two fixtypes.")
(xdoc::p
"The lists may be true or dotted, depending on
the @(':true-listp') option used in @(tsee deflist).
The macro @('deflist-of-len') preserves that option.")
(xdoc::p
"Future versions of this macro could support
richer constraints on list length than equality with a certain value,
e.g. introduce fixtypes of lists of lengths below a certain value.")
(xdoc::h3 "General Form")
(xdoc::codeblock
"(deflist-of-len type"
" :list-type ..."
" :length ..."
" :pred ..."
" :fix ..."
" :equiv ..."
" :parents ..."
" :short ..."
" :long ..."
" )")
(xdoc::h3 "Inputs")
(xdoc::desc
"@('type')"
(xdoc::p
"A symbol that specifies the name of the fixtype."))
(xdoc::desc
"@(':list-type')"
(xdoc::p
"A symbol that names a fixtype previously introduced via @(tsee deflist).
This is the fixtype of the lists of arbitrary lengths,
which are a superset of the lists of the generated fixtype.")
(xdoc::p
"The recognizer, fixer, and equivalence of the list fixtype
must be all guard-verified.
Let @('list-pred'), @('list-fix') and @('list-equiv')
be their names.")
(xdoc::p
"This input must be supplied; there is no default."))
(xdoc::desc
"@(':length')"
(xdoc::p
"A non-negative integer that specifies the length of the lists.")
(xdoc::p
"This input must be supplied; there is no default."))
(xdoc::desc
"@(':pred')"
(xdoc::p
"A symbol that specifies the name of the recognizer for @('type').
If this is @('nil') (the default),
the name of the recognizer is @('type') followed by @('-p')."))
(xdoc::desc
"@(':fix')"
(xdoc::p
"A symbol that specifies the name of the fixer for @('type').
If this is @('nil') (the default),
the name of the fixer is @('type') followed by @('-fix')."))
(xdoc::desc
"@(':equiv')"
(xdoc::p
"A symbol that specifies the name of the equivalence for @('type').
If this is @('nil') (the default),
the name of the equivalence is @('type') followed by @('-equiv')."))
(xdoc::desc
(list
"@(':parents')"
"@(':short')"
"@(':long')")
(xdoc::p
"These, if present, are added to
the XDOC topic generated for the fixtype."))
(xdoc::h3 "Generated Events")
(xdoc::desc
"@('pred')"
(xdoc::p
"The recognizer for the fixtype, guard-verified."))
(xdoc::desc
"@('booleanp-of-pred')"
(xdoc::p
"A rewrite rule saying that @('pred') is boolean-valued."))
(xdoc::desc
(list
"@('list-pred-when-pred-rewrite')"
"@('list-pred-when-pred-forward')")
(xdoc::p
"A rewrite rule and a forward chaining rule
saying that a value satisfies @('list-pred')
when it satisfies @('pred')."))
(xdoc::desc
"@('len-when-pred-tau')"
(xdoc::p
"A tau system rule saying that if a value satisfies @('pred')
then its length is the one specified by @(':length')."))
(xdoc::desc
"@('fix')"
(xdoc::p
"The fixer for the fixtype, guard-verified.")
(xdoc::p
"It fixes values outside of @('pred') by applying
first @(tsee take) with the number specified by @(':length')
and then @('list-fix') to the result."))
(xdoc::desc
"@('pred-of-fix')"
(xdoc::p
"A rewrite rule saying that @('fix') always returns
a value that satisfies @('pred')."))
(xdoc::desc
"@('fix-when-pred')"
(xdoc::p
"A rewrite rule saying that @('fix') disappears
when its argument satisfies @('pred')."))
(xdoc::desc
(list
"@('type')"
"@('equiv')")
(xdoc::p
"The fixtype, via a call of @(tsee fty::deffixtype)
that also introduces the equivalence @('equiv')."))
(xdoc::p
"The above items are generated with XDOC documentation.")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(acl2::defxdoc+ deflist-of-len-implementation
:parents (deflist-of-len)
:short "Implementation of @(tsee deflist-of-len)."
:order-subtopics t
:default-parent t)
(defruled deflist-of-len-support-lemma
:short "Support lemma for generated fixing theorem."
:long
(xdoc::topstring
(xdoc::p
"In the events generated by @(tsee deflist-of-len),
proving that the fixer returns a value that satisifes the recognizer
involves showing that @(tsee take) returns a list of length
equal to the first argument of @(tsee take).
This is not readily provable from the built-in definition of @(tsee take),
but it is proved in @(see acl2::std/lists/take).
To avoid implicitly including that file
when including this file for @(tsee deflist-of-len),
we locally include that file and provide the theorem here,
so that it can be used in the generated theorem."))
(equal (len (take n x)) (nfix n)))
(define deflist-of-len-fn (type
list-type
length
pred
fix
equiv
parents
short
long
(wrld plist-worldp))
:returns (event "A @(tsee acl2::maybe-pseudo-event-formp).")
:mode :program
:short "Events generated by @(tsee deflist-of-len)."
:long
(xdoc::topstring-p
"For now we only perform partial validation of the inputs.
Future implementations may perform a more thorough validation.")
(b* (;; validate the TYPE input:
((unless (symbolp type))
(raise "The TYPE input must be a symbol, ~
but it is ~x0 instead." type))
;; validate the :LIST-TYPE input:
((unless (symbolp list-type))
(raise "The :LIST-TYPE input must be a symbol, ~
but it is ~x0 instead." list-type))
(fty-table (get-fixtypes-alist wrld))
(fty-info (find-fixtype list-type fty-table))
((unless fty-info)
(raise "The :LIST-TYPE input ~x0 must name a fixtype, ~
but it does not." list-type))
;; retrieve the recognizer and fixer of the existing list type:
(list-pred (fixtype->pred fty-info))
(list-fix (fixtype->fix fty-info))
;; validate the :LENGTH input:
((unless (natp length))
(raise "The :LENGTH input must be a non-negative integer, ~
but it is ~x0 instead." length))
;; validate the :PRED input:
((unless (symbolp pred))
(raise "The :PRED input must be a symbol, ~
but it is ~x0 instead." pred))
;; validate the :FIX input:
((unless (symbolp fix))
(raise "The :FIX input must be a symbol, ~
but it is ~x0 instead." fix))
;; validate the :EQUIV input:
((unless (symbolp equiv))
(raise "The :EQUIV input must be a symbol, ~
but it is ~x0 instead." equiv))
;; package for the generated theorem and variable names:
(pkg (symbol-package-name type))
(pkg (if (equal pkg *main-lisp-package-name*) "ACL2" pkg))
(pkg-witness (pkg-witness pkg))
;; names of the generated functions:
(pred (or pred (acl2::add-suffix-to-fn type "-P")))
(fix (or fix (acl2::add-suffix-to-fn type "-FIX")))
(equiv (or equiv (acl2::add-suffix-to-fn type "-EQUIV")))
;; names of the generated theorems:
(booleanp-of-pred (acl2::packn-pos (list 'booleanp-of- pred)
pkg-witness))
(list-pred-when-pred-rewrite (acl2::packn-pos (list list-pred
'-when-
pred
'-rewrite)
pkg-witness))
(list-pred-when-pred-forward (acl2::packn-pos (list list-pred
'-when-
pred
'-forward)
pkg-witness))
(len-when-pred-tau (acl2::packn-pos (list 'len-when- pred '-tau)
pkg-witness))
(pred-of-fix (acl2::packn-pos (list pred '-of- fix)
pkg-witness))
(fix-when-pred (acl2::packn-pos (list fix '-when- pred)
pkg-witness))
;; variable to use in the generated functions and theorems:
(x (intern-in-package-of-symbol "X" pkg-witness))
;; reference to the fixtype for the generated XDOC documentation:
(type-ref (concatenate 'string
"@(tsee "
(acl2::string-downcase (symbol-package-name type))
"::"
(acl2::string-downcase (symbol-name type))
")"))
;; generated events:
(pred-event
`(define ,pred (,x)
:parents (,type)
:short ,(concatenate 'string "Recognizer for " type-ref ".")
(and (,list-pred ,x)
(equal (len ,x) ,length))
:no-function t
///
(defrule ,booleanp-of-pred
(booleanp (,pred ,x)))
(defrule ,list-pred-when-pred-rewrite
(implies (,pred ,x)
(,list-pred ,x)))
(defrule ,list-pred-when-pred-forward
(implies (,pred ,x)
(,list-pred ,x))
:rule-classes :forward-chaining)
(defrule ,len-when-pred-tau
(implies (,pred ,x)
(equal (len ,x) ,length))
:rule-classes :tau-system)))
(fix-event
`(define ,fix ((,x ,pred))
:parents (,type)
:short ,(concatenate 'string "Fixer for " type-ref ".")
(mbe :logic (if (,pred ,x)
,x
(,list-fix (take ,length ,x)))
:exec ,x)
:no-function t
///
(defrule ,pred-of-fix
(,pred (,fix ,x))
:enable (,pred deflist-of-len-support-lemma)
:disable take)
(defrule ,fix-when-pred
(implies (,pred ,x)
(equal (,fix ,x) ,x)))))
(type-event
`(defsection ,type
,@(and parents (list :parents parents))
,@(and short (list :short short))
,@(and long (list :long long))
(fty::deffixtype ,type
:pred ,pred
:fix ,fix
:equiv ,equiv
:define t
:forward t))))
;; top-level event:
`(encapsulate
()
(logic)
,pred-event
,fix-event
,type-event)))
(defsection deflist-of-len-macro-definition
:short "Definition of the @(tsee deflist-of-len) macro."
:long "@(def deflist-of-len)"
(defmacro deflist-of-len (type
&key
list-type
length
pred
fix
equiv
parents
short
long)
`(make-event (deflist-of-len-fn
',type
',list-type
',length
',pred
',fix
',equiv
',parents
,short
,long
(w state)))))
|
[
{
"context": "Copyright (C) 2019, ForrestHunt, Inc.\n; Written by Matt Kaufmann and J Moore\n; License: A 3-clause BSD license. S",
"end": 66,
"score": 0.9998292326927185,
"start": 53,
"tag": "NAME",
"value": "Matt Kaufmann"
},
{
"context": ", ForrestHunt, Inc.\n; Written by Matt Kaufmann and J Moore\n; License: A 3-clause BSD license. See the LICEN",
"end": 78,
"score": 0.9998754262924194,
"start": 71,
"tag": "NAME",
"value": "J Moore"
}
] |
books/projects/apply-model-2/ex2/user-thms.lisp
|
mayankmanj/acl2
| 305 |
; Copyright (C) 2019, ForrestHunt, Inc.
; Written by Matt Kaufmann and J Moore
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
(in-package "MODAPP")
(include-book "user-defs")
; -----------------------------------------------------------------
; Some Sample Theorems about Mapping Functions
; Theorems just showing some evaluations:
(defthm collect-example
(equal (collect '(1 2 3) '(LAMBDA (X) (CONS 'A X)))
'((A . 1) (A . 2) (A . 3)))
:rule-classes nil)
(defthm collect-collect-example
(implies (warrant collect)
(equal (collect '((1 2 3) (4 5 6))
'(LAMBDA (X)
(COLLECT X '(LAMBDA (X) (CONS 'A X)))))
'(((A . 1) (A . 2) (A . 3))
((A . 4) (A . 5) (A . 6)))))
:rule-classes nil
:hints (("Goal" :expand ((:free (x) (hide x))))))
(defthm recur-by-collect-example
(equal (recur-by-collect '(1 1 1)
'(LAMBDA (X) (BINARY-+ '1 X)))
'(1 2 3))
:rule-classes nil)
; A theorem showing that functions can be data, i.e., we can apply mapping functions
; to mapping functions, as long as the data functions are tame.
(defthm collect*-collect-example
(implies (warrant square collect)
(equal (collect* '(((1 2 3) (LAMBDA (X) (CONS 'A X)))
((4 5 6 7) SQUARE)
(((20 21 22)
(30 31 32)
(40 41 42))
(LAMBDA (Y)
(COLLECT Y '(LAMBDA (Z) (CONS 'C Z)))))
)
'COLLECT)
'(((A . 1)(A . 2)(A . 3))
(16 25 36 49)
(((C . 20) (C . 21) (C . 22))
((C . 30) (C . 31) (C . 32))
((C . 40) (C . 41) (C . 42)))
)))
:rule-classes nil
:hints
(("Goal"
:in-theory
(disable (:executable-counterpart collect)
(:executable-counterpart collect*)))))
; Theorems about general relationships
(defthm collect-my-append1
(equal (collect (my-append1 a b) fn)
(my-append1 (collect a fn)
(collect b fn))))
(defthm sumlist-my-append1
(equal (sumlist (my-append1 a b) u)
(+ (sumlist a u)
(sumlist b u))))
(defthm all-my-append1
(equal (all (my-append1 a b) fn)
(and (all a fn) (all b fn))))
(defthm xists-my-append1
(equal (xists (my-append1 a b) fn)
(if (xists a fn)
t
(xists b fn))))
(defthm len-filter
(<= (len (filter lst fn)) (len lst))
:rule-classes :linear)
(defthm filter-v-all
(implies (true-listp lst)
(iff (equal (filter lst fn) lst)
(all lst fn)))
:hints (("Subgoal *1/3.2'" :in-theory (disable len-filter)
:use ((:instance len-filter (lst (cdr lst)) (fn fn))))))
(defthm filter-v-xists
(iff (filter lst fn)
(xists lst fn))
:rule-classes nil)
; We show some theorems about FOLDR further below.
; Theorems about concrete uses of mapping functions.
(encapsulate nil
(local (include-book "arithmetic-5/top" :dir :system))
(defthm sumlist-nats
(implies (and (warrant square)
(natp n))
(equal (sumlist (nats n) 'SQUARE)
(/ (* n (+ n 1) (+ (* 2 n) 1))
6)))
:hints (("Goal" :expand ((:free (x) (HIDE x)))))))
; If lst is a true-list and every element of lst is also, then reversing each element twice
; leaves lst unchanged:
(defthm rev-rev-version-1
(implies (and (warrant my-rev)
(true-listp lst)
(all lst 'true-listp))
(equal (collect (collect lst 'my-rev) 'my-rev) lst)))
; We can actually accomplish an append and a reverse via FOLDRs. So after we
; establish that, we repeat the above theorem but this time without referring
; to my-rev.
(defthm foldr-as-my-append1
(equal (foldr x 'CONS y)
(my-append1 x y)))
(defthm foldr-as-my-rev
(implies (warrant foldr)
(equal (foldr x
'(LAMBDA (X Y)
(FOLDR Y 'CONS (CONS X 'NIL)))
nil)
(my-rev x))))
(defthm rev-rev-version-2
(implies (and (warrant foldr)
(true-listp lst)
(all lst 'true-listp))
(equal (collect (collect lst
'(lambda (x)
(foldr x
'(LAMBDA (X Y)
(FOLDR Y 'CONS (CONS X 'NIL)))
nil)))
'(lambda (x)
(foldr x
'(LAMBDA (X Y)
(FOLDR Y 'CONS (CONS X 'NIL)))
nil)))
lst)))
; And ALL and COLLECT are also FOLDRs, so we can make this an all FOLDR show:
(defthm rev-rev-version-3
(implies (and (warrant foldr)
(true-listp lst)
(foldr lst
'(LAMBDA (X Y)
(IF (TRUE-LISTP X) Y 'NIL))
t))
(equal (foldr
(foldr lst
'(LAMBDA (X Y)
(CONS (foldr x
'(LAMBDA (X Y)
(FOLDR Y 'CONS (CONS X 'NIL)))
nil)
Y))
nil)
'(LAMBDA (X Y)
(CONS (foldr x
'(LAMBDA (X Y)
(FOLDR Y 'CONS (CONS X 'NIL)))
nil)
Y))
nil)
lst)))
; A few theorems manipulating mapping functions and the functions they
; apply.
; Here is a way to move a constant factor out of a sumlist regardless of the
; names of the variables.
(defthm sumlist-binary-*-constant
(implies (tamep body)
(equal (sumlist lst (lamb (list v) (list 'binary-* (list 'quote const) body)))
(* const (sumlist lst (lamb (list v) body))))))
(defthm lamb-x-x-is-identity
(implies (symbolp x)
(fn-equal (lamb (list x) x) 'identity))
:hints (("Goal" :in-theory (enable fn-equal))))
; The hint below is only provided to show that the theorem is proved by
; rewriting, not induction.
(defthm example-of-loop$-rewriting
(equal (sumlist (my-append1 aaa bbb) (lamb '(x) '(binary-* '2 x)))
(+ (* 2 (sumlist aaa 'identity))
(* 2 (sumlist bbb 'identity))))
:hints (("Goal" :do-not-induct t))
:rule-classes nil)
; A couple of nice foldr theorems. The first two are redundant; they were
; critical as rewrite rules in our rev-rev versions above. We repeat them here
; just to summarize the relations with foldr. The rest These are really just
; designed to illustrate the relationships, not to be used as rewrites.
(defthm foldr-as-my-append1
(equal (foldr x 'CONS y)
(my-append1 x y)))
(defthm foldr-as-my-rev
(implies (warrant foldr)
(equal (foldr x
'(LAMBDA (X Y)
(FOLDR Y 'CONS (CONS X 'NIL)))
nil)
(my-rev x))))
; The theorem below, which is not being stored as a rule, illustrates the most
; general fact we can think of relating COLLECT and FOLDR:
(defthm general-collect-is-a-foldr
(implies (and (not (equal fn 'QUOTE))
(not (equal fn 'IF))
(symbolp x)
(symbolp y)
(not (eq x y))
(tamep `(,fn ,x)))
(equal (collect lst fn)
(foldr lst
`(lambda (,x ,y)
(cons (,fn ,x) ,y))
nil)))
:rule-classes nil)
; But this rule is not useful as a rewrite rule because x and y are free
; variables. Furthermore, if the goal is to rewrite COLLECTs into FOLDRs, it's
; not necessary to be so general: we could just choose the x and y we want to
; use. But we're not interested in rewriting in either direction here so we
; make this (and subsequent theorems) :rule-classes nil.
; We use a convenient abbreviation for the hypotheses we'll see over and over
; here.
(defthm foldr-as-collect
(implies (force (ok-fnp fn))
(equal (foldr lst
`(LAMBDA (X Y)
(CONS (,fn X) Y))
nil)
(collect lst fn)))
:rule-classes nil)
(defthm foldr-as-sumlist
(implies (ok-fnp fn)
(equal (foldr lst
`(LAMBDA (X Y)
(BINARY-+ (,fn X) Y))
0)
(sumlist lst fn)))
:rule-classes nil)
(defthm foldr-as-filter
(implies (ok-fnp fn)
(equal (foldr lst
`(LAMBDA (X Y)
(IF (,fn X) (CONS X Y) Y))
nil)
(filter lst fn)))
:rule-classes nil)
(defthm foldr-as-all
(implies (ok-fnp fn)
(equal (foldr lst
`(LAMBDA (X Y)
(IF (,fn X) Y 'NIL))
t)
(all lst fn)))
:rule-classes nil)
(defthm foldr-as-xists
(implies (ok-fnp fn)
(equal (foldr lst
`(LAMBDA (X Y)
(IF (,fn X) 'T Y))
nil)
(xists lst fn)))
:rule-classes nil)
(defthm maxlist-non-nil
(implies (and (ok-fnp fn)
(all (collect lst fn) 'ACL2-NUMBERP))
(iff (maxlist lst fn)
(consp lst)))
:rule-classes nil)
(defthm foldr-as-maxlist
(implies (and (ok-fnp fn)
(all (collect lst fn) 'ACL2-NUMBERP))
(equal (foldr lst `(LAMBDA (X Y)
(IF (EQUAL Y 'NIL)
(,fn X)
(MAX (,fn X) Y)))
nil)
(maxlist lst fn)))
:rule-classes nil)
|
88685
|
; Copyright (C) 2019, ForrestHunt, Inc.
; Written by <NAME> and <NAME>
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
(in-package "MODAPP")
(include-book "user-defs")
; -----------------------------------------------------------------
; Some Sample Theorems about Mapping Functions
; Theorems just showing some evaluations:
(defthm collect-example
(equal (collect '(1 2 3) '(LAMBDA (X) (CONS 'A X)))
'((A . 1) (A . 2) (A . 3)))
:rule-classes nil)
(defthm collect-collect-example
(implies (warrant collect)
(equal (collect '((1 2 3) (4 5 6))
'(LAMBDA (X)
(COLLECT X '(LAMBDA (X) (CONS 'A X)))))
'(((A . 1) (A . 2) (A . 3))
((A . 4) (A . 5) (A . 6)))))
:rule-classes nil
:hints (("Goal" :expand ((:free (x) (hide x))))))
(defthm recur-by-collect-example
(equal (recur-by-collect '(1 1 1)
'(LAMBDA (X) (BINARY-+ '1 X)))
'(1 2 3))
:rule-classes nil)
; A theorem showing that functions can be data, i.e., we can apply mapping functions
; to mapping functions, as long as the data functions are tame.
(defthm collect*-collect-example
(implies (warrant square collect)
(equal (collect* '(((1 2 3) (LAMBDA (X) (CONS 'A X)))
((4 5 6 7) SQUARE)
(((20 21 22)
(30 31 32)
(40 41 42))
(LAMBDA (Y)
(COLLECT Y '(LAMBDA (Z) (CONS 'C Z)))))
)
'COLLECT)
'(((A . 1)(A . 2)(A . 3))
(16 25 36 49)
(((C . 20) (C . 21) (C . 22))
((C . 30) (C . 31) (C . 32))
((C . 40) (C . 41) (C . 42)))
)))
:rule-classes nil
:hints
(("Goal"
:in-theory
(disable (:executable-counterpart collect)
(:executable-counterpart collect*)))))
; Theorems about general relationships
(defthm collect-my-append1
(equal (collect (my-append1 a b) fn)
(my-append1 (collect a fn)
(collect b fn))))
(defthm sumlist-my-append1
(equal (sumlist (my-append1 a b) u)
(+ (sumlist a u)
(sumlist b u))))
(defthm all-my-append1
(equal (all (my-append1 a b) fn)
(and (all a fn) (all b fn))))
(defthm xists-my-append1
(equal (xists (my-append1 a b) fn)
(if (xists a fn)
t
(xists b fn))))
(defthm len-filter
(<= (len (filter lst fn)) (len lst))
:rule-classes :linear)
(defthm filter-v-all
(implies (true-listp lst)
(iff (equal (filter lst fn) lst)
(all lst fn)))
:hints (("Subgoal *1/3.2'" :in-theory (disable len-filter)
:use ((:instance len-filter (lst (cdr lst)) (fn fn))))))
(defthm filter-v-xists
(iff (filter lst fn)
(xists lst fn))
:rule-classes nil)
; We show some theorems about FOLDR further below.
; Theorems about concrete uses of mapping functions.
(encapsulate nil
(local (include-book "arithmetic-5/top" :dir :system))
(defthm sumlist-nats
(implies (and (warrant square)
(natp n))
(equal (sumlist (nats n) 'SQUARE)
(/ (* n (+ n 1) (+ (* 2 n) 1))
6)))
:hints (("Goal" :expand ((:free (x) (HIDE x)))))))
; If lst is a true-list and every element of lst is also, then reversing each element twice
; leaves lst unchanged:
(defthm rev-rev-version-1
(implies (and (warrant my-rev)
(true-listp lst)
(all lst 'true-listp))
(equal (collect (collect lst 'my-rev) 'my-rev) lst)))
; We can actually accomplish an append and a reverse via FOLDRs. So after we
; establish that, we repeat the above theorem but this time without referring
; to my-rev.
(defthm foldr-as-my-append1
(equal (foldr x 'CONS y)
(my-append1 x y)))
(defthm foldr-as-my-rev
(implies (warrant foldr)
(equal (foldr x
'(LAMBDA (X Y)
(FOLDR Y 'CONS (CONS X 'NIL)))
nil)
(my-rev x))))
(defthm rev-rev-version-2
(implies (and (warrant foldr)
(true-listp lst)
(all lst 'true-listp))
(equal (collect (collect lst
'(lambda (x)
(foldr x
'(LAMBDA (X Y)
(FOLDR Y 'CONS (CONS X 'NIL)))
nil)))
'(lambda (x)
(foldr x
'(LAMBDA (X Y)
(FOLDR Y 'CONS (CONS X 'NIL)))
nil)))
lst)))
; And ALL and COLLECT are also FOLDRs, so we can make this an all FOLDR show:
(defthm rev-rev-version-3
(implies (and (warrant foldr)
(true-listp lst)
(foldr lst
'(LAMBDA (X Y)
(IF (TRUE-LISTP X) Y 'NIL))
t))
(equal (foldr
(foldr lst
'(LAMBDA (X Y)
(CONS (foldr x
'(LAMBDA (X Y)
(FOLDR Y 'CONS (CONS X 'NIL)))
nil)
Y))
nil)
'(LAMBDA (X Y)
(CONS (foldr x
'(LAMBDA (X Y)
(FOLDR Y 'CONS (CONS X 'NIL)))
nil)
Y))
nil)
lst)))
; A few theorems manipulating mapping functions and the functions they
; apply.
; Here is a way to move a constant factor out of a sumlist regardless of the
; names of the variables.
(defthm sumlist-binary-*-constant
(implies (tamep body)
(equal (sumlist lst (lamb (list v) (list 'binary-* (list 'quote const) body)))
(* const (sumlist lst (lamb (list v) body))))))
(defthm lamb-x-x-is-identity
(implies (symbolp x)
(fn-equal (lamb (list x) x) 'identity))
:hints (("Goal" :in-theory (enable fn-equal))))
; The hint below is only provided to show that the theorem is proved by
; rewriting, not induction.
(defthm example-of-loop$-rewriting
(equal (sumlist (my-append1 aaa bbb) (lamb '(x) '(binary-* '2 x)))
(+ (* 2 (sumlist aaa 'identity))
(* 2 (sumlist bbb 'identity))))
:hints (("Goal" :do-not-induct t))
:rule-classes nil)
; A couple of nice foldr theorems. The first two are redundant; they were
; critical as rewrite rules in our rev-rev versions above. We repeat them here
; just to summarize the relations with foldr. The rest These are really just
; designed to illustrate the relationships, not to be used as rewrites.
(defthm foldr-as-my-append1
(equal (foldr x 'CONS y)
(my-append1 x y)))
(defthm foldr-as-my-rev
(implies (warrant foldr)
(equal (foldr x
'(LAMBDA (X Y)
(FOLDR Y 'CONS (CONS X 'NIL)))
nil)
(my-rev x))))
; The theorem below, which is not being stored as a rule, illustrates the most
; general fact we can think of relating COLLECT and FOLDR:
(defthm general-collect-is-a-foldr
(implies (and (not (equal fn 'QUOTE))
(not (equal fn 'IF))
(symbolp x)
(symbolp y)
(not (eq x y))
(tamep `(,fn ,x)))
(equal (collect lst fn)
(foldr lst
`(lambda (,x ,y)
(cons (,fn ,x) ,y))
nil)))
:rule-classes nil)
; But this rule is not useful as a rewrite rule because x and y are free
; variables. Furthermore, if the goal is to rewrite COLLECTs into FOLDRs, it's
; not necessary to be so general: we could just choose the x and y we want to
; use. But we're not interested in rewriting in either direction here so we
; make this (and subsequent theorems) :rule-classes nil.
; We use a convenient abbreviation for the hypotheses we'll see over and over
; here.
(defthm foldr-as-collect
(implies (force (ok-fnp fn))
(equal (foldr lst
`(LAMBDA (X Y)
(CONS (,fn X) Y))
nil)
(collect lst fn)))
:rule-classes nil)
(defthm foldr-as-sumlist
(implies (ok-fnp fn)
(equal (foldr lst
`(LAMBDA (X Y)
(BINARY-+ (,fn X) Y))
0)
(sumlist lst fn)))
:rule-classes nil)
(defthm foldr-as-filter
(implies (ok-fnp fn)
(equal (foldr lst
`(LAMBDA (X Y)
(IF (,fn X) (CONS X Y) Y))
nil)
(filter lst fn)))
:rule-classes nil)
(defthm foldr-as-all
(implies (ok-fnp fn)
(equal (foldr lst
`(LAMBDA (X Y)
(IF (,fn X) Y 'NIL))
t)
(all lst fn)))
:rule-classes nil)
(defthm foldr-as-xists
(implies (ok-fnp fn)
(equal (foldr lst
`(LAMBDA (X Y)
(IF (,fn X) 'T Y))
nil)
(xists lst fn)))
:rule-classes nil)
(defthm maxlist-non-nil
(implies (and (ok-fnp fn)
(all (collect lst fn) 'ACL2-NUMBERP))
(iff (maxlist lst fn)
(consp lst)))
:rule-classes nil)
(defthm foldr-as-maxlist
(implies (and (ok-fnp fn)
(all (collect lst fn) 'ACL2-NUMBERP))
(equal (foldr lst `(LAMBDA (X Y)
(IF (EQUAL Y 'NIL)
(,fn X)
(MAX (,fn X) Y)))
nil)
(maxlist lst fn)))
:rule-classes nil)
| true |
; Copyright (C) 2019, ForrestHunt, Inc.
; Written by PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
(in-package "MODAPP")
(include-book "user-defs")
; -----------------------------------------------------------------
; Some Sample Theorems about Mapping Functions
; Theorems just showing some evaluations:
(defthm collect-example
(equal (collect '(1 2 3) '(LAMBDA (X) (CONS 'A X)))
'((A . 1) (A . 2) (A . 3)))
:rule-classes nil)
(defthm collect-collect-example
(implies (warrant collect)
(equal (collect '((1 2 3) (4 5 6))
'(LAMBDA (X)
(COLLECT X '(LAMBDA (X) (CONS 'A X)))))
'(((A . 1) (A . 2) (A . 3))
((A . 4) (A . 5) (A . 6)))))
:rule-classes nil
:hints (("Goal" :expand ((:free (x) (hide x))))))
(defthm recur-by-collect-example
(equal (recur-by-collect '(1 1 1)
'(LAMBDA (X) (BINARY-+ '1 X)))
'(1 2 3))
:rule-classes nil)
; A theorem showing that functions can be data, i.e., we can apply mapping functions
; to mapping functions, as long as the data functions are tame.
(defthm collect*-collect-example
(implies (warrant square collect)
(equal (collect* '(((1 2 3) (LAMBDA (X) (CONS 'A X)))
((4 5 6 7) SQUARE)
(((20 21 22)
(30 31 32)
(40 41 42))
(LAMBDA (Y)
(COLLECT Y '(LAMBDA (Z) (CONS 'C Z)))))
)
'COLLECT)
'(((A . 1)(A . 2)(A . 3))
(16 25 36 49)
(((C . 20) (C . 21) (C . 22))
((C . 30) (C . 31) (C . 32))
((C . 40) (C . 41) (C . 42)))
)))
:rule-classes nil
:hints
(("Goal"
:in-theory
(disable (:executable-counterpart collect)
(:executable-counterpart collect*)))))
; Theorems about general relationships
(defthm collect-my-append1
(equal (collect (my-append1 a b) fn)
(my-append1 (collect a fn)
(collect b fn))))
(defthm sumlist-my-append1
(equal (sumlist (my-append1 a b) u)
(+ (sumlist a u)
(sumlist b u))))
(defthm all-my-append1
(equal (all (my-append1 a b) fn)
(and (all a fn) (all b fn))))
(defthm xists-my-append1
(equal (xists (my-append1 a b) fn)
(if (xists a fn)
t
(xists b fn))))
(defthm len-filter
(<= (len (filter lst fn)) (len lst))
:rule-classes :linear)
(defthm filter-v-all
(implies (true-listp lst)
(iff (equal (filter lst fn) lst)
(all lst fn)))
:hints (("Subgoal *1/3.2'" :in-theory (disable len-filter)
:use ((:instance len-filter (lst (cdr lst)) (fn fn))))))
(defthm filter-v-xists
(iff (filter lst fn)
(xists lst fn))
:rule-classes nil)
; We show some theorems about FOLDR further below.
; Theorems about concrete uses of mapping functions.
(encapsulate nil
(local (include-book "arithmetic-5/top" :dir :system))
(defthm sumlist-nats
(implies (and (warrant square)
(natp n))
(equal (sumlist (nats n) 'SQUARE)
(/ (* n (+ n 1) (+ (* 2 n) 1))
6)))
:hints (("Goal" :expand ((:free (x) (HIDE x)))))))
; If lst is a true-list and every element of lst is also, then reversing each element twice
; leaves lst unchanged:
(defthm rev-rev-version-1
(implies (and (warrant my-rev)
(true-listp lst)
(all lst 'true-listp))
(equal (collect (collect lst 'my-rev) 'my-rev) lst)))
; We can actually accomplish an append and a reverse via FOLDRs. So after we
; establish that, we repeat the above theorem but this time without referring
; to my-rev.
(defthm foldr-as-my-append1
(equal (foldr x 'CONS y)
(my-append1 x y)))
(defthm foldr-as-my-rev
(implies (warrant foldr)
(equal (foldr x
'(LAMBDA (X Y)
(FOLDR Y 'CONS (CONS X 'NIL)))
nil)
(my-rev x))))
(defthm rev-rev-version-2
(implies (and (warrant foldr)
(true-listp lst)
(all lst 'true-listp))
(equal (collect (collect lst
'(lambda (x)
(foldr x
'(LAMBDA (X Y)
(FOLDR Y 'CONS (CONS X 'NIL)))
nil)))
'(lambda (x)
(foldr x
'(LAMBDA (X Y)
(FOLDR Y 'CONS (CONS X 'NIL)))
nil)))
lst)))
; And ALL and COLLECT are also FOLDRs, so we can make this an all FOLDR show:
(defthm rev-rev-version-3
(implies (and (warrant foldr)
(true-listp lst)
(foldr lst
'(LAMBDA (X Y)
(IF (TRUE-LISTP X) Y 'NIL))
t))
(equal (foldr
(foldr lst
'(LAMBDA (X Y)
(CONS (foldr x
'(LAMBDA (X Y)
(FOLDR Y 'CONS (CONS X 'NIL)))
nil)
Y))
nil)
'(LAMBDA (X Y)
(CONS (foldr x
'(LAMBDA (X Y)
(FOLDR Y 'CONS (CONS X 'NIL)))
nil)
Y))
nil)
lst)))
; A few theorems manipulating mapping functions and the functions they
; apply.
; Here is a way to move a constant factor out of a sumlist regardless of the
; names of the variables.
(defthm sumlist-binary-*-constant
(implies (tamep body)
(equal (sumlist lst (lamb (list v) (list 'binary-* (list 'quote const) body)))
(* const (sumlist lst (lamb (list v) body))))))
(defthm lamb-x-x-is-identity
(implies (symbolp x)
(fn-equal (lamb (list x) x) 'identity))
:hints (("Goal" :in-theory (enable fn-equal))))
; The hint below is only provided to show that the theorem is proved by
; rewriting, not induction.
(defthm example-of-loop$-rewriting
(equal (sumlist (my-append1 aaa bbb) (lamb '(x) '(binary-* '2 x)))
(+ (* 2 (sumlist aaa 'identity))
(* 2 (sumlist bbb 'identity))))
:hints (("Goal" :do-not-induct t))
:rule-classes nil)
; A couple of nice foldr theorems. The first two are redundant; they were
; critical as rewrite rules in our rev-rev versions above. We repeat them here
; just to summarize the relations with foldr. The rest These are really just
; designed to illustrate the relationships, not to be used as rewrites.
(defthm foldr-as-my-append1
(equal (foldr x 'CONS y)
(my-append1 x y)))
(defthm foldr-as-my-rev
(implies (warrant foldr)
(equal (foldr x
'(LAMBDA (X Y)
(FOLDR Y 'CONS (CONS X 'NIL)))
nil)
(my-rev x))))
; The theorem below, which is not being stored as a rule, illustrates the most
; general fact we can think of relating COLLECT and FOLDR:
(defthm general-collect-is-a-foldr
(implies (and (not (equal fn 'QUOTE))
(not (equal fn 'IF))
(symbolp x)
(symbolp y)
(not (eq x y))
(tamep `(,fn ,x)))
(equal (collect lst fn)
(foldr lst
`(lambda (,x ,y)
(cons (,fn ,x) ,y))
nil)))
:rule-classes nil)
; But this rule is not useful as a rewrite rule because x and y are free
; variables. Furthermore, if the goal is to rewrite COLLECTs into FOLDRs, it's
; not necessary to be so general: we could just choose the x and y we want to
; use. But we're not interested in rewriting in either direction here so we
; make this (and subsequent theorems) :rule-classes nil.
; We use a convenient abbreviation for the hypotheses we'll see over and over
; here.
(defthm foldr-as-collect
(implies (force (ok-fnp fn))
(equal (foldr lst
`(LAMBDA (X Y)
(CONS (,fn X) Y))
nil)
(collect lst fn)))
:rule-classes nil)
(defthm foldr-as-sumlist
(implies (ok-fnp fn)
(equal (foldr lst
`(LAMBDA (X Y)
(BINARY-+ (,fn X) Y))
0)
(sumlist lst fn)))
:rule-classes nil)
(defthm foldr-as-filter
(implies (ok-fnp fn)
(equal (foldr lst
`(LAMBDA (X Y)
(IF (,fn X) (CONS X Y) Y))
nil)
(filter lst fn)))
:rule-classes nil)
(defthm foldr-as-all
(implies (ok-fnp fn)
(equal (foldr lst
`(LAMBDA (X Y)
(IF (,fn X) Y 'NIL))
t)
(all lst fn)))
:rule-classes nil)
(defthm foldr-as-xists
(implies (ok-fnp fn)
(equal (foldr lst
`(LAMBDA (X Y)
(IF (,fn X) 'T Y))
nil)
(xists lst fn)))
:rule-classes nil)
(defthm maxlist-non-nil
(implies (and (ok-fnp fn)
(all (collect lst fn) 'ACL2-NUMBERP))
(iff (maxlist lst fn)
(consp lst)))
:rule-classes nil)
(defthm foldr-as-maxlist
(implies (and (ok-fnp fn)
(all (collect lst fn) 'ACL2-NUMBERP))
(equal (foldr lst `(LAMBDA (X Y)
(IF (EQUAL Y 'NIL)
(,fn X)
(MAX (,fn X) Y)))
nil)
(maxlist lst fn)))
:rule-classes nil)
|
[
{
"context": "em cl-online-learning\n :version \"0.5\"\n :author \"Satoshi Imai\"\n :licence \"MIT Licence\"\n :encoding :utf-8\n :d",
"end": 224,
"score": 0.9998574256896973,
"start": 212,
"tag": "NAME",
"value": "Satoshi Imai"
}
] |
cl-online-learning.asd
|
masatoi/cl-online-learning
| 50 |
;;; -*- coding:utf-8; mode: lisp; -*-
(in-package :cl-user)
(defpackage cl-online-learning-asd
(:use :cl :asdf))
(in-package :cl-online-learning-asd)
(defsystem cl-online-learning
:version "0.5"
:author "Satoshi Imai"
:licence "MIT Licence"
:encoding :utf-8
:depends-on (:cl-libsvm-format :cl-store)
:components ((:module "src"
:components
((:file "vector")
(:file "utils" :depends-on ("vector"))
(:file "cl-online-learning" :depends-on ("vector"))
(:file "rls" :depends-on ("vector" "cl-online-learning")))
))
:description "Online Machine Learning for Common Lisp"
:long-description
#.(with-open-file (stream (merge-pathnames
#p"README.org"
(or *load-pathname* *compile-file-pathname*))
:if-does-not-exist nil
:direction :input)
(when stream
(let ((seq (make-array (file-length stream)
:element-type 'character
:fill-pointer t)))
(setf (fill-pointer seq) (read-sequence seq stream))
seq)))
:in-order-to ((test-op (test-op cl-online-learning-test))))
|
6437
|
;;; -*- coding:utf-8; mode: lisp; -*-
(in-package :cl-user)
(defpackage cl-online-learning-asd
(:use :cl :asdf))
(in-package :cl-online-learning-asd)
(defsystem cl-online-learning
:version "0.5"
:author "<NAME>"
:licence "MIT Licence"
:encoding :utf-8
:depends-on (:cl-libsvm-format :cl-store)
:components ((:module "src"
:components
((:file "vector")
(:file "utils" :depends-on ("vector"))
(:file "cl-online-learning" :depends-on ("vector"))
(:file "rls" :depends-on ("vector" "cl-online-learning")))
))
:description "Online Machine Learning for Common Lisp"
:long-description
#.(with-open-file (stream (merge-pathnames
#p"README.org"
(or *load-pathname* *compile-file-pathname*))
:if-does-not-exist nil
:direction :input)
(when stream
(let ((seq (make-array (file-length stream)
:element-type 'character
:fill-pointer t)))
(setf (fill-pointer seq) (read-sequence seq stream))
seq)))
:in-order-to ((test-op (test-op cl-online-learning-test))))
| true |
;;; -*- coding:utf-8; mode: lisp; -*-
(in-package :cl-user)
(defpackage cl-online-learning-asd
(:use :cl :asdf))
(in-package :cl-online-learning-asd)
(defsystem cl-online-learning
:version "0.5"
:author "PI:NAME:<NAME>END_PI"
:licence "MIT Licence"
:encoding :utf-8
:depends-on (:cl-libsvm-format :cl-store)
:components ((:module "src"
:components
((:file "vector")
(:file "utils" :depends-on ("vector"))
(:file "cl-online-learning" :depends-on ("vector"))
(:file "rls" :depends-on ("vector" "cl-online-learning")))
))
:description "Online Machine Learning for Common Lisp"
:long-description
#.(with-open-file (stream (merge-pathnames
#p"README.org"
(or *load-pathname* *compile-file-pathname*))
:if-does-not-exist nil
:direction :input)
(when stream
(let ((seq (make-array (file-length stream)
:element-type 'character
:fill-pointer t)))
(setf (fill-pointer seq) (read-sequence seq stream))
seq)))
:in-order-to ((test-op (test-op cl-online-learning-test))))
|
[
{
"context": "oading and representation\n;;;;\n;;;; Programmer: Ian S. Eslick\n;;;; Date Started: October 2004\n;;;;\n\n(in-packag",
"end": 399,
"score": 0.9998899102210999,
"start": 386,
"tag": "NAME",
"value": "Ian S. Eslick"
},
{
"context": "air)\n\t\t\t pair))\n\t\t pair)))))\n\t ((string= name \"hassuf\")\n\t (let ((suffix (first list))\n\t\t (count (re",
"end": 9747,
"score": 0.6297450661659241,
"start": 9743,
"tag": "USERNAME",
"value": "hass"
}
] |
src/tagger-data.lisp
|
eslick/cl-langutils
| 25 |
;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10; Package: utils -*-
;;;; *************************************************************************
;;;; FILE IDENTIFICATION
;;;;
;;;; Name: tagger-data
;;;; Purpose: Lisp version of the Brill tagger w/ WSJ/BROWN data; implements
;;;; the data file loading and representation
;;;;
;;;; Programmer: Ian S. Eslick
;;;; Date Started: October 2004
;;;;
(in-package :langutils)
;; -----------------------------------
;; Contextual rule files
;;
;; The parser builds rules from tokenized rule expressions of the form:
;; <oldtag> <newtag> RULE-TYPE <arg1> <arg2>
;;
;; Where <arg1> can be tag1 or word1 with semantics as described
;; in *contextual-rule-args* above; similarly for <arg2>
;;
(def-contextual-rule-parser make-contextual-rule
("SURROUNDTAG" (match (0 oldtag) (-1 tag1) (+1 tag2)) => newtag)
("NEXTTAG" (match (0 oldtag) (+1 tag1)) => newtag)
("CURWD" (match (0 oldtag) (0 word1)) => newtag)
("NEXTWD" (match (0 oldtag) (+1 word1)) => newtag)
("RBIGRAM" (match (0 oldtag) (0 word1) (+1 word2)) => newtag)
("WDNEXTTAG" (match (0 oldtag) (0 word1) (+1 tag2)) => newtag)
("WDAND2AFT" (match (0 oldtag) (0 word1) (+2 word2)) => newtag)
("WDAND2TAGAFT" (match (0 oldtag) (0 word1) (+2 tag2)) => newtag)
("NEXT2TAG" (match (0 oldtag) (+2 tag1)) => newtag)
("NEXT2WD" (match (0 oldtag) (+2 word1)) => newtag)
("NEXTBIGRAM" (match (0 oldtag) (+1 tag1) (+2 tag2)) => newtag)
("NEXT1OR2TAG" (match (0 oldtag) (or (+1 tag1) (+2 tag1))) => newtag)
("NEXT1OR2WD" (match (0 oldtag) (or (+1 word1) (+2 word1))) => newtag)
("NEXT1OR2OR3TAG" (match (0 oldtag) (or (+1 tag1) (+2 tag1) (+3 tag1))) => newtag)
("PREVTAG" (match (0 oldtag) (-1 tag1)) => newtag)
("PREVWD" (match (0 oldtag) (-1 word1)) => newtag)
("LBIGRAM" (match (0 oldtag) (0 word1) (-1 word2)) => newtag)
("WDPREVTAG" (match (0 oldtag) (0 word1) (-1 tag2)) => newtag)
("WDAND2BFR" (match (0 oldtag) (0 word1) (-2 word2)) => newtag)
("WDAND2TAGBFR" (match (0 oldtag) (0 word1) (-2 tag2)) => newtag)
("PREV2TAG" (match (0 oldtag) (-2 tag1)) => newtag)
("PREV2WD" (match (0 oldtag) (-2 word1)) => newtag)
("PREV1OR2TAG" (match (0 oldtag) (or (-1 tag1) (-2 tag1))) => newtag)
("PREV1OR2WD" (match (0 oldtag) (or (-1 word1) (-2 word1))) => newtag)
("PREV1OR2OR3TAG" (match (0 oldtag) (or (-1 tag1) (-2 tag1) (-3 tag1))) => newtag)
("PREV1OR2OR3WD" (match (0 oldtag) (or (-1 word1) (-2 word1) (-3 word1))) => newtag)
("PREVBIGRAM" (match (0 oldtag) (-1 tag2) (-2 tag1)) => newtag))
#|
Macroexpand this to see code for a single rule closure:
(def-contextual-rule-parser make-contextual-rule
("SURROUNDTAG" (match (0 oldtag) (-1 tag1) (+1 tag2)) => newtag))
|#
(defun load-contextual-rules ( rule-file &aux rules )
(write-log tagger-init "Loading contextual rules")
(with-open-file ( s rule-file :external-format :ascii)
(do-contentful-lines (line s ) ;; :count count)
(let* ((context-rule (ppcre:split "\\s+" line))
(closure (make-contextual-rule context-rule)))
(if closure (push closure rules)))))
(nreverse rules))
;; -----------------------------------------
;; LEXICAL RULE FILE INITIALIZATION AND I/F
(defun load-lexical-rules ( rule-file &optional bigram-hash word-hash &aux (rule-list nil))
"Return a list of closure implementing the lexical rules
in rule-file to tag words not found in the lexicon"
(write-log tagger-init "Loading lexical rules")
(with-open-file ( s rule-file :external-format :ascii)
(do-contentful-lines (line s)
(let ((lex-rule (ppcre:split "\\s+" line)))
(let ((rule (make-lexical-rule lex-rule *lexicon* bigram-hash word-hash)))
(if rule (push rule rule-list))))))
(nreverse rule-list))
(let ((pair (cons nil nil)))
(defun guess-tag ( token initial-tag rule-list )
"Using rules in rule-table guess the tag of the token 'token'"
(declare (optimize (speed 3) (safety 0) (debug 0) (space 0)))
(setf (car pair) token)
(setf (cdr pair) initial-tag)
(aif (apply-rules pair rule-list)
(cdr it)
initial-tag)))
;; Expanded implementation, not great but was fast and easy...
;;
;; Example of lexical rule file format:
;; NN would fgoodright VB x
;; NN 0 fchar CD x
;; NN be fgoodright JJ x
(defun make-lexical-rule (list lh bh wh)
"Look through list for rule name"
(declare (ignore bh)
;; (inline strncmp list eq equal char subseq strncmp-end2 length concatenate)
(optimize (speed 0) (safety 3) (debug 3)))
(let ((name (second list))
(fname (third list)))
(cond ((string= name "char")
(let ((prefix (char (first list) 0))
(new-tag (mkkeysym (third list))))
(declare (type character prefix)
(type symbol new-tag))
#'(lambda (pair)
(declare (type cons pair));; (inline char))
(let ((token (car pair))
(tag (cdr pair)))
(declare (type string token) (type symbol tag) (ignore tag))
(if (eq prefix (char token 0))
(progn (setf (cdr pair) new-tag) pair)
pair)))))
((string= fname "fchar")
(let ((old-tag (mkkeysym (first list)))
(prefix (char (second list) 0))
(new-tag (mkkeysym (fourth list))))
(declare (type symbol old-tag new-tag) (type character prefix))
#'(lambda (pair)
(declare (type cons pair));; (inline char))
(let ((token (car pair))
(tag (cdr pair)))
(declare (type string token) (type symbol tag))
(if (and (eq tag old-tag)
(eq prefix (char token 0)))
(progn (setf (cdr pair) new-tag) pair)
pair)))))
((string= name "deletepref")
(let ((prefix (first list))
(count (read-from-string (third list)))
(new-tag (mkkeysym (fourth list))))
(declare #-mcl (type symbol new-tag)
#-mcl (type fixnum count)
#-mcl (type string prefix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare (type string token) (type symbol tag) (ignore tag))
(if (strncmp prefix token count 0)
(let ((root (subseq token count)))
(if (or (hash-get lh root)
(and wh (hash-get wh root)))
(progn (setf (cdr pair) new-tag) pair)
pair))
pair)))))
((string= fname "fdeletepref")
(let ((old-tag (mkkeysym (first list)))
(prefix (second list))
(count (read-from-string (fourth list)))
(new-tag (mkkeysym (fifth list))))
(declare #-mcl (type symbol old-tag new-tag)
#-mcl (type fixnum count)
#-mcl (type string prefix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare (type string token) (type symbol tag))
(if (and (eq tag old-tag)
(strncmp prefix token count 0))
(let ((root (subseq token count)))
(if (or (hash-get lh root)
(and wh (hash-get wh root)))
(progn (setf (cdr pair) new-tag) pair)
pair))
pair)))))
((string= name "haspref")
(let ((prefix (first list))
(count (read-from-string (third list)))
(new-tag (mkkeysym (fourth list))))
(declare #-mcl (type symbol new-tag)
#-mcl (type fixnum count)
#-mcl (type string prefix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag)
(ignore tag))
(if (strncmp prefix token count 0)
(progn (setf (cdr pair) new-tag) pair)
pair)))))
((string= fname "fhaspref")
(let ((old-tag (mkkeysym (first list)))
(prefix (second list))
(count (read-from-string (fourth list)))
(new-tag (mkkeysym (fifth list))))
(declare #-mcl (type symbol new-tag old-tag)
#-mcl (type fixnum count)
#-mcl (type string prefix))
#'(lambda (pair)
(declare (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag))
(if (and (eq tag old-tag)
(strncmp prefix token count 0))
(progn (setf (cdr pair) new-tag) pair)
pair)))))
((string= name "deletesuf")
(let ((suffix (first list))
(count (read-from-string (third list)))
(new-tag (mkkeysym (fourth list))))
(declare #-mcl (type symbol new-tag)
#-mcl (type fixnum count)
#-mcl (type string suffix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag)
(ignore tag))
(if (strncmp-end2 suffix token count (- (length token) count))
(let ((root (subseq token 0 (- (length token) count))))
(if (or (hash-get lh root)
(and wh (hash-get wh root)))
(progn (setf (cdr pair) new-tag) pair)
pair))
pair)))))
((string= fname "fdeletesuf")
(let ((old-tag (mkkeysym (first list)))
(suffix (second list))
(count (read-from-string (fourth list)))
(new-tag (mkkeysym (fifth list))))
(declare #-mcl (type symbol new-tag old-tag)
#-mcl (type fixnum count)
#-mcl (type string suffix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag))
(if (and (eq tag old-tag)
(strncmp-end2 suffix token count (- (length token) count)))
(let ((root (subseq token 0 (- (length token) count))))
(if (or (hash-get lh root)
(and wh (hash-get wh root)))
(progn (setf (cdr pair) new-tag) pair)
pair))
pair)))))
((string= name "hassuf")
(let ((suffix (first list))
(count (read-from-string (third list)))
(new-tag (mkkeysym (fourth list))))
(declare #-mcl (type symbol new-tag)
#-mcl (type fixnum count)
#-mcl (type string suffix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag)
(ignore tag))
(if (strncmp-end2 suffix token count (- (length token) count))
(progn (setf (cdr pair) new-tag) pair)
pair)))))
((string= fname "fhassuf")
(let ((old-tag (mkkeysym (first list)))
(suffix (second list))
(count (read-from-string (fourth list)))
(new-tag (mkkeysym (fifth list))))
(declare #-mcl (type symbol new-tag old-tag)
#-mcl (type fixnum count)
#-mcl (type string suffix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag))
(if (and (eq tag old-tag)
(strncmp-end2 suffix token count (- (length token) count)))
(progn (setf (cdr pair) new-tag) pair)
pair)))))
((string= name "addsuf")
(let ((suffix (first list))
;; (count (read-from-string (third list)))
(new-tag (mkkeysym (fourth list))))
(declare #-mcl (type symbol new-tag)
; #-mcl (type fixnum count)
#-mcl (type string suffix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag)
(ignore tag))
(let ((new-word (concatenate 'string token suffix)))
(if (or (hash-get lh new-word)
(and wh (hash-get wh new-word)))
(progn (setf (cdr pair) new-tag) pair)
pair))))))
((string= fname "faddsuf")
(let ((old-tag (mkkeysym (first list)))
(suffix (second list))
;; (count (read-from-string (fourth list)))
(new-tag (mkkeysym (fifth list))))
(declare #-mcl (type symbol new-tag old-tag)
;; #-mcl (type fixnum count)
#-mcl (type string suffix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag))
(if (eq tag old-tag)
(let ((new-word (concatenate 'string token suffix)))
(if (or (hash-get lh new-word)
(and wh (hash-get wh new-word)))
(progn (setf (cdr pair) new-tag) pair)
pair))
pair)))))
;; ((string= name "addpref")
;; (let ((prefix (first list))
;; (count (read-from-string (third list)))
;; (new-tag (mkkeysym (fourth list))))
;; #'(lambda (token tag)
;; ((string= fname "faddpref")
;; (let ((old-tag (mkkeysym (first list)))
;; (prefix (second list))
;; (count (read-from-string (fourth list)))
;; (new-tag (mkkeysym (fifth list))))
;; #'(lambda (token tag)
;; NOTE: NO BIGRAM SUPPORT YET
;; "goodleft" "fgoodleft" "goodright" "fgoodright"
(t (progn
(write-log tagger-contextual "No rule found for: ~A." list)
nil)))))
(defun apply-rules ( datum rule-list )
"Apply rules to the values in values presuming that
the returned list is also a list of values that can
be passed to the next rule"
(declare (optimize (speed 3) (safety 1) (debug 1) (space 0))
(type list rule-list)
(type list datum))
(cond ((null rule-list)
datum)
((null datum)
(error "Null datum in rule prior to ~A.~%" (car rule-list)))
(t (apply-rules (funcall (car rule-list) datum) (cdr rule-list)))))
|
33053
|
;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10; Package: utils -*-
;;;; *************************************************************************
;;;; FILE IDENTIFICATION
;;;;
;;;; Name: tagger-data
;;;; Purpose: Lisp version of the Brill tagger w/ WSJ/BROWN data; implements
;;;; the data file loading and representation
;;;;
;;;; Programmer: <NAME>
;;;; Date Started: October 2004
;;;;
(in-package :langutils)
;; -----------------------------------
;; Contextual rule files
;;
;; The parser builds rules from tokenized rule expressions of the form:
;; <oldtag> <newtag> RULE-TYPE <arg1> <arg2>
;;
;; Where <arg1> can be tag1 or word1 with semantics as described
;; in *contextual-rule-args* above; similarly for <arg2>
;;
(def-contextual-rule-parser make-contextual-rule
("SURROUNDTAG" (match (0 oldtag) (-1 tag1) (+1 tag2)) => newtag)
("NEXTTAG" (match (0 oldtag) (+1 tag1)) => newtag)
("CURWD" (match (0 oldtag) (0 word1)) => newtag)
("NEXTWD" (match (0 oldtag) (+1 word1)) => newtag)
("RBIGRAM" (match (0 oldtag) (0 word1) (+1 word2)) => newtag)
("WDNEXTTAG" (match (0 oldtag) (0 word1) (+1 tag2)) => newtag)
("WDAND2AFT" (match (0 oldtag) (0 word1) (+2 word2)) => newtag)
("WDAND2TAGAFT" (match (0 oldtag) (0 word1) (+2 tag2)) => newtag)
("NEXT2TAG" (match (0 oldtag) (+2 tag1)) => newtag)
("NEXT2WD" (match (0 oldtag) (+2 word1)) => newtag)
("NEXTBIGRAM" (match (0 oldtag) (+1 tag1) (+2 tag2)) => newtag)
("NEXT1OR2TAG" (match (0 oldtag) (or (+1 tag1) (+2 tag1))) => newtag)
("NEXT1OR2WD" (match (0 oldtag) (or (+1 word1) (+2 word1))) => newtag)
("NEXT1OR2OR3TAG" (match (0 oldtag) (or (+1 tag1) (+2 tag1) (+3 tag1))) => newtag)
("PREVTAG" (match (0 oldtag) (-1 tag1)) => newtag)
("PREVWD" (match (0 oldtag) (-1 word1)) => newtag)
("LBIGRAM" (match (0 oldtag) (0 word1) (-1 word2)) => newtag)
("WDPREVTAG" (match (0 oldtag) (0 word1) (-1 tag2)) => newtag)
("WDAND2BFR" (match (0 oldtag) (0 word1) (-2 word2)) => newtag)
("WDAND2TAGBFR" (match (0 oldtag) (0 word1) (-2 tag2)) => newtag)
("PREV2TAG" (match (0 oldtag) (-2 tag1)) => newtag)
("PREV2WD" (match (0 oldtag) (-2 word1)) => newtag)
("PREV1OR2TAG" (match (0 oldtag) (or (-1 tag1) (-2 tag1))) => newtag)
("PREV1OR2WD" (match (0 oldtag) (or (-1 word1) (-2 word1))) => newtag)
("PREV1OR2OR3TAG" (match (0 oldtag) (or (-1 tag1) (-2 tag1) (-3 tag1))) => newtag)
("PREV1OR2OR3WD" (match (0 oldtag) (or (-1 word1) (-2 word1) (-3 word1))) => newtag)
("PREVBIGRAM" (match (0 oldtag) (-1 tag2) (-2 tag1)) => newtag))
#|
Macroexpand this to see code for a single rule closure:
(def-contextual-rule-parser make-contextual-rule
("SURROUNDTAG" (match (0 oldtag) (-1 tag1) (+1 tag2)) => newtag))
|#
(defun load-contextual-rules ( rule-file &aux rules )
(write-log tagger-init "Loading contextual rules")
(with-open-file ( s rule-file :external-format :ascii)
(do-contentful-lines (line s ) ;; :count count)
(let* ((context-rule (ppcre:split "\\s+" line))
(closure (make-contextual-rule context-rule)))
(if closure (push closure rules)))))
(nreverse rules))
;; -----------------------------------------
;; LEXICAL RULE FILE INITIALIZATION AND I/F
(defun load-lexical-rules ( rule-file &optional bigram-hash word-hash &aux (rule-list nil))
"Return a list of closure implementing the lexical rules
in rule-file to tag words not found in the lexicon"
(write-log tagger-init "Loading lexical rules")
(with-open-file ( s rule-file :external-format :ascii)
(do-contentful-lines (line s)
(let ((lex-rule (ppcre:split "\\s+" line)))
(let ((rule (make-lexical-rule lex-rule *lexicon* bigram-hash word-hash)))
(if rule (push rule rule-list))))))
(nreverse rule-list))
(let ((pair (cons nil nil)))
(defun guess-tag ( token initial-tag rule-list )
"Using rules in rule-table guess the tag of the token 'token'"
(declare (optimize (speed 3) (safety 0) (debug 0) (space 0)))
(setf (car pair) token)
(setf (cdr pair) initial-tag)
(aif (apply-rules pair rule-list)
(cdr it)
initial-tag)))
;; Expanded implementation, not great but was fast and easy...
;;
;; Example of lexical rule file format:
;; NN would fgoodright VB x
;; NN 0 fchar CD x
;; NN be fgoodright JJ x
(defun make-lexical-rule (list lh bh wh)
"Look through list for rule name"
(declare (ignore bh)
;; (inline strncmp list eq equal char subseq strncmp-end2 length concatenate)
(optimize (speed 0) (safety 3) (debug 3)))
(let ((name (second list))
(fname (third list)))
(cond ((string= name "char")
(let ((prefix (char (first list) 0))
(new-tag (mkkeysym (third list))))
(declare (type character prefix)
(type symbol new-tag))
#'(lambda (pair)
(declare (type cons pair));; (inline char))
(let ((token (car pair))
(tag (cdr pair)))
(declare (type string token) (type symbol tag) (ignore tag))
(if (eq prefix (char token 0))
(progn (setf (cdr pair) new-tag) pair)
pair)))))
((string= fname "fchar")
(let ((old-tag (mkkeysym (first list)))
(prefix (char (second list) 0))
(new-tag (mkkeysym (fourth list))))
(declare (type symbol old-tag new-tag) (type character prefix))
#'(lambda (pair)
(declare (type cons pair));; (inline char))
(let ((token (car pair))
(tag (cdr pair)))
(declare (type string token) (type symbol tag))
(if (and (eq tag old-tag)
(eq prefix (char token 0)))
(progn (setf (cdr pair) new-tag) pair)
pair)))))
((string= name "deletepref")
(let ((prefix (first list))
(count (read-from-string (third list)))
(new-tag (mkkeysym (fourth list))))
(declare #-mcl (type symbol new-tag)
#-mcl (type fixnum count)
#-mcl (type string prefix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare (type string token) (type symbol tag) (ignore tag))
(if (strncmp prefix token count 0)
(let ((root (subseq token count)))
(if (or (hash-get lh root)
(and wh (hash-get wh root)))
(progn (setf (cdr pair) new-tag) pair)
pair))
pair)))))
((string= fname "fdeletepref")
(let ((old-tag (mkkeysym (first list)))
(prefix (second list))
(count (read-from-string (fourth list)))
(new-tag (mkkeysym (fifth list))))
(declare #-mcl (type symbol old-tag new-tag)
#-mcl (type fixnum count)
#-mcl (type string prefix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare (type string token) (type symbol tag))
(if (and (eq tag old-tag)
(strncmp prefix token count 0))
(let ((root (subseq token count)))
(if (or (hash-get lh root)
(and wh (hash-get wh root)))
(progn (setf (cdr pair) new-tag) pair)
pair))
pair)))))
((string= name "haspref")
(let ((prefix (first list))
(count (read-from-string (third list)))
(new-tag (mkkeysym (fourth list))))
(declare #-mcl (type symbol new-tag)
#-mcl (type fixnum count)
#-mcl (type string prefix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag)
(ignore tag))
(if (strncmp prefix token count 0)
(progn (setf (cdr pair) new-tag) pair)
pair)))))
((string= fname "fhaspref")
(let ((old-tag (mkkeysym (first list)))
(prefix (second list))
(count (read-from-string (fourth list)))
(new-tag (mkkeysym (fifth list))))
(declare #-mcl (type symbol new-tag old-tag)
#-mcl (type fixnum count)
#-mcl (type string prefix))
#'(lambda (pair)
(declare (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag))
(if (and (eq tag old-tag)
(strncmp prefix token count 0))
(progn (setf (cdr pair) new-tag) pair)
pair)))))
((string= name "deletesuf")
(let ((suffix (first list))
(count (read-from-string (third list)))
(new-tag (mkkeysym (fourth list))))
(declare #-mcl (type symbol new-tag)
#-mcl (type fixnum count)
#-mcl (type string suffix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag)
(ignore tag))
(if (strncmp-end2 suffix token count (- (length token) count))
(let ((root (subseq token 0 (- (length token) count))))
(if (or (hash-get lh root)
(and wh (hash-get wh root)))
(progn (setf (cdr pair) new-tag) pair)
pair))
pair)))))
((string= fname "fdeletesuf")
(let ((old-tag (mkkeysym (first list)))
(suffix (second list))
(count (read-from-string (fourth list)))
(new-tag (mkkeysym (fifth list))))
(declare #-mcl (type symbol new-tag old-tag)
#-mcl (type fixnum count)
#-mcl (type string suffix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag))
(if (and (eq tag old-tag)
(strncmp-end2 suffix token count (- (length token) count)))
(let ((root (subseq token 0 (- (length token) count))))
(if (or (hash-get lh root)
(and wh (hash-get wh root)))
(progn (setf (cdr pair) new-tag) pair)
pair))
pair)))))
((string= name "hassuf")
(let ((suffix (first list))
(count (read-from-string (third list)))
(new-tag (mkkeysym (fourth list))))
(declare #-mcl (type symbol new-tag)
#-mcl (type fixnum count)
#-mcl (type string suffix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag)
(ignore tag))
(if (strncmp-end2 suffix token count (- (length token) count))
(progn (setf (cdr pair) new-tag) pair)
pair)))))
((string= fname "fhassuf")
(let ((old-tag (mkkeysym (first list)))
(suffix (second list))
(count (read-from-string (fourth list)))
(new-tag (mkkeysym (fifth list))))
(declare #-mcl (type symbol new-tag old-tag)
#-mcl (type fixnum count)
#-mcl (type string suffix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag))
(if (and (eq tag old-tag)
(strncmp-end2 suffix token count (- (length token) count)))
(progn (setf (cdr pair) new-tag) pair)
pair)))))
((string= name "addsuf")
(let ((suffix (first list))
;; (count (read-from-string (third list)))
(new-tag (mkkeysym (fourth list))))
(declare #-mcl (type symbol new-tag)
; #-mcl (type fixnum count)
#-mcl (type string suffix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag)
(ignore tag))
(let ((new-word (concatenate 'string token suffix)))
(if (or (hash-get lh new-word)
(and wh (hash-get wh new-word)))
(progn (setf (cdr pair) new-tag) pair)
pair))))))
((string= fname "faddsuf")
(let ((old-tag (mkkeysym (first list)))
(suffix (second list))
;; (count (read-from-string (fourth list)))
(new-tag (mkkeysym (fifth list))))
(declare #-mcl (type symbol new-tag old-tag)
;; #-mcl (type fixnum count)
#-mcl (type string suffix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag))
(if (eq tag old-tag)
(let ((new-word (concatenate 'string token suffix)))
(if (or (hash-get lh new-word)
(and wh (hash-get wh new-word)))
(progn (setf (cdr pair) new-tag) pair)
pair))
pair)))))
;; ((string= name "addpref")
;; (let ((prefix (first list))
;; (count (read-from-string (third list)))
;; (new-tag (mkkeysym (fourth list))))
;; #'(lambda (token tag)
;; ((string= fname "faddpref")
;; (let ((old-tag (mkkeysym (first list)))
;; (prefix (second list))
;; (count (read-from-string (fourth list)))
;; (new-tag (mkkeysym (fifth list))))
;; #'(lambda (token tag)
;; NOTE: NO BIGRAM SUPPORT YET
;; "goodleft" "fgoodleft" "goodright" "fgoodright"
(t (progn
(write-log tagger-contextual "No rule found for: ~A." list)
nil)))))
(defun apply-rules ( datum rule-list )
"Apply rules to the values in values presuming that
the returned list is also a list of values that can
be passed to the next rule"
(declare (optimize (speed 3) (safety 1) (debug 1) (space 0))
(type list rule-list)
(type list datum))
(cond ((null rule-list)
datum)
((null datum)
(error "Null datum in rule prior to ~A.~%" (car rule-list)))
(t (apply-rules (funcall (car rule-list) datum) (cdr rule-list)))))
| true |
;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10; Package: utils -*-
;;;; *************************************************************************
;;;; FILE IDENTIFICATION
;;;;
;;;; Name: tagger-data
;;;; Purpose: Lisp version of the Brill tagger w/ WSJ/BROWN data; implements
;;;; the data file loading and representation
;;;;
;;;; Programmer: PI:NAME:<NAME>END_PI
;;;; Date Started: October 2004
;;;;
(in-package :langutils)
;; -----------------------------------
;; Contextual rule files
;;
;; The parser builds rules from tokenized rule expressions of the form:
;; <oldtag> <newtag> RULE-TYPE <arg1> <arg2>
;;
;; Where <arg1> can be tag1 or word1 with semantics as described
;; in *contextual-rule-args* above; similarly for <arg2>
;;
(def-contextual-rule-parser make-contextual-rule
("SURROUNDTAG" (match (0 oldtag) (-1 tag1) (+1 tag2)) => newtag)
("NEXTTAG" (match (0 oldtag) (+1 tag1)) => newtag)
("CURWD" (match (0 oldtag) (0 word1)) => newtag)
("NEXTWD" (match (0 oldtag) (+1 word1)) => newtag)
("RBIGRAM" (match (0 oldtag) (0 word1) (+1 word2)) => newtag)
("WDNEXTTAG" (match (0 oldtag) (0 word1) (+1 tag2)) => newtag)
("WDAND2AFT" (match (0 oldtag) (0 word1) (+2 word2)) => newtag)
("WDAND2TAGAFT" (match (0 oldtag) (0 word1) (+2 tag2)) => newtag)
("NEXT2TAG" (match (0 oldtag) (+2 tag1)) => newtag)
("NEXT2WD" (match (0 oldtag) (+2 word1)) => newtag)
("NEXTBIGRAM" (match (0 oldtag) (+1 tag1) (+2 tag2)) => newtag)
("NEXT1OR2TAG" (match (0 oldtag) (or (+1 tag1) (+2 tag1))) => newtag)
("NEXT1OR2WD" (match (0 oldtag) (or (+1 word1) (+2 word1))) => newtag)
("NEXT1OR2OR3TAG" (match (0 oldtag) (or (+1 tag1) (+2 tag1) (+3 tag1))) => newtag)
("PREVTAG" (match (0 oldtag) (-1 tag1)) => newtag)
("PREVWD" (match (0 oldtag) (-1 word1)) => newtag)
("LBIGRAM" (match (0 oldtag) (0 word1) (-1 word2)) => newtag)
("WDPREVTAG" (match (0 oldtag) (0 word1) (-1 tag2)) => newtag)
("WDAND2BFR" (match (0 oldtag) (0 word1) (-2 word2)) => newtag)
("WDAND2TAGBFR" (match (0 oldtag) (0 word1) (-2 tag2)) => newtag)
("PREV2TAG" (match (0 oldtag) (-2 tag1)) => newtag)
("PREV2WD" (match (0 oldtag) (-2 word1)) => newtag)
("PREV1OR2TAG" (match (0 oldtag) (or (-1 tag1) (-2 tag1))) => newtag)
("PREV1OR2WD" (match (0 oldtag) (or (-1 word1) (-2 word1))) => newtag)
("PREV1OR2OR3TAG" (match (0 oldtag) (or (-1 tag1) (-2 tag1) (-3 tag1))) => newtag)
("PREV1OR2OR3WD" (match (0 oldtag) (or (-1 word1) (-2 word1) (-3 word1))) => newtag)
("PREVBIGRAM" (match (0 oldtag) (-1 tag2) (-2 tag1)) => newtag))
#|
Macroexpand this to see code for a single rule closure:
(def-contextual-rule-parser make-contextual-rule
("SURROUNDTAG" (match (0 oldtag) (-1 tag1) (+1 tag2)) => newtag))
|#
(defun load-contextual-rules ( rule-file &aux rules )
(write-log tagger-init "Loading contextual rules")
(with-open-file ( s rule-file :external-format :ascii)
(do-contentful-lines (line s ) ;; :count count)
(let* ((context-rule (ppcre:split "\\s+" line))
(closure (make-contextual-rule context-rule)))
(if closure (push closure rules)))))
(nreverse rules))
;; -----------------------------------------
;; LEXICAL RULE FILE INITIALIZATION AND I/F
(defun load-lexical-rules ( rule-file &optional bigram-hash word-hash &aux (rule-list nil))
"Return a list of closure implementing the lexical rules
in rule-file to tag words not found in the lexicon"
(write-log tagger-init "Loading lexical rules")
(with-open-file ( s rule-file :external-format :ascii)
(do-contentful-lines (line s)
(let ((lex-rule (ppcre:split "\\s+" line)))
(let ((rule (make-lexical-rule lex-rule *lexicon* bigram-hash word-hash)))
(if rule (push rule rule-list))))))
(nreverse rule-list))
(let ((pair (cons nil nil)))
(defun guess-tag ( token initial-tag rule-list )
"Using rules in rule-table guess the tag of the token 'token'"
(declare (optimize (speed 3) (safety 0) (debug 0) (space 0)))
(setf (car pair) token)
(setf (cdr pair) initial-tag)
(aif (apply-rules pair rule-list)
(cdr it)
initial-tag)))
;; Expanded implementation, not great but was fast and easy...
;;
;; Example of lexical rule file format:
;; NN would fgoodright VB x
;; NN 0 fchar CD x
;; NN be fgoodright JJ x
(defun make-lexical-rule (list lh bh wh)
"Look through list for rule name"
(declare (ignore bh)
;; (inline strncmp list eq equal char subseq strncmp-end2 length concatenate)
(optimize (speed 0) (safety 3) (debug 3)))
(let ((name (second list))
(fname (third list)))
(cond ((string= name "char")
(let ((prefix (char (first list) 0))
(new-tag (mkkeysym (third list))))
(declare (type character prefix)
(type symbol new-tag))
#'(lambda (pair)
(declare (type cons pair));; (inline char))
(let ((token (car pair))
(tag (cdr pair)))
(declare (type string token) (type symbol tag) (ignore tag))
(if (eq prefix (char token 0))
(progn (setf (cdr pair) new-tag) pair)
pair)))))
((string= fname "fchar")
(let ((old-tag (mkkeysym (first list)))
(prefix (char (second list) 0))
(new-tag (mkkeysym (fourth list))))
(declare (type symbol old-tag new-tag) (type character prefix))
#'(lambda (pair)
(declare (type cons pair));; (inline char))
(let ((token (car pair))
(tag (cdr pair)))
(declare (type string token) (type symbol tag))
(if (and (eq tag old-tag)
(eq prefix (char token 0)))
(progn (setf (cdr pair) new-tag) pair)
pair)))))
((string= name "deletepref")
(let ((prefix (first list))
(count (read-from-string (third list)))
(new-tag (mkkeysym (fourth list))))
(declare #-mcl (type symbol new-tag)
#-mcl (type fixnum count)
#-mcl (type string prefix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare (type string token) (type symbol tag) (ignore tag))
(if (strncmp prefix token count 0)
(let ((root (subseq token count)))
(if (or (hash-get lh root)
(and wh (hash-get wh root)))
(progn (setf (cdr pair) new-tag) pair)
pair))
pair)))))
((string= fname "fdeletepref")
(let ((old-tag (mkkeysym (first list)))
(prefix (second list))
(count (read-from-string (fourth list)))
(new-tag (mkkeysym (fifth list))))
(declare #-mcl (type symbol old-tag new-tag)
#-mcl (type fixnum count)
#-mcl (type string prefix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare (type string token) (type symbol tag))
(if (and (eq tag old-tag)
(strncmp prefix token count 0))
(let ((root (subseq token count)))
(if (or (hash-get lh root)
(and wh (hash-get wh root)))
(progn (setf (cdr pair) new-tag) pair)
pair))
pair)))))
((string= name "haspref")
(let ((prefix (first list))
(count (read-from-string (third list)))
(new-tag (mkkeysym (fourth list))))
(declare #-mcl (type symbol new-tag)
#-mcl (type fixnum count)
#-mcl (type string prefix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag)
(ignore tag))
(if (strncmp prefix token count 0)
(progn (setf (cdr pair) new-tag) pair)
pair)))))
((string= fname "fhaspref")
(let ((old-tag (mkkeysym (first list)))
(prefix (second list))
(count (read-from-string (fourth list)))
(new-tag (mkkeysym (fifth list))))
(declare #-mcl (type symbol new-tag old-tag)
#-mcl (type fixnum count)
#-mcl (type string prefix))
#'(lambda (pair)
(declare (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag))
(if (and (eq tag old-tag)
(strncmp prefix token count 0))
(progn (setf (cdr pair) new-tag) pair)
pair)))))
((string= name "deletesuf")
(let ((suffix (first list))
(count (read-from-string (third list)))
(new-tag (mkkeysym (fourth list))))
(declare #-mcl (type symbol new-tag)
#-mcl (type fixnum count)
#-mcl (type string suffix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag)
(ignore tag))
(if (strncmp-end2 suffix token count (- (length token) count))
(let ((root (subseq token 0 (- (length token) count))))
(if (or (hash-get lh root)
(and wh (hash-get wh root)))
(progn (setf (cdr pair) new-tag) pair)
pair))
pair)))))
((string= fname "fdeletesuf")
(let ((old-tag (mkkeysym (first list)))
(suffix (second list))
(count (read-from-string (fourth list)))
(new-tag (mkkeysym (fifth list))))
(declare #-mcl (type symbol new-tag old-tag)
#-mcl (type fixnum count)
#-mcl (type string suffix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag))
(if (and (eq tag old-tag)
(strncmp-end2 suffix token count (- (length token) count)))
(let ((root (subseq token 0 (- (length token) count))))
(if (or (hash-get lh root)
(and wh (hash-get wh root)))
(progn (setf (cdr pair) new-tag) pair)
pair))
pair)))))
((string= name "hassuf")
(let ((suffix (first list))
(count (read-from-string (third list)))
(new-tag (mkkeysym (fourth list))))
(declare #-mcl (type symbol new-tag)
#-mcl (type fixnum count)
#-mcl (type string suffix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag)
(ignore tag))
(if (strncmp-end2 suffix token count (- (length token) count))
(progn (setf (cdr pair) new-tag) pair)
pair)))))
((string= fname "fhassuf")
(let ((old-tag (mkkeysym (first list)))
(suffix (second list))
(count (read-from-string (fourth list)))
(new-tag (mkkeysym (fifth list))))
(declare #-mcl (type symbol new-tag old-tag)
#-mcl (type fixnum count)
#-mcl (type string suffix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag))
(if (and (eq tag old-tag)
(strncmp-end2 suffix token count (- (length token) count)))
(progn (setf (cdr pair) new-tag) pair)
pair)))))
((string= name "addsuf")
(let ((suffix (first list))
;; (count (read-from-string (third list)))
(new-tag (mkkeysym (fourth list))))
(declare #-mcl (type symbol new-tag)
; #-mcl (type fixnum count)
#-mcl (type string suffix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag)
(ignore tag))
(let ((new-word (concatenate 'string token suffix)))
(if (or (hash-get lh new-word)
(and wh (hash-get wh new-word)))
(progn (setf (cdr pair) new-tag) pair)
pair))))))
((string= fname "faddsuf")
(let ((old-tag (mkkeysym (first list)))
(suffix (second list))
;; (count (read-from-string (fourth list)))
(new-tag (mkkeysym (fifth list))))
(declare #-mcl (type symbol new-tag old-tag)
;; #-mcl (type fixnum count)
#-mcl (type string suffix))
#'(lambda (pair)
(declare #-mcl (type cons pair))
(let ((token (car pair))
(tag (cdr pair)))
(declare #-mcl (type string token)
#-mcl (type symbol tag))
(if (eq tag old-tag)
(let ((new-word (concatenate 'string token suffix)))
(if (or (hash-get lh new-word)
(and wh (hash-get wh new-word)))
(progn (setf (cdr pair) new-tag) pair)
pair))
pair)))))
;; ((string= name "addpref")
;; (let ((prefix (first list))
;; (count (read-from-string (third list)))
;; (new-tag (mkkeysym (fourth list))))
;; #'(lambda (token tag)
;; ((string= fname "faddpref")
;; (let ((old-tag (mkkeysym (first list)))
;; (prefix (second list))
;; (count (read-from-string (fourth list)))
;; (new-tag (mkkeysym (fifth list))))
;; #'(lambda (token tag)
;; NOTE: NO BIGRAM SUPPORT YET
;; "goodleft" "fgoodleft" "goodright" "fgoodright"
(t (progn
(write-log tagger-contextual "No rule found for: ~A." list)
nil)))))
(defun apply-rules ( datum rule-list )
"Apply rules to the values in values presuming that
the returned list is also a list of values that can
be passed to the next rule"
(declare (optimize (speed 3) (safety 1) (debug 1) (space 0))
(type list rule-list)
(type list datum))
(cond ((null rule-list)
datum)
((null datum)
(error "Null datum in rule prior to ~A.~%" (car rule-list)))
(t (apply-rules (funcall (car rule-list) datum) (cdr rule-list)))))
|
[
{
"context": "ght (C) 2016, Regents of the University of Texas\n; Marijn Heule, Warren A. Hunt, Jr., and Matt Kaufmann\n; License",
"end": 71,
"score": 0.999869167804718,
"start": 59,
"tag": "NAME",
"value": "Marijn Heule"
},
{
"context": "Regents of the University of Texas\n; Marijn Heule, Warren A. Hunt, Jr., and Matt Kaufmann\n; License: A 3-clause BSD",
"end": 87,
"score": 0.9998817443847656,
"start": 73,
"tag": "NAME",
"value": "Warren A. Hunt"
},
{
"context": "niversity of Texas\n; Marijn Heule, Warren A. Hunt, Jr., and Matt Kaufmann\n; License: A 3-clause BSD lic",
"end": 91,
"score": 0.5751527547836304,
"start": 89,
"tag": "NAME",
"value": "Jr"
},
{
"context": " of Texas\n; Marijn Heule, Warren A. Hunt, Jr., and Matt Kaufmann\n; License: A 3-clause BSD license. See the LICEN",
"end": 111,
"score": 0.9998588562011719,
"start": 98,
"tag": "NAME",
"value": "Matt Kaufmann"
}
] |
books/projects/sat/lrat/early/rev2/satisfiable-add-proof-clause-rup.lisp
|
mayankmanj/acl2
| 305 |
; Copyright (C) 2016, Regents of the University of Texas
; Marijn Heule, Warren A. Hunt, Jr., and Matt Kaufmann
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
; See soundness.lisp. Here we prove a key lemma in support of that book.
(in-package "ACL2")
(include-book "satisfiable-add-proof-clause-base")
(include-book "satisfiable-maybe-shrink-formula")
(defthm formula-truep-cons-forward
(implies (and ; (formula-truep formula assignment)
(consp pair)
(not (equal (cdr pair) *deleted-clause*)))
(implies
(formula-truep (make-formula (cons pair (formula-fal formula)))
assignment)
(equal (evaluate-clause (cdr pair) assignment)
t)))
:hints (("Goal" :restrict ((formula-truep-necc
((index (car pair)))))))
:rule-classes nil)
(defthm formula-truep-cons-backward
(implies (and (formula-truep formula assignment)
(consp pair)
(not (equal (cdr pair) *deleted-clause*)))
(implies
(equal (evaluate-clause (cdr pair) assignment)
t)
(formula-truep (make-formula (cons pair (formula-fal formula)))
assignment)))
:hints (("Goal"
:expand ((formula-truep (cons pair formula)
assignment))
:restrict
((formula-truep-necc
((index (formula-truep-witness (cons pair formula)
assignment)))))))
:rule-classes nil)
(defthm formula-truep-cons
(implies (and (formula-truep formula assignment)
(consp pair)
(not (equal (cdr pair) *deleted-clause*)))
(equal
(formula-truep (make-formula (cons pair (formula-fal formula)))
assignment)
(equal (evaluate-clause (cdr pair) assignment)
t)))
:hints (("Goal" :use (formula-truep-cons-forward
formula-truep-cons-backward))))
(defthm satisfiable-add-proof-clause-rup-basic
(implies (and (proof-entry-p entry)
(formula-p formula)
(satisfiable formula)
(equal (unit-propagation formula
(access add-step entry :rup-indices)
(negate-clause-or-assignment
(access add-step entry :clause)))
t))
(satisfiable (add-proof-clause
(access add-step entry :index)
(access add-step entry :clause)
formula)))
:hints (("Goal"
:expand ((satisfiable formula))
:restrict ((satisfiable-suff
((assignment (satisfiable-witness formula)))))))
:rule-classes nil)
(defthm satisfiable-add-proof-clause-rup
(mv-let (ncls ndel new-formula)
(verify-clause formula
(access add-step entry :clause)
(access add-step entry :rup-indices)
(access add-step entry :drat-hints)
ncls
ndel)
(declare (ignore ncls ndel))
(implies (and (proof-entry-p entry)
(formula-p formula)
(satisfiable formula)
(equal (unit-propagation formula
(access add-step entry :rup-indices)
(negate-clause-or-assignment
(access add-step entry :clause)))
t))
(satisfiable (add-proof-clause
(access add-step entry :index)
(access add-step entry :clause)
new-formula))))
:hints (("Goal"
:in-theory (enable formula-p)
:use satisfiable-add-proof-clause-rup-basic))
:rule-classes nil)
|
29297
|
; Copyright (C) 2016, Regents of the University of Texas
; <NAME>, <NAME>, <NAME>., and <NAME>
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
; See soundness.lisp. Here we prove a key lemma in support of that book.
(in-package "ACL2")
(include-book "satisfiable-add-proof-clause-base")
(include-book "satisfiable-maybe-shrink-formula")
(defthm formula-truep-cons-forward
(implies (and ; (formula-truep formula assignment)
(consp pair)
(not (equal (cdr pair) *deleted-clause*)))
(implies
(formula-truep (make-formula (cons pair (formula-fal formula)))
assignment)
(equal (evaluate-clause (cdr pair) assignment)
t)))
:hints (("Goal" :restrict ((formula-truep-necc
((index (car pair)))))))
:rule-classes nil)
(defthm formula-truep-cons-backward
(implies (and (formula-truep formula assignment)
(consp pair)
(not (equal (cdr pair) *deleted-clause*)))
(implies
(equal (evaluate-clause (cdr pair) assignment)
t)
(formula-truep (make-formula (cons pair (formula-fal formula)))
assignment)))
:hints (("Goal"
:expand ((formula-truep (cons pair formula)
assignment))
:restrict
((formula-truep-necc
((index (formula-truep-witness (cons pair formula)
assignment)))))))
:rule-classes nil)
(defthm formula-truep-cons
(implies (and (formula-truep formula assignment)
(consp pair)
(not (equal (cdr pair) *deleted-clause*)))
(equal
(formula-truep (make-formula (cons pair (formula-fal formula)))
assignment)
(equal (evaluate-clause (cdr pair) assignment)
t)))
:hints (("Goal" :use (formula-truep-cons-forward
formula-truep-cons-backward))))
(defthm satisfiable-add-proof-clause-rup-basic
(implies (and (proof-entry-p entry)
(formula-p formula)
(satisfiable formula)
(equal (unit-propagation formula
(access add-step entry :rup-indices)
(negate-clause-or-assignment
(access add-step entry :clause)))
t))
(satisfiable (add-proof-clause
(access add-step entry :index)
(access add-step entry :clause)
formula)))
:hints (("Goal"
:expand ((satisfiable formula))
:restrict ((satisfiable-suff
((assignment (satisfiable-witness formula)))))))
:rule-classes nil)
(defthm satisfiable-add-proof-clause-rup
(mv-let (ncls ndel new-formula)
(verify-clause formula
(access add-step entry :clause)
(access add-step entry :rup-indices)
(access add-step entry :drat-hints)
ncls
ndel)
(declare (ignore ncls ndel))
(implies (and (proof-entry-p entry)
(formula-p formula)
(satisfiable formula)
(equal (unit-propagation formula
(access add-step entry :rup-indices)
(negate-clause-or-assignment
(access add-step entry :clause)))
t))
(satisfiable (add-proof-clause
(access add-step entry :index)
(access add-step entry :clause)
new-formula))))
:hints (("Goal"
:in-theory (enable formula-p)
:use satisfiable-add-proof-clause-rup-basic))
:rule-classes nil)
| true |
; Copyright (C) 2016, Regents of the University of Texas
; PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI., and PI:NAME:<NAME>END_PI
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
; See soundness.lisp. Here we prove a key lemma in support of that book.
(in-package "ACL2")
(include-book "satisfiable-add-proof-clause-base")
(include-book "satisfiable-maybe-shrink-formula")
(defthm formula-truep-cons-forward
(implies (and ; (formula-truep formula assignment)
(consp pair)
(not (equal (cdr pair) *deleted-clause*)))
(implies
(formula-truep (make-formula (cons pair (formula-fal formula)))
assignment)
(equal (evaluate-clause (cdr pair) assignment)
t)))
:hints (("Goal" :restrict ((formula-truep-necc
((index (car pair)))))))
:rule-classes nil)
(defthm formula-truep-cons-backward
(implies (and (formula-truep formula assignment)
(consp pair)
(not (equal (cdr pair) *deleted-clause*)))
(implies
(equal (evaluate-clause (cdr pair) assignment)
t)
(formula-truep (make-formula (cons pair (formula-fal formula)))
assignment)))
:hints (("Goal"
:expand ((formula-truep (cons pair formula)
assignment))
:restrict
((formula-truep-necc
((index (formula-truep-witness (cons pair formula)
assignment)))))))
:rule-classes nil)
(defthm formula-truep-cons
(implies (and (formula-truep formula assignment)
(consp pair)
(not (equal (cdr pair) *deleted-clause*)))
(equal
(formula-truep (make-formula (cons pair (formula-fal formula)))
assignment)
(equal (evaluate-clause (cdr pair) assignment)
t)))
:hints (("Goal" :use (formula-truep-cons-forward
formula-truep-cons-backward))))
(defthm satisfiable-add-proof-clause-rup-basic
(implies (and (proof-entry-p entry)
(formula-p formula)
(satisfiable formula)
(equal (unit-propagation formula
(access add-step entry :rup-indices)
(negate-clause-or-assignment
(access add-step entry :clause)))
t))
(satisfiable (add-proof-clause
(access add-step entry :index)
(access add-step entry :clause)
formula)))
:hints (("Goal"
:expand ((satisfiable formula))
:restrict ((satisfiable-suff
((assignment (satisfiable-witness formula)))))))
:rule-classes nil)
(defthm satisfiable-add-proof-clause-rup
(mv-let (ncls ndel new-formula)
(verify-clause formula
(access add-step entry :clause)
(access add-step entry :rup-indices)
(access add-step entry :drat-hints)
ncls
ndel)
(declare (ignore ncls ndel))
(implies (and (proof-entry-p entry)
(formula-p formula)
(satisfiable formula)
(equal (unit-propagation formula
(access add-step entry :rup-indices)
(negate-clause-or-assignment
(access add-step entry :clause)))
t))
(satisfiable (add-proof-clause
(access add-step entry :index)
(access add-step entry :clause)
new-formula))))
:hints (("Goal"
:in-theory (enable formula-p)
:use satisfiable-add-proof-clause-rup-basic))
:rule-classes nil)
|
[
{
"context": "*********\nPRODIGY Version 2.01 \nCopyright 1989 by Steven Minton, Craig Knoblock, Dan Kuokka and Jaime Carbonell\n\n",
"end": 137,
"score": 0.999881386756897,
"start": 124,
"tag": "NAME",
"value": "Steven Minton"
},
{
"context": "GY Version 2.01 \nCopyright 1989 by Steven Minton, Craig Knoblock, Dan Kuokka and Jaime Carbonell\n\nThe PRODIGY Syst",
"end": 153,
"score": 0.9998682737350464,
"start": 139,
"tag": "NAME",
"value": "Craig Knoblock"
},
{
"context": " \nCopyright 1989 by Steven Minton, Craig Knoblock, Dan Kuokka and Jaime Carbonell\n\nThe PRODIGY System was desig",
"end": 165,
"score": 0.999864399433136,
"start": 155,
"tag": "NAME",
"value": "Dan Kuokka"
},
{
"context": "9 by Steven Minton, Craig Knoblock, Dan Kuokka and Jaime Carbonell\n\nThe PRODIGY System was designed and built by Ste",
"end": 185,
"score": 0.9998776316642761,
"start": 170,
"tag": "NAME",
"value": "Jaime Carbonell"
},
{
"context": "nell\n\nThe PRODIGY System was designed and built by Steven Minton, Craig Knoblock,\nDan Kuokka and Jaime Carbonell. ",
"end": 245,
"score": 0.9998770952224731,
"start": 232,
"tag": "NAME",
"value": "Steven Minton"
},
{
"context": "GY System was designed and built by Steven Minton, Craig Knoblock,\nDan Kuokka and Jaime Carbonell. Additional cont",
"end": 261,
"score": 0.9998807907104492,
"start": 247,
"tag": "NAME",
"value": "Craig Knoblock"
},
{
"context": "igned and built by Steven Minton, Craig Knoblock,\nDan Kuokka and Jaime Carbonell. Additional contributors inc",
"end": 273,
"score": 0.9998762011528015,
"start": 263,
"tag": "NAME",
"value": "Dan Kuokka"
},
{
"context": "t by Steven Minton, Craig Knoblock,\nDan Kuokka and Jaime Carbonell. Additional contributors include Henrik Nordin,\n",
"end": 293,
"score": 0.9998750686645508,
"start": 278,
"tag": "NAME",
"value": "Jaime Carbonell"
},
{
"context": " Jaime Carbonell. Additional contributors include Henrik Nordin,\nYolanda Gil, Manuela Veloso, Robert Joseph, Sant",
"end": 341,
"score": 0.9998595118522644,
"start": 328,
"tag": "NAME",
"value": "Henrik Nordin"
},
{
"context": ". Additional contributors include Henrik Nordin,\nYolanda Gil, Manuela Veloso, Robert Joseph, Santiago Rementer",
"end": 354,
"score": 0.9998610615730286,
"start": 343,
"tag": "NAME",
"value": "Yolanda Gil"
},
{
"context": "l contributors include Henrik Nordin,\nYolanda Gil, Manuela Veloso, Robert Joseph, Santiago Rementeria, Alicia Perez",
"end": 370,
"score": 0.9998647570610046,
"start": 356,
"tag": "NAME",
"value": "Manuela Veloso"
},
{
"context": "nclude Henrik Nordin,\nYolanda Gil, Manuela Veloso, Robert Joseph, Santiago Rementeria, Alicia Perez, \nEllen Riloff",
"end": 385,
"score": 0.9998428225517273,
"start": 372,
"tag": "NAME",
"value": "Robert Joseph"
},
{
"context": "ordin,\nYolanda Gil, Manuela Veloso, Robert Joseph, Santiago Rementeria, Alicia Perez, \nEllen Riloff, Michael Miller, and",
"end": 406,
"score": 0.9998416900634766,
"start": 387,
"tag": "NAME",
"value": "Santiago Rementeria"
},
{
"context": "anuela Veloso, Robert Joseph, Santiago Rementeria, Alicia Perez, \nEllen Riloff, Michael Miller, and Dan Kahn.\n\nTh",
"end": 420,
"score": 0.9998530745506287,
"start": 408,
"tag": "NAME",
"value": "Alicia Perez"
},
{
"context": "obert Joseph, Santiago Rementeria, Alicia Perez, \nEllen Riloff, Michael Miller, and Dan Kahn.\n\nThe PRODIGY syste",
"end": 435,
"score": 0.9998626708984375,
"start": 423,
"tag": "NAME",
"value": "Ellen Riloff"
},
{
"context": " Santiago Rementeria, Alicia Perez, \nEllen Riloff, Michael Miller, and Dan Kahn.\n\nThe PRODIGY system is experimenta",
"end": 451,
"score": 0.9998542666435242,
"start": 437,
"tag": "NAME",
"value": "Michael Miller"
},
{
"context": ", Alicia Perez, \nEllen Riloff, Michael Miller, and Dan Kahn.\n\nThe PRODIGY system is experimental software for",
"end": 465,
"score": 0.9998632669448853,
"start": 457,
"tag": "NAME",
"value": "Dan Kahn"
},
{
"context": " to the designers. \n\nSend comments or requests to: [email protected] or The PRODIGY PROJECT,\nSchool of Computer Scienc",
"end": 943,
"score": 0.9999237060546875,
"start": 925,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
algorithm/java-ml/UCI-small/prodigy/domains/extended-strips/domain.lisp
|
diyerland/saveAll
| 0 |
#|
*******************************************************************************
PRODIGY Version 2.01
Copyright 1989 by Steven Minton, Craig Knoblock, Dan Kuokka and Jaime Carbonell
The PRODIGY System was designed and built by Steven Minton, Craig Knoblock,
Dan Kuokka and Jaime Carbonell. Additional contributors include Henrik Nordin,
Yolanda Gil, Manuela Veloso, Robert Joseph, Santiago Rementeria, Alicia Perez,
Ellen Riloff, Michael Miller, and Dan Kahn.
The PRODIGY system is experimental software for research purposes only.
This software is made available under the following conditions:
1) PRODIGY will only be used for internal, noncommercial research purposes.
2) The code will not be distributed to other sites without the explicit
permission of the designers. PRODIGY is available by request.
3) Any bugs, bug fixes, or extensions will be forwarded to the designers.
Send comments or requests to: [email protected] or The PRODIGY PROJECT,
School of Computer Science, Carnegie Mellon University, Pittsburgh, PA 15213.
*******************************************************************************|#
; oops - noticed by -- domain allows pushing an
; object through the door while your holding another.
; Screws up putdown...
; modified by and changing types...
(setq *OPERATORS* '(
;(GOTO-BOX
; (params (<b> <rm>))
; (preconds
; (and (is-box <b>)
; (inroom <b> <rm>)
; (inroom robot <rm>)))
; (effects ((add (next-to robot <b>))
; (del (at robot <x> <y>))
; (if (next-to robot <z>)(del (next-to robot <z>)))))) ; for testing
(PICKUP-OBJ
(params (<o1>))
(preconds
(and (arm-empty)
(next-to robot <o1>)
(carriable <o1>)))
(effects ((del (arm-empty))
(del (next-to <o1> <*30>))
(del (next-to <*31> <o1>))
(add (holding <o1>)))))
(PUTDOWN
(params (<o2>))
(preconds
(holding <o2>))
; (inroom robot <o2-rm>)
(effects
((del (holding <*35>))
(add (next-to robot <o2>))
(add (arm-empty)))))
(PUTDOWN-NEXT-TO
(params (<o3> <other-ob> <o3-rm>))
(preconds
(and (holding <o3>)
(is-object <other-ob>)
(inroom <other-ob> <o3-rm>)
(inroom <o3> <o3-rm>)
(next-to robot <other-ob>)))
(effects
((del (holding <*35>))
(add (next-to <o3> <other-ob>))
(add (next-to robot <o3>)) ; ordering important
(add (next-to <other-ob> <o3>))
(add (arm-empty)))))
; Steve, if you add this back in, add appropriate scrs too.
(PUSH-TO-DR
(params (<b1> <d1> <r1>))
(preconds
(and (is-door <d1>)
(dr-to-rm <d1> <r1>)
(inroom <b1> <r1>)
(next-to robot <b1>)
(pushable <b1>)))
(effects
((del (next-to robot <*3>))
(del (next-to <b1> <5>))
(del (next-to <*13> <b1>))
(add (next-to <b1> <d1>))
(add (next-to robot <b1>)))))
(PUSH-THRU-DR
(params (<b-x> <d-x> <r-x> <r-y>))
(preconds
(and
(is-room <r-x>)
(dr-to-rm <d-x> <r-x>)
(is-door <d-x>)
(dr-open <d-x>)
(next-to <b-x> <d-x>)
(next-to robot <b-x>)
(pushable <b-x>)
(connects <d-x> <r-x> <r-y>)
(inroom <b-x> <r-y>)))
(effects
(
(del (next-to robot <*1>)) ;confuses regres-state-diff
; next to one thing at a time, so must
(del (next-to <b-x> <*12>)) ; be next to door, but complication, box
; isnt oh well
(del (next-to <*7> <b-x>))
(del (inroom robot <*21>))
(del (inroom <b-x> <*22>))
(add (inroom robot <r-x>))
(add (inroom <b-x> <r-x>))
(add (next-to robot <b-x>)))))
(GO-THRU-DR
(params (<ddx> <rrx> <rry>))
(preconds
(and (arm-empty)
(is-room <rrx>)
(dr-to-rm <ddx> <rrx>)
(is-door <ddx>)
(dr-open <ddx>)
(next-to robot <ddx>)
(connects <ddx> <rrx> <rry>)
(inroom robot <rry>)))
(effects
(
(del (next-to robot <*19>)) ; robot must be next to door only
(del (inroom robot <*20>))
(add (inroom robot <rrx>)))))
(CARRY-THRU-DR
(params (<b-zz> <d-zz> <r-zz> <r-ww>))
(preconds
(and
(is-room <r-zz>)
(dr-to-rm <d-zz> <r-zz>)
(is-door <d-zz>)
(dr-open <d-zz>)
(is-object <b-zz>)
(holding <b-zz>)
(connects <d-zz> <r-zz> <r-ww>)
(inroom <b-zz> <r-ww>)
(inroom robot <r-ww>)
(next-to robot <d-zz>)))
(effects
(
(del (next-to robot <*48>)) ;confuses regres-state-diff
(del (inroom robot <*41>))
(del (inroom <b-zz> <*42>))
(add (inroom robot <r-zz>))
(add (inroom <b-zz> <r-zz>)))))
(GOTO-DR
(params (<dx> <rx>))
(preconds
(and (is-door <dx>)
(dr-to-rm <dx> <rx>)
(inroom robot <rx>)))
(effects
((del (next-to robot <*18>))
(add (next-to robot <dx>)))))
(PUSH-BOX
(params (<ba> <bb> <ra>))
(preconds
(and (is-object <ba>)
(is-object <bb>)
(inroom <bb> <ra>)
(inroom <ba> <ra>)
(pushable <ba>)
(next-to robot <ba>)))
(effects
((del (next-to robot <*14>))
(del (next-to <ba> <*5>))
(del (next-to <*6> <ba>))
(add (next-to robot <ba>))
(add (next-to robot <bb>))
(add (next-to <ba> <bb>))
(add (next-to <bb> <ba>))
)))
(GOTO-OBJ
(params (<b> <rm>))
(preconds
(and
(is-object <b>)
(inroom <b> <rm>)
(inroom robot <rm>)))
(effects ((add (next-to robot <b>))
(del (next-to robot <*109>)))))
(OPEN
(params (<door>))
(preconds
(and (is-door <door>)
(unlocked <door>)
(next-to robot <door>)
(dr-closed <door>)))
(effects
((del (dr-closed <door>))
(add (dr-open <door>)))))
(CLOSE
(params (<door1>))
(preconds
(and (is-door <door1>)
(next-to robot <door1>)
(dr-open <door1>)))
(effects
((del (dr-open <door1>))
(add (dr-closed <door1>)))))
; should probably kill carriable scr rule
(LOCK
(params (<door2> <k1> <rm-b>))
(preconds
(and (is-door <door2>)
(is-key <door2> <k1>)
(holding <k1>)
(dr-to-rm <door2> <rm-b>)
(inroom <k1> <rm-b>)
(next-to robot <door2>)
(dr-closed <door2>)
(unlocked <door2>)))
(effects
((del (unlocked <door2>))
(add (locked <door2>)))))
(UNLOCK
(params (<door3> <k2> <rm-a>))
(preconds
(and (is-door <door3>)
(is-key <door3> <k2>)
(holding <k2>)
(dr-to-rm <door3> <rm-a>)
(inroom <k2> <rm-a>)
(inroom robot <rm-a>)
(next-to robot <door3>)
(locked <door3>)))
(effects
((del (locked <door3>))
(add (unlocked <door3>)))))
))
(setq *INFERENCE-RULES* nil)
|
4156
|
#|
*******************************************************************************
PRODIGY Version 2.01
Copyright 1989 by <NAME>, <NAME>, <NAME> and <NAME>
The PRODIGY System was designed and built by <NAME>, <NAME>,
<NAME> and <NAME>. Additional contributors include <NAME>,
<NAME>, <NAME>, <NAME>, <NAME>, <NAME>,
<NAME>, <NAME>, and <NAME>.
The PRODIGY system is experimental software for research purposes only.
This software is made available under the following conditions:
1) PRODIGY will only be used for internal, noncommercial research purposes.
2) The code will not be distributed to other sites without the explicit
permission of the designers. PRODIGY is available by request.
3) Any bugs, bug fixes, or extensions will be forwarded to the designers.
Send comments or requests to: <EMAIL> or The PRODIGY PROJECT,
School of Computer Science, Carnegie Mellon University, Pittsburgh, PA 15213.
*******************************************************************************|#
; oops - noticed by -- domain allows pushing an
; object through the door while your holding another.
; Screws up putdown...
; modified by and changing types...
(setq *OPERATORS* '(
;(GOTO-BOX
; (params (<b> <rm>))
; (preconds
; (and (is-box <b>)
; (inroom <b> <rm>)
; (inroom robot <rm>)))
; (effects ((add (next-to robot <b>))
; (del (at robot <x> <y>))
; (if (next-to robot <z>)(del (next-to robot <z>)))))) ; for testing
(PICKUP-OBJ
(params (<o1>))
(preconds
(and (arm-empty)
(next-to robot <o1>)
(carriable <o1>)))
(effects ((del (arm-empty))
(del (next-to <o1> <*30>))
(del (next-to <*31> <o1>))
(add (holding <o1>)))))
(PUTDOWN
(params (<o2>))
(preconds
(holding <o2>))
; (inroom robot <o2-rm>)
(effects
((del (holding <*35>))
(add (next-to robot <o2>))
(add (arm-empty)))))
(PUTDOWN-NEXT-TO
(params (<o3> <other-ob> <o3-rm>))
(preconds
(and (holding <o3>)
(is-object <other-ob>)
(inroom <other-ob> <o3-rm>)
(inroom <o3> <o3-rm>)
(next-to robot <other-ob>)))
(effects
((del (holding <*35>))
(add (next-to <o3> <other-ob>))
(add (next-to robot <o3>)) ; ordering important
(add (next-to <other-ob> <o3>))
(add (arm-empty)))))
; Steve, if you add this back in, add appropriate scrs too.
(PUSH-TO-DR
(params (<b1> <d1> <r1>))
(preconds
(and (is-door <d1>)
(dr-to-rm <d1> <r1>)
(inroom <b1> <r1>)
(next-to robot <b1>)
(pushable <b1>)))
(effects
((del (next-to robot <*3>))
(del (next-to <b1> <5>))
(del (next-to <*13> <b1>))
(add (next-to <b1> <d1>))
(add (next-to robot <b1>)))))
(PUSH-THRU-DR
(params (<b-x> <d-x> <r-x> <r-y>))
(preconds
(and
(is-room <r-x>)
(dr-to-rm <d-x> <r-x>)
(is-door <d-x>)
(dr-open <d-x>)
(next-to <b-x> <d-x>)
(next-to robot <b-x>)
(pushable <b-x>)
(connects <d-x> <r-x> <r-y>)
(inroom <b-x> <r-y>)))
(effects
(
(del (next-to robot <*1>)) ;confuses regres-state-diff
; next to one thing at a time, so must
(del (next-to <b-x> <*12>)) ; be next to door, but complication, box
; isnt oh well
(del (next-to <*7> <b-x>))
(del (inroom robot <*21>))
(del (inroom <b-x> <*22>))
(add (inroom robot <r-x>))
(add (inroom <b-x> <r-x>))
(add (next-to robot <b-x>)))))
(GO-THRU-DR
(params (<ddx> <rrx> <rry>))
(preconds
(and (arm-empty)
(is-room <rrx>)
(dr-to-rm <ddx> <rrx>)
(is-door <ddx>)
(dr-open <ddx>)
(next-to robot <ddx>)
(connects <ddx> <rrx> <rry>)
(inroom robot <rry>)))
(effects
(
(del (next-to robot <*19>)) ; robot must be next to door only
(del (inroom robot <*20>))
(add (inroom robot <rrx>)))))
(CARRY-THRU-DR
(params (<b-zz> <d-zz> <r-zz> <r-ww>))
(preconds
(and
(is-room <r-zz>)
(dr-to-rm <d-zz> <r-zz>)
(is-door <d-zz>)
(dr-open <d-zz>)
(is-object <b-zz>)
(holding <b-zz>)
(connects <d-zz> <r-zz> <r-ww>)
(inroom <b-zz> <r-ww>)
(inroom robot <r-ww>)
(next-to robot <d-zz>)))
(effects
(
(del (next-to robot <*48>)) ;confuses regres-state-diff
(del (inroom robot <*41>))
(del (inroom <b-zz> <*42>))
(add (inroom robot <r-zz>))
(add (inroom <b-zz> <r-zz>)))))
(GOTO-DR
(params (<dx> <rx>))
(preconds
(and (is-door <dx>)
(dr-to-rm <dx> <rx>)
(inroom robot <rx>)))
(effects
((del (next-to robot <*18>))
(add (next-to robot <dx>)))))
(PUSH-BOX
(params (<ba> <bb> <ra>))
(preconds
(and (is-object <ba>)
(is-object <bb>)
(inroom <bb> <ra>)
(inroom <ba> <ra>)
(pushable <ba>)
(next-to robot <ba>)))
(effects
((del (next-to robot <*14>))
(del (next-to <ba> <*5>))
(del (next-to <*6> <ba>))
(add (next-to robot <ba>))
(add (next-to robot <bb>))
(add (next-to <ba> <bb>))
(add (next-to <bb> <ba>))
)))
(GOTO-OBJ
(params (<b> <rm>))
(preconds
(and
(is-object <b>)
(inroom <b> <rm>)
(inroom robot <rm>)))
(effects ((add (next-to robot <b>))
(del (next-to robot <*109>)))))
(OPEN
(params (<door>))
(preconds
(and (is-door <door>)
(unlocked <door>)
(next-to robot <door>)
(dr-closed <door>)))
(effects
((del (dr-closed <door>))
(add (dr-open <door>)))))
(CLOSE
(params (<door1>))
(preconds
(and (is-door <door1>)
(next-to robot <door1>)
(dr-open <door1>)))
(effects
((del (dr-open <door1>))
(add (dr-closed <door1>)))))
; should probably kill carriable scr rule
(LOCK
(params (<door2> <k1> <rm-b>))
(preconds
(and (is-door <door2>)
(is-key <door2> <k1>)
(holding <k1>)
(dr-to-rm <door2> <rm-b>)
(inroom <k1> <rm-b>)
(next-to robot <door2>)
(dr-closed <door2>)
(unlocked <door2>)))
(effects
((del (unlocked <door2>))
(add (locked <door2>)))))
(UNLOCK
(params (<door3> <k2> <rm-a>))
(preconds
(and (is-door <door3>)
(is-key <door3> <k2>)
(holding <k2>)
(dr-to-rm <door3> <rm-a>)
(inroom <k2> <rm-a>)
(inroom robot <rm-a>)
(next-to robot <door3>)
(locked <door3>)))
(effects
((del (locked <door3>))
(add (unlocked <door3>)))))
))
(setq *INFERENCE-RULES* nil)
| true |
#|
*******************************************************************************
PRODIGY Version 2.01
Copyright 1989 by PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI
The PRODIGY System was designed and built by PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI,
PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI. Additional contributors include PI:NAME:<NAME>END_PI,
PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI,
PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, and PI:NAME:<NAME>END_PI.
The PRODIGY system is experimental software for research purposes only.
This software is made available under the following conditions:
1) PRODIGY will only be used for internal, noncommercial research purposes.
2) The code will not be distributed to other sites without the explicit
permission of the designers. PRODIGY is available by request.
3) Any bugs, bug fixes, or extensions will be forwarded to the designers.
Send comments or requests to: PI:EMAIL:<EMAIL>END_PI or The PRODIGY PROJECT,
School of Computer Science, Carnegie Mellon University, Pittsburgh, PA 15213.
*******************************************************************************|#
; oops - noticed by -- domain allows pushing an
; object through the door while your holding another.
; Screws up putdown...
; modified by and changing types...
(setq *OPERATORS* '(
;(GOTO-BOX
; (params (<b> <rm>))
; (preconds
; (and (is-box <b>)
; (inroom <b> <rm>)
; (inroom robot <rm>)))
; (effects ((add (next-to robot <b>))
; (del (at robot <x> <y>))
; (if (next-to robot <z>)(del (next-to robot <z>)))))) ; for testing
(PICKUP-OBJ
(params (<o1>))
(preconds
(and (arm-empty)
(next-to robot <o1>)
(carriable <o1>)))
(effects ((del (arm-empty))
(del (next-to <o1> <*30>))
(del (next-to <*31> <o1>))
(add (holding <o1>)))))
(PUTDOWN
(params (<o2>))
(preconds
(holding <o2>))
; (inroom robot <o2-rm>)
(effects
((del (holding <*35>))
(add (next-to robot <o2>))
(add (arm-empty)))))
(PUTDOWN-NEXT-TO
(params (<o3> <other-ob> <o3-rm>))
(preconds
(and (holding <o3>)
(is-object <other-ob>)
(inroom <other-ob> <o3-rm>)
(inroom <o3> <o3-rm>)
(next-to robot <other-ob>)))
(effects
((del (holding <*35>))
(add (next-to <o3> <other-ob>))
(add (next-to robot <o3>)) ; ordering important
(add (next-to <other-ob> <o3>))
(add (arm-empty)))))
; Steve, if you add this back in, add appropriate scrs too.
(PUSH-TO-DR
(params (<b1> <d1> <r1>))
(preconds
(and (is-door <d1>)
(dr-to-rm <d1> <r1>)
(inroom <b1> <r1>)
(next-to robot <b1>)
(pushable <b1>)))
(effects
((del (next-to robot <*3>))
(del (next-to <b1> <5>))
(del (next-to <*13> <b1>))
(add (next-to <b1> <d1>))
(add (next-to robot <b1>)))))
(PUSH-THRU-DR
(params (<b-x> <d-x> <r-x> <r-y>))
(preconds
(and
(is-room <r-x>)
(dr-to-rm <d-x> <r-x>)
(is-door <d-x>)
(dr-open <d-x>)
(next-to <b-x> <d-x>)
(next-to robot <b-x>)
(pushable <b-x>)
(connects <d-x> <r-x> <r-y>)
(inroom <b-x> <r-y>)))
(effects
(
(del (next-to robot <*1>)) ;confuses regres-state-diff
; next to one thing at a time, so must
(del (next-to <b-x> <*12>)) ; be next to door, but complication, box
; isnt oh well
(del (next-to <*7> <b-x>))
(del (inroom robot <*21>))
(del (inroom <b-x> <*22>))
(add (inroom robot <r-x>))
(add (inroom <b-x> <r-x>))
(add (next-to robot <b-x>)))))
(GO-THRU-DR
(params (<ddx> <rrx> <rry>))
(preconds
(and (arm-empty)
(is-room <rrx>)
(dr-to-rm <ddx> <rrx>)
(is-door <ddx>)
(dr-open <ddx>)
(next-to robot <ddx>)
(connects <ddx> <rrx> <rry>)
(inroom robot <rry>)))
(effects
(
(del (next-to robot <*19>)) ; robot must be next to door only
(del (inroom robot <*20>))
(add (inroom robot <rrx>)))))
(CARRY-THRU-DR
(params (<b-zz> <d-zz> <r-zz> <r-ww>))
(preconds
(and
(is-room <r-zz>)
(dr-to-rm <d-zz> <r-zz>)
(is-door <d-zz>)
(dr-open <d-zz>)
(is-object <b-zz>)
(holding <b-zz>)
(connects <d-zz> <r-zz> <r-ww>)
(inroom <b-zz> <r-ww>)
(inroom robot <r-ww>)
(next-to robot <d-zz>)))
(effects
(
(del (next-to robot <*48>)) ;confuses regres-state-diff
(del (inroom robot <*41>))
(del (inroom <b-zz> <*42>))
(add (inroom robot <r-zz>))
(add (inroom <b-zz> <r-zz>)))))
(GOTO-DR
(params (<dx> <rx>))
(preconds
(and (is-door <dx>)
(dr-to-rm <dx> <rx>)
(inroom robot <rx>)))
(effects
((del (next-to robot <*18>))
(add (next-to robot <dx>)))))
(PUSH-BOX
(params (<ba> <bb> <ra>))
(preconds
(and (is-object <ba>)
(is-object <bb>)
(inroom <bb> <ra>)
(inroom <ba> <ra>)
(pushable <ba>)
(next-to robot <ba>)))
(effects
((del (next-to robot <*14>))
(del (next-to <ba> <*5>))
(del (next-to <*6> <ba>))
(add (next-to robot <ba>))
(add (next-to robot <bb>))
(add (next-to <ba> <bb>))
(add (next-to <bb> <ba>))
)))
(GOTO-OBJ
(params (<b> <rm>))
(preconds
(and
(is-object <b>)
(inroom <b> <rm>)
(inroom robot <rm>)))
(effects ((add (next-to robot <b>))
(del (next-to robot <*109>)))))
(OPEN
(params (<door>))
(preconds
(and (is-door <door>)
(unlocked <door>)
(next-to robot <door>)
(dr-closed <door>)))
(effects
((del (dr-closed <door>))
(add (dr-open <door>)))))
(CLOSE
(params (<door1>))
(preconds
(and (is-door <door1>)
(next-to robot <door1>)
(dr-open <door1>)))
(effects
((del (dr-open <door1>))
(add (dr-closed <door1>)))))
; should probably kill carriable scr rule
(LOCK
(params (<door2> <k1> <rm-b>))
(preconds
(and (is-door <door2>)
(is-key <door2> <k1>)
(holding <k1>)
(dr-to-rm <door2> <rm-b>)
(inroom <k1> <rm-b>)
(next-to robot <door2>)
(dr-closed <door2>)
(unlocked <door2>)))
(effects
((del (unlocked <door2>))
(add (locked <door2>)))))
(UNLOCK
(params (<door3> <k2> <rm-a>))
(preconds
(and (is-door <door3>)
(is-key <door3> <k2>)
(holding <k2>)
(dr-to-rm <door3> <rm-a>)
(inroom <k2> <rm-a>)
(inroom robot <rm-a>)
(next-to robot <door3>)
(locked <door3>)))
(effects
((del (locked <door3>))
(add (unlocked <door3>)))))
))
(setq *INFERENCE-RULES* nil)
|
[
{
"context": "se: 10 -*-\n\n;;; cl-typesetting copyright 2002-2021 Marc Battyani see license.txt for the details\n;;; You can reach",
"end": 113,
"score": 0.9998986124992371,
"start": 100,
"tag": "NAME",
"value": "Marc Battyani"
},
{
"context": "icense.txt for the details\n;;; You can reach me at [email protected] or [email protected]\n;;; The homepage of cl-types",
"end": 202,
"score": 0.9999369978904724,
"start": 170,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "an reach me at [email protected] or [email protected]\n;;; The homepage of cl-typesetting is here: http:",
"end": 223,
"score": 0.9999369382858276,
"start": 206,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "pesetting\n :name \"cl-typesetting\"\n :author \"Marc Battyani <[email protected]>\"\n :version ",
"end": 539,
"score": 0.9999026656150818,
"start": 526,
"tag": "NAME",
"value": "Marc Battyani"
},
{
"context": "name \"cl-typesetting\"\n :author \"Marc Battyani <[email protected]>\"\n :version \"0.8\"\n :maintainer \"Marc Battya",
"end": 573,
"score": 0.9999358057975769,
"start": 541,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "concept.com>\"\n :version \"0.8\"\n :maintainer \"Marc Battyani <[email protected]>\"\n :licence ",
"end": 625,
"score": 0.9999020099639893,
"start": 612,
"tag": "NAME",
"value": "Marc Battyani"
},
{
"context": " :version \"0.8\"\n :maintainer \"Marc Battyani <[email protected]>\"\n :licence \"BSD like licence\"\n :descriptio",
"end": 659,
"score": 0.9999359250068665,
"start": 627,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
cl-typesetting.asd
|
mbattyani/cl-typesetting
| 39 |
;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
;;; cl-typesetting copyright 2002-2021 Marc Battyani see license.txt for the details
;;; You can reach me at [email protected] or [email protected]
;;; The homepage of cl-typesetting is here: http://www.fractalconcept.com/asp/html/cl-typesetting.html
(in-package :common-lisp-user)
(defpackage #:cl-typesetting-system
(:use #:cl #:asdf))
(in-package #:cl-typesetting-system)
(defsystem :cl-typesetting
:name "cl-typesetting"
:author "Marc Battyani <[email protected]>"
:version "0.8"
:maintainer "Marc Battyani <[email protected]>"
:licence "BSD like licence"
:description "Common Lisp Typesetting system"
:long-description "The cl-typesetting package is a stand-alone Common Lisp typesetting system."
:perform (load-op :after (op cl-typesetting)
(pushnew :cl-typesetting cl:*features*))
:components ((:file "defpackage")
(:file "specials" :depends-on ("defpackage"))
(:file "boxes" :depends-on ("specials"))
(:file "boxes-fn" :depends-on ("boxes"))
(:file "graphics" :depends-on ("boxes"))
(:file "typo" :depends-on ("boxes"))
(:file "math" :depends-on ("boxes"))
(:file "hyphenation-fp" :depends-on ("specials"))
(:file "hyphenation" :depends-on ("boxes" "hyphenation-fp"))
(:file "layout" :depends-on ("typo" "graphics"))
(:file "tables" :depends-on ("layout"))
(:file "stroke" :depends-on ("layout"))
(:file "references" :depends-on ("specials"))
(:file "top-level" :depends-on ("stroke" "typo" "references"))
(:file "kw-extensions" :depends-on ("top-level" "hyphenation"))
; (:file "test" :depends-on ("top-level" "tables" "math"))
(:file "pprint" :depends-on ("top-level"))
(:file "zzinit" :depends-on ("specials" "hyphenation-fp")))
:depends-on (:cl-pdf))
|
42508
|
;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
;;; cl-typesetting copyright 2002-2021 <NAME> see license.txt for the details
;;; You can reach me at <EMAIL> or <EMAIL>
;;; The homepage of cl-typesetting is here: http://www.fractalconcept.com/asp/html/cl-typesetting.html
(in-package :common-lisp-user)
(defpackage #:cl-typesetting-system
(:use #:cl #:asdf))
(in-package #:cl-typesetting-system)
(defsystem :cl-typesetting
:name "cl-typesetting"
:author "<NAME> <<EMAIL>>"
:version "0.8"
:maintainer "<NAME> <<EMAIL>>"
:licence "BSD like licence"
:description "Common Lisp Typesetting system"
:long-description "The cl-typesetting package is a stand-alone Common Lisp typesetting system."
:perform (load-op :after (op cl-typesetting)
(pushnew :cl-typesetting cl:*features*))
:components ((:file "defpackage")
(:file "specials" :depends-on ("defpackage"))
(:file "boxes" :depends-on ("specials"))
(:file "boxes-fn" :depends-on ("boxes"))
(:file "graphics" :depends-on ("boxes"))
(:file "typo" :depends-on ("boxes"))
(:file "math" :depends-on ("boxes"))
(:file "hyphenation-fp" :depends-on ("specials"))
(:file "hyphenation" :depends-on ("boxes" "hyphenation-fp"))
(:file "layout" :depends-on ("typo" "graphics"))
(:file "tables" :depends-on ("layout"))
(:file "stroke" :depends-on ("layout"))
(:file "references" :depends-on ("specials"))
(:file "top-level" :depends-on ("stroke" "typo" "references"))
(:file "kw-extensions" :depends-on ("top-level" "hyphenation"))
; (:file "test" :depends-on ("top-level" "tables" "math"))
(:file "pprint" :depends-on ("top-level"))
(:file "zzinit" :depends-on ("specials" "hyphenation-fp")))
:depends-on (:cl-pdf))
| true |
;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
;;; cl-typesetting copyright 2002-2021 PI:NAME:<NAME>END_PI see license.txt for the details
;;; You can reach me at PI:EMAIL:<EMAIL>END_PI or PI:EMAIL:<EMAIL>END_PI
;;; The homepage of cl-typesetting is here: http://www.fractalconcept.com/asp/html/cl-typesetting.html
(in-package :common-lisp-user)
(defpackage #:cl-typesetting-system
(:use #:cl #:asdf))
(in-package #:cl-typesetting-system)
(defsystem :cl-typesetting
:name "cl-typesetting"
:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:version "0.8"
:maintainer "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:licence "BSD like licence"
:description "Common Lisp Typesetting system"
:long-description "The cl-typesetting package is a stand-alone Common Lisp typesetting system."
:perform (load-op :after (op cl-typesetting)
(pushnew :cl-typesetting cl:*features*))
:components ((:file "defpackage")
(:file "specials" :depends-on ("defpackage"))
(:file "boxes" :depends-on ("specials"))
(:file "boxes-fn" :depends-on ("boxes"))
(:file "graphics" :depends-on ("boxes"))
(:file "typo" :depends-on ("boxes"))
(:file "math" :depends-on ("boxes"))
(:file "hyphenation-fp" :depends-on ("specials"))
(:file "hyphenation" :depends-on ("boxes" "hyphenation-fp"))
(:file "layout" :depends-on ("typo" "graphics"))
(:file "tables" :depends-on ("layout"))
(:file "stroke" :depends-on ("layout"))
(:file "references" :depends-on ("specials"))
(:file "top-level" :depends-on ("stroke" "typo" "references"))
(:file "kw-extensions" :depends-on ("top-level" "hyphenation"))
; (:file "test" :depends-on ("top-level" "tables" "math"))
(:file "pprint" :depends-on ("top-level"))
(:file "zzinit" :depends-on ("specials" "hyphenation-fp")))
:depends-on (:cl-pdf))
|
[
{
"context": "; Jared: what's this file for? It's not certifiable, so ",
"end": 7,
"score": 0.999681830406189,
"start": 2,
"tag": "NAME",
"value": "Jared"
},
{
"context": "==================|#\n;; alists-definitions.lisp\n;; John D. Powell\n;(in-package \"ALIST\")\n\n;;\n;; This file isolates a",
"end": 403,
"score": 0.9997992515563965,
"start": 389,
"tag": "NAME",
"value": "John D. Powell"
},
{
"context": "d\n (alist::use-equivp domain x x))\n\n; [Removed by Matt K. to handle changes to member, assoc, etc. after AC",
"end": 744,
"score": 0.9801530838012695,
"start": 738,
"tag": "NAME",
"value": "Matt K"
}
] |
books/coi/alists/alists-definitions.lsp
|
ragerdl/acl2-defthm-rc2
| 1 |
; Jared: what's this file for? It's not certifiable, so I'm
; renaming it to a .lsp extension for Make compatibility
#|-*-Lisp-*-=================================================================|#
#| |#
#|===========================================================================|#
;; alists-definitions.lisp
;; John D. Powell
;(in-package "ALIST")
;;
;; This file isolates alists definitions and types. The file currently
;; contains the following ACL2 constructs as they occur in the alists book:
;; - defun
;; - defund
;; - defstub
;; - defchoose
;; - defthm
;; - in-theory
;;
(defthm alist::use-equivp-id
(alist::use-equivp domain x x))
; [Removed by Matt K. to handle changes to member, assoc, etc. after ACL2 4.2.]
; (defthm assoc-eq-is-assoc
; (equal (assoc-eq key list)
; (assoc key list)))
(defthm assoc-equiv-rewrite-order
(implies
(syntaxp (acl2::good-rewrite-order y x))
(equal (alist::assoc-equiv domain x y)
(alist::assoc-equiv domain y x))))
(in-theory (disable ALIST::ASSOC-EQUIV-COMMUTE))
(defthm assoc-equiv-substitution
(implies
(and
(alist::assoc-equiv d1 x y)
(subsetp d2 d1))
(alist::use-equiv :lhs x
:rhs y
:domain d2)))
(defthm assoc-use-cong
(implies
(and
(equal domain (list a))
(acl2::bind-contextp ((b1 (equal b2 (alist::use-ctx b1 :domain domain))))))
(alist::cons-equiv (assoc a b1)
(assoc a b2))))
(defthm alist::use-equivp-self-characterization
(implies
(acl2::bind-contextp ((x (equal a (alist::use-ctx x :domain domain)))
(y (equal b (alist::use-ctx y :domain domain)))))
(equal (alist::use-equivp domain x y)
(alist::use-equivp domain a b))))
(defthm use-equiv-cons-not-member-reduction
(implies
(not (list::memberp (car a) domain))
(alist::use-equiv :lhs (cons a list)
:rhs list
:domain domain)))
(defthm use-equiv-cons-normal-form
(implies
(and
(syntaxp (acl2::<< (car b) (car a)))
(not (equal (car a) (car b))))
(alist::use-equiv :lhs (cons a (cons b x))
:rhs (cons b (cons a x)))))
(defthm use-equiv-append-normal-form
(implies
(and
(syntaxp (acl2::<< y x))
(bag::disjoint (alist::keys x) (alist::keys y)))
(alist::use-equiv :lhs (append x y)
:rhs (append y x))))
;; ===========================================================================
;;
;; This was the easy property .. dropping the first argument to
;; append will be tougher.
;;
;; ===========================================================================
(defthm use-equiv-append-reduction-2
(implies
(subsetp domain (alist::keys x))
(alist::use-equiv :lhs (append x y)
:rhs x
:domain domain)))
;; ===========================================================================
;;
;; assoc-transparent: either the keys are disjoint or the bound values
;; are equal.
;;
;; ===========================================================================
(defun assoc-transparent (key value alist)
(if (consp alist)
(and (implies (equal key (caar alist)) (equal value (cdar alist)))
(assoc-transparent key value (cdr alist)))
t))
(defthm assoc-transparent-append
(equal (assoc-transparent key value (append x y))
(and (assoc-transparent key value x)
(assoc-transparent key value y))))
(defthm assoc-transparent-implies-cons-equiv-assoc
(implies
(assoc-transparent key value x)
(alist::cons-equiv (assoc key x)
(and (list::memberp key (alist::keys x)) (cons key value))))
:hints (("Goal" :in-theory (enable alist::keys))))
(defthm assoc-transparent-implies-cons-equiv-assoc-2
(implies
(and
(assoc-transparent key (cdr (assoc key x)) y)
(list::memberp key (alist::keys y)))
(alist::cons-equiv (assoc key x)
(and (list::memberp key (alist::keys x)) (assoc key y))))
:hints (("Goal" :induct (assoc key y)
:in-theory (enable alist::keys))))
(defthm assoc-transparent-non-memberp
(implies
(not (list::memberp key (alist::keys x)))
(assoc-transparent key nil x))
:hints (("Goal" :in-theory (enable alist::keys))))
(defthm use-equiv-cons-assoc-transparent-reduction
(implies
(and
(assoc-transparent (car a) (cdr a) list)
(list::memberp (car a) (alist::keys list)))
(alist::use-equiv :lhs (cons a list)
:rhs list
:domain domain))
:hints (("Goal" :in-theory (enable alist::keys))))
;; ===========================================================================
;;
;; unified-domain-binding: the alist is self-assoc-transparent.
;;
;; cross-domain-binding: the glue that combines two parts of a
;; unified-domain-binding.
;;
;; ===========================================================================
(defun unified-domain-binding (domain alist)
(if (consp domain)
(and (assoc-transparent (car domain) (cdr (assoc (car domain) alist)) alist)
(unified-domain-binding (cdr domain) alist))
t))
(defun cross-domain-binding (domain x y)
(if (consp domain)
(let ((key (car domain)))
(and (implies (list::memberp key (alist::keys x))
(assoc-transparent key (cdr (assoc key x)) y))
(cross-domain-binding (cdr domain) x y)))
t))
(defthm disjoint-cross-domain-binding
(implies
(bag::disjoint (alist::keys x) (alist::keys y))
(cross-domain-binding domain x y))
:hints (("Goal" :in-theory (enable alist::keys))))
(defthm cross-domain-binding-replacement
(implies
(and
(cross-domain-binding domain x y)
(list::memberp key domain)
(list::memberp key (alist::keys y)))
(alist::cons-equiv (assoc key x)
(and (list::memberp key (alist::keys x)) (assoc key y)))))
(defthmd cross-domain-binding-cons
(implies
(and
(consp x)
(unified-domain-binding domain x))
(equal (cross-domain-binding domain x y)
(and (implies (list::memberp (caar x) domain)
(assoc-transparent (caar x) (cdar x) y))
(cross-domain-binding domain (cdr x) y))))
:hints (("Goal" :induct (cross-domain-binding domain x y)
:in-theory (enable alist::keys))))
(defthmd cross-domain-binding-not-cons
(implies
(not (consp x))
(cross-domain-binding domain x y))
:hints (("Goal" :in-theory (enable alist::keys))))
(defthmd unified-domain-binding-cons
(implies
(consp x)
(equal (unified-domain-binding domain x)
(and (implies (list::memberp (caar x) domain)
(assoc-transparent (caar x) (cdar x) (cdr x)))
(unified-domain-binding domain (cdr x)))))
:hints (("Goal" :induct (unified-domain-binding domain x)
:in-theory (enable alist::keys))))
(defthmd unified-domain-binding-non-cons
(implies
(not (consp x))
(unified-domain-binding domain x)))
(defthm unified-domain-binding-append
(equal (unified-domain-binding domain (append x y))
(and (unified-domain-binding domain x)
(unified-domain-binding domain y)
(cross-domain-binding domain x y)))
:hints (("Goal" :induct (append x y)
:in-theory (enable append
unified-domain-binding-cons
unified-domain-binding-non-cons
cross-domain-binding-cons
cross-domain-binding-not-cons
))))
(defthm use-equiv-append-reduction-1
(implies
(and
(cross-domain-binding d1 x y)
(subsetp domain d1)
(subsetp domain (alist::keys y)))
(alist::use-equiv :lhs (append x y)
:rhs y
:domain domain))
:hints (("Goal" :in-theory (disable ASSOC-EQUIV-SUBSTITUTION)))
:otf-flg t)
;; ===========================================================================
;;
;; unified-binding: the alist is self-consistent w/to unified-domain-bindings
;;
;; ===========================================================================
(defund unified-binding (alist)
(unified-domain-binding (alist::keys alist) alist))
(defun equiv-domain-binding (domain x y)
(and (cross-domain-binding domain x y)
(cross-domain-binding domain y x)))
(defthm unified-domain-binding-subsetp
(implies
(and
(unified-domain-binding y a)
(subsetp x y))
(unified-domain-binding x a)))
(defund clearkey (k x)
(declare (xargs :guard (alistp x)))
(if (consp x)
(if (equal k (caar x))
(clearkey k (cdr x))
(cons (consfix (car x))
(clearkey k (cdr x))))
nil))
(defthm alistp-of-clearkey
(alistp (clearkey k x))
:hints(("Goal" :in-theory (enable clearkey))))
(defthm clearkey-of-cons
(equal (clearkey k (cons a x))
(if (equal k (car a))
(clearkey k x)
(cons (consfix a) (clearkey k x))))
:hints(("Goal" :in-theory (enable clearkey))))
; no theorem about car-of-clearkey, too hard to describe
; no theorem about cdr-of-clearkey, too hard to describe
(defthm len-of-clearkey-bound-tight
(implies (memberp k (strip-cars x))
(< (len (clearkey k x))
(len x)))
:rule-classes :linear
:hints(("Goal" :in-theory (enable clearkey))))
(defthm len-of-clearkey-bound-tight-rewrite
(implies (memberp k (strip-cars x))
(equal (< (len (clearkey k x)) (len x))
t)))
(defthm len-of-clearkey-bound-weak
(<= (len (clearkey k x))
(len x))
:rule-classes :linear
:hints(("Goal" :in-theory (enable clearkey))))
(defthm len-of-clearkey-bound-weak-rewrite
(equal (< (len x) (len (clearkey k x)))
nil))
;; no theorem about clearkey-of-firstn, too awkward to describe
;; no theorem about clearkey-of-nthcdr, too awkward to describe
(defthm clearkey-of-append
(equal (clearkey k (append x y))
(append (clearkey k x)
(clearkey k y)))
:hints(("Goal" :in-theory (enable clearkey))))
(defthm clearkey-reorder
(equal (clearkey k1 (clearkey k2 r))
(clearkey k2 (clearkey k1 r)))
:hints(("Goal" :in-theory (enable clearkey))))
(defthm clearkey-when-non-memberp
(implies (not (memberp key (strip-cars x)))
(equal (clearkey key x)
(alistfix x)))
:hints(("Goal" :in-theory (enable clearkey))))
(defthm clearkey-caar-when-unique
(implies (and (consp x)
(BAG::unique (strip-cars x)))
(equal (clearkey (caar x) (cdr x))
(alistfix (cdr x)))))
(defthm strip-cars-of-clearkey
(equal (strip-cars (clearkey k x))
(BAG::remove-all k (strip-cars x)))
:hints(("Goal" :in-theory (enable clearkey))))
(defthm clearkey-idempotent
(equal (clearkey k (clearkey k r))
(clearkey k r)))
(defthm not-memberp-of-strip-cdrs-of-clearkey
(implies (not (memberp val (strip-cdrs x)))
(not (memberp val (strip-cdrs (clearkey key x)))))
:hints(("Goal" :in-theory (enable clearkey))))
;; bzo move to bags library
(defthm count-of-remove-all-diff
(implies (not (equal a b))
(equal (BAG::count a (BAG::remove-all b x))
(BAG::count a x)))
:hints(("Goal" :in-theory (enable BAG::remove-all))))
(defund deshadow (x)
(declare (xargs :guard (alistp x)
:measure (len x)))
(if (consp x)
(cons (consfix (car x))
(deshadow (clearkey (caar x) (cdr x))))
nil))
(defthm deshadow-type-1
(implies (not (consp x))
(equal (deshadow x) nil))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable deshadow))))
(defthm deshadow-type-2
(implies (consp x)
(consp (deshadow x)))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable deshadow))))
(defthm deshadow-of-non-consp
(implies (not (consp x))
(equal (deshadow x)
nil)))
(defthm consp-of-deshadow
(equal (consp (deshadow x))
(consp x)))
(defthm deshadow-of-cons
(equal (deshadow (cons x y))
(cons (consfix x)
(deshadow (clearkey (car x) y))))
:hints(("Goal" :in-theory (enable deshadow clearkey))))
(defthm car-of-deshadow
(equal (car (deshadow x))
(if (consp x)
(consfix (car x))
nil)))
;; no rules about cdr-of-deshadow, it is weird
(defthm len-of-deshadow-weak
(<= (len (deshadow x))
(len x))
:rule-classes :linear
:hints(("Goal" :in-theory (enable deshadow))))
(defthm len-of-deshadow-weak-rewrite
(equal (< (len x) (len (deshadow x)))
nil))
;; Even though we will shortly prove deshadow-when-strip-cars-unique, we will
;; go ahead and prove both :linear rules below, so that we can backchain to
;; the unique of strip cars hypothesis when necessary.
(defthm len-of-deshadow-when-strip-cars-not-unique
(implies (not (BAG::unique (strip-cars x)))
(< (len (deshadow x))
(len x)))
:rule-classes :linear
:hints(("Goal" :in-theory (enable deshadow))))
(defthm len-of-deshadow-when-strip-cars-unique
(implies (BAG::unique (strip-cars x))
(equal (len (deshadow x))
(len x)))
:rule-classes :linear
:hints(("Goal" :in-theory (enable deshadow))))
(defthm len-of-deshadow-decreases-rewrite
(equal (< (len (deshadow x)) (len x))
(not (BAG::unique (strip-cars x)))))
(defthm alistp-of-deshadow
(alistp (deshadow x))
:hints(("Goal" :in-theory (enable deshadow))))
(defthm deshadow-of-clearkey
(equal (deshadow (clearkey key x))
(clearkey key (deshadow x)))
:hints(("Goal" :in-theory (enable deshadow))))
(defthm unique-of-strip-cars-of-deshadow
(BAG::unique (strip-cars (deshadow x)))
:hints(("Goal" :in-theory (enable deshadow))))
(defthm deshadow-when-strip-cars-unique
(implies (BAG::unique (strip-cars x))
(equal (deshadow x)
(alistfix x)))
:hints(("Goal" :in-theory (enable deshadow))))
(defthm deshadow-idempotent
(equal (deshadow (deshadow x))
(deshadow x)))
(defthm memberp-of-strip-cars-of-deshadow
(equal (memberp key (strip-cars (deshadow x)))
(memberp key (strip-cars x)))
:hints(("Goal" :in-theory (enable deshadow))))
(defthm count-of-strip-cars-of-deshadow
(<= (BAG::count key (strip-cars (deshadow x)))
(BAG::count key (strip-cars x)))
:hints(("Goal" :in-theory (enable deshadow))))
;; There is probably an equivalent rule for strip-cdrs, but I haven't tried
;; to prove it yet.
(defthm not-memberp-of-strip-cdrs-of-deshadow
(implies (not (memberp val (strip-cdrs x)))
(equal (memberp val (strip-cdrs (deshadow x)))
nil))
:hints(("Goal" :in-theory (enable deshadow))))
;; Interpreting Objects as Conses (consfix)
;;
;; We can think of a mapping between all ACL2 objects and conses, so that any
;; atom is mapped to (nil . nil) and any cons is mapped to itself. The
;; function consfix applies this mapping for us, i.e., it interprets any ACL2
;; object as a cons. Because this is how car and cdr interpret their
;; arguments, there are some very nice properties that we can prove about this
;; operation.
(defund consfix (x)
(declare (type t x))
(if (consp x)
x
(cons nil nil)))
(defthm consfix-when-non-consp
(implies (not (consp x))
(equal (consfix x)
(cons nil nil)))
:hints(("Goal" :in-theory (enable consfix))))
(defthm consfix-when-consp
(implies (consp x)
(equal (consfix x)
x))
:hints(("Goal" :in-theory (enable consfix))))
(defthm consfix-does-nothing
(equal (equal x (consfix x))
(consp x))
:hints(("Goal" :in-theory (enable consfix))))
(defthm consfix-of-cons
(equal (consfix (cons a b))
(cons a b)))
;; Note (jcd): Do not add the following rules. They are trivial consequences
;; of the congruence rules under cons-equiv below, so adding them is not
;; necessary.
;;
;; (defthm consfix-of-car
;; (equal (car (consfix a))
;; (car a)))
;;
;; (defthm consfix-of-cdr
;; (equal (cdr (consfix a))
;; (cdr a)))
;; The Cons Equivalence Relation (cons-equiv)
;;
;; Given that (with consfix) we can now think of any object as a cons, the next
;; natural step is to define an equivalence relation wherein objects are
;; considered to be equivalent when their interpretations as conses are the
;; same.
(defund cons-equiv (x y)
(declare (type t x y))
(equal (consfix x)
(consfix y)))
(defthm consfix-in-cons-equiv
(cons-equiv (consfix x)
x)
:hints(("Goal" :in-theory (enable cons-equiv))))
(defthm equal-of-consfixes
(equal (equal (consfix x) (consfix y))
(cons-equiv x y))
:hints (("Goal" :in-theory (enable cons-equiv))))
;; Interpreting Objects as Alists (alistfix)
;;
;; An alist is a list of pairs. Since we can now interpret any ACL2 object as
;; a pair using consfix, it is straightforward to interpet any ACL2 object as
;; an alist: any atom is interpreted as the empty alist, and any list is fixed
;; by pair-fixing each of its elements.
;;
;; An alternate definition that I considered was to simply interpret any
;; non-alistp object as the empty alist, and any alist as itself. But, I think
;; the current approach gives us many nice rules. In particular, our approach
;; allows alist-equiv to be a refinement of list::equiv, giving us a lot of
;; rewrite rules "for free" (e.g., the lengths are the same). Other rules work
;; nicely (the keys are the same, the values are the same, etc.) Finally, we
;; also get to provide very nice congruence rules, e.g., the cars of alist
;; interpretations are cons-equiv.
(defund alistfix (x)
(declare (type t x))
(if (consp x)
(cons (consfix (car x))
(alistfix (cdr x)))
nil))
(defthm alistfix-type-consp
(implies (consp x)
(consp (alistfix x)))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable alistfix))))
(defthm alistfix-type-non-consp
(implies (not (consp x))
(equal (alistfix x)
nil))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable alistfix))))
;; Note (jcd): Do not add the following rule. It is redundant with the defcong
;; below for alist-equiv over consp.
;;
;; (defthm consp-alistfix
;; (equal (consp (alistfix x))
;; (consp x)))
(defthm alistfix-when-non-consp
(implies (not (consp alist))
(equal (alistfix alist)
nil)))
(defthm alistfix-when-alist
(implies (alistp x)
(equal (alistfix x)
x))
:hints(("Goal" :in-theory (enable alistfix))))
(defthm alistfix-does-nothing
(equal (equal x (alistfix x))
(alistp x))
:hints(("Goal" :in-theory (enable alistfix))))
(defthm alistp-of-alistfix
(alistp (alistfix x))
:hints(("Goal" :in-theory (enable alistfix))))
(defthm alistfix-of-cons
(equal (alistfix (cons a x))
(cons (consfix a) (alistfix x)))
:hints(("Goal" :in-theory (enable alistfix))))
(defthm car-of-alistfix
(equal (car (alistfix a))
(if (consp a)
(consfix (car a))
nil)))
(defthm cdr-of-alistfix
(equal (cdr (alistfix a))
(alistfix (cdr a))))
;; Note (jcd): Do not add the following rule. It is trivial using the
;; congruence rule of alist-equiv for len, along with alistfix-in-alist-equiv.
;;
;; (defthm len-of-alistfix
;; (equal (len (alistfix a))
;; (len a)))
(defthm alistfix-of-append
(equal (alistfix (append x y))
(append (alistfix x)
(alistfix y)))
:hints(("Goal" :in-theory (enable append))))
(defthm alistfix-of-firstn
(equal (alistfix (list::firstn n x))
(list::firstn n (alistfix x)))
:hints(("Goal" :in-theory (enable list::firstn))))
(defthm alistfix-of-nthcdr
(equal (alistfix (nthcdr n x))
(nthcdr n (alistfix x)))
:hints(("Goal" :in-theory (enable nthcdr))))
;; The Alist Equivalence Relation
;;
;; Given that (with alistfix) we can now think of any object as an alist, the
;; next natural step is to define an equivalence relation wherein objects are
;; considered to be equivalent when their interpretations as alists are the
;; same.
;;
;; IMPORTANT: You might think that alists should be considered to be equivalent
;; whenever "forall a, (assoc a x) = (assoc a y)." Although equivalent alists
;; will satisfy this property, the converse is NOT true! For example, if x and
;; y satisfy this property but x has shadowed pairs and y does not, then x and
;; y will not be considered equivalent under alist-equiv!
;;
;; Instead, you should think of alist-equiv as a "structural" relation that
;; essentially is comparing the interpretation of x and y as lists of pairs.
;; But understand that no a priori judgement is made as to how those lists of
;; pairs will be used, and we do not assume that shadowed pairs are irrelevant.
(defund alist-equiv (a b)
(equal (alistfix a)
(alistfix b)))
(defthm alistfix-in-alist-equiv
(alist-equiv (alistfix a)
a)
:hints(("Goal" :in-theory (enable alist-equiv))))
(defthm alist-equiv-cons-cases
(equal (alist-equiv x (cons y z))
(and (consp x)
(cons-equiv y (car x))
(alist-equiv z (cdr x))))
:hints(("Goal" :in-theory (enable alist-equiv))))
(defthm equal-of-alistfixes
(equal (equal (alistfix x) (alistfix y))
(alist-equiv x y))
:hints(("Goal" :in-theory (enable alist-equiv))))
;; Interpreting Objects as Conses (consfix)
;;
;; We can think of a mapping between all ACL2 objects and conses, so that any
;; atom is mapped to (nil . nil) and any cons is mapped to itself. The
;; function consfix applies this mapping for us, i.e., it interprets any ACL2
;; object as a cons. Because this is how car and cdr interpret their
;; arguments, there are some very nice properties that we can prove about this
;; operation.
(defund consfix (x)
(declare (type t x))
(if (consp x)
x
(cons nil nil)))
(defthm consfix-when-non-consp
(implies (not (consp x))
(equal (consfix x)
(cons nil nil)))
:hints(("Goal" :in-theory (enable consfix))))
(defthm consfix-when-consp
(implies (consp x)
(equal (consfix x)
x))
:hints(("Goal" :in-theory (enable consfix))))
(defthm consfix-does-nothing
(equal (equal x (consfix x))
(consp x))
:hints(("Goal" :in-theory (enable consfix))))
(defthm consfix-of-cons
(equal (consfix (cons a b))
(cons a b)))
;; Note (jcd): Do not add the following rules. They are trivial consequences
;; of the congruence rules under cons-equiv below, so adding them is not
;; necessary.
;;
;; (defthm consfix-of-car
;; (equal (car (consfix a))
;; (car a)))
;;
;; (defthm consfix-of-cdr
;; (equal (cdr (consfix a))
;; (cdr a)))
;; The Cons Equivalence Relation (cons-equiv)
;;
;; Given that (with consfix) we can now think of any object as a cons, the next
;; natural step is to define an equivalence relation wherein objects are
;; considered to be equivalent when their interpretations as conses are the
;; same.
(defund cons-equiv (x y)
(declare (type t x y))
(equal (consfix x)
(consfix y)))
(defthm cons-equiv-cases-fwd
(implies
(and (equal (car x) (car y))
(equal (cdr x) (cdr y)))
(cons-equiv x y))
:hints (("Goal" :in-theory (enable cons-equiv)))
:rule-classes (:forward-chaining))
(defthm not-cons-equiv-cases-fwd-1
(implies
(not (equal (car x) (car y)))
(not (cons-equiv x y)))
:hints (("Goal" :in-theory (enable cons-equiv)))
:rule-classes (:forward-chaining))
(defthm not-cons-equiv-cases-fwd-2
(implies
(not (equal (cdr x) (cdr y)))
(not (cons-equiv x y)))
:hints (("Goal" :in-theory (enable cons-equiv)))
:rule-classes (:forward-chaining))
(defthm cons-equiv-fwd
(implies
(cons-equiv x y)
(and (equal (car x) (car y))
(equal (cdr x) (cdr y))))
:hints (("Goal" :in-theory (enable cons-equiv)))
:rule-classes (:forward-chaining))
(defthm cons-equiv-cons-reduction-1
(equal (cons-equiv (cons a b) c)
(and (equal a (car c))
(equal b (cdr c))))
:hints (("Goal" :in-theory (enable cons-equiv))))
(defthm cons-equiv-cons-reduction-2
(equal (cons-equiv a (cons b c))
(and (equal (car a) b)
(equal (cdr a) c)))
:hints (("Goal" :in-theory (enable cons-equiv))))
(defthm consfix-in-cons-equiv
(cons-equiv (consfix x)
x)
:hints(("Goal" :in-theory (enable cons-equiv))))
(defthm equal-of-consfixes
(equal (equal (consfix x) (consfix y))
(cons-equiv x y))
:hints (("Goal" :in-theory (enable cons-equiv))))
(defun keys (alist)
(declare (type t alist))
(if (consp alist)
(if (consp (car alist))
(cons (caar alist)
(keys (cdr alist)))
(cons nil (keys (cdr alist))))
nil))
#|
(defthm memberp-cons-keys
(implies
(consp alist)
(memberp (caar alist) (keys alist))))
(defthm clrv-len-reduction
(implies
(memberp a (keys alist))
(< (len (clrv a alist)) (len alist)))
:rule-classes (:linear))
(defun element (a y)
(if (consp y)
(if (equal (car a) (caar y))
(equal (cdr a) (cdar y))
(element a (cdr y)))
nil))
(defthm element-definition
(equal (element a y)
(and (memberp (car a) (keys y))
(equal (cdr a) (cdr (getv (car a) y)))))
:rule-classes (:definition))
(defthm element-implication
(implies
(element a y)
(and (memberp (car a) (keys y))
(equal (cdr a) (cdr (getv (car a) y)))))
:rule-classes (:forward-chaining))
(defthm element-elements-implication
(implies
(and (memberp (car a) (keys y))
(equal (cdr a) (cdr (getv (car a) y))))
(element a y))
:rule-classes (:forward-chaining))
(defthm not-element-elements-implication-1
(implies
(not (memberp (car a) (keys y)))
(not (element a y)))
:rule-classes (:forward-chaining))
(defthm not-element-elements-implication-2
(implies
(not (equal (cdr a) (cdr (getv (car a) y))))
(not (element a y)))
:rule-classes (:forward-chaining))
(defthm element-base
(implies
(not (consp x))
(not (element a x)))
:hints (("Goal" :in-theory (enable element))))
(defthm element-cons
(equal (element a (cons x y))
(if (equal (car a) (car x))
(equal (cdr a) (cdr x))
(element a y)))
:hints (("Goal" :in-theory (enable element))))
(defthm element-append
(equal (element a (append x y))
(if (memberp (car a) (keys x))
(element a x)
(element a y)))
:hints (("Goal" :induct (append x y)
:in-theory (enable memberp append element))))
|#
(defthm assoc-append
(equal (assoc a (append x y))
(if (memberp a (keys x))
(assoc a x)
(assoc a y))))
(defthm keys-append
(equal (keys (append x y))
(append (keys x)
(keys y))))
;; pick-a-point
#|
(defthm consp-implies-memberp
(implies
(consp x)
(memberp (caar x) (keys x))))
|#
(defun assoc-equiv (list x y)
(if (consp list)
(and (cons-equiv (assoc (car list) x)
(assoc (car list) y))
(assoc-equiv (cdr list) x y))
t))
(defthmd assoc-equiv-commute
(equal (assoc-equiv list x y)
(assoc-equiv list y x)))
(defthm assoc-equiv-commute-fwd
(implies
(assoc-equiv list x y)
(assoc-equiv list y x))
:hints (("Goal" :in-theory (enable assoc-equiv-commute))))
(defthm assoc-equiv-memberp
(implies
(and
(memberp a list)
(assoc-equiv list x y))
(cons-equiv (assoc a x)
(assoc a y)))
:rule-classes (:forward-chaining))
(defthm assoc-equiv-subsetp-1
(implies
(and
(subsetp a b)
(assoc-equiv b x y))
(assoc-equiv a x y))
:rule-classes (:rewrite :forward-chaining))
(defthm assoc-equiv-subsetp-2
(implies
(and
(assoc-equiv b x y)
(subsetp a b))
(assoc-equiv a x y))
:rule-classes (:rewrite :forward-chaining))
(defthm assoc-equiv-chaining-1
(implies
(and
(assoc-equiv a w x)
(assoc-equiv a x y))
(assoc-equiv a w y))
:rule-classes (:rewrite :forward-chaining))
(defthm assoc-equiv-chaining-2
(implies
(and
(assoc-equiv a x y)
(assoc-equiv a w x))
(assoc-equiv a w y))
:rule-classes (:rewrite :forward-chaining))
(defun subdomain (x y)
(and (assoc-equiv (keys x) x y)
(subsetp (keys x) (keys y))))
(defun keyquiv (x y)
(and (list::setequiv (keys x) (keys y))
(assoc-equiv (keys x) x y)
(assoc-equiv (keys y) y x)))
(defthm assoc-non-memberp
(implies
(not (memberp a (keys alist)))
(equal (assoc a alist) nil)))
(defthm car-assoc-memberp
(implies
(memberp a (keys alist))
(equal (car (assoc a alist))
a)))
(defthm keyquiv-cons-commute
(implies
(not (equal (car a) (car b)))
(keyquiv (cons a (cons b x))
(cons b (cons a x)))))
(defthm keyquiv-cons-crush
(implies
(equal (car a) (car b))
(keyquiv (cons a (cons b x))
(cons a x))))
(in-theory (disable keyquiv))
(defun setv (a v alist)
(cons (cons a v) alist))
(defun getv (a alist)
(cdr (assoc a alist)))
(defthm getv-over-setv
(equal (getv a (setv b v r))
(if (equal a b)
v
(getv a r))))
(defthm setv-over-setv
(implies
(not (equal a b))
(keyquiv (setv a v (setv b w r))
(setv b w (setv a v r)))))
(defthm setv-of-setv
(keyquiv (setv a v (setv a w r))
(setv a v r)))
(defthm setv-of-getv
(implies
(memberp a (keys r))
(keyquiv (setv a (getv a r) r)
r))
:hints (("Goal" :in-theory (enable keyquiv))))
(defthm keys-setv
(equal (keys (setv a v r))
(cons a (keys r))))
(defun clr (key alist)
(if (consp alist)
(if (equal key (caar alist))
(clr key (cdr alist))
(cons (car alist)
(clr key (cdr alist))))
alist))
(defthm clr-append
(equal (clr a (append x y))
(append (clr a x) (clr a y))))
(defthm clr-clr-commute
(equal (clr a (clr b x))
(clr b (clr a x))))
(defthm keys-clr
(equal (keys (clr key alist))
(remove key (keys alist))))
(defthm assoc-clr
(equal (assoc a (clr key x))
(if (equal a key) nil
(assoc a x))))
(in-theory (disable LIST::SETEQUIV-REMOVE-DEFINITION))
(defthm getv-clr
(equal (getv a (clr key alist))
(if (equal a key) nil
(getv a alist))))
(defthm clr-over-setv
(implies
(not (equal a b))
(keyquiv (clr a (setv b v r))
(setv b v (clr a r)))))
(defthm clr-of-setv
(keyquiv (clr a (setv a v r))
(clr a r)))
(defthm acl2-count-cdr-<=
(<= (acl2-count (cdr x)) (acl2-count x))
:rule-classes (:linear))
(defthm acl2-count-car-<=
(<= (acl2-count (car x)) (acl2-count x))
:rule-classes (:linear))
(defthm memberp-clr-non-increasing
(<= (acl2-count (clr a alist)) (acl2-count alist))
:hints (("goal" :induct (clr a alist)))
:rule-classes (:linear))
(defthm memberp-clr-decreases
(implies
(memberp a (keys alist))
(< (acl2-count (clr a alist)) (acl2-count alist)))
:hints (("goal" :induct (clr a alist)))
:rule-classes (:linear))
(defthm memberp-cons
(implies
(consp alist)
(memberp (caar alist) (keys alist))))
(defthm acl2-count-assoc-<=
(<= (acl2-count (assoc a list)) (acl2-count list))
:hints (("Goal" :induct (assoc a list)))
:rule-classes (:linear))
(defthm acl2-count-assoc-memberp-<
(implies
(memberp key (keys list))
(< (acl2-count (assoc a list)) (acl2-count list)))
:hints (("Goal" :induct (assoc a list)))
:rule-classes (:linear))
(defthm acl2-count-getv-<=
(<= (acl2-count (alist::getv key alist1)) (acl2-count alist1))
:rule-classes (:linear))
(defthm acl2-count-getv-<
(implies
(memberp key (alist::keys alist1))
(< (acl2-count (alist::getv key alist1)) (acl2-count alist1)))
:rule-classes (:linear))
(in-theory (disable setv getv clr keys))
;; Preimage-aux scans the list looking for our value, and collects any keys it
;; finds along the way. Note that it will collect shadowed pairs if they are
;; bound to our value.
(defund preimage-aux (val x)
(declare (xargs :guard (alistp x)))
(if (consp x)
(if (equal (cdar x) val)
(cons (caar x)
(preimage-aux val (cdr x)))
(preimage-aux val (cdr x)))
nil))
(defthm preimage-aux-when-value-missing
(implies (not (memberp val (strip-cdrs x)))
(equal (preimage-aux val x)
nil))
:hints(("Goal" :in-theory (enable preimage-aux))))
(defthm not-memberp-of-preimage-aux
(implies (not (memberp key (strip-cars x)))
(equal (memberp key (preimage-aux val x))
nil))
:hints(("Goal" :in-theory (enable preimage-aux))))
(defthm unique-of-preimage-aux-when-unique-of-strip-cdrs
(implies (BAG::unique (strip-cdrs x))
(BAG::unique (preimage-aux val x)))
:hints(("Goal" :in-theory (enable preimage-aux))))
(defthm unique-of-preimage-aux-when-unique-of-strip-cars
(implies (BAG::unique (strip-cars x))
(BAG::unique (preimage-aux val x)))
:hints(("Goal" :in-theory (enable preimage-aux))))
(defthm memberp-of-caar-in-preimage-aux
(implies (BAG::unique (strip-cars x))
(equal (memberp (caar x) (preimage-aux a x))
(and (consp x)
(equal (cdar x) a))))
:hints(("goal" :in-theory (enable preimage-aux))))
(defthm preimage-aux-when-not-member-of-cdr-of-strip-cdrs
(implies (not (memberp a (cdr (strip-cdrs x))))
(equal (preimage-aux a x)
(if (and (consp x)
(equal a (cdar x)))
(list (caar x))
nil)))
:hints(("Goal" :in-theory (enable preimage-aux))))
(defthm preimage-aux-of-cdar-with-self
(equal (preimage-aux (cdar x) x)
(if (consp x)
(cons (caar x) (preimage-aux (cdar x) (cdr x)))
nil))
:hints(("Goal" :in-theory (enable preimage-aux))))
(defthm preimage-aux-of-cdr-when-not-cdar
(implies (not (equal (cdar x) a))
(equal (preimage-aux a (cdr x))
(if (consp x)
(preimage-aux a x)
nil)))
:hints(("Goal" :in-theory (enable preimage-aux))))
;; Preimage simply calls Preimage-aux after deshadowing x. This produces a
;; list of keys that would actually map to the desired value when given to
;; assoc.
(defund preimage (val x)
(declare (xargs :guard (alistp x)))
(preimage-aux val (deshadow x)))
(defthm preimage-when-value-missing
(implies (not (memberp val (strip-cdrs x)))
(equal (preimage val x)
nil))
:hints(("Goal" :in-theory (enable preimage))))
(defthm not-memberp-of-preimage
(implies (not (memberp key (strip-cars x)))
(equal (memberp key (preimage val x))
nil))
:hints(("Goal" :in-theory (enable preimage))))
(defthm unique-preimage
(BAG::unique (preimage val x))
:hints(("Goal" :in-theory (enable preimage))))
(defthm preimage-of-deshadow
(equal (preimage val (deshadow x))
(preimage val x))
:hints(("Goal" :in-theory (enable preimage))))
(defthm memberp-of-caar-in-preimage
(equal (memberp (caar x) (preimage a x))
(and (consp x)
(equal (cdar x) a)))
:hints(("Goal" :in-theory (enable preimage)
:use (:instance memberp-of-caar-in-preimage-aux
(x (deshadow x))))))
(defthm preimage-when-not-member-of-cdr-of-strip-cdrs
(implies (not (memberp a (cdr (strip-cdrs x))))
(equal (preimage a x)
(if (and (consp x)
(equal a (cdar x)))
(list (caar x))
nil)))
:hints(("Goal" :in-theory (enable preimage))))
(defthm preimage-of-cdar-with-self
(equal (preimage (cdar x) x)
(if (consp x)
(cons (caar x)
(preimage (cdar x)
(clearkey (caar x) (cdr x))))
nil))
:hints(("Goal" :in-theory (e/d (preimage)
(preimage-aux-of-cdar-with-self))
:use (:instance preimage-aux-of-cdar-with-self
(x (deshadow x))))))
(defthm preimage-of-cdr-when-not-cdar-and-unique
(implies (and (not (equal (cdar x) a))
(BAG::unique (strip-cars x)))
(equal (preimage a (cdr x))
(if (consp x)
(preimage a x)
nil)))
:hints(("Goal" :in-theory (enable preimage))))
(in-theory (disable strip-cars strip-cdrs))
(defthm strip-cars-type-consp
(implies (consp x)
(consp (strip-cars x)))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable strip-cars))))
(defthm strip-cars-type-non-consp
(implies (not (consp x))
(not (consp (strip-cars x))))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable strip-cars))))
(defthm consp-strip-cars
(equal (consp (strip-cars x))
(consp x)))
(defthm strip-cars-of-non-consp
(implies (not (consp x))
(equal (strip-cars x)
nil))
:hints(("Goal" :in-theory (enable strip-cars))))
(defthm strip-cars-of-cons
(equal (strip-cars (cons x y))
(cons (car x)
(strip-cars y)))
:hints(("Goal" :in-theory (enable strip-cars))))
(defthm car-of-strip-cars
(equal (car (strip-cars x))
(car (car x))))
(defthm strip-cars-of-cdr
(equal (strip-cars (cdr x))
(cdr (strip-cars x))))
(defthm len-of-strip-cars
(equal (len (strip-cars x))
(len x))
:hints(("Goal" :in-theory (enable len))))
(defthm strip-cars-of-append
(equal (strip-cars (append x y))
(append (strip-cars x)
(strip-cars y)))
:hints(("Goal" :in-theory (enable append))))
(defthm strip-cars-of-firstn
(equal (strip-cars (firstn n x))
(firstn n (strip-cars x)))
:hints(("Goal" :in-theory (enable firstn))))
(defthm strip-cars-of-nthcdr
(equal (strip-cars (nthcdr n x))
(nthcdr n (strip-cars x)))
:hints(("Goal" :in-theory (enable nthcdr))))
(defthm memberp-caar-strip-cars
(equal (memberp (caar x) (strip-cars x))
(consp x)))
(defthm strip-cdrs-type-consp
(implies (consp x)
(consp (strip-cdrs x)))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable strip-cdrs))))
(defthm strip-cdrs-type-non-consp
(implies (not (consp x))
(not (consp (strip-cdrs x))))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable strip-cdrs))))
(defthm consp-strip-cdrs
(equal (consp (strip-cdrs x))
(consp x)))
(defthm strip-cdrs-of-non-consp
(implies (not (consp x))
(equal (strip-cdrs x)
nil))
:hints(("Goal" :in-theory (enable strip-cdrs))))
(defthm strip-cdrs-of-cons
(equal (strip-cdrs (cons x y))
(cons (cdr x)
(strip-cdrs y)))
:hints(("Goal" :in-theory (enable strip-cdrs))))
(defthm car-of-strip-cdrs
(equal (car (strip-cdrs x))
(cdr (car x))))
(defthm strip-cdrs-of-cdr
(equal (strip-cdrs (cdr x))
(cdr (strip-cdrs x))))
(defthm len-of-strip-cdrs
(equal (len (strip-cdrs x))
(len x))
:hints(("Goal" :in-theory (enable len))))
(defthm strip-cdrs-of-append
(equal (strip-cdrs (append x y))
(append (strip-cdrs x)
(strip-cdrs y)))
:hints(("Goal" :in-theory (enable append))))
(defthm strip-cdrs-of-firstn
(equal (strip-cdrs (firstn n x))
(firstn n (strip-cdrs x)))
:hints(("Goal" :in-theory (enable firstn))))
(defthm strip-cdrs-of-nthcdr
(equal (strip-cdrs (nthcdr n x))
(nthcdr n (strip-cdrs x)))
:hints(("Goal" :in-theory (enable nthcdr))))
(defthm memberp-cdar-strip-cdrs
(equal (memberp (cdar x) (strip-cdrs x))
(consp x)))
|
80551
|
; <NAME>: what's this file for? It's not certifiable, so I'm
; renaming it to a .lsp extension for Make compatibility
#|-*-Lisp-*-=================================================================|#
#| |#
#|===========================================================================|#
;; alists-definitions.lisp
;; <NAME>
;(in-package "ALIST")
;;
;; This file isolates alists definitions and types. The file currently
;; contains the following ACL2 constructs as they occur in the alists book:
;; - defun
;; - defund
;; - defstub
;; - defchoose
;; - defthm
;; - in-theory
;;
(defthm alist::use-equivp-id
(alist::use-equivp domain x x))
; [Removed by <NAME>. to handle changes to member, assoc, etc. after ACL2 4.2.]
; (defthm assoc-eq-is-assoc
; (equal (assoc-eq key list)
; (assoc key list)))
(defthm assoc-equiv-rewrite-order
(implies
(syntaxp (acl2::good-rewrite-order y x))
(equal (alist::assoc-equiv domain x y)
(alist::assoc-equiv domain y x))))
(in-theory (disable ALIST::ASSOC-EQUIV-COMMUTE))
(defthm assoc-equiv-substitution
(implies
(and
(alist::assoc-equiv d1 x y)
(subsetp d2 d1))
(alist::use-equiv :lhs x
:rhs y
:domain d2)))
(defthm assoc-use-cong
(implies
(and
(equal domain (list a))
(acl2::bind-contextp ((b1 (equal b2 (alist::use-ctx b1 :domain domain))))))
(alist::cons-equiv (assoc a b1)
(assoc a b2))))
(defthm alist::use-equivp-self-characterization
(implies
(acl2::bind-contextp ((x (equal a (alist::use-ctx x :domain domain)))
(y (equal b (alist::use-ctx y :domain domain)))))
(equal (alist::use-equivp domain x y)
(alist::use-equivp domain a b))))
(defthm use-equiv-cons-not-member-reduction
(implies
(not (list::memberp (car a) domain))
(alist::use-equiv :lhs (cons a list)
:rhs list
:domain domain)))
(defthm use-equiv-cons-normal-form
(implies
(and
(syntaxp (acl2::<< (car b) (car a)))
(not (equal (car a) (car b))))
(alist::use-equiv :lhs (cons a (cons b x))
:rhs (cons b (cons a x)))))
(defthm use-equiv-append-normal-form
(implies
(and
(syntaxp (acl2::<< y x))
(bag::disjoint (alist::keys x) (alist::keys y)))
(alist::use-equiv :lhs (append x y)
:rhs (append y x))))
;; ===========================================================================
;;
;; This was the easy property .. dropping the first argument to
;; append will be tougher.
;;
;; ===========================================================================
(defthm use-equiv-append-reduction-2
(implies
(subsetp domain (alist::keys x))
(alist::use-equiv :lhs (append x y)
:rhs x
:domain domain)))
;; ===========================================================================
;;
;; assoc-transparent: either the keys are disjoint or the bound values
;; are equal.
;;
;; ===========================================================================
(defun assoc-transparent (key value alist)
(if (consp alist)
(and (implies (equal key (caar alist)) (equal value (cdar alist)))
(assoc-transparent key value (cdr alist)))
t))
(defthm assoc-transparent-append
(equal (assoc-transparent key value (append x y))
(and (assoc-transparent key value x)
(assoc-transparent key value y))))
(defthm assoc-transparent-implies-cons-equiv-assoc
(implies
(assoc-transparent key value x)
(alist::cons-equiv (assoc key x)
(and (list::memberp key (alist::keys x)) (cons key value))))
:hints (("Goal" :in-theory (enable alist::keys))))
(defthm assoc-transparent-implies-cons-equiv-assoc-2
(implies
(and
(assoc-transparent key (cdr (assoc key x)) y)
(list::memberp key (alist::keys y)))
(alist::cons-equiv (assoc key x)
(and (list::memberp key (alist::keys x)) (assoc key y))))
:hints (("Goal" :induct (assoc key y)
:in-theory (enable alist::keys))))
(defthm assoc-transparent-non-memberp
(implies
(not (list::memberp key (alist::keys x)))
(assoc-transparent key nil x))
:hints (("Goal" :in-theory (enable alist::keys))))
(defthm use-equiv-cons-assoc-transparent-reduction
(implies
(and
(assoc-transparent (car a) (cdr a) list)
(list::memberp (car a) (alist::keys list)))
(alist::use-equiv :lhs (cons a list)
:rhs list
:domain domain))
:hints (("Goal" :in-theory (enable alist::keys))))
;; ===========================================================================
;;
;; unified-domain-binding: the alist is self-assoc-transparent.
;;
;; cross-domain-binding: the glue that combines two parts of a
;; unified-domain-binding.
;;
;; ===========================================================================
(defun unified-domain-binding (domain alist)
(if (consp domain)
(and (assoc-transparent (car domain) (cdr (assoc (car domain) alist)) alist)
(unified-domain-binding (cdr domain) alist))
t))
(defun cross-domain-binding (domain x y)
(if (consp domain)
(let ((key (car domain)))
(and (implies (list::memberp key (alist::keys x))
(assoc-transparent key (cdr (assoc key x)) y))
(cross-domain-binding (cdr domain) x y)))
t))
(defthm disjoint-cross-domain-binding
(implies
(bag::disjoint (alist::keys x) (alist::keys y))
(cross-domain-binding domain x y))
:hints (("Goal" :in-theory (enable alist::keys))))
(defthm cross-domain-binding-replacement
(implies
(and
(cross-domain-binding domain x y)
(list::memberp key domain)
(list::memberp key (alist::keys y)))
(alist::cons-equiv (assoc key x)
(and (list::memberp key (alist::keys x)) (assoc key y)))))
(defthmd cross-domain-binding-cons
(implies
(and
(consp x)
(unified-domain-binding domain x))
(equal (cross-domain-binding domain x y)
(and (implies (list::memberp (caar x) domain)
(assoc-transparent (caar x) (cdar x) y))
(cross-domain-binding domain (cdr x) y))))
:hints (("Goal" :induct (cross-domain-binding domain x y)
:in-theory (enable alist::keys))))
(defthmd cross-domain-binding-not-cons
(implies
(not (consp x))
(cross-domain-binding domain x y))
:hints (("Goal" :in-theory (enable alist::keys))))
(defthmd unified-domain-binding-cons
(implies
(consp x)
(equal (unified-domain-binding domain x)
(and (implies (list::memberp (caar x) domain)
(assoc-transparent (caar x) (cdar x) (cdr x)))
(unified-domain-binding domain (cdr x)))))
:hints (("Goal" :induct (unified-domain-binding domain x)
:in-theory (enable alist::keys))))
(defthmd unified-domain-binding-non-cons
(implies
(not (consp x))
(unified-domain-binding domain x)))
(defthm unified-domain-binding-append
(equal (unified-domain-binding domain (append x y))
(and (unified-domain-binding domain x)
(unified-domain-binding domain y)
(cross-domain-binding domain x y)))
:hints (("Goal" :induct (append x y)
:in-theory (enable append
unified-domain-binding-cons
unified-domain-binding-non-cons
cross-domain-binding-cons
cross-domain-binding-not-cons
))))
(defthm use-equiv-append-reduction-1
(implies
(and
(cross-domain-binding d1 x y)
(subsetp domain d1)
(subsetp domain (alist::keys y)))
(alist::use-equiv :lhs (append x y)
:rhs y
:domain domain))
:hints (("Goal" :in-theory (disable ASSOC-EQUIV-SUBSTITUTION)))
:otf-flg t)
;; ===========================================================================
;;
;; unified-binding: the alist is self-consistent w/to unified-domain-bindings
;;
;; ===========================================================================
(defund unified-binding (alist)
(unified-domain-binding (alist::keys alist) alist))
(defun equiv-domain-binding (domain x y)
(and (cross-domain-binding domain x y)
(cross-domain-binding domain y x)))
(defthm unified-domain-binding-subsetp
(implies
(and
(unified-domain-binding y a)
(subsetp x y))
(unified-domain-binding x a)))
(defund clearkey (k x)
(declare (xargs :guard (alistp x)))
(if (consp x)
(if (equal k (caar x))
(clearkey k (cdr x))
(cons (consfix (car x))
(clearkey k (cdr x))))
nil))
(defthm alistp-of-clearkey
(alistp (clearkey k x))
:hints(("Goal" :in-theory (enable clearkey))))
(defthm clearkey-of-cons
(equal (clearkey k (cons a x))
(if (equal k (car a))
(clearkey k x)
(cons (consfix a) (clearkey k x))))
:hints(("Goal" :in-theory (enable clearkey))))
; no theorem about car-of-clearkey, too hard to describe
; no theorem about cdr-of-clearkey, too hard to describe
(defthm len-of-clearkey-bound-tight
(implies (memberp k (strip-cars x))
(< (len (clearkey k x))
(len x)))
:rule-classes :linear
:hints(("Goal" :in-theory (enable clearkey))))
(defthm len-of-clearkey-bound-tight-rewrite
(implies (memberp k (strip-cars x))
(equal (< (len (clearkey k x)) (len x))
t)))
(defthm len-of-clearkey-bound-weak
(<= (len (clearkey k x))
(len x))
:rule-classes :linear
:hints(("Goal" :in-theory (enable clearkey))))
(defthm len-of-clearkey-bound-weak-rewrite
(equal (< (len x) (len (clearkey k x)))
nil))
;; no theorem about clearkey-of-firstn, too awkward to describe
;; no theorem about clearkey-of-nthcdr, too awkward to describe
(defthm clearkey-of-append
(equal (clearkey k (append x y))
(append (clearkey k x)
(clearkey k y)))
:hints(("Goal" :in-theory (enable clearkey))))
(defthm clearkey-reorder
(equal (clearkey k1 (clearkey k2 r))
(clearkey k2 (clearkey k1 r)))
:hints(("Goal" :in-theory (enable clearkey))))
(defthm clearkey-when-non-memberp
(implies (not (memberp key (strip-cars x)))
(equal (clearkey key x)
(alistfix x)))
:hints(("Goal" :in-theory (enable clearkey))))
(defthm clearkey-caar-when-unique
(implies (and (consp x)
(BAG::unique (strip-cars x)))
(equal (clearkey (caar x) (cdr x))
(alistfix (cdr x)))))
(defthm strip-cars-of-clearkey
(equal (strip-cars (clearkey k x))
(BAG::remove-all k (strip-cars x)))
:hints(("Goal" :in-theory (enable clearkey))))
(defthm clearkey-idempotent
(equal (clearkey k (clearkey k r))
(clearkey k r)))
(defthm not-memberp-of-strip-cdrs-of-clearkey
(implies (not (memberp val (strip-cdrs x)))
(not (memberp val (strip-cdrs (clearkey key x)))))
:hints(("Goal" :in-theory (enable clearkey))))
;; bzo move to bags library
(defthm count-of-remove-all-diff
(implies (not (equal a b))
(equal (BAG::count a (BAG::remove-all b x))
(BAG::count a x)))
:hints(("Goal" :in-theory (enable BAG::remove-all))))
(defund deshadow (x)
(declare (xargs :guard (alistp x)
:measure (len x)))
(if (consp x)
(cons (consfix (car x))
(deshadow (clearkey (caar x) (cdr x))))
nil))
(defthm deshadow-type-1
(implies (not (consp x))
(equal (deshadow x) nil))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable deshadow))))
(defthm deshadow-type-2
(implies (consp x)
(consp (deshadow x)))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable deshadow))))
(defthm deshadow-of-non-consp
(implies (not (consp x))
(equal (deshadow x)
nil)))
(defthm consp-of-deshadow
(equal (consp (deshadow x))
(consp x)))
(defthm deshadow-of-cons
(equal (deshadow (cons x y))
(cons (consfix x)
(deshadow (clearkey (car x) y))))
:hints(("Goal" :in-theory (enable deshadow clearkey))))
(defthm car-of-deshadow
(equal (car (deshadow x))
(if (consp x)
(consfix (car x))
nil)))
;; no rules about cdr-of-deshadow, it is weird
(defthm len-of-deshadow-weak
(<= (len (deshadow x))
(len x))
:rule-classes :linear
:hints(("Goal" :in-theory (enable deshadow))))
(defthm len-of-deshadow-weak-rewrite
(equal (< (len x) (len (deshadow x)))
nil))
;; Even though we will shortly prove deshadow-when-strip-cars-unique, we will
;; go ahead and prove both :linear rules below, so that we can backchain to
;; the unique of strip cars hypothesis when necessary.
(defthm len-of-deshadow-when-strip-cars-not-unique
(implies (not (BAG::unique (strip-cars x)))
(< (len (deshadow x))
(len x)))
:rule-classes :linear
:hints(("Goal" :in-theory (enable deshadow))))
(defthm len-of-deshadow-when-strip-cars-unique
(implies (BAG::unique (strip-cars x))
(equal (len (deshadow x))
(len x)))
:rule-classes :linear
:hints(("Goal" :in-theory (enable deshadow))))
(defthm len-of-deshadow-decreases-rewrite
(equal (< (len (deshadow x)) (len x))
(not (BAG::unique (strip-cars x)))))
(defthm alistp-of-deshadow
(alistp (deshadow x))
:hints(("Goal" :in-theory (enable deshadow))))
(defthm deshadow-of-clearkey
(equal (deshadow (clearkey key x))
(clearkey key (deshadow x)))
:hints(("Goal" :in-theory (enable deshadow))))
(defthm unique-of-strip-cars-of-deshadow
(BAG::unique (strip-cars (deshadow x)))
:hints(("Goal" :in-theory (enable deshadow))))
(defthm deshadow-when-strip-cars-unique
(implies (BAG::unique (strip-cars x))
(equal (deshadow x)
(alistfix x)))
:hints(("Goal" :in-theory (enable deshadow))))
(defthm deshadow-idempotent
(equal (deshadow (deshadow x))
(deshadow x)))
(defthm memberp-of-strip-cars-of-deshadow
(equal (memberp key (strip-cars (deshadow x)))
(memberp key (strip-cars x)))
:hints(("Goal" :in-theory (enable deshadow))))
(defthm count-of-strip-cars-of-deshadow
(<= (BAG::count key (strip-cars (deshadow x)))
(BAG::count key (strip-cars x)))
:hints(("Goal" :in-theory (enable deshadow))))
;; There is probably an equivalent rule for strip-cdrs, but I haven't tried
;; to prove it yet.
(defthm not-memberp-of-strip-cdrs-of-deshadow
(implies (not (memberp val (strip-cdrs x)))
(equal (memberp val (strip-cdrs (deshadow x)))
nil))
:hints(("Goal" :in-theory (enable deshadow))))
;; Interpreting Objects as Conses (consfix)
;;
;; We can think of a mapping between all ACL2 objects and conses, so that any
;; atom is mapped to (nil . nil) and any cons is mapped to itself. The
;; function consfix applies this mapping for us, i.e., it interprets any ACL2
;; object as a cons. Because this is how car and cdr interpret their
;; arguments, there are some very nice properties that we can prove about this
;; operation.
(defund consfix (x)
(declare (type t x))
(if (consp x)
x
(cons nil nil)))
(defthm consfix-when-non-consp
(implies (not (consp x))
(equal (consfix x)
(cons nil nil)))
:hints(("Goal" :in-theory (enable consfix))))
(defthm consfix-when-consp
(implies (consp x)
(equal (consfix x)
x))
:hints(("Goal" :in-theory (enable consfix))))
(defthm consfix-does-nothing
(equal (equal x (consfix x))
(consp x))
:hints(("Goal" :in-theory (enable consfix))))
(defthm consfix-of-cons
(equal (consfix (cons a b))
(cons a b)))
;; Note (jcd): Do not add the following rules. They are trivial consequences
;; of the congruence rules under cons-equiv below, so adding them is not
;; necessary.
;;
;; (defthm consfix-of-car
;; (equal (car (consfix a))
;; (car a)))
;;
;; (defthm consfix-of-cdr
;; (equal (cdr (consfix a))
;; (cdr a)))
;; The Cons Equivalence Relation (cons-equiv)
;;
;; Given that (with consfix) we can now think of any object as a cons, the next
;; natural step is to define an equivalence relation wherein objects are
;; considered to be equivalent when their interpretations as conses are the
;; same.
(defund cons-equiv (x y)
(declare (type t x y))
(equal (consfix x)
(consfix y)))
(defthm consfix-in-cons-equiv
(cons-equiv (consfix x)
x)
:hints(("Goal" :in-theory (enable cons-equiv))))
(defthm equal-of-consfixes
(equal (equal (consfix x) (consfix y))
(cons-equiv x y))
:hints (("Goal" :in-theory (enable cons-equiv))))
;; Interpreting Objects as Alists (alistfix)
;;
;; An alist is a list of pairs. Since we can now interpret any ACL2 object as
;; a pair using consfix, it is straightforward to interpet any ACL2 object as
;; an alist: any atom is interpreted as the empty alist, and any list is fixed
;; by pair-fixing each of its elements.
;;
;; An alternate definition that I considered was to simply interpret any
;; non-alistp object as the empty alist, and any alist as itself. But, I think
;; the current approach gives us many nice rules. In particular, our approach
;; allows alist-equiv to be a refinement of list::equiv, giving us a lot of
;; rewrite rules "for free" (e.g., the lengths are the same). Other rules work
;; nicely (the keys are the same, the values are the same, etc.) Finally, we
;; also get to provide very nice congruence rules, e.g., the cars of alist
;; interpretations are cons-equiv.
(defund alistfix (x)
(declare (type t x))
(if (consp x)
(cons (consfix (car x))
(alistfix (cdr x)))
nil))
(defthm alistfix-type-consp
(implies (consp x)
(consp (alistfix x)))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable alistfix))))
(defthm alistfix-type-non-consp
(implies (not (consp x))
(equal (alistfix x)
nil))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable alistfix))))
;; Note (jcd): Do not add the following rule. It is redundant with the defcong
;; below for alist-equiv over consp.
;;
;; (defthm consp-alistfix
;; (equal (consp (alistfix x))
;; (consp x)))
(defthm alistfix-when-non-consp
(implies (not (consp alist))
(equal (alistfix alist)
nil)))
(defthm alistfix-when-alist
(implies (alistp x)
(equal (alistfix x)
x))
:hints(("Goal" :in-theory (enable alistfix))))
(defthm alistfix-does-nothing
(equal (equal x (alistfix x))
(alistp x))
:hints(("Goal" :in-theory (enable alistfix))))
(defthm alistp-of-alistfix
(alistp (alistfix x))
:hints(("Goal" :in-theory (enable alistfix))))
(defthm alistfix-of-cons
(equal (alistfix (cons a x))
(cons (consfix a) (alistfix x)))
:hints(("Goal" :in-theory (enable alistfix))))
(defthm car-of-alistfix
(equal (car (alistfix a))
(if (consp a)
(consfix (car a))
nil)))
(defthm cdr-of-alistfix
(equal (cdr (alistfix a))
(alistfix (cdr a))))
;; Note (jcd): Do not add the following rule. It is trivial using the
;; congruence rule of alist-equiv for len, along with alistfix-in-alist-equiv.
;;
;; (defthm len-of-alistfix
;; (equal (len (alistfix a))
;; (len a)))
(defthm alistfix-of-append
(equal (alistfix (append x y))
(append (alistfix x)
(alistfix y)))
:hints(("Goal" :in-theory (enable append))))
(defthm alistfix-of-firstn
(equal (alistfix (list::firstn n x))
(list::firstn n (alistfix x)))
:hints(("Goal" :in-theory (enable list::firstn))))
(defthm alistfix-of-nthcdr
(equal (alistfix (nthcdr n x))
(nthcdr n (alistfix x)))
:hints(("Goal" :in-theory (enable nthcdr))))
;; The Alist Equivalence Relation
;;
;; Given that (with alistfix) we can now think of any object as an alist, the
;; next natural step is to define an equivalence relation wherein objects are
;; considered to be equivalent when their interpretations as alists are the
;; same.
;;
;; IMPORTANT: You might think that alists should be considered to be equivalent
;; whenever "forall a, (assoc a x) = (assoc a y)." Although equivalent alists
;; will satisfy this property, the converse is NOT true! For example, if x and
;; y satisfy this property but x has shadowed pairs and y does not, then x and
;; y will not be considered equivalent under alist-equiv!
;;
;; Instead, you should think of alist-equiv as a "structural" relation that
;; essentially is comparing the interpretation of x and y as lists of pairs.
;; But understand that no a priori judgement is made as to how those lists of
;; pairs will be used, and we do not assume that shadowed pairs are irrelevant.
(defund alist-equiv (a b)
(equal (alistfix a)
(alistfix b)))
(defthm alistfix-in-alist-equiv
(alist-equiv (alistfix a)
a)
:hints(("Goal" :in-theory (enable alist-equiv))))
(defthm alist-equiv-cons-cases
(equal (alist-equiv x (cons y z))
(and (consp x)
(cons-equiv y (car x))
(alist-equiv z (cdr x))))
:hints(("Goal" :in-theory (enable alist-equiv))))
(defthm equal-of-alistfixes
(equal (equal (alistfix x) (alistfix y))
(alist-equiv x y))
:hints(("Goal" :in-theory (enable alist-equiv))))
;; Interpreting Objects as Conses (consfix)
;;
;; We can think of a mapping between all ACL2 objects and conses, so that any
;; atom is mapped to (nil . nil) and any cons is mapped to itself. The
;; function consfix applies this mapping for us, i.e., it interprets any ACL2
;; object as a cons. Because this is how car and cdr interpret their
;; arguments, there are some very nice properties that we can prove about this
;; operation.
(defund consfix (x)
(declare (type t x))
(if (consp x)
x
(cons nil nil)))
(defthm consfix-when-non-consp
(implies (not (consp x))
(equal (consfix x)
(cons nil nil)))
:hints(("Goal" :in-theory (enable consfix))))
(defthm consfix-when-consp
(implies (consp x)
(equal (consfix x)
x))
:hints(("Goal" :in-theory (enable consfix))))
(defthm consfix-does-nothing
(equal (equal x (consfix x))
(consp x))
:hints(("Goal" :in-theory (enable consfix))))
(defthm consfix-of-cons
(equal (consfix (cons a b))
(cons a b)))
;; Note (jcd): Do not add the following rules. They are trivial consequences
;; of the congruence rules under cons-equiv below, so adding them is not
;; necessary.
;;
;; (defthm consfix-of-car
;; (equal (car (consfix a))
;; (car a)))
;;
;; (defthm consfix-of-cdr
;; (equal (cdr (consfix a))
;; (cdr a)))
;; The Cons Equivalence Relation (cons-equiv)
;;
;; Given that (with consfix) we can now think of any object as a cons, the next
;; natural step is to define an equivalence relation wherein objects are
;; considered to be equivalent when their interpretations as conses are the
;; same.
(defund cons-equiv (x y)
(declare (type t x y))
(equal (consfix x)
(consfix y)))
(defthm cons-equiv-cases-fwd
(implies
(and (equal (car x) (car y))
(equal (cdr x) (cdr y)))
(cons-equiv x y))
:hints (("Goal" :in-theory (enable cons-equiv)))
:rule-classes (:forward-chaining))
(defthm not-cons-equiv-cases-fwd-1
(implies
(not (equal (car x) (car y)))
(not (cons-equiv x y)))
:hints (("Goal" :in-theory (enable cons-equiv)))
:rule-classes (:forward-chaining))
(defthm not-cons-equiv-cases-fwd-2
(implies
(not (equal (cdr x) (cdr y)))
(not (cons-equiv x y)))
:hints (("Goal" :in-theory (enable cons-equiv)))
:rule-classes (:forward-chaining))
(defthm cons-equiv-fwd
(implies
(cons-equiv x y)
(and (equal (car x) (car y))
(equal (cdr x) (cdr y))))
:hints (("Goal" :in-theory (enable cons-equiv)))
:rule-classes (:forward-chaining))
(defthm cons-equiv-cons-reduction-1
(equal (cons-equiv (cons a b) c)
(and (equal a (car c))
(equal b (cdr c))))
:hints (("Goal" :in-theory (enable cons-equiv))))
(defthm cons-equiv-cons-reduction-2
(equal (cons-equiv a (cons b c))
(and (equal (car a) b)
(equal (cdr a) c)))
:hints (("Goal" :in-theory (enable cons-equiv))))
(defthm consfix-in-cons-equiv
(cons-equiv (consfix x)
x)
:hints(("Goal" :in-theory (enable cons-equiv))))
(defthm equal-of-consfixes
(equal (equal (consfix x) (consfix y))
(cons-equiv x y))
:hints (("Goal" :in-theory (enable cons-equiv))))
(defun keys (alist)
(declare (type t alist))
(if (consp alist)
(if (consp (car alist))
(cons (caar alist)
(keys (cdr alist)))
(cons nil (keys (cdr alist))))
nil))
#|
(defthm memberp-cons-keys
(implies
(consp alist)
(memberp (caar alist) (keys alist))))
(defthm clrv-len-reduction
(implies
(memberp a (keys alist))
(< (len (clrv a alist)) (len alist)))
:rule-classes (:linear))
(defun element (a y)
(if (consp y)
(if (equal (car a) (caar y))
(equal (cdr a) (cdar y))
(element a (cdr y)))
nil))
(defthm element-definition
(equal (element a y)
(and (memberp (car a) (keys y))
(equal (cdr a) (cdr (getv (car a) y)))))
:rule-classes (:definition))
(defthm element-implication
(implies
(element a y)
(and (memberp (car a) (keys y))
(equal (cdr a) (cdr (getv (car a) y)))))
:rule-classes (:forward-chaining))
(defthm element-elements-implication
(implies
(and (memberp (car a) (keys y))
(equal (cdr a) (cdr (getv (car a) y))))
(element a y))
:rule-classes (:forward-chaining))
(defthm not-element-elements-implication-1
(implies
(not (memberp (car a) (keys y)))
(not (element a y)))
:rule-classes (:forward-chaining))
(defthm not-element-elements-implication-2
(implies
(not (equal (cdr a) (cdr (getv (car a) y))))
(not (element a y)))
:rule-classes (:forward-chaining))
(defthm element-base
(implies
(not (consp x))
(not (element a x)))
:hints (("Goal" :in-theory (enable element))))
(defthm element-cons
(equal (element a (cons x y))
(if (equal (car a) (car x))
(equal (cdr a) (cdr x))
(element a y)))
:hints (("Goal" :in-theory (enable element))))
(defthm element-append
(equal (element a (append x y))
(if (memberp (car a) (keys x))
(element a x)
(element a y)))
:hints (("Goal" :induct (append x y)
:in-theory (enable memberp append element))))
|#
(defthm assoc-append
(equal (assoc a (append x y))
(if (memberp a (keys x))
(assoc a x)
(assoc a y))))
(defthm keys-append
(equal (keys (append x y))
(append (keys x)
(keys y))))
;; pick-a-point
#|
(defthm consp-implies-memberp
(implies
(consp x)
(memberp (caar x) (keys x))))
|#
(defun assoc-equiv (list x y)
(if (consp list)
(and (cons-equiv (assoc (car list) x)
(assoc (car list) y))
(assoc-equiv (cdr list) x y))
t))
(defthmd assoc-equiv-commute
(equal (assoc-equiv list x y)
(assoc-equiv list y x)))
(defthm assoc-equiv-commute-fwd
(implies
(assoc-equiv list x y)
(assoc-equiv list y x))
:hints (("Goal" :in-theory (enable assoc-equiv-commute))))
(defthm assoc-equiv-memberp
(implies
(and
(memberp a list)
(assoc-equiv list x y))
(cons-equiv (assoc a x)
(assoc a y)))
:rule-classes (:forward-chaining))
(defthm assoc-equiv-subsetp-1
(implies
(and
(subsetp a b)
(assoc-equiv b x y))
(assoc-equiv a x y))
:rule-classes (:rewrite :forward-chaining))
(defthm assoc-equiv-subsetp-2
(implies
(and
(assoc-equiv b x y)
(subsetp a b))
(assoc-equiv a x y))
:rule-classes (:rewrite :forward-chaining))
(defthm assoc-equiv-chaining-1
(implies
(and
(assoc-equiv a w x)
(assoc-equiv a x y))
(assoc-equiv a w y))
:rule-classes (:rewrite :forward-chaining))
(defthm assoc-equiv-chaining-2
(implies
(and
(assoc-equiv a x y)
(assoc-equiv a w x))
(assoc-equiv a w y))
:rule-classes (:rewrite :forward-chaining))
(defun subdomain (x y)
(and (assoc-equiv (keys x) x y)
(subsetp (keys x) (keys y))))
(defun keyquiv (x y)
(and (list::setequiv (keys x) (keys y))
(assoc-equiv (keys x) x y)
(assoc-equiv (keys y) y x)))
(defthm assoc-non-memberp
(implies
(not (memberp a (keys alist)))
(equal (assoc a alist) nil)))
(defthm car-assoc-memberp
(implies
(memberp a (keys alist))
(equal (car (assoc a alist))
a)))
(defthm keyquiv-cons-commute
(implies
(not (equal (car a) (car b)))
(keyquiv (cons a (cons b x))
(cons b (cons a x)))))
(defthm keyquiv-cons-crush
(implies
(equal (car a) (car b))
(keyquiv (cons a (cons b x))
(cons a x))))
(in-theory (disable keyquiv))
(defun setv (a v alist)
(cons (cons a v) alist))
(defun getv (a alist)
(cdr (assoc a alist)))
(defthm getv-over-setv
(equal (getv a (setv b v r))
(if (equal a b)
v
(getv a r))))
(defthm setv-over-setv
(implies
(not (equal a b))
(keyquiv (setv a v (setv b w r))
(setv b w (setv a v r)))))
(defthm setv-of-setv
(keyquiv (setv a v (setv a w r))
(setv a v r)))
(defthm setv-of-getv
(implies
(memberp a (keys r))
(keyquiv (setv a (getv a r) r)
r))
:hints (("Goal" :in-theory (enable keyquiv))))
(defthm keys-setv
(equal (keys (setv a v r))
(cons a (keys r))))
(defun clr (key alist)
(if (consp alist)
(if (equal key (caar alist))
(clr key (cdr alist))
(cons (car alist)
(clr key (cdr alist))))
alist))
(defthm clr-append
(equal (clr a (append x y))
(append (clr a x) (clr a y))))
(defthm clr-clr-commute
(equal (clr a (clr b x))
(clr b (clr a x))))
(defthm keys-clr
(equal (keys (clr key alist))
(remove key (keys alist))))
(defthm assoc-clr
(equal (assoc a (clr key x))
(if (equal a key) nil
(assoc a x))))
(in-theory (disable LIST::SETEQUIV-REMOVE-DEFINITION))
(defthm getv-clr
(equal (getv a (clr key alist))
(if (equal a key) nil
(getv a alist))))
(defthm clr-over-setv
(implies
(not (equal a b))
(keyquiv (clr a (setv b v r))
(setv b v (clr a r)))))
(defthm clr-of-setv
(keyquiv (clr a (setv a v r))
(clr a r)))
(defthm acl2-count-cdr-<=
(<= (acl2-count (cdr x)) (acl2-count x))
:rule-classes (:linear))
(defthm acl2-count-car-<=
(<= (acl2-count (car x)) (acl2-count x))
:rule-classes (:linear))
(defthm memberp-clr-non-increasing
(<= (acl2-count (clr a alist)) (acl2-count alist))
:hints (("goal" :induct (clr a alist)))
:rule-classes (:linear))
(defthm memberp-clr-decreases
(implies
(memberp a (keys alist))
(< (acl2-count (clr a alist)) (acl2-count alist)))
:hints (("goal" :induct (clr a alist)))
:rule-classes (:linear))
(defthm memberp-cons
(implies
(consp alist)
(memberp (caar alist) (keys alist))))
(defthm acl2-count-assoc-<=
(<= (acl2-count (assoc a list)) (acl2-count list))
:hints (("Goal" :induct (assoc a list)))
:rule-classes (:linear))
(defthm acl2-count-assoc-memberp-<
(implies
(memberp key (keys list))
(< (acl2-count (assoc a list)) (acl2-count list)))
:hints (("Goal" :induct (assoc a list)))
:rule-classes (:linear))
(defthm acl2-count-getv-<=
(<= (acl2-count (alist::getv key alist1)) (acl2-count alist1))
:rule-classes (:linear))
(defthm acl2-count-getv-<
(implies
(memberp key (alist::keys alist1))
(< (acl2-count (alist::getv key alist1)) (acl2-count alist1)))
:rule-classes (:linear))
(in-theory (disable setv getv clr keys))
;; Preimage-aux scans the list looking for our value, and collects any keys it
;; finds along the way. Note that it will collect shadowed pairs if they are
;; bound to our value.
(defund preimage-aux (val x)
(declare (xargs :guard (alistp x)))
(if (consp x)
(if (equal (cdar x) val)
(cons (caar x)
(preimage-aux val (cdr x)))
(preimage-aux val (cdr x)))
nil))
(defthm preimage-aux-when-value-missing
(implies (not (memberp val (strip-cdrs x)))
(equal (preimage-aux val x)
nil))
:hints(("Goal" :in-theory (enable preimage-aux))))
(defthm not-memberp-of-preimage-aux
(implies (not (memberp key (strip-cars x)))
(equal (memberp key (preimage-aux val x))
nil))
:hints(("Goal" :in-theory (enable preimage-aux))))
(defthm unique-of-preimage-aux-when-unique-of-strip-cdrs
(implies (BAG::unique (strip-cdrs x))
(BAG::unique (preimage-aux val x)))
:hints(("Goal" :in-theory (enable preimage-aux))))
(defthm unique-of-preimage-aux-when-unique-of-strip-cars
(implies (BAG::unique (strip-cars x))
(BAG::unique (preimage-aux val x)))
:hints(("Goal" :in-theory (enable preimage-aux))))
(defthm memberp-of-caar-in-preimage-aux
(implies (BAG::unique (strip-cars x))
(equal (memberp (caar x) (preimage-aux a x))
(and (consp x)
(equal (cdar x) a))))
:hints(("goal" :in-theory (enable preimage-aux))))
(defthm preimage-aux-when-not-member-of-cdr-of-strip-cdrs
(implies (not (memberp a (cdr (strip-cdrs x))))
(equal (preimage-aux a x)
(if (and (consp x)
(equal a (cdar x)))
(list (caar x))
nil)))
:hints(("Goal" :in-theory (enable preimage-aux))))
(defthm preimage-aux-of-cdar-with-self
(equal (preimage-aux (cdar x) x)
(if (consp x)
(cons (caar x) (preimage-aux (cdar x) (cdr x)))
nil))
:hints(("Goal" :in-theory (enable preimage-aux))))
(defthm preimage-aux-of-cdr-when-not-cdar
(implies (not (equal (cdar x) a))
(equal (preimage-aux a (cdr x))
(if (consp x)
(preimage-aux a x)
nil)))
:hints(("Goal" :in-theory (enable preimage-aux))))
;; Preimage simply calls Preimage-aux after deshadowing x. This produces a
;; list of keys that would actually map to the desired value when given to
;; assoc.
(defund preimage (val x)
(declare (xargs :guard (alistp x)))
(preimage-aux val (deshadow x)))
(defthm preimage-when-value-missing
(implies (not (memberp val (strip-cdrs x)))
(equal (preimage val x)
nil))
:hints(("Goal" :in-theory (enable preimage))))
(defthm not-memberp-of-preimage
(implies (not (memberp key (strip-cars x)))
(equal (memberp key (preimage val x))
nil))
:hints(("Goal" :in-theory (enable preimage))))
(defthm unique-preimage
(BAG::unique (preimage val x))
:hints(("Goal" :in-theory (enable preimage))))
(defthm preimage-of-deshadow
(equal (preimage val (deshadow x))
(preimage val x))
:hints(("Goal" :in-theory (enable preimage))))
(defthm memberp-of-caar-in-preimage
(equal (memberp (caar x) (preimage a x))
(and (consp x)
(equal (cdar x) a)))
:hints(("Goal" :in-theory (enable preimage)
:use (:instance memberp-of-caar-in-preimage-aux
(x (deshadow x))))))
(defthm preimage-when-not-member-of-cdr-of-strip-cdrs
(implies (not (memberp a (cdr (strip-cdrs x))))
(equal (preimage a x)
(if (and (consp x)
(equal a (cdar x)))
(list (caar x))
nil)))
:hints(("Goal" :in-theory (enable preimage))))
(defthm preimage-of-cdar-with-self
(equal (preimage (cdar x) x)
(if (consp x)
(cons (caar x)
(preimage (cdar x)
(clearkey (caar x) (cdr x))))
nil))
:hints(("Goal" :in-theory (e/d (preimage)
(preimage-aux-of-cdar-with-self))
:use (:instance preimage-aux-of-cdar-with-self
(x (deshadow x))))))
(defthm preimage-of-cdr-when-not-cdar-and-unique
(implies (and (not (equal (cdar x) a))
(BAG::unique (strip-cars x)))
(equal (preimage a (cdr x))
(if (consp x)
(preimage a x)
nil)))
:hints(("Goal" :in-theory (enable preimage))))
(in-theory (disable strip-cars strip-cdrs))
(defthm strip-cars-type-consp
(implies (consp x)
(consp (strip-cars x)))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable strip-cars))))
(defthm strip-cars-type-non-consp
(implies (not (consp x))
(not (consp (strip-cars x))))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable strip-cars))))
(defthm consp-strip-cars
(equal (consp (strip-cars x))
(consp x)))
(defthm strip-cars-of-non-consp
(implies (not (consp x))
(equal (strip-cars x)
nil))
:hints(("Goal" :in-theory (enable strip-cars))))
(defthm strip-cars-of-cons
(equal (strip-cars (cons x y))
(cons (car x)
(strip-cars y)))
:hints(("Goal" :in-theory (enable strip-cars))))
(defthm car-of-strip-cars
(equal (car (strip-cars x))
(car (car x))))
(defthm strip-cars-of-cdr
(equal (strip-cars (cdr x))
(cdr (strip-cars x))))
(defthm len-of-strip-cars
(equal (len (strip-cars x))
(len x))
:hints(("Goal" :in-theory (enable len))))
(defthm strip-cars-of-append
(equal (strip-cars (append x y))
(append (strip-cars x)
(strip-cars y)))
:hints(("Goal" :in-theory (enable append))))
(defthm strip-cars-of-firstn
(equal (strip-cars (firstn n x))
(firstn n (strip-cars x)))
:hints(("Goal" :in-theory (enable firstn))))
(defthm strip-cars-of-nthcdr
(equal (strip-cars (nthcdr n x))
(nthcdr n (strip-cars x)))
:hints(("Goal" :in-theory (enable nthcdr))))
(defthm memberp-caar-strip-cars
(equal (memberp (caar x) (strip-cars x))
(consp x)))
(defthm strip-cdrs-type-consp
(implies (consp x)
(consp (strip-cdrs x)))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable strip-cdrs))))
(defthm strip-cdrs-type-non-consp
(implies (not (consp x))
(not (consp (strip-cdrs x))))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable strip-cdrs))))
(defthm consp-strip-cdrs
(equal (consp (strip-cdrs x))
(consp x)))
(defthm strip-cdrs-of-non-consp
(implies (not (consp x))
(equal (strip-cdrs x)
nil))
:hints(("Goal" :in-theory (enable strip-cdrs))))
(defthm strip-cdrs-of-cons
(equal (strip-cdrs (cons x y))
(cons (cdr x)
(strip-cdrs y)))
:hints(("Goal" :in-theory (enable strip-cdrs))))
(defthm car-of-strip-cdrs
(equal (car (strip-cdrs x))
(cdr (car x))))
(defthm strip-cdrs-of-cdr
(equal (strip-cdrs (cdr x))
(cdr (strip-cdrs x))))
(defthm len-of-strip-cdrs
(equal (len (strip-cdrs x))
(len x))
:hints(("Goal" :in-theory (enable len))))
(defthm strip-cdrs-of-append
(equal (strip-cdrs (append x y))
(append (strip-cdrs x)
(strip-cdrs y)))
:hints(("Goal" :in-theory (enable append))))
(defthm strip-cdrs-of-firstn
(equal (strip-cdrs (firstn n x))
(firstn n (strip-cdrs x)))
:hints(("Goal" :in-theory (enable firstn))))
(defthm strip-cdrs-of-nthcdr
(equal (strip-cdrs (nthcdr n x))
(nthcdr n (strip-cdrs x)))
:hints(("Goal" :in-theory (enable nthcdr))))
(defthm memberp-cdar-strip-cdrs
(equal (memberp (cdar x) (strip-cdrs x))
(consp x)))
| true |
; PI:NAME:<NAME>END_PI: what's this file for? It's not certifiable, so I'm
; renaming it to a .lsp extension for Make compatibility
#|-*-Lisp-*-=================================================================|#
#| |#
#|===========================================================================|#
;; alists-definitions.lisp
;; PI:NAME:<NAME>END_PI
;(in-package "ALIST")
;;
;; This file isolates alists definitions and types. The file currently
;; contains the following ACL2 constructs as they occur in the alists book:
;; - defun
;; - defund
;; - defstub
;; - defchoose
;; - defthm
;; - in-theory
;;
(defthm alist::use-equivp-id
(alist::use-equivp domain x x))
; [Removed by PI:NAME:<NAME>END_PI. to handle changes to member, assoc, etc. after ACL2 4.2.]
; (defthm assoc-eq-is-assoc
; (equal (assoc-eq key list)
; (assoc key list)))
(defthm assoc-equiv-rewrite-order
(implies
(syntaxp (acl2::good-rewrite-order y x))
(equal (alist::assoc-equiv domain x y)
(alist::assoc-equiv domain y x))))
(in-theory (disable ALIST::ASSOC-EQUIV-COMMUTE))
(defthm assoc-equiv-substitution
(implies
(and
(alist::assoc-equiv d1 x y)
(subsetp d2 d1))
(alist::use-equiv :lhs x
:rhs y
:domain d2)))
(defthm assoc-use-cong
(implies
(and
(equal domain (list a))
(acl2::bind-contextp ((b1 (equal b2 (alist::use-ctx b1 :domain domain))))))
(alist::cons-equiv (assoc a b1)
(assoc a b2))))
(defthm alist::use-equivp-self-characterization
(implies
(acl2::bind-contextp ((x (equal a (alist::use-ctx x :domain domain)))
(y (equal b (alist::use-ctx y :domain domain)))))
(equal (alist::use-equivp domain x y)
(alist::use-equivp domain a b))))
(defthm use-equiv-cons-not-member-reduction
(implies
(not (list::memberp (car a) domain))
(alist::use-equiv :lhs (cons a list)
:rhs list
:domain domain)))
(defthm use-equiv-cons-normal-form
(implies
(and
(syntaxp (acl2::<< (car b) (car a)))
(not (equal (car a) (car b))))
(alist::use-equiv :lhs (cons a (cons b x))
:rhs (cons b (cons a x)))))
(defthm use-equiv-append-normal-form
(implies
(and
(syntaxp (acl2::<< y x))
(bag::disjoint (alist::keys x) (alist::keys y)))
(alist::use-equiv :lhs (append x y)
:rhs (append y x))))
;; ===========================================================================
;;
;; This was the easy property .. dropping the first argument to
;; append will be tougher.
;;
;; ===========================================================================
(defthm use-equiv-append-reduction-2
(implies
(subsetp domain (alist::keys x))
(alist::use-equiv :lhs (append x y)
:rhs x
:domain domain)))
;; ===========================================================================
;;
;; assoc-transparent: either the keys are disjoint or the bound values
;; are equal.
;;
;; ===========================================================================
(defun assoc-transparent (key value alist)
(if (consp alist)
(and (implies (equal key (caar alist)) (equal value (cdar alist)))
(assoc-transparent key value (cdr alist)))
t))
(defthm assoc-transparent-append
(equal (assoc-transparent key value (append x y))
(and (assoc-transparent key value x)
(assoc-transparent key value y))))
(defthm assoc-transparent-implies-cons-equiv-assoc
(implies
(assoc-transparent key value x)
(alist::cons-equiv (assoc key x)
(and (list::memberp key (alist::keys x)) (cons key value))))
:hints (("Goal" :in-theory (enable alist::keys))))
(defthm assoc-transparent-implies-cons-equiv-assoc-2
(implies
(and
(assoc-transparent key (cdr (assoc key x)) y)
(list::memberp key (alist::keys y)))
(alist::cons-equiv (assoc key x)
(and (list::memberp key (alist::keys x)) (assoc key y))))
:hints (("Goal" :induct (assoc key y)
:in-theory (enable alist::keys))))
(defthm assoc-transparent-non-memberp
(implies
(not (list::memberp key (alist::keys x)))
(assoc-transparent key nil x))
:hints (("Goal" :in-theory (enable alist::keys))))
(defthm use-equiv-cons-assoc-transparent-reduction
(implies
(and
(assoc-transparent (car a) (cdr a) list)
(list::memberp (car a) (alist::keys list)))
(alist::use-equiv :lhs (cons a list)
:rhs list
:domain domain))
:hints (("Goal" :in-theory (enable alist::keys))))
;; ===========================================================================
;;
;; unified-domain-binding: the alist is self-assoc-transparent.
;;
;; cross-domain-binding: the glue that combines two parts of a
;; unified-domain-binding.
;;
;; ===========================================================================
(defun unified-domain-binding (domain alist)
(if (consp domain)
(and (assoc-transparent (car domain) (cdr (assoc (car domain) alist)) alist)
(unified-domain-binding (cdr domain) alist))
t))
(defun cross-domain-binding (domain x y)
(if (consp domain)
(let ((key (car domain)))
(and (implies (list::memberp key (alist::keys x))
(assoc-transparent key (cdr (assoc key x)) y))
(cross-domain-binding (cdr domain) x y)))
t))
(defthm disjoint-cross-domain-binding
(implies
(bag::disjoint (alist::keys x) (alist::keys y))
(cross-domain-binding domain x y))
:hints (("Goal" :in-theory (enable alist::keys))))
(defthm cross-domain-binding-replacement
(implies
(and
(cross-domain-binding domain x y)
(list::memberp key domain)
(list::memberp key (alist::keys y)))
(alist::cons-equiv (assoc key x)
(and (list::memberp key (alist::keys x)) (assoc key y)))))
(defthmd cross-domain-binding-cons
(implies
(and
(consp x)
(unified-domain-binding domain x))
(equal (cross-domain-binding domain x y)
(and (implies (list::memberp (caar x) domain)
(assoc-transparent (caar x) (cdar x) y))
(cross-domain-binding domain (cdr x) y))))
:hints (("Goal" :induct (cross-domain-binding domain x y)
:in-theory (enable alist::keys))))
(defthmd cross-domain-binding-not-cons
(implies
(not (consp x))
(cross-domain-binding domain x y))
:hints (("Goal" :in-theory (enable alist::keys))))
(defthmd unified-domain-binding-cons
(implies
(consp x)
(equal (unified-domain-binding domain x)
(and (implies (list::memberp (caar x) domain)
(assoc-transparent (caar x) (cdar x) (cdr x)))
(unified-domain-binding domain (cdr x)))))
:hints (("Goal" :induct (unified-domain-binding domain x)
:in-theory (enable alist::keys))))
(defthmd unified-domain-binding-non-cons
(implies
(not (consp x))
(unified-domain-binding domain x)))
(defthm unified-domain-binding-append
(equal (unified-domain-binding domain (append x y))
(and (unified-domain-binding domain x)
(unified-domain-binding domain y)
(cross-domain-binding domain x y)))
:hints (("Goal" :induct (append x y)
:in-theory (enable append
unified-domain-binding-cons
unified-domain-binding-non-cons
cross-domain-binding-cons
cross-domain-binding-not-cons
))))
(defthm use-equiv-append-reduction-1
(implies
(and
(cross-domain-binding d1 x y)
(subsetp domain d1)
(subsetp domain (alist::keys y)))
(alist::use-equiv :lhs (append x y)
:rhs y
:domain domain))
:hints (("Goal" :in-theory (disable ASSOC-EQUIV-SUBSTITUTION)))
:otf-flg t)
;; ===========================================================================
;;
;; unified-binding: the alist is self-consistent w/to unified-domain-bindings
;;
;; ===========================================================================
(defund unified-binding (alist)
(unified-domain-binding (alist::keys alist) alist))
(defun equiv-domain-binding (domain x y)
(and (cross-domain-binding domain x y)
(cross-domain-binding domain y x)))
(defthm unified-domain-binding-subsetp
(implies
(and
(unified-domain-binding y a)
(subsetp x y))
(unified-domain-binding x a)))
(defund clearkey (k x)
(declare (xargs :guard (alistp x)))
(if (consp x)
(if (equal k (caar x))
(clearkey k (cdr x))
(cons (consfix (car x))
(clearkey k (cdr x))))
nil))
(defthm alistp-of-clearkey
(alistp (clearkey k x))
:hints(("Goal" :in-theory (enable clearkey))))
(defthm clearkey-of-cons
(equal (clearkey k (cons a x))
(if (equal k (car a))
(clearkey k x)
(cons (consfix a) (clearkey k x))))
:hints(("Goal" :in-theory (enable clearkey))))
; no theorem about car-of-clearkey, too hard to describe
; no theorem about cdr-of-clearkey, too hard to describe
(defthm len-of-clearkey-bound-tight
(implies (memberp k (strip-cars x))
(< (len (clearkey k x))
(len x)))
:rule-classes :linear
:hints(("Goal" :in-theory (enable clearkey))))
(defthm len-of-clearkey-bound-tight-rewrite
(implies (memberp k (strip-cars x))
(equal (< (len (clearkey k x)) (len x))
t)))
(defthm len-of-clearkey-bound-weak
(<= (len (clearkey k x))
(len x))
:rule-classes :linear
:hints(("Goal" :in-theory (enable clearkey))))
(defthm len-of-clearkey-bound-weak-rewrite
(equal (< (len x) (len (clearkey k x)))
nil))
;; no theorem about clearkey-of-firstn, too awkward to describe
;; no theorem about clearkey-of-nthcdr, too awkward to describe
(defthm clearkey-of-append
(equal (clearkey k (append x y))
(append (clearkey k x)
(clearkey k y)))
:hints(("Goal" :in-theory (enable clearkey))))
(defthm clearkey-reorder
(equal (clearkey k1 (clearkey k2 r))
(clearkey k2 (clearkey k1 r)))
:hints(("Goal" :in-theory (enable clearkey))))
(defthm clearkey-when-non-memberp
(implies (not (memberp key (strip-cars x)))
(equal (clearkey key x)
(alistfix x)))
:hints(("Goal" :in-theory (enable clearkey))))
(defthm clearkey-caar-when-unique
(implies (and (consp x)
(BAG::unique (strip-cars x)))
(equal (clearkey (caar x) (cdr x))
(alistfix (cdr x)))))
(defthm strip-cars-of-clearkey
(equal (strip-cars (clearkey k x))
(BAG::remove-all k (strip-cars x)))
:hints(("Goal" :in-theory (enable clearkey))))
(defthm clearkey-idempotent
(equal (clearkey k (clearkey k r))
(clearkey k r)))
(defthm not-memberp-of-strip-cdrs-of-clearkey
(implies (not (memberp val (strip-cdrs x)))
(not (memberp val (strip-cdrs (clearkey key x)))))
:hints(("Goal" :in-theory (enable clearkey))))
;; bzo move to bags library
(defthm count-of-remove-all-diff
(implies (not (equal a b))
(equal (BAG::count a (BAG::remove-all b x))
(BAG::count a x)))
:hints(("Goal" :in-theory (enable BAG::remove-all))))
(defund deshadow (x)
(declare (xargs :guard (alistp x)
:measure (len x)))
(if (consp x)
(cons (consfix (car x))
(deshadow (clearkey (caar x) (cdr x))))
nil))
(defthm deshadow-type-1
(implies (not (consp x))
(equal (deshadow x) nil))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable deshadow))))
(defthm deshadow-type-2
(implies (consp x)
(consp (deshadow x)))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable deshadow))))
(defthm deshadow-of-non-consp
(implies (not (consp x))
(equal (deshadow x)
nil)))
(defthm consp-of-deshadow
(equal (consp (deshadow x))
(consp x)))
(defthm deshadow-of-cons
(equal (deshadow (cons x y))
(cons (consfix x)
(deshadow (clearkey (car x) y))))
:hints(("Goal" :in-theory (enable deshadow clearkey))))
(defthm car-of-deshadow
(equal (car (deshadow x))
(if (consp x)
(consfix (car x))
nil)))
;; no rules about cdr-of-deshadow, it is weird
(defthm len-of-deshadow-weak
(<= (len (deshadow x))
(len x))
:rule-classes :linear
:hints(("Goal" :in-theory (enable deshadow))))
(defthm len-of-deshadow-weak-rewrite
(equal (< (len x) (len (deshadow x)))
nil))
;; Even though we will shortly prove deshadow-when-strip-cars-unique, we will
;; go ahead and prove both :linear rules below, so that we can backchain to
;; the unique of strip cars hypothesis when necessary.
(defthm len-of-deshadow-when-strip-cars-not-unique
(implies (not (BAG::unique (strip-cars x)))
(< (len (deshadow x))
(len x)))
:rule-classes :linear
:hints(("Goal" :in-theory (enable deshadow))))
(defthm len-of-deshadow-when-strip-cars-unique
(implies (BAG::unique (strip-cars x))
(equal (len (deshadow x))
(len x)))
:rule-classes :linear
:hints(("Goal" :in-theory (enable deshadow))))
(defthm len-of-deshadow-decreases-rewrite
(equal (< (len (deshadow x)) (len x))
(not (BAG::unique (strip-cars x)))))
(defthm alistp-of-deshadow
(alistp (deshadow x))
:hints(("Goal" :in-theory (enable deshadow))))
(defthm deshadow-of-clearkey
(equal (deshadow (clearkey key x))
(clearkey key (deshadow x)))
:hints(("Goal" :in-theory (enable deshadow))))
(defthm unique-of-strip-cars-of-deshadow
(BAG::unique (strip-cars (deshadow x)))
:hints(("Goal" :in-theory (enable deshadow))))
(defthm deshadow-when-strip-cars-unique
(implies (BAG::unique (strip-cars x))
(equal (deshadow x)
(alistfix x)))
:hints(("Goal" :in-theory (enable deshadow))))
(defthm deshadow-idempotent
(equal (deshadow (deshadow x))
(deshadow x)))
(defthm memberp-of-strip-cars-of-deshadow
(equal (memberp key (strip-cars (deshadow x)))
(memberp key (strip-cars x)))
:hints(("Goal" :in-theory (enable deshadow))))
(defthm count-of-strip-cars-of-deshadow
(<= (BAG::count key (strip-cars (deshadow x)))
(BAG::count key (strip-cars x)))
:hints(("Goal" :in-theory (enable deshadow))))
;; There is probably an equivalent rule for strip-cdrs, but I haven't tried
;; to prove it yet.
(defthm not-memberp-of-strip-cdrs-of-deshadow
(implies (not (memberp val (strip-cdrs x)))
(equal (memberp val (strip-cdrs (deshadow x)))
nil))
:hints(("Goal" :in-theory (enable deshadow))))
;; Interpreting Objects as Conses (consfix)
;;
;; We can think of a mapping between all ACL2 objects and conses, so that any
;; atom is mapped to (nil . nil) and any cons is mapped to itself. The
;; function consfix applies this mapping for us, i.e., it interprets any ACL2
;; object as a cons. Because this is how car and cdr interpret their
;; arguments, there are some very nice properties that we can prove about this
;; operation.
(defund consfix (x)
(declare (type t x))
(if (consp x)
x
(cons nil nil)))
(defthm consfix-when-non-consp
(implies (not (consp x))
(equal (consfix x)
(cons nil nil)))
:hints(("Goal" :in-theory (enable consfix))))
(defthm consfix-when-consp
(implies (consp x)
(equal (consfix x)
x))
:hints(("Goal" :in-theory (enable consfix))))
(defthm consfix-does-nothing
(equal (equal x (consfix x))
(consp x))
:hints(("Goal" :in-theory (enable consfix))))
(defthm consfix-of-cons
(equal (consfix (cons a b))
(cons a b)))
;; Note (jcd): Do not add the following rules. They are trivial consequences
;; of the congruence rules under cons-equiv below, so adding them is not
;; necessary.
;;
;; (defthm consfix-of-car
;; (equal (car (consfix a))
;; (car a)))
;;
;; (defthm consfix-of-cdr
;; (equal (cdr (consfix a))
;; (cdr a)))
;; The Cons Equivalence Relation (cons-equiv)
;;
;; Given that (with consfix) we can now think of any object as a cons, the next
;; natural step is to define an equivalence relation wherein objects are
;; considered to be equivalent when their interpretations as conses are the
;; same.
(defund cons-equiv (x y)
(declare (type t x y))
(equal (consfix x)
(consfix y)))
(defthm consfix-in-cons-equiv
(cons-equiv (consfix x)
x)
:hints(("Goal" :in-theory (enable cons-equiv))))
(defthm equal-of-consfixes
(equal (equal (consfix x) (consfix y))
(cons-equiv x y))
:hints (("Goal" :in-theory (enable cons-equiv))))
;; Interpreting Objects as Alists (alistfix)
;;
;; An alist is a list of pairs. Since we can now interpret any ACL2 object as
;; a pair using consfix, it is straightforward to interpet any ACL2 object as
;; an alist: any atom is interpreted as the empty alist, and any list is fixed
;; by pair-fixing each of its elements.
;;
;; An alternate definition that I considered was to simply interpret any
;; non-alistp object as the empty alist, and any alist as itself. But, I think
;; the current approach gives us many nice rules. In particular, our approach
;; allows alist-equiv to be a refinement of list::equiv, giving us a lot of
;; rewrite rules "for free" (e.g., the lengths are the same). Other rules work
;; nicely (the keys are the same, the values are the same, etc.) Finally, we
;; also get to provide very nice congruence rules, e.g., the cars of alist
;; interpretations are cons-equiv.
(defund alistfix (x)
(declare (type t x))
(if (consp x)
(cons (consfix (car x))
(alistfix (cdr x)))
nil))
(defthm alistfix-type-consp
(implies (consp x)
(consp (alistfix x)))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable alistfix))))
(defthm alistfix-type-non-consp
(implies (not (consp x))
(equal (alistfix x)
nil))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable alistfix))))
;; Note (jcd): Do not add the following rule. It is redundant with the defcong
;; below for alist-equiv over consp.
;;
;; (defthm consp-alistfix
;; (equal (consp (alistfix x))
;; (consp x)))
(defthm alistfix-when-non-consp
(implies (not (consp alist))
(equal (alistfix alist)
nil)))
(defthm alistfix-when-alist
(implies (alistp x)
(equal (alistfix x)
x))
:hints(("Goal" :in-theory (enable alistfix))))
(defthm alistfix-does-nothing
(equal (equal x (alistfix x))
(alistp x))
:hints(("Goal" :in-theory (enable alistfix))))
(defthm alistp-of-alistfix
(alistp (alistfix x))
:hints(("Goal" :in-theory (enable alistfix))))
(defthm alistfix-of-cons
(equal (alistfix (cons a x))
(cons (consfix a) (alistfix x)))
:hints(("Goal" :in-theory (enable alistfix))))
(defthm car-of-alistfix
(equal (car (alistfix a))
(if (consp a)
(consfix (car a))
nil)))
(defthm cdr-of-alistfix
(equal (cdr (alistfix a))
(alistfix (cdr a))))
;; Note (jcd): Do not add the following rule. It is trivial using the
;; congruence rule of alist-equiv for len, along with alistfix-in-alist-equiv.
;;
;; (defthm len-of-alistfix
;; (equal (len (alistfix a))
;; (len a)))
(defthm alistfix-of-append
(equal (alistfix (append x y))
(append (alistfix x)
(alistfix y)))
:hints(("Goal" :in-theory (enable append))))
(defthm alistfix-of-firstn
(equal (alistfix (list::firstn n x))
(list::firstn n (alistfix x)))
:hints(("Goal" :in-theory (enable list::firstn))))
(defthm alistfix-of-nthcdr
(equal (alistfix (nthcdr n x))
(nthcdr n (alistfix x)))
:hints(("Goal" :in-theory (enable nthcdr))))
;; The Alist Equivalence Relation
;;
;; Given that (with alistfix) we can now think of any object as an alist, the
;; next natural step is to define an equivalence relation wherein objects are
;; considered to be equivalent when their interpretations as alists are the
;; same.
;;
;; IMPORTANT: You might think that alists should be considered to be equivalent
;; whenever "forall a, (assoc a x) = (assoc a y)." Although equivalent alists
;; will satisfy this property, the converse is NOT true! For example, if x and
;; y satisfy this property but x has shadowed pairs and y does not, then x and
;; y will not be considered equivalent under alist-equiv!
;;
;; Instead, you should think of alist-equiv as a "structural" relation that
;; essentially is comparing the interpretation of x and y as lists of pairs.
;; But understand that no a priori judgement is made as to how those lists of
;; pairs will be used, and we do not assume that shadowed pairs are irrelevant.
(defund alist-equiv (a b)
(equal (alistfix a)
(alistfix b)))
(defthm alistfix-in-alist-equiv
(alist-equiv (alistfix a)
a)
:hints(("Goal" :in-theory (enable alist-equiv))))
(defthm alist-equiv-cons-cases
(equal (alist-equiv x (cons y z))
(and (consp x)
(cons-equiv y (car x))
(alist-equiv z (cdr x))))
:hints(("Goal" :in-theory (enable alist-equiv))))
(defthm equal-of-alistfixes
(equal (equal (alistfix x) (alistfix y))
(alist-equiv x y))
:hints(("Goal" :in-theory (enable alist-equiv))))
;; Interpreting Objects as Conses (consfix)
;;
;; We can think of a mapping between all ACL2 objects and conses, so that any
;; atom is mapped to (nil . nil) and any cons is mapped to itself. The
;; function consfix applies this mapping for us, i.e., it interprets any ACL2
;; object as a cons. Because this is how car and cdr interpret their
;; arguments, there are some very nice properties that we can prove about this
;; operation.
(defund consfix (x)
(declare (type t x))
(if (consp x)
x
(cons nil nil)))
(defthm consfix-when-non-consp
(implies (not (consp x))
(equal (consfix x)
(cons nil nil)))
:hints(("Goal" :in-theory (enable consfix))))
(defthm consfix-when-consp
(implies (consp x)
(equal (consfix x)
x))
:hints(("Goal" :in-theory (enable consfix))))
(defthm consfix-does-nothing
(equal (equal x (consfix x))
(consp x))
:hints(("Goal" :in-theory (enable consfix))))
(defthm consfix-of-cons
(equal (consfix (cons a b))
(cons a b)))
;; Note (jcd): Do not add the following rules. They are trivial consequences
;; of the congruence rules under cons-equiv below, so adding them is not
;; necessary.
;;
;; (defthm consfix-of-car
;; (equal (car (consfix a))
;; (car a)))
;;
;; (defthm consfix-of-cdr
;; (equal (cdr (consfix a))
;; (cdr a)))
;; The Cons Equivalence Relation (cons-equiv)
;;
;; Given that (with consfix) we can now think of any object as a cons, the next
;; natural step is to define an equivalence relation wherein objects are
;; considered to be equivalent when their interpretations as conses are the
;; same.
(defund cons-equiv (x y)
(declare (type t x y))
(equal (consfix x)
(consfix y)))
(defthm cons-equiv-cases-fwd
(implies
(and (equal (car x) (car y))
(equal (cdr x) (cdr y)))
(cons-equiv x y))
:hints (("Goal" :in-theory (enable cons-equiv)))
:rule-classes (:forward-chaining))
(defthm not-cons-equiv-cases-fwd-1
(implies
(not (equal (car x) (car y)))
(not (cons-equiv x y)))
:hints (("Goal" :in-theory (enable cons-equiv)))
:rule-classes (:forward-chaining))
(defthm not-cons-equiv-cases-fwd-2
(implies
(not (equal (cdr x) (cdr y)))
(not (cons-equiv x y)))
:hints (("Goal" :in-theory (enable cons-equiv)))
:rule-classes (:forward-chaining))
(defthm cons-equiv-fwd
(implies
(cons-equiv x y)
(and (equal (car x) (car y))
(equal (cdr x) (cdr y))))
:hints (("Goal" :in-theory (enable cons-equiv)))
:rule-classes (:forward-chaining))
(defthm cons-equiv-cons-reduction-1
(equal (cons-equiv (cons a b) c)
(and (equal a (car c))
(equal b (cdr c))))
:hints (("Goal" :in-theory (enable cons-equiv))))
(defthm cons-equiv-cons-reduction-2
(equal (cons-equiv a (cons b c))
(and (equal (car a) b)
(equal (cdr a) c)))
:hints (("Goal" :in-theory (enable cons-equiv))))
(defthm consfix-in-cons-equiv
(cons-equiv (consfix x)
x)
:hints(("Goal" :in-theory (enable cons-equiv))))
(defthm equal-of-consfixes
(equal (equal (consfix x) (consfix y))
(cons-equiv x y))
:hints (("Goal" :in-theory (enable cons-equiv))))
(defun keys (alist)
(declare (type t alist))
(if (consp alist)
(if (consp (car alist))
(cons (caar alist)
(keys (cdr alist)))
(cons nil (keys (cdr alist))))
nil))
#|
(defthm memberp-cons-keys
(implies
(consp alist)
(memberp (caar alist) (keys alist))))
(defthm clrv-len-reduction
(implies
(memberp a (keys alist))
(< (len (clrv a alist)) (len alist)))
:rule-classes (:linear))
(defun element (a y)
(if (consp y)
(if (equal (car a) (caar y))
(equal (cdr a) (cdar y))
(element a (cdr y)))
nil))
(defthm element-definition
(equal (element a y)
(and (memberp (car a) (keys y))
(equal (cdr a) (cdr (getv (car a) y)))))
:rule-classes (:definition))
(defthm element-implication
(implies
(element a y)
(and (memberp (car a) (keys y))
(equal (cdr a) (cdr (getv (car a) y)))))
:rule-classes (:forward-chaining))
(defthm element-elements-implication
(implies
(and (memberp (car a) (keys y))
(equal (cdr a) (cdr (getv (car a) y))))
(element a y))
:rule-classes (:forward-chaining))
(defthm not-element-elements-implication-1
(implies
(not (memberp (car a) (keys y)))
(not (element a y)))
:rule-classes (:forward-chaining))
(defthm not-element-elements-implication-2
(implies
(not (equal (cdr a) (cdr (getv (car a) y))))
(not (element a y)))
:rule-classes (:forward-chaining))
(defthm element-base
(implies
(not (consp x))
(not (element a x)))
:hints (("Goal" :in-theory (enable element))))
(defthm element-cons
(equal (element a (cons x y))
(if (equal (car a) (car x))
(equal (cdr a) (cdr x))
(element a y)))
:hints (("Goal" :in-theory (enable element))))
(defthm element-append
(equal (element a (append x y))
(if (memberp (car a) (keys x))
(element a x)
(element a y)))
:hints (("Goal" :induct (append x y)
:in-theory (enable memberp append element))))
|#
(defthm assoc-append
(equal (assoc a (append x y))
(if (memberp a (keys x))
(assoc a x)
(assoc a y))))
(defthm keys-append
(equal (keys (append x y))
(append (keys x)
(keys y))))
;; pick-a-point
#|
(defthm consp-implies-memberp
(implies
(consp x)
(memberp (caar x) (keys x))))
|#
(defun assoc-equiv (list x y)
(if (consp list)
(and (cons-equiv (assoc (car list) x)
(assoc (car list) y))
(assoc-equiv (cdr list) x y))
t))
(defthmd assoc-equiv-commute
(equal (assoc-equiv list x y)
(assoc-equiv list y x)))
(defthm assoc-equiv-commute-fwd
(implies
(assoc-equiv list x y)
(assoc-equiv list y x))
:hints (("Goal" :in-theory (enable assoc-equiv-commute))))
(defthm assoc-equiv-memberp
(implies
(and
(memberp a list)
(assoc-equiv list x y))
(cons-equiv (assoc a x)
(assoc a y)))
:rule-classes (:forward-chaining))
(defthm assoc-equiv-subsetp-1
(implies
(and
(subsetp a b)
(assoc-equiv b x y))
(assoc-equiv a x y))
:rule-classes (:rewrite :forward-chaining))
(defthm assoc-equiv-subsetp-2
(implies
(and
(assoc-equiv b x y)
(subsetp a b))
(assoc-equiv a x y))
:rule-classes (:rewrite :forward-chaining))
(defthm assoc-equiv-chaining-1
(implies
(and
(assoc-equiv a w x)
(assoc-equiv a x y))
(assoc-equiv a w y))
:rule-classes (:rewrite :forward-chaining))
(defthm assoc-equiv-chaining-2
(implies
(and
(assoc-equiv a x y)
(assoc-equiv a w x))
(assoc-equiv a w y))
:rule-classes (:rewrite :forward-chaining))
(defun subdomain (x y)
(and (assoc-equiv (keys x) x y)
(subsetp (keys x) (keys y))))
(defun keyquiv (x y)
(and (list::setequiv (keys x) (keys y))
(assoc-equiv (keys x) x y)
(assoc-equiv (keys y) y x)))
(defthm assoc-non-memberp
(implies
(not (memberp a (keys alist)))
(equal (assoc a alist) nil)))
(defthm car-assoc-memberp
(implies
(memberp a (keys alist))
(equal (car (assoc a alist))
a)))
(defthm keyquiv-cons-commute
(implies
(not (equal (car a) (car b)))
(keyquiv (cons a (cons b x))
(cons b (cons a x)))))
(defthm keyquiv-cons-crush
(implies
(equal (car a) (car b))
(keyquiv (cons a (cons b x))
(cons a x))))
(in-theory (disable keyquiv))
(defun setv (a v alist)
(cons (cons a v) alist))
(defun getv (a alist)
(cdr (assoc a alist)))
(defthm getv-over-setv
(equal (getv a (setv b v r))
(if (equal a b)
v
(getv a r))))
(defthm setv-over-setv
(implies
(not (equal a b))
(keyquiv (setv a v (setv b w r))
(setv b w (setv a v r)))))
(defthm setv-of-setv
(keyquiv (setv a v (setv a w r))
(setv a v r)))
(defthm setv-of-getv
(implies
(memberp a (keys r))
(keyquiv (setv a (getv a r) r)
r))
:hints (("Goal" :in-theory (enable keyquiv))))
(defthm keys-setv
(equal (keys (setv a v r))
(cons a (keys r))))
(defun clr (key alist)
(if (consp alist)
(if (equal key (caar alist))
(clr key (cdr alist))
(cons (car alist)
(clr key (cdr alist))))
alist))
(defthm clr-append
(equal (clr a (append x y))
(append (clr a x) (clr a y))))
(defthm clr-clr-commute
(equal (clr a (clr b x))
(clr b (clr a x))))
(defthm keys-clr
(equal (keys (clr key alist))
(remove key (keys alist))))
(defthm assoc-clr
(equal (assoc a (clr key x))
(if (equal a key) nil
(assoc a x))))
(in-theory (disable LIST::SETEQUIV-REMOVE-DEFINITION))
(defthm getv-clr
(equal (getv a (clr key alist))
(if (equal a key) nil
(getv a alist))))
(defthm clr-over-setv
(implies
(not (equal a b))
(keyquiv (clr a (setv b v r))
(setv b v (clr a r)))))
(defthm clr-of-setv
(keyquiv (clr a (setv a v r))
(clr a r)))
(defthm acl2-count-cdr-<=
(<= (acl2-count (cdr x)) (acl2-count x))
:rule-classes (:linear))
(defthm acl2-count-car-<=
(<= (acl2-count (car x)) (acl2-count x))
:rule-classes (:linear))
(defthm memberp-clr-non-increasing
(<= (acl2-count (clr a alist)) (acl2-count alist))
:hints (("goal" :induct (clr a alist)))
:rule-classes (:linear))
(defthm memberp-clr-decreases
(implies
(memberp a (keys alist))
(< (acl2-count (clr a alist)) (acl2-count alist)))
:hints (("goal" :induct (clr a alist)))
:rule-classes (:linear))
(defthm memberp-cons
(implies
(consp alist)
(memberp (caar alist) (keys alist))))
(defthm acl2-count-assoc-<=
(<= (acl2-count (assoc a list)) (acl2-count list))
:hints (("Goal" :induct (assoc a list)))
:rule-classes (:linear))
(defthm acl2-count-assoc-memberp-<
(implies
(memberp key (keys list))
(< (acl2-count (assoc a list)) (acl2-count list)))
:hints (("Goal" :induct (assoc a list)))
:rule-classes (:linear))
(defthm acl2-count-getv-<=
(<= (acl2-count (alist::getv key alist1)) (acl2-count alist1))
:rule-classes (:linear))
(defthm acl2-count-getv-<
(implies
(memberp key (alist::keys alist1))
(< (acl2-count (alist::getv key alist1)) (acl2-count alist1)))
:rule-classes (:linear))
(in-theory (disable setv getv clr keys))
;; Preimage-aux scans the list looking for our value, and collects any keys it
;; finds along the way. Note that it will collect shadowed pairs if they are
;; bound to our value.
(defund preimage-aux (val x)
(declare (xargs :guard (alistp x)))
(if (consp x)
(if (equal (cdar x) val)
(cons (caar x)
(preimage-aux val (cdr x)))
(preimage-aux val (cdr x)))
nil))
(defthm preimage-aux-when-value-missing
(implies (not (memberp val (strip-cdrs x)))
(equal (preimage-aux val x)
nil))
:hints(("Goal" :in-theory (enable preimage-aux))))
(defthm not-memberp-of-preimage-aux
(implies (not (memberp key (strip-cars x)))
(equal (memberp key (preimage-aux val x))
nil))
:hints(("Goal" :in-theory (enable preimage-aux))))
(defthm unique-of-preimage-aux-when-unique-of-strip-cdrs
(implies (BAG::unique (strip-cdrs x))
(BAG::unique (preimage-aux val x)))
:hints(("Goal" :in-theory (enable preimage-aux))))
(defthm unique-of-preimage-aux-when-unique-of-strip-cars
(implies (BAG::unique (strip-cars x))
(BAG::unique (preimage-aux val x)))
:hints(("Goal" :in-theory (enable preimage-aux))))
(defthm memberp-of-caar-in-preimage-aux
(implies (BAG::unique (strip-cars x))
(equal (memberp (caar x) (preimage-aux a x))
(and (consp x)
(equal (cdar x) a))))
:hints(("goal" :in-theory (enable preimage-aux))))
(defthm preimage-aux-when-not-member-of-cdr-of-strip-cdrs
(implies (not (memberp a (cdr (strip-cdrs x))))
(equal (preimage-aux a x)
(if (and (consp x)
(equal a (cdar x)))
(list (caar x))
nil)))
:hints(("Goal" :in-theory (enable preimage-aux))))
(defthm preimage-aux-of-cdar-with-self
(equal (preimage-aux (cdar x) x)
(if (consp x)
(cons (caar x) (preimage-aux (cdar x) (cdr x)))
nil))
:hints(("Goal" :in-theory (enable preimage-aux))))
(defthm preimage-aux-of-cdr-when-not-cdar
(implies (not (equal (cdar x) a))
(equal (preimage-aux a (cdr x))
(if (consp x)
(preimage-aux a x)
nil)))
:hints(("Goal" :in-theory (enable preimage-aux))))
;; Preimage simply calls Preimage-aux after deshadowing x. This produces a
;; list of keys that would actually map to the desired value when given to
;; assoc.
(defund preimage (val x)
(declare (xargs :guard (alistp x)))
(preimage-aux val (deshadow x)))
(defthm preimage-when-value-missing
(implies (not (memberp val (strip-cdrs x)))
(equal (preimage val x)
nil))
:hints(("Goal" :in-theory (enable preimage))))
(defthm not-memberp-of-preimage
(implies (not (memberp key (strip-cars x)))
(equal (memberp key (preimage val x))
nil))
:hints(("Goal" :in-theory (enable preimage))))
(defthm unique-preimage
(BAG::unique (preimage val x))
:hints(("Goal" :in-theory (enable preimage))))
(defthm preimage-of-deshadow
(equal (preimage val (deshadow x))
(preimage val x))
:hints(("Goal" :in-theory (enable preimage))))
(defthm memberp-of-caar-in-preimage
(equal (memberp (caar x) (preimage a x))
(and (consp x)
(equal (cdar x) a)))
:hints(("Goal" :in-theory (enable preimage)
:use (:instance memberp-of-caar-in-preimage-aux
(x (deshadow x))))))
(defthm preimage-when-not-member-of-cdr-of-strip-cdrs
(implies (not (memberp a (cdr (strip-cdrs x))))
(equal (preimage a x)
(if (and (consp x)
(equal a (cdar x)))
(list (caar x))
nil)))
:hints(("Goal" :in-theory (enable preimage))))
(defthm preimage-of-cdar-with-self
(equal (preimage (cdar x) x)
(if (consp x)
(cons (caar x)
(preimage (cdar x)
(clearkey (caar x) (cdr x))))
nil))
:hints(("Goal" :in-theory (e/d (preimage)
(preimage-aux-of-cdar-with-self))
:use (:instance preimage-aux-of-cdar-with-self
(x (deshadow x))))))
(defthm preimage-of-cdr-when-not-cdar-and-unique
(implies (and (not (equal (cdar x) a))
(BAG::unique (strip-cars x)))
(equal (preimage a (cdr x))
(if (consp x)
(preimage a x)
nil)))
:hints(("Goal" :in-theory (enable preimage))))
(in-theory (disable strip-cars strip-cdrs))
(defthm strip-cars-type-consp
(implies (consp x)
(consp (strip-cars x)))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable strip-cars))))
(defthm strip-cars-type-non-consp
(implies (not (consp x))
(not (consp (strip-cars x))))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable strip-cars))))
(defthm consp-strip-cars
(equal (consp (strip-cars x))
(consp x)))
(defthm strip-cars-of-non-consp
(implies (not (consp x))
(equal (strip-cars x)
nil))
:hints(("Goal" :in-theory (enable strip-cars))))
(defthm strip-cars-of-cons
(equal (strip-cars (cons x y))
(cons (car x)
(strip-cars y)))
:hints(("Goal" :in-theory (enable strip-cars))))
(defthm car-of-strip-cars
(equal (car (strip-cars x))
(car (car x))))
(defthm strip-cars-of-cdr
(equal (strip-cars (cdr x))
(cdr (strip-cars x))))
(defthm len-of-strip-cars
(equal (len (strip-cars x))
(len x))
:hints(("Goal" :in-theory (enable len))))
(defthm strip-cars-of-append
(equal (strip-cars (append x y))
(append (strip-cars x)
(strip-cars y)))
:hints(("Goal" :in-theory (enable append))))
(defthm strip-cars-of-firstn
(equal (strip-cars (firstn n x))
(firstn n (strip-cars x)))
:hints(("Goal" :in-theory (enable firstn))))
(defthm strip-cars-of-nthcdr
(equal (strip-cars (nthcdr n x))
(nthcdr n (strip-cars x)))
:hints(("Goal" :in-theory (enable nthcdr))))
(defthm memberp-caar-strip-cars
(equal (memberp (caar x) (strip-cars x))
(consp x)))
(defthm strip-cdrs-type-consp
(implies (consp x)
(consp (strip-cdrs x)))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable strip-cdrs))))
(defthm strip-cdrs-type-non-consp
(implies (not (consp x))
(not (consp (strip-cdrs x))))
:rule-classes :type-prescription
:hints(("Goal" :in-theory (enable strip-cdrs))))
(defthm consp-strip-cdrs
(equal (consp (strip-cdrs x))
(consp x)))
(defthm strip-cdrs-of-non-consp
(implies (not (consp x))
(equal (strip-cdrs x)
nil))
:hints(("Goal" :in-theory (enable strip-cdrs))))
(defthm strip-cdrs-of-cons
(equal (strip-cdrs (cons x y))
(cons (cdr x)
(strip-cdrs y)))
:hints(("Goal" :in-theory (enable strip-cdrs))))
(defthm car-of-strip-cdrs
(equal (car (strip-cdrs x))
(cdr (car x))))
(defthm strip-cdrs-of-cdr
(equal (strip-cdrs (cdr x))
(cdr (strip-cdrs x))))
(defthm len-of-strip-cdrs
(equal (len (strip-cdrs x))
(len x))
:hints(("Goal" :in-theory (enable len))))
(defthm strip-cdrs-of-append
(equal (strip-cdrs (append x y))
(append (strip-cdrs x)
(strip-cdrs y)))
:hints(("Goal" :in-theory (enable append))))
(defthm strip-cdrs-of-firstn
(equal (strip-cdrs (firstn n x))
(firstn n (strip-cdrs x)))
:hints(("Goal" :in-theory (enable firstn))))
(defthm strip-cdrs-of-nthcdr
(equal (strip-cdrs (nthcdr n x))
(nthcdr n (strip-cdrs x)))
:hints(("Goal" :in-theory (enable nthcdr))))
(defthm memberp-cdar-strip-cdrs
(equal (memberp (cdar x) (strip-cdrs x))
(consp x)))
|
[
{
"context": "hat uses an Axe Prover\n;\n; Copyright (C) 2008-2011 Eric Smith and Stanford University\n; Copyright (C) 2013-2020",
"end": 98,
"score": 0.9995678067207336,
"start": 88,
"tag": "NAME",
"value": "Eric Smith"
},
{
"context": "ense. See the file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;",
"end": 309,
"score": 0.9993159770965576,
"start": 299,
"tag": "NAME",
"value": "Eric Smith"
},
{
"context": " file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 333,
"score": 0.9999303817749023,
"start": 311,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/kestrel/axe/make-clause-processor-simple.lisp
|
airbornemihir/acl2
| 1 |
; A tool to make a clause processor that uses an Axe Prover
;
; Copyright (C) 2008-2011 Eric Smith and Stanford University
; Copyright (C) 2013-2020 Kestrel Institute
; Copyright (C) 2016-2020 Kestrel Technology, LLC
;
; License: A 3-clause BSD license. See the file books/3BSD-mod.txt.
;
; Author: Eric Smith ([email protected])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(include-book "kestrel/utilities/pack" :dir :system)
;; Returns an event
(defun make-clause-processor-simple-fn (suffix ;; gets added to generated names
)
(declare (xargs :guard (symbolp suffix)))
(let* ((clause-processor-name (pack$ suffix '-prover-clause-processor)) ; should already be defined
(defthm-with-clause-processor-name (pack$ 'defthm-with- clause-processor-name))
(defthm-with-clause-processor-fn-name (pack$ 'defthm-with- clause-processor-name '-fn)))
`(encapsulate ()
;; (local (include-book "kestrel/lists-light/nth" :dir :system))
;; (local (include-book "kestrel/lists-light/remove-equal" :dir :system))
;; (local (include-book "kestrel/lists-light/len" :dir :system))
;; (local (include-book "kestrel/lists-light/reverse" :dir :system))
;; (local (include-book "kestrel/lists-light/last" :dir :system))
;; (local (include-book "kestrel/lists-light/subsetp-equal" :dir :system))
;; (local (include-book "kestrel/lists-light/take" :dir :system))
;; (local (include-book "kestrel/lists-light/true-list-fix" :dir :system))
;; (local (include-book "kestrel/lists-light/cons" :dir :system)) ; for true-listp-of-cons
;; (local (include-book "kestrel/alists-light/strip-cdrs" :dir :system))
;; (local (include-book "kestrel/alists-light/pairlis-dollar" :dir :system))
;; (local (include-book "kestrel/arithmetic-light/plus" :dir :system))
;; (local (include-book "kestrel/utilities/acl2-count" :dir :system))
;; (local (include-book "kestrel/typed-lists-light/nat-listp" :dir :system))
;; (local (include-book "kestrel/typed-lists-light/symbol-listp" :dir :system))
;; See also the define-trusted-clause-processor in prover2.lisp.
(define-trusted-clause-processor
,clause-processor-name
nil ;supporters ; todo: Think about this (I don't understand what :doc define-trusted-clause-processor says about "supporters")
:ttag ,clause-processor-name)
;; Returns a defthm event.
(defun ,defthm-with-clause-processor-fn-name (name term tactic rules rule-lists remove-rules no-splitp rule-classes print state)
(declare (xargs :guard (and (symbolp name)
;; term need not be a pseudo-term
(rule-item-listp rules)
(rule-item-list-listp rule-lists)
(symbol-listp remove-rules) ;allow rule-items?
;; todo: rule-classes
(booleanp no-splitp)
;; print
)
:stobjs state))
(b* (((when (and rules rule-lists))
(er hard? ',defthm-with-clause-processor-fn-name "Both :rules and :rule-lists were given for ~x0." name))
(rule-lists (if rules
(list (elaborate-rule-items rules nil state))
(elaborate-rule-item-lists rule-lists state)))
(rule-lists (remove-from-all rule-lists remove-rules)))
`(defthm ,name
,term
:hints (("Goal" :clause-processor (,',clause-processor-name clause
'((:must-prove . t)
(:rule-lists . ,rule-lists)
(:no-splitp . ,no-splitp)
(:print . ,print)
(:tactic . ,tactic))
state)))
,@(if (eq :auto rule-classes)
nil
`(:rule-classes ,rule-classes)))))
;; Submit a defthm that uses the clause-processor:
(defmacro ,defthm-with-clause-processor-name (name
term
&key
(tactic '(:rep :rewrite :subst))
(rules 'nil)
(rule-lists 'nil)
(remove-rules 'nil)
(no-splitp 'nil) ; whether to prevent splitting into cases
(rule-classes ':auto)
(print 'nil))
(if (and (consp term)
(eq :eval (car term)))
;; Evaluate TERM:
`(make-event (,',defthm-with-clause-processor-fn-name ',name ,(cadr term) ',tactic ',rules ',rule-lists ',remove-rules ',no-splitp ',rule-classes ',print state))
;; Don't evaluate TERM:
`(make-event (,',defthm-with-clause-processor-fn-name ',name ',term ',tactic ',rules ',rule-lists ',remove-rules ',no-splitp ',rule-classes ',print state))))
)))
(defmacro make-clause-processor-simple (suffix)
(make-clause-processor-simple-fn suffix))
|
79554
|
; A tool to make a clause processor that uses an Axe Prover
;
; Copyright (C) 2008-2011 <NAME> and Stanford University
; Copyright (C) 2013-2020 Kestrel Institute
; Copyright (C) 2016-2020 Kestrel Technology, LLC
;
; License: A 3-clause BSD license. See the file books/3BSD-mod.txt.
;
; Author: <NAME> (<EMAIL>)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(include-book "kestrel/utilities/pack" :dir :system)
;; Returns an event
(defun make-clause-processor-simple-fn (suffix ;; gets added to generated names
)
(declare (xargs :guard (symbolp suffix)))
(let* ((clause-processor-name (pack$ suffix '-prover-clause-processor)) ; should already be defined
(defthm-with-clause-processor-name (pack$ 'defthm-with- clause-processor-name))
(defthm-with-clause-processor-fn-name (pack$ 'defthm-with- clause-processor-name '-fn)))
`(encapsulate ()
;; (local (include-book "kestrel/lists-light/nth" :dir :system))
;; (local (include-book "kestrel/lists-light/remove-equal" :dir :system))
;; (local (include-book "kestrel/lists-light/len" :dir :system))
;; (local (include-book "kestrel/lists-light/reverse" :dir :system))
;; (local (include-book "kestrel/lists-light/last" :dir :system))
;; (local (include-book "kestrel/lists-light/subsetp-equal" :dir :system))
;; (local (include-book "kestrel/lists-light/take" :dir :system))
;; (local (include-book "kestrel/lists-light/true-list-fix" :dir :system))
;; (local (include-book "kestrel/lists-light/cons" :dir :system)) ; for true-listp-of-cons
;; (local (include-book "kestrel/alists-light/strip-cdrs" :dir :system))
;; (local (include-book "kestrel/alists-light/pairlis-dollar" :dir :system))
;; (local (include-book "kestrel/arithmetic-light/plus" :dir :system))
;; (local (include-book "kestrel/utilities/acl2-count" :dir :system))
;; (local (include-book "kestrel/typed-lists-light/nat-listp" :dir :system))
;; (local (include-book "kestrel/typed-lists-light/symbol-listp" :dir :system))
;; See also the define-trusted-clause-processor in prover2.lisp.
(define-trusted-clause-processor
,clause-processor-name
nil ;supporters ; todo: Think about this (I don't understand what :doc define-trusted-clause-processor says about "supporters")
:ttag ,clause-processor-name)
;; Returns a defthm event.
(defun ,defthm-with-clause-processor-fn-name (name term tactic rules rule-lists remove-rules no-splitp rule-classes print state)
(declare (xargs :guard (and (symbolp name)
;; term need not be a pseudo-term
(rule-item-listp rules)
(rule-item-list-listp rule-lists)
(symbol-listp remove-rules) ;allow rule-items?
;; todo: rule-classes
(booleanp no-splitp)
;; print
)
:stobjs state))
(b* (((when (and rules rule-lists))
(er hard? ',defthm-with-clause-processor-fn-name "Both :rules and :rule-lists were given for ~x0." name))
(rule-lists (if rules
(list (elaborate-rule-items rules nil state))
(elaborate-rule-item-lists rule-lists state)))
(rule-lists (remove-from-all rule-lists remove-rules)))
`(defthm ,name
,term
:hints (("Goal" :clause-processor (,',clause-processor-name clause
'((:must-prove . t)
(:rule-lists . ,rule-lists)
(:no-splitp . ,no-splitp)
(:print . ,print)
(:tactic . ,tactic))
state)))
,@(if (eq :auto rule-classes)
nil
`(:rule-classes ,rule-classes)))))
;; Submit a defthm that uses the clause-processor:
(defmacro ,defthm-with-clause-processor-name (name
term
&key
(tactic '(:rep :rewrite :subst))
(rules 'nil)
(rule-lists 'nil)
(remove-rules 'nil)
(no-splitp 'nil) ; whether to prevent splitting into cases
(rule-classes ':auto)
(print 'nil))
(if (and (consp term)
(eq :eval (car term)))
;; Evaluate TERM:
`(make-event (,',defthm-with-clause-processor-fn-name ',name ,(cadr term) ',tactic ',rules ',rule-lists ',remove-rules ',no-splitp ',rule-classes ',print state))
;; Don't evaluate TERM:
`(make-event (,',defthm-with-clause-processor-fn-name ',name ',term ',tactic ',rules ',rule-lists ',remove-rules ',no-splitp ',rule-classes ',print state))))
)))
(defmacro make-clause-processor-simple (suffix)
(make-clause-processor-simple-fn suffix))
| true |
; A tool to make a clause processor that uses an Axe Prover
;
; Copyright (C) 2008-2011 PI:NAME:<NAME>END_PI and Stanford University
; Copyright (C) 2013-2020 Kestrel Institute
; Copyright (C) 2016-2020 Kestrel Technology, LLC
;
; License: A 3-clause BSD license. See the file books/3BSD-mod.txt.
;
; Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(include-book "kestrel/utilities/pack" :dir :system)
;; Returns an event
(defun make-clause-processor-simple-fn (suffix ;; gets added to generated names
)
(declare (xargs :guard (symbolp suffix)))
(let* ((clause-processor-name (pack$ suffix '-prover-clause-processor)) ; should already be defined
(defthm-with-clause-processor-name (pack$ 'defthm-with- clause-processor-name))
(defthm-with-clause-processor-fn-name (pack$ 'defthm-with- clause-processor-name '-fn)))
`(encapsulate ()
;; (local (include-book "kestrel/lists-light/nth" :dir :system))
;; (local (include-book "kestrel/lists-light/remove-equal" :dir :system))
;; (local (include-book "kestrel/lists-light/len" :dir :system))
;; (local (include-book "kestrel/lists-light/reverse" :dir :system))
;; (local (include-book "kestrel/lists-light/last" :dir :system))
;; (local (include-book "kestrel/lists-light/subsetp-equal" :dir :system))
;; (local (include-book "kestrel/lists-light/take" :dir :system))
;; (local (include-book "kestrel/lists-light/true-list-fix" :dir :system))
;; (local (include-book "kestrel/lists-light/cons" :dir :system)) ; for true-listp-of-cons
;; (local (include-book "kestrel/alists-light/strip-cdrs" :dir :system))
;; (local (include-book "kestrel/alists-light/pairlis-dollar" :dir :system))
;; (local (include-book "kestrel/arithmetic-light/plus" :dir :system))
;; (local (include-book "kestrel/utilities/acl2-count" :dir :system))
;; (local (include-book "kestrel/typed-lists-light/nat-listp" :dir :system))
;; (local (include-book "kestrel/typed-lists-light/symbol-listp" :dir :system))
;; See also the define-trusted-clause-processor in prover2.lisp.
(define-trusted-clause-processor
,clause-processor-name
nil ;supporters ; todo: Think about this (I don't understand what :doc define-trusted-clause-processor says about "supporters")
:ttag ,clause-processor-name)
;; Returns a defthm event.
(defun ,defthm-with-clause-processor-fn-name (name term tactic rules rule-lists remove-rules no-splitp rule-classes print state)
(declare (xargs :guard (and (symbolp name)
;; term need not be a pseudo-term
(rule-item-listp rules)
(rule-item-list-listp rule-lists)
(symbol-listp remove-rules) ;allow rule-items?
;; todo: rule-classes
(booleanp no-splitp)
;; print
)
:stobjs state))
(b* (((when (and rules rule-lists))
(er hard? ',defthm-with-clause-processor-fn-name "Both :rules and :rule-lists were given for ~x0." name))
(rule-lists (if rules
(list (elaborate-rule-items rules nil state))
(elaborate-rule-item-lists rule-lists state)))
(rule-lists (remove-from-all rule-lists remove-rules)))
`(defthm ,name
,term
:hints (("Goal" :clause-processor (,',clause-processor-name clause
'((:must-prove . t)
(:rule-lists . ,rule-lists)
(:no-splitp . ,no-splitp)
(:print . ,print)
(:tactic . ,tactic))
state)))
,@(if (eq :auto rule-classes)
nil
`(:rule-classes ,rule-classes)))))
;; Submit a defthm that uses the clause-processor:
(defmacro ,defthm-with-clause-processor-name (name
term
&key
(tactic '(:rep :rewrite :subst))
(rules 'nil)
(rule-lists 'nil)
(remove-rules 'nil)
(no-splitp 'nil) ; whether to prevent splitting into cases
(rule-classes ':auto)
(print 'nil))
(if (and (consp term)
(eq :eval (car term)))
;; Evaluate TERM:
`(make-event (,',defthm-with-clause-processor-fn-name ',name ,(cadr term) ',tactic ',rules ',rule-lists ',remove-rules ',no-splitp ',rule-classes ',print state))
;; Don't evaluate TERM:
`(make-event (,',defthm-with-clause-processor-fn-name ',name ',term ',tactic ',rules ',rule-lists ',remove-rules ',no-splitp ',rule-classes ',print state))))
)))
(defmacro make-clause-processor-simple (suffix)
(make-clause-processor-simple-fn suffix))
|
[
{
"context": "LISP; Package: CCL -*-\n;;;\n;;; Copyright 1994-2009 Clozure Associates\n;;;\n;;; Licensed under the Apache License, Versio",
"end": 81,
"score": 0.9956216216087341,
"start": 63,
"tag": "NAME",
"value": "Clozure Associates"
}
] |
lib/level-2.lisp
|
digikar99/ccl
| 732 |
;;;-*-Mode: LISP; Package: CCL -*-
;;;
;;; Copyright 1994-2009 Clozure Associates
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
;; Level-2.lisp
(in-package "CCL")
(eval-when (eval compile)
(require "LEVEL-2")
(require "BACKQUOTE")
(require "DEFSTRUCT-MACROS"))
(eval-when (eval compile)
(require "LISPEQU"))
; This incredibly essential thing is part of ANSI CL; put it in the
; right package someday.
; Like maybe when it says something about doc strings, or otherwise
; becomes useful.
(defun parse-macro (name arglist body &optional env)
(values (parse-macro-1 name arglist body env)))
; Return a list containing a special declaration for SYM
; if SYM is declared special in decls.
; This is so we can be pedantic about binding &WHOLE/&ENVIRONMENT args
; that have been scarfed out of a macro-like lambda list.
; The returned value is supposed to be suitable for splicing ...
(defun hoist-special-decls (sym decls)
(when sym
(dolist (decl decls)
(dolist (spec (cdr decl))
(when (eq (car spec) 'special)
(dolist (s (%cdr spec))
(when (eq s sym)
(return-from hoist-special-decls `((declare (special ,sym)))))))))))
(defun parse-macro-1 (name arglist body &optional env)
(parse-macro-internal name arglist body env nil))
(defun parse-macro-internal (name arglist body env default-initial-value)
(unless (verify-lambda-list arglist t t t)
(error "Invalid lambda list ~s" arglist))
(multiple-value-bind (lambda-list whole environment)
(normalize-lambda-list arglist t t)
(multiple-value-bind (body local-decs doc)
(parse-body body env t)
(let ((whole-var (gensym "WHOLE"))
(env-var (gensym "ENVIRONMENT")))
(multiple-value-bind (bindings binding-decls)
(%destructure-lambda-list lambda-list whole-var nil nil
:cdr-p t
:whole-p nil
:use-whole-var t
:default-initial-value default-initial-value)
(when environment
(setq bindings (nconc bindings (list `(,environment ,env-var)))))
(when whole
(setq bindings (nconc bindings (list `(,whole ,whole-var)))))
(values
`(lambda (,whole-var ,env-var)
(declare (ignorable ,whole-var ,env-var))
(block ,name
(let* ,(nreverse bindings)
,@(when binding-decls `((declare ,@binding-decls)))
,@local-decs
,@body)))
doc))))))
(defun lambda-list-bounds (lambda-list)
(let* ((state :required)
(min 0)
(max 0))
(do* ((lambda-list lambda-list (cdr lambda-list)))
((null lambda-list) (values min max))
(case (car lambda-list)
((&rest &key &body) (return (values min nil)))
(&aux (return (values min max)))
(&optional (setq state :optional))
(t (ecase state
(:required (incf min) (incf max))
(:optional (incf max))))))))
(defun prepare-to-destructure (list lambda-list min max)
(if (if max
(and (proper-list-p list)
(let* ((len (length list)))
(<= min len max)))
(do* ((tail list (cdr tail))
(n min (1- n)))
((zerop n) t)
(when (atom tail)
(return))))
list
(let* ((reason
(if max
(if (not (proper-list-p list))
"it is not a proper list"
(let* ((len (length list)))
(if (eql min max)
(format nil "it contains ~d elements, and exactly ~d are expected" len min)
(if (< len min)
(format nil "it contains ~d elements, and at least ~d are expected" len min)
(format nil "it contains ~d elements, and at most ~d are expected" len max)))))
(format nil "it does not contain at least ~d elements" min))))
(signal-program-error "~s can't be destructured against the lambda list ~s, because ~a."
list lambda-list reason))))
(defun %destructure-lambda-list (lambda-list wholeform lets decls
&key cdr-p (whole-p t) use-whole-var default-initial-value)
(unless (and (listp lambda-list)
(verify-lambda-list lambda-list t whole-p))
(signal-simple-program-error "Invalid lambda list: ~s" lambda-list))
(multiple-value-bind (normalized whole) (normalize-lambda-list
lambda-list whole-p)
(let* ((argstate :required)
(allow-other-keys nil)
(rest-arg-name nil)
(w (if use-whole-var wholeform (or whole (gensym "WHOLE"))))
(argptr (gensym "ARGS"))
(has-&key nil)
(keywords ())
(first-keyword-init ())
(restp nil))
(labels ((simple-var (var &optional (initform `,default-initial-value))
(let* ((binding `(,var ,initform)))
(push binding lets)
binding))
(structured-var (context sub-lambda-list initform)
(let* ((v (gensym (string context))))
(simple-var v initform)
(multiple-value-setq (lets decls)
(%destructure-lambda-list
sub-lambda-list
v
lets
decls
:default-initial-value default-initial-value
))
v)))
(unless use-whole-var
(if (atom w)
(simple-var w wholeform)
(progn
(setq w (structured-var "WHOLE" w (if cdr-p `(cdr ,wholeform) wholeform))
cdr-p nil))))
(multiple-value-bind (min max) (lambda-list-bounds normalized)
(simple-var argptr `(prepare-to-destructure ,@(if cdr-p `((cdr ,w)) `(,w)) ',lambda-list ,min ,max))
(push `(ignorable ,argptr) decls)
(when max
(push `(list ,argptr) decls))
(do* ((tail normalized (cdr tail)))
((null tail)
(if has-&key
(let* ((key-check-form `(check-keywords
',(nreverse keywords)
,rest-arg-name ,allow-other-keys)))
(if first-keyword-init
(rplaca (cdr first-keyword-init)
`(progn
,key-check-form
,(cadr first-keyword-init)))
(let* ((check-var (gensym "CHECK")))
(push `(ignorable ,check-var) decls)
(simple-var check-var key-check-form)))))
(values lets decls))
(let* ((var (car tail)))
(cond ((or (eq var '&rest) (eq var '&body))
(let* ((r (cadr tail))
(init argptr))
(if (listp r)
(setq rest-arg-name
(structured-var "REST" r init))
(progn
(setq rest-arg-name (gensym "REST"))
(simple-var rest-arg-name init)
(simple-var r rest-arg-name ))))
(setq restp t)
(setq tail (cdr tail)))
((eq var '&optional) (setq argstate :optional))
((eq var '&key)
(setq argstate :key)
(setq has-&key t)
(unless restp
(setq restp t
rest-arg-name (gensym "KEYS"))
(push `(ignorable ,rest-arg-name) decls)
(simple-var rest-arg-name
argptr)))
((eq var '&allow-other-keys)
(setq allow-other-keys t))
((eq var '&aux)
(setq argstate :aux))
((listp var)
(case argstate
(:required
(structured-var "REQ" var `(pop ,argptr)))
(:optional
(let* ((variable (car var))
(initform (if (cdr var)
(cadr var)
`,default-initial-value))
(anon-spvar (gensym "OPT-SUPPLIED-P"))
(spvar (if (cddr var)
(caddr var)))
(varinit `(if ,anon-spvar
(pop ,argptr)
,initform)))
(simple-var anon-spvar
`(not (null ,argptr)))
(if (listp variable)
(structured-var "OPT" variable varinit)
(simple-var variable varinit))
(if spvar
(simple-var spvar anon-spvar))))
(:key
(let* ((explicit-key (consp (car var)))
(variable (if explicit-key
(cadar var)
(car var)))
(keyword (if explicit-key
(caar var)
(make-keyword variable)))
(initform (if (cdr var)
(cadr var)
`,default-initial-value))
(anon-spvar (gensym "KEY-SUPPLIED-P"))
(spvar (if (cddr var)
(caddr var))))
(push keyword keywords)
(let* ((sp-init (simple-var anon-spvar
`(%keyword-present-p
,rest-arg-name
',keyword)))
(var-init `(if ,anon-spvar
(getf ,rest-arg-name ',keyword)
,initform)))
(unless first-keyword-init
(setq first-keyword-init sp-init))
(if (listp variable)
(structured-var "KEY" variable var-init)
(simple-var variable var-init))
(if spvar
(simple-var spvar anon-spvar)))))
(:aux
(simple-var (car var) (cadr var)))
(t (error "NYI: ~s" argstate))))
((symbolp var)
(case argstate
(:required
(simple-var var `(pop ,argptr)))
(:optional
(simple-var var `(if ,argptr
(pop ,argptr)
',default-initial-value)))
(:key
(let* ((keyword (make-keyword var)))
(push keyword keywords)
(let* ((init (simple-var
var
`(getf ,rest-arg-name
',keyword
,@(if default-initial-value
`(',default-initial-value))))))
(unless first-keyword-init
(setq first-keyword-init init)))))
(:aux
(simple-var var))))))))))))
(defun apply-to-htab-syms (function pkg-vector)
(let* ((sym nil)
(foundp nil))
(dotimes (i (uvsize pkg-vector))
(declare (fixnum i))
(multiple-value-setq (sym foundp) (%htab-symbol pkg-vector i))
(when foundp (funcall function sym)))))
(defun iterate-over-external-symbols (pkg-spec function)
(apply-to-htab-syms function (car (pkg.etab (pkg-arg (or pkg-spec *package*))))))
(defun iterate-over-present-symbols (pkg-spec function)
(let ((pkg (pkg-arg (or pkg-spec *package*))))
(apply-to-htab-syms function (car (pkg.etab pkg)))
(apply-to-htab-syms function (car (pkg.itab pkg)))))
(defun iterate-over-accessable-symbols (pkg-spec function)
(let* ((pkg (pkg-arg (or pkg-spec *package*)))
(used (pkg.used pkg))
(shadowed (pkg.shadowed pkg)))
(iterate-over-present-symbols pkg function)
(when used
(if shadowed
(flet ((ignore-shadowed-conflicts (var)
(unless (%name-present-in-package-p (symbol-name var) pkg)
(funcall function var))))
(declare (dynamic-extent #'ignore-shadowed-conflicts))
(dolist (u used) (iterate-over-external-symbols u #'ignore-shadowed-conflicts)))
(dolist (u used) (iterate-over-external-symbols u function))))))
(defun iterate-over-all-symbols (function)
(dolist (pkg %all-packages%)
(iterate-over-present-symbols pkg function)))
;;;Eval definitions for things open-coded by the compiler.
;;;Don't use DEFUN since it should be illegal to DEFUN compiler special forms...
;;;Of course, these aren't special forms.
(macrolet ((%eval-redef (name vars &rest body)
(when (null body) (setq body `((,name ,@vars))))
`(setf (symbol-function ',name)
(qlfun ,name ,vars ,@body))))
(declare (optimize (speed 1) (safety 1)))
(%eval-redef %ilsl (n x))
(%eval-redef %ilsr (n x))
(%eval-redef neq (x y))
(%eval-redef not (x))
(%eval-redef null (x))
(%eval-redef rplaca (x y))
(%eval-redef rplacd (x y))
(%eval-redef set-car (x y))
(%eval-redef set-cdr (x y))
(%eval-redef int>0-p (x))
(%eval-redef %get-byte (ptr &optional (offset 0)) (%get-byte ptr offset))
(%eval-redef %get-word (ptr &optional (offset 0)) (%get-word ptr offset))
(%eval-redef %get-signed-byte (ptr &optional (offset 0)) (%get-signed-byte ptr offset))
(%eval-redef %get-signed-word (ptr &optional (offset 0)) (%get-signed-word ptr offset))
(%eval-redef %get-long (ptr &optional (offset 0)) (%get-long ptr offset))
(%eval-redef %get-fixnum (ptr &optional (offset 0)) (%get-fixnum ptr offset))
(%eval-redef %get-signed-long (ptr &optional (offset 0)) (%get-signed-long ptr offset))
(%eval-redef %get-unsigned-long (ptr &optional (offset 0)) (%get-unsigned-long ptr offset))
(%eval-redef %get-ptr (ptr &optional (offset 0)) (%get-ptr ptr offset))
(%eval-redef %get-full-long (ptr &optional (offset 0)) (%get-full-long ptr offset))
(%eval-redef %int-to-ptr (int))
(%eval-redef %ptr-to-int (ptr))
(%eval-redef %ptr-eql (ptr1 ptr2))
(%eval-redef %setf-macptr (ptr1 ptr2))
(%eval-redef %null-ptr-p (ptr))
(%eval-redef %iasr (x y))
(%eval-redef %set-byte (p o &optional (new (prog1 o (setq o 0))))
(%set-byte p o new))
(%eval-redef %set-unsigned-byte (p o &optional (new (prog1 o (setq o 0))))
(%set-unsigned-byte p o new))
(%eval-redef %set-word (p o &optional (new (prog1 o (setq o 0))))
(%set-word p o new))
(%eval-redef %set-unsigned-word (p o &optional (new (prog1 o (setq o 0))))
(%set-unsigned-word p o new))
(%eval-redef %set-long (p o &optional (new (prog1 o (setq o 0))))
(%set-long p o new))
(%eval-redef %set-unsigned-long (p o &optional (new (prog1 o (setq o 0))))
(%set-unsigned-long p o new))
(%eval-redef %set-ptr (p o &optional (new (prog1 o (setq o 0))))
(%set-ptr p o new))
(%eval-redef %word-to-int (word))
(%eval-redef %inc-ptr (ptr &optional (by 1)) (%inc-ptr ptr by))
(%eval-redef char-code (x))
(%eval-redef code-char (x))
(%eval-redef 1- (n))
(%eval-redef 1+ (n))
(%eval-redef uvref (x y))
(%eval-redef uvset (x y z))
(%eval-redef uvsize (x))
(%eval-redef svref (x y))
(%eval-redef svset (x y z))
(%eval-redef cons (x y))
(%eval-redef endp (x))
(progn
(%eval-redef typecode (x))
(%eval-redef lisptag (x))
(%eval-redef fulltag (x))
(%eval-redef %unbound-marker ())
(%eval-redef %slot-unbound-marker ())
(%eval-redef %slot-ref (v i))
(%eval-redef %alloc-misc (count subtag &optional (initial nil initial-p))
(if initial-p
(%alloc-misc count subtag initial)
(%alloc-misc count subtag)))
(%eval-redef %setf-double-float (x y))
(%eval-redef %lisp-word-ref (x y))
(%eval-redef %temp-cons (x y))
(%eval-redef require-fixnum (x))
(%eval-redef require-symbol (x))
(%eval-redef require-list (x))
(%eval-redef require-real (x))
(%eval-redef require-simple-string (x))
(%eval-redef require-simple-vector (x))
(%eval-redef require-character (x))
(%eval-redef require-number (x))
(%eval-redef require-integer (x))
(%eval-redef require-s8 (x))
(%eval-redef require-u8 (x))
(%eval-redef require-s16 (x))
(%eval-redef require-u16 (x))
(%eval-redef require-s32 (x))
(%eval-redef require-u32 (x))
(%eval-redef require-s64 (x))
(%eval-redef require-u64 (x))
(%eval-redef %reference-external-entry-point (x))
)
(%eval-redef %get-bit (ptr offset))
(%eval-redef %set-bit (ptr offset val))
(%eval-redef %get-double-float (ptr &optional (offset 0))
(%get-double-float ptr offset))
(%eval-redef %get-single-float (ptr &optional (offset 0))
(%get-single-float ptr offset))
(%eval-redef %set-double-float (p o &optional (new (prog1 o (setq o 0))))
(%set-double-float p o new))
(%eval-redef %set-single-float (p o &optional (new (prog1 o (setq o 0))))
(%set-single-float p o new))
(%eval-redef assq (item list))
(%eval-redef %fixnum-ref-double-float (base &optional (index 0))
(%fixnum-ref-double-float base index))
(%eval-redef %fixnum-set-double-float (base index &optional (new (prog1 index (setq index 0))))
(%fixnum-set-double-float base index new))
(%eval-redef ivector-typecode-p (arg))
(%eval-redef gvector-typecode-p (arg))
)
; In the spirit of eval-redef ...
;; pointer hacking stuff
;
;
;;; I'd guess that the majority of bitfields in the world whose width is
;;; greater than 1 have a width of two. If that's true, this is probably
;;; faster than trying to be more clever about it would be.
(defun %get-bitfield (ptr start-bit width)
(declare (fixnum start-bit width))
(do* ((bit #+big-endian-target start-bit
#+little-endian-target (the fixnum (1- (the fixnum (+ start-bit width))))
#+big-endian-target (1+ bit)
#+little-endian-target (1- bit))
(i 0 (1+ i))
(val 0))
((= i width) val)
(declare (fixnum val i bit))
(setq val (logior (ash val 1) (%get-bit ptr bit)))))
(defun %set-bitfield (ptr start width val)
(declare (fixnum val start width))
(do* ((v val (ash v -1))
(bit #+big-endian-target (1- (+ start width))
#+little-endian-target start
#+big-endian-target (1- bit)
#+little-endian-target (1+ bit))
(i 0 (1+ i)))
((= i width) val)
(declare (fixnum v bit i))
(setf (%get-bit ptr bit) (logand v 1))))
; expands into compiler stuff
(setf (symbol-function '%get-unsigned-byte) (symbol-function '%get-byte))
(setf (symbol-function '%get-unsigned-word) (symbol-function '%get-word))
(setf (symbol-function '%get-signed-long) (symbol-function '%get-long))
(defun decompose-record-accessor (accessor &aux ret)
(do* ((str (symbol-name accessor) (%substr str (+ i 1) len))
(len (length str) (length str))
(i (%str-member #\. str) (%str-member #\. str))
(field (%substr str 0 (or i len)) (%substr str 0 (or i len))))
((not i) (nreverse (cons (make-keyword field) ret)))
(push (make-keyword field) ret)))
(provide 'level-2)
;; end of level-2.lisp
|
79521
|
;;;-*-Mode: LISP; Package: CCL -*-
;;;
;;; Copyright 1994-2009 <NAME>
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
;; Level-2.lisp
(in-package "CCL")
(eval-when (eval compile)
(require "LEVEL-2")
(require "BACKQUOTE")
(require "DEFSTRUCT-MACROS"))
(eval-when (eval compile)
(require "LISPEQU"))
; This incredibly essential thing is part of ANSI CL; put it in the
; right package someday.
; Like maybe when it says something about doc strings, or otherwise
; becomes useful.
(defun parse-macro (name arglist body &optional env)
(values (parse-macro-1 name arglist body env)))
; Return a list containing a special declaration for SYM
; if SYM is declared special in decls.
; This is so we can be pedantic about binding &WHOLE/&ENVIRONMENT args
; that have been scarfed out of a macro-like lambda list.
; The returned value is supposed to be suitable for splicing ...
(defun hoist-special-decls (sym decls)
(when sym
(dolist (decl decls)
(dolist (spec (cdr decl))
(when (eq (car spec) 'special)
(dolist (s (%cdr spec))
(when (eq s sym)
(return-from hoist-special-decls `((declare (special ,sym)))))))))))
(defun parse-macro-1 (name arglist body &optional env)
(parse-macro-internal name arglist body env nil))
(defun parse-macro-internal (name arglist body env default-initial-value)
(unless (verify-lambda-list arglist t t t)
(error "Invalid lambda list ~s" arglist))
(multiple-value-bind (lambda-list whole environment)
(normalize-lambda-list arglist t t)
(multiple-value-bind (body local-decs doc)
(parse-body body env t)
(let ((whole-var (gensym "WHOLE"))
(env-var (gensym "ENVIRONMENT")))
(multiple-value-bind (bindings binding-decls)
(%destructure-lambda-list lambda-list whole-var nil nil
:cdr-p t
:whole-p nil
:use-whole-var t
:default-initial-value default-initial-value)
(when environment
(setq bindings (nconc bindings (list `(,environment ,env-var)))))
(when whole
(setq bindings (nconc bindings (list `(,whole ,whole-var)))))
(values
`(lambda (,whole-var ,env-var)
(declare (ignorable ,whole-var ,env-var))
(block ,name
(let* ,(nreverse bindings)
,@(when binding-decls `((declare ,@binding-decls)))
,@local-decs
,@body)))
doc))))))
(defun lambda-list-bounds (lambda-list)
(let* ((state :required)
(min 0)
(max 0))
(do* ((lambda-list lambda-list (cdr lambda-list)))
((null lambda-list) (values min max))
(case (car lambda-list)
((&rest &key &body) (return (values min nil)))
(&aux (return (values min max)))
(&optional (setq state :optional))
(t (ecase state
(:required (incf min) (incf max))
(:optional (incf max))))))))
(defun prepare-to-destructure (list lambda-list min max)
(if (if max
(and (proper-list-p list)
(let* ((len (length list)))
(<= min len max)))
(do* ((tail list (cdr tail))
(n min (1- n)))
((zerop n) t)
(when (atom tail)
(return))))
list
(let* ((reason
(if max
(if (not (proper-list-p list))
"it is not a proper list"
(let* ((len (length list)))
(if (eql min max)
(format nil "it contains ~d elements, and exactly ~d are expected" len min)
(if (< len min)
(format nil "it contains ~d elements, and at least ~d are expected" len min)
(format nil "it contains ~d elements, and at most ~d are expected" len max)))))
(format nil "it does not contain at least ~d elements" min))))
(signal-program-error "~s can't be destructured against the lambda list ~s, because ~a."
list lambda-list reason))))
(defun %destructure-lambda-list (lambda-list wholeform lets decls
&key cdr-p (whole-p t) use-whole-var default-initial-value)
(unless (and (listp lambda-list)
(verify-lambda-list lambda-list t whole-p))
(signal-simple-program-error "Invalid lambda list: ~s" lambda-list))
(multiple-value-bind (normalized whole) (normalize-lambda-list
lambda-list whole-p)
(let* ((argstate :required)
(allow-other-keys nil)
(rest-arg-name nil)
(w (if use-whole-var wholeform (or whole (gensym "WHOLE"))))
(argptr (gensym "ARGS"))
(has-&key nil)
(keywords ())
(first-keyword-init ())
(restp nil))
(labels ((simple-var (var &optional (initform `,default-initial-value))
(let* ((binding `(,var ,initform)))
(push binding lets)
binding))
(structured-var (context sub-lambda-list initform)
(let* ((v (gensym (string context))))
(simple-var v initform)
(multiple-value-setq (lets decls)
(%destructure-lambda-list
sub-lambda-list
v
lets
decls
:default-initial-value default-initial-value
))
v)))
(unless use-whole-var
(if (atom w)
(simple-var w wholeform)
(progn
(setq w (structured-var "WHOLE" w (if cdr-p `(cdr ,wholeform) wholeform))
cdr-p nil))))
(multiple-value-bind (min max) (lambda-list-bounds normalized)
(simple-var argptr `(prepare-to-destructure ,@(if cdr-p `((cdr ,w)) `(,w)) ',lambda-list ,min ,max))
(push `(ignorable ,argptr) decls)
(when max
(push `(list ,argptr) decls))
(do* ((tail normalized (cdr tail)))
((null tail)
(if has-&key
(let* ((key-check-form `(check-keywords
',(nreverse keywords)
,rest-arg-name ,allow-other-keys)))
(if first-keyword-init
(rplaca (cdr first-keyword-init)
`(progn
,key-check-form
,(cadr first-keyword-init)))
(let* ((check-var (gensym "CHECK")))
(push `(ignorable ,check-var) decls)
(simple-var check-var key-check-form)))))
(values lets decls))
(let* ((var (car tail)))
(cond ((or (eq var '&rest) (eq var '&body))
(let* ((r (cadr tail))
(init argptr))
(if (listp r)
(setq rest-arg-name
(structured-var "REST" r init))
(progn
(setq rest-arg-name (gensym "REST"))
(simple-var rest-arg-name init)
(simple-var r rest-arg-name ))))
(setq restp t)
(setq tail (cdr tail)))
((eq var '&optional) (setq argstate :optional))
((eq var '&key)
(setq argstate :key)
(setq has-&key t)
(unless restp
(setq restp t
rest-arg-name (gensym "KEYS"))
(push `(ignorable ,rest-arg-name) decls)
(simple-var rest-arg-name
argptr)))
((eq var '&allow-other-keys)
(setq allow-other-keys t))
((eq var '&aux)
(setq argstate :aux))
((listp var)
(case argstate
(:required
(structured-var "REQ" var `(pop ,argptr)))
(:optional
(let* ((variable (car var))
(initform (if (cdr var)
(cadr var)
`,default-initial-value))
(anon-spvar (gensym "OPT-SUPPLIED-P"))
(spvar (if (cddr var)
(caddr var)))
(varinit `(if ,anon-spvar
(pop ,argptr)
,initform)))
(simple-var anon-spvar
`(not (null ,argptr)))
(if (listp variable)
(structured-var "OPT" variable varinit)
(simple-var variable varinit))
(if spvar
(simple-var spvar anon-spvar))))
(:key
(let* ((explicit-key (consp (car var)))
(variable (if explicit-key
(cadar var)
(car var)))
(keyword (if explicit-key
(caar var)
(make-keyword variable)))
(initform (if (cdr var)
(cadr var)
`,default-initial-value))
(anon-spvar (gensym "KEY-SUPPLIED-P"))
(spvar (if (cddr var)
(caddr var))))
(push keyword keywords)
(let* ((sp-init (simple-var anon-spvar
`(%keyword-present-p
,rest-arg-name
',keyword)))
(var-init `(if ,anon-spvar
(getf ,rest-arg-name ',keyword)
,initform)))
(unless first-keyword-init
(setq first-keyword-init sp-init))
(if (listp variable)
(structured-var "KEY" variable var-init)
(simple-var variable var-init))
(if spvar
(simple-var spvar anon-spvar)))))
(:aux
(simple-var (car var) (cadr var)))
(t (error "NYI: ~s" argstate))))
((symbolp var)
(case argstate
(:required
(simple-var var `(pop ,argptr)))
(:optional
(simple-var var `(if ,argptr
(pop ,argptr)
',default-initial-value)))
(:key
(let* ((keyword (make-keyword var)))
(push keyword keywords)
(let* ((init (simple-var
var
`(getf ,rest-arg-name
',keyword
,@(if default-initial-value
`(',default-initial-value))))))
(unless first-keyword-init
(setq first-keyword-init init)))))
(:aux
(simple-var var))))))))))))
(defun apply-to-htab-syms (function pkg-vector)
(let* ((sym nil)
(foundp nil))
(dotimes (i (uvsize pkg-vector))
(declare (fixnum i))
(multiple-value-setq (sym foundp) (%htab-symbol pkg-vector i))
(when foundp (funcall function sym)))))
(defun iterate-over-external-symbols (pkg-spec function)
(apply-to-htab-syms function (car (pkg.etab (pkg-arg (or pkg-spec *package*))))))
(defun iterate-over-present-symbols (pkg-spec function)
(let ((pkg (pkg-arg (or pkg-spec *package*))))
(apply-to-htab-syms function (car (pkg.etab pkg)))
(apply-to-htab-syms function (car (pkg.itab pkg)))))
(defun iterate-over-accessable-symbols (pkg-spec function)
(let* ((pkg (pkg-arg (or pkg-spec *package*)))
(used (pkg.used pkg))
(shadowed (pkg.shadowed pkg)))
(iterate-over-present-symbols pkg function)
(when used
(if shadowed
(flet ((ignore-shadowed-conflicts (var)
(unless (%name-present-in-package-p (symbol-name var) pkg)
(funcall function var))))
(declare (dynamic-extent #'ignore-shadowed-conflicts))
(dolist (u used) (iterate-over-external-symbols u #'ignore-shadowed-conflicts)))
(dolist (u used) (iterate-over-external-symbols u function))))))
(defun iterate-over-all-symbols (function)
(dolist (pkg %all-packages%)
(iterate-over-present-symbols pkg function)))
;;;Eval definitions for things open-coded by the compiler.
;;;Don't use DEFUN since it should be illegal to DEFUN compiler special forms...
;;;Of course, these aren't special forms.
(macrolet ((%eval-redef (name vars &rest body)
(when (null body) (setq body `((,name ,@vars))))
`(setf (symbol-function ',name)
(qlfun ,name ,vars ,@body))))
(declare (optimize (speed 1) (safety 1)))
(%eval-redef %ilsl (n x))
(%eval-redef %ilsr (n x))
(%eval-redef neq (x y))
(%eval-redef not (x))
(%eval-redef null (x))
(%eval-redef rplaca (x y))
(%eval-redef rplacd (x y))
(%eval-redef set-car (x y))
(%eval-redef set-cdr (x y))
(%eval-redef int>0-p (x))
(%eval-redef %get-byte (ptr &optional (offset 0)) (%get-byte ptr offset))
(%eval-redef %get-word (ptr &optional (offset 0)) (%get-word ptr offset))
(%eval-redef %get-signed-byte (ptr &optional (offset 0)) (%get-signed-byte ptr offset))
(%eval-redef %get-signed-word (ptr &optional (offset 0)) (%get-signed-word ptr offset))
(%eval-redef %get-long (ptr &optional (offset 0)) (%get-long ptr offset))
(%eval-redef %get-fixnum (ptr &optional (offset 0)) (%get-fixnum ptr offset))
(%eval-redef %get-signed-long (ptr &optional (offset 0)) (%get-signed-long ptr offset))
(%eval-redef %get-unsigned-long (ptr &optional (offset 0)) (%get-unsigned-long ptr offset))
(%eval-redef %get-ptr (ptr &optional (offset 0)) (%get-ptr ptr offset))
(%eval-redef %get-full-long (ptr &optional (offset 0)) (%get-full-long ptr offset))
(%eval-redef %int-to-ptr (int))
(%eval-redef %ptr-to-int (ptr))
(%eval-redef %ptr-eql (ptr1 ptr2))
(%eval-redef %setf-macptr (ptr1 ptr2))
(%eval-redef %null-ptr-p (ptr))
(%eval-redef %iasr (x y))
(%eval-redef %set-byte (p o &optional (new (prog1 o (setq o 0))))
(%set-byte p o new))
(%eval-redef %set-unsigned-byte (p o &optional (new (prog1 o (setq o 0))))
(%set-unsigned-byte p o new))
(%eval-redef %set-word (p o &optional (new (prog1 o (setq o 0))))
(%set-word p o new))
(%eval-redef %set-unsigned-word (p o &optional (new (prog1 o (setq o 0))))
(%set-unsigned-word p o new))
(%eval-redef %set-long (p o &optional (new (prog1 o (setq o 0))))
(%set-long p o new))
(%eval-redef %set-unsigned-long (p o &optional (new (prog1 o (setq o 0))))
(%set-unsigned-long p o new))
(%eval-redef %set-ptr (p o &optional (new (prog1 o (setq o 0))))
(%set-ptr p o new))
(%eval-redef %word-to-int (word))
(%eval-redef %inc-ptr (ptr &optional (by 1)) (%inc-ptr ptr by))
(%eval-redef char-code (x))
(%eval-redef code-char (x))
(%eval-redef 1- (n))
(%eval-redef 1+ (n))
(%eval-redef uvref (x y))
(%eval-redef uvset (x y z))
(%eval-redef uvsize (x))
(%eval-redef svref (x y))
(%eval-redef svset (x y z))
(%eval-redef cons (x y))
(%eval-redef endp (x))
(progn
(%eval-redef typecode (x))
(%eval-redef lisptag (x))
(%eval-redef fulltag (x))
(%eval-redef %unbound-marker ())
(%eval-redef %slot-unbound-marker ())
(%eval-redef %slot-ref (v i))
(%eval-redef %alloc-misc (count subtag &optional (initial nil initial-p))
(if initial-p
(%alloc-misc count subtag initial)
(%alloc-misc count subtag)))
(%eval-redef %setf-double-float (x y))
(%eval-redef %lisp-word-ref (x y))
(%eval-redef %temp-cons (x y))
(%eval-redef require-fixnum (x))
(%eval-redef require-symbol (x))
(%eval-redef require-list (x))
(%eval-redef require-real (x))
(%eval-redef require-simple-string (x))
(%eval-redef require-simple-vector (x))
(%eval-redef require-character (x))
(%eval-redef require-number (x))
(%eval-redef require-integer (x))
(%eval-redef require-s8 (x))
(%eval-redef require-u8 (x))
(%eval-redef require-s16 (x))
(%eval-redef require-u16 (x))
(%eval-redef require-s32 (x))
(%eval-redef require-u32 (x))
(%eval-redef require-s64 (x))
(%eval-redef require-u64 (x))
(%eval-redef %reference-external-entry-point (x))
)
(%eval-redef %get-bit (ptr offset))
(%eval-redef %set-bit (ptr offset val))
(%eval-redef %get-double-float (ptr &optional (offset 0))
(%get-double-float ptr offset))
(%eval-redef %get-single-float (ptr &optional (offset 0))
(%get-single-float ptr offset))
(%eval-redef %set-double-float (p o &optional (new (prog1 o (setq o 0))))
(%set-double-float p o new))
(%eval-redef %set-single-float (p o &optional (new (prog1 o (setq o 0))))
(%set-single-float p o new))
(%eval-redef assq (item list))
(%eval-redef %fixnum-ref-double-float (base &optional (index 0))
(%fixnum-ref-double-float base index))
(%eval-redef %fixnum-set-double-float (base index &optional (new (prog1 index (setq index 0))))
(%fixnum-set-double-float base index new))
(%eval-redef ivector-typecode-p (arg))
(%eval-redef gvector-typecode-p (arg))
)
; In the spirit of eval-redef ...
;; pointer hacking stuff
;
;
;;; I'd guess that the majority of bitfields in the world whose width is
;;; greater than 1 have a width of two. If that's true, this is probably
;;; faster than trying to be more clever about it would be.
(defun %get-bitfield (ptr start-bit width)
(declare (fixnum start-bit width))
(do* ((bit #+big-endian-target start-bit
#+little-endian-target (the fixnum (1- (the fixnum (+ start-bit width))))
#+big-endian-target (1+ bit)
#+little-endian-target (1- bit))
(i 0 (1+ i))
(val 0))
((= i width) val)
(declare (fixnum val i bit))
(setq val (logior (ash val 1) (%get-bit ptr bit)))))
(defun %set-bitfield (ptr start width val)
(declare (fixnum val start width))
(do* ((v val (ash v -1))
(bit #+big-endian-target (1- (+ start width))
#+little-endian-target start
#+big-endian-target (1- bit)
#+little-endian-target (1+ bit))
(i 0 (1+ i)))
((= i width) val)
(declare (fixnum v bit i))
(setf (%get-bit ptr bit) (logand v 1))))
; expands into compiler stuff
(setf (symbol-function '%get-unsigned-byte) (symbol-function '%get-byte))
(setf (symbol-function '%get-unsigned-word) (symbol-function '%get-word))
(setf (symbol-function '%get-signed-long) (symbol-function '%get-long))
(defun decompose-record-accessor (accessor &aux ret)
(do* ((str (symbol-name accessor) (%substr str (+ i 1) len))
(len (length str) (length str))
(i (%str-member #\. str) (%str-member #\. str))
(field (%substr str 0 (or i len)) (%substr str 0 (or i len))))
((not i) (nreverse (cons (make-keyword field) ret)))
(push (make-keyword field) ret)))
(provide 'level-2)
;; end of level-2.lisp
| true |
;;;-*-Mode: LISP; Package: CCL -*-
;;;
;;; Copyright 1994-2009 PI:NAME:<NAME>END_PI
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
;; Level-2.lisp
(in-package "CCL")
(eval-when (eval compile)
(require "LEVEL-2")
(require "BACKQUOTE")
(require "DEFSTRUCT-MACROS"))
(eval-when (eval compile)
(require "LISPEQU"))
; This incredibly essential thing is part of ANSI CL; put it in the
; right package someday.
; Like maybe when it says something about doc strings, or otherwise
; becomes useful.
(defun parse-macro (name arglist body &optional env)
(values (parse-macro-1 name arglist body env)))
; Return a list containing a special declaration for SYM
; if SYM is declared special in decls.
; This is so we can be pedantic about binding &WHOLE/&ENVIRONMENT args
; that have been scarfed out of a macro-like lambda list.
; The returned value is supposed to be suitable for splicing ...
(defun hoist-special-decls (sym decls)
(when sym
(dolist (decl decls)
(dolist (spec (cdr decl))
(when (eq (car spec) 'special)
(dolist (s (%cdr spec))
(when (eq s sym)
(return-from hoist-special-decls `((declare (special ,sym)))))))))))
(defun parse-macro-1 (name arglist body &optional env)
(parse-macro-internal name arglist body env nil))
(defun parse-macro-internal (name arglist body env default-initial-value)
(unless (verify-lambda-list arglist t t t)
(error "Invalid lambda list ~s" arglist))
(multiple-value-bind (lambda-list whole environment)
(normalize-lambda-list arglist t t)
(multiple-value-bind (body local-decs doc)
(parse-body body env t)
(let ((whole-var (gensym "WHOLE"))
(env-var (gensym "ENVIRONMENT")))
(multiple-value-bind (bindings binding-decls)
(%destructure-lambda-list lambda-list whole-var nil nil
:cdr-p t
:whole-p nil
:use-whole-var t
:default-initial-value default-initial-value)
(when environment
(setq bindings (nconc bindings (list `(,environment ,env-var)))))
(when whole
(setq bindings (nconc bindings (list `(,whole ,whole-var)))))
(values
`(lambda (,whole-var ,env-var)
(declare (ignorable ,whole-var ,env-var))
(block ,name
(let* ,(nreverse bindings)
,@(when binding-decls `((declare ,@binding-decls)))
,@local-decs
,@body)))
doc))))))
(defun lambda-list-bounds (lambda-list)
(let* ((state :required)
(min 0)
(max 0))
(do* ((lambda-list lambda-list (cdr lambda-list)))
((null lambda-list) (values min max))
(case (car lambda-list)
((&rest &key &body) (return (values min nil)))
(&aux (return (values min max)))
(&optional (setq state :optional))
(t (ecase state
(:required (incf min) (incf max))
(:optional (incf max))))))))
(defun prepare-to-destructure (list lambda-list min max)
(if (if max
(and (proper-list-p list)
(let* ((len (length list)))
(<= min len max)))
(do* ((tail list (cdr tail))
(n min (1- n)))
((zerop n) t)
(when (atom tail)
(return))))
list
(let* ((reason
(if max
(if (not (proper-list-p list))
"it is not a proper list"
(let* ((len (length list)))
(if (eql min max)
(format nil "it contains ~d elements, and exactly ~d are expected" len min)
(if (< len min)
(format nil "it contains ~d elements, and at least ~d are expected" len min)
(format nil "it contains ~d elements, and at most ~d are expected" len max)))))
(format nil "it does not contain at least ~d elements" min))))
(signal-program-error "~s can't be destructured against the lambda list ~s, because ~a."
list lambda-list reason))))
(defun %destructure-lambda-list (lambda-list wholeform lets decls
&key cdr-p (whole-p t) use-whole-var default-initial-value)
(unless (and (listp lambda-list)
(verify-lambda-list lambda-list t whole-p))
(signal-simple-program-error "Invalid lambda list: ~s" lambda-list))
(multiple-value-bind (normalized whole) (normalize-lambda-list
lambda-list whole-p)
(let* ((argstate :required)
(allow-other-keys nil)
(rest-arg-name nil)
(w (if use-whole-var wholeform (or whole (gensym "WHOLE"))))
(argptr (gensym "ARGS"))
(has-&key nil)
(keywords ())
(first-keyword-init ())
(restp nil))
(labels ((simple-var (var &optional (initform `,default-initial-value))
(let* ((binding `(,var ,initform)))
(push binding lets)
binding))
(structured-var (context sub-lambda-list initform)
(let* ((v (gensym (string context))))
(simple-var v initform)
(multiple-value-setq (lets decls)
(%destructure-lambda-list
sub-lambda-list
v
lets
decls
:default-initial-value default-initial-value
))
v)))
(unless use-whole-var
(if (atom w)
(simple-var w wholeform)
(progn
(setq w (structured-var "WHOLE" w (if cdr-p `(cdr ,wholeform) wholeform))
cdr-p nil))))
(multiple-value-bind (min max) (lambda-list-bounds normalized)
(simple-var argptr `(prepare-to-destructure ,@(if cdr-p `((cdr ,w)) `(,w)) ',lambda-list ,min ,max))
(push `(ignorable ,argptr) decls)
(when max
(push `(list ,argptr) decls))
(do* ((tail normalized (cdr tail)))
((null tail)
(if has-&key
(let* ((key-check-form `(check-keywords
',(nreverse keywords)
,rest-arg-name ,allow-other-keys)))
(if first-keyword-init
(rplaca (cdr first-keyword-init)
`(progn
,key-check-form
,(cadr first-keyword-init)))
(let* ((check-var (gensym "CHECK")))
(push `(ignorable ,check-var) decls)
(simple-var check-var key-check-form)))))
(values lets decls))
(let* ((var (car tail)))
(cond ((or (eq var '&rest) (eq var '&body))
(let* ((r (cadr tail))
(init argptr))
(if (listp r)
(setq rest-arg-name
(structured-var "REST" r init))
(progn
(setq rest-arg-name (gensym "REST"))
(simple-var rest-arg-name init)
(simple-var r rest-arg-name ))))
(setq restp t)
(setq tail (cdr tail)))
((eq var '&optional) (setq argstate :optional))
((eq var '&key)
(setq argstate :key)
(setq has-&key t)
(unless restp
(setq restp t
rest-arg-name (gensym "KEYS"))
(push `(ignorable ,rest-arg-name) decls)
(simple-var rest-arg-name
argptr)))
((eq var '&allow-other-keys)
(setq allow-other-keys t))
((eq var '&aux)
(setq argstate :aux))
((listp var)
(case argstate
(:required
(structured-var "REQ" var `(pop ,argptr)))
(:optional
(let* ((variable (car var))
(initform (if (cdr var)
(cadr var)
`,default-initial-value))
(anon-spvar (gensym "OPT-SUPPLIED-P"))
(spvar (if (cddr var)
(caddr var)))
(varinit `(if ,anon-spvar
(pop ,argptr)
,initform)))
(simple-var anon-spvar
`(not (null ,argptr)))
(if (listp variable)
(structured-var "OPT" variable varinit)
(simple-var variable varinit))
(if spvar
(simple-var spvar anon-spvar))))
(:key
(let* ((explicit-key (consp (car var)))
(variable (if explicit-key
(cadar var)
(car var)))
(keyword (if explicit-key
(caar var)
(make-keyword variable)))
(initform (if (cdr var)
(cadr var)
`,default-initial-value))
(anon-spvar (gensym "KEY-SUPPLIED-P"))
(spvar (if (cddr var)
(caddr var))))
(push keyword keywords)
(let* ((sp-init (simple-var anon-spvar
`(%keyword-present-p
,rest-arg-name
',keyword)))
(var-init `(if ,anon-spvar
(getf ,rest-arg-name ',keyword)
,initform)))
(unless first-keyword-init
(setq first-keyword-init sp-init))
(if (listp variable)
(structured-var "KEY" variable var-init)
(simple-var variable var-init))
(if spvar
(simple-var spvar anon-spvar)))))
(:aux
(simple-var (car var) (cadr var)))
(t (error "NYI: ~s" argstate))))
((symbolp var)
(case argstate
(:required
(simple-var var `(pop ,argptr)))
(:optional
(simple-var var `(if ,argptr
(pop ,argptr)
',default-initial-value)))
(:key
(let* ((keyword (make-keyword var)))
(push keyword keywords)
(let* ((init (simple-var
var
`(getf ,rest-arg-name
',keyword
,@(if default-initial-value
`(',default-initial-value))))))
(unless first-keyword-init
(setq first-keyword-init init)))))
(:aux
(simple-var var))))))))))))
(defun apply-to-htab-syms (function pkg-vector)
(let* ((sym nil)
(foundp nil))
(dotimes (i (uvsize pkg-vector))
(declare (fixnum i))
(multiple-value-setq (sym foundp) (%htab-symbol pkg-vector i))
(when foundp (funcall function sym)))))
(defun iterate-over-external-symbols (pkg-spec function)
(apply-to-htab-syms function (car (pkg.etab (pkg-arg (or pkg-spec *package*))))))
(defun iterate-over-present-symbols (pkg-spec function)
(let ((pkg (pkg-arg (or pkg-spec *package*))))
(apply-to-htab-syms function (car (pkg.etab pkg)))
(apply-to-htab-syms function (car (pkg.itab pkg)))))
(defun iterate-over-accessable-symbols (pkg-spec function)
(let* ((pkg (pkg-arg (or pkg-spec *package*)))
(used (pkg.used pkg))
(shadowed (pkg.shadowed pkg)))
(iterate-over-present-symbols pkg function)
(when used
(if shadowed
(flet ((ignore-shadowed-conflicts (var)
(unless (%name-present-in-package-p (symbol-name var) pkg)
(funcall function var))))
(declare (dynamic-extent #'ignore-shadowed-conflicts))
(dolist (u used) (iterate-over-external-symbols u #'ignore-shadowed-conflicts)))
(dolist (u used) (iterate-over-external-symbols u function))))))
(defun iterate-over-all-symbols (function)
(dolist (pkg %all-packages%)
(iterate-over-present-symbols pkg function)))
;;;Eval definitions for things open-coded by the compiler.
;;;Don't use DEFUN since it should be illegal to DEFUN compiler special forms...
;;;Of course, these aren't special forms.
(macrolet ((%eval-redef (name vars &rest body)
(when (null body) (setq body `((,name ,@vars))))
`(setf (symbol-function ',name)
(qlfun ,name ,vars ,@body))))
(declare (optimize (speed 1) (safety 1)))
(%eval-redef %ilsl (n x))
(%eval-redef %ilsr (n x))
(%eval-redef neq (x y))
(%eval-redef not (x))
(%eval-redef null (x))
(%eval-redef rplaca (x y))
(%eval-redef rplacd (x y))
(%eval-redef set-car (x y))
(%eval-redef set-cdr (x y))
(%eval-redef int>0-p (x))
(%eval-redef %get-byte (ptr &optional (offset 0)) (%get-byte ptr offset))
(%eval-redef %get-word (ptr &optional (offset 0)) (%get-word ptr offset))
(%eval-redef %get-signed-byte (ptr &optional (offset 0)) (%get-signed-byte ptr offset))
(%eval-redef %get-signed-word (ptr &optional (offset 0)) (%get-signed-word ptr offset))
(%eval-redef %get-long (ptr &optional (offset 0)) (%get-long ptr offset))
(%eval-redef %get-fixnum (ptr &optional (offset 0)) (%get-fixnum ptr offset))
(%eval-redef %get-signed-long (ptr &optional (offset 0)) (%get-signed-long ptr offset))
(%eval-redef %get-unsigned-long (ptr &optional (offset 0)) (%get-unsigned-long ptr offset))
(%eval-redef %get-ptr (ptr &optional (offset 0)) (%get-ptr ptr offset))
(%eval-redef %get-full-long (ptr &optional (offset 0)) (%get-full-long ptr offset))
(%eval-redef %int-to-ptr (int))
(%eval-redef %ptr-to-int (ptr))
(%eval-redef %ptr-eql (ptr1 ptr2))
(%eval-redef %setf-macptr (ptr1 ptr2))
(%eval-redef %null-ptr-p (ptr))
(%eval-redef %iasr (x y))
(%eval-redef %set-byte (p o &optional (new (prog1 o (setq o 0))))
(%set-byte p o new))
(%eval-redef %set-unsigned-byte (p o &optional (new (prog1 o (setq o 0))))
(%set-unsigned-byte p o new))
(%eval-redef %set-word (p o &optional (new (prog1 o (setq o 0))))
(%set-word p o new))
(%eval-redef %set-unsigned-word (p o &optional (new (prog1 o (setq o 0))))
(%set-unsigned-word p o new))
(%eval-redef %set-long (p o &optional (new (prog1 o (setq o 0))))
(%set-long p o new))
(%eval-redef %set-unsigned-long (p o &optional (new (prog1 o (setq o 0))))
(%set-unsigned-long p o new))
(%eval-redef %set-ptr (p o &optional (new (prog1 o (setq o 0))))
(%set-ptr p o new))
(%eval-redef %word-to-int (word))
(%eval-redef %inc-ptr (ptr &optional (by 1)) (%inc-ptr ptr by))
(%eval-redef char-code (x))
(%eval-redef code-char (x))
(%eval-redef 1- (n))
(%eval-redef 1+ (n))
(%eval-redef uvref (x y))
(%eval-redef uvset (x y z))
(%eval-redef uvsize (x))
(%eval-redef svref (x y))
(%eval-redef svset (x y z))
(%eval-redef cons (x y))
(%eval-redef endp (x))
(progn
(%eval-redef typecode (x))
(%eval-redef lisptag (x))
(%eval-redef fulltag (x))
(%eval-redef %unbound-marker ())
(%eval-redef %slot-unbound-marker ())
(%eval-redef %slot-ref (v i))
(%eval-redef %alloc-misc (count subtag &optional (initial nil initial-p))
(if initial-p
(%alloc-misc count subtag initial)
(%alloc-misc count subtag)))
(%eval-redef %setf-double-float (x y))
(%eval-redef %lisp-word-ref (x y))
(%eval-redef %temp-cons (x y))
(%eval-redef require-fixnum (x))
(%eval-redef require-symbol (x))
(%eval-redef require-list (x))
(%eval-redef require-real (x))
(%eval-redef require-simple-string (x))
(%eval-redef require-simple-vector (x))
(%eval-redef require-character (x))
(%eval-redef require-number (x))
(%eval-redef require-integer (x))
(%eval-redef require-s8 (x))
(%eval-redef require-u8 (x))
(%eval-redef require-s16 (x))
(%eval-redef require-u16 (x))
(%eval-redef require-s32 (x))
(%eval-redef require-u32 (x))
(%eval-redef require-s64 (x))
(%eval-redef require-u64 (x))
(%eval-redef %reference-external-entry-point (x))
)
(%eval-redef %get-bit (ptr offset))
(%eval-redef %set-bit (ptr offset val))
(%eval-redef %get-double-float (ptr &optional (offset 0))
(%get-double-float ptr offset))
(%eval-redef %get-single-float (ptr &optional (offset 0))
(%get-single-float ptr offset))
(%eval-redef %set-double-float (p o &optional (new (prog1 o (setq o 0))))
(%set-double-float p o new))
(%eval-redef %set-single-float (p o &optional (new (prog1 o (setq o 0))))
(%set-single-float p o new))
(%eval-redef assq (item list))
(%eval-redef %fixnum-ref-double-float (base &optional (index 0))
(%fixnum-ref-double-float base index))
(%eval-redef %fixnum-set-double-float (base index &optional (new (prog1 index (setq index 0))))
(%fixnum-set-double-float base index new))
(%eval-redef ivector-typecode-p (arg))
(%eval-redef gvector-typecode-p (arg))
)
; In the spirit of eval-redef ...
;; pointer hacking stuff
;
;
;;; I'd guess that the majority of bitfields in the world whose width is
;;; greater than 1 have a width of two. If that's true, this is probably
;;; faster than trying to be more clever about it would be.
(defun %get-bitfield (ptr start-bit width)
(declare (fixnum start-bit width))
(do* ((bit #+big-endian-target start-bit
#+little-endian-target (the fixnum (1- (the fixnum (+ start-bit width))))
#+big-endian-target (1+ bit)
#+little-endian-target (1- bit))
(i 0 (1+ i))
(val 0))
((= i width) val)
(declare (fixnum val i bit))
(setq val (logior (ash val 1) (%get-bit ptr bit)))))
(defun %set-bitfield (ptr start width val)
(declare (fixnum val start width))
(do* ((v val (ash v -1))
(bit #+big-endian-target (1- (+ start width))
#+little-endian-target start
#+big-endian-target (1- bit)
#+little-endian-target (1+ bit))
(i 0 (1+ i)))
((= i width) val)
(declare (fixnum v bit i))
(setf (%get-bit ptr bit) (logand v 1))))
; expands into compiler stuff
(setf (symbol-function '%get-unsigned-byte) (symbol-function '%get-byte))
(setf (symbol-function '%get-unsigned-word) (symbol-function '%get-word))
(setf (symbol-function '%get-signed-long) (symbol-function '%get-long))
(defun decompose-record-accessor (accessor &aux ret)
(do* ((str (symbol-name accessor) (%substr str (+ i 1) len))
(len (length str) (length str))
(i (%str-member #\. str) (%str-member #\. str))
(field (%substr str 0 (or i len)) (%substr str 0 (or i len))))
((not i) (nreverse (cons (make-keyword field) ret)))
(push (make-keyword field) ret)))
(provide 'level-2)
;; end of level-2.lisp
|
[
{
"context": "defsystem #:clsc\n :description \"clsc\"\n :author \"zeldacl <[email protected]>\"\n :license \"Specify license ",
"end": 412,
"score": 0.9993804097175598,
"start": 405,
"tag": "USERNAME",
"value": "zeldacl"
},
{
"context": " #:clsc\n :description \"clsc\"\n :author \"zeldacl <[email protected]>\"\n :license \"Specify license here\"\n :version (:",
"end": 431,
"score": 0.9999229311943054,
"start": 414,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
clsc.asd
|
zeldacl/clsc
| 0 |
#-asdf3.1 (error "CLSC requires ASDF 3.1 or later. Please upgrade your ASDF.")
;;;; clsc.asd
;; (when (asdf:find-system :ql nil))
(let ((third-path #P"thirdparty/"))
(when (not (find third-path ql:*local-project-directories* :test #'pathname-match-p))
(setf ql:*local-project-directories* (cons third-path ql:*local-project-directories*))))
(asdf:defsystem #:clsc
:description "clsc"
:author "zeldacl <[email protected]>"
:license "Specify license here"
:version (:read-file-form "version.text")
;; :pathname "src/"
:components
((:module "s2-proto"
:serial t
:pathname "protocol/sc2/"
;; :search-path "proto"
:components
(
;; (:protobuf-file "s2clientprotocol/common")
;; (:protobuf-file "s2clientprotocol/debug" search-path (#p"protocol/sc2/"))
(:protobuf-file "s2clientprotocol/sc2api" :search-path (#p""))
)))
;; :protobuf-file "proto"
:class :package-inferred-system
;; :serial t
;; :components (
;; (:module framework
;; :components ((:file "package")
;; (:file "network")))
;; (:file "package")
;; (:file "clsc"))
:defsystem-depends-on ((:version :cl-protobufs "1.0"))
:depends-on ("clsc/lab/dx/sc2/s2client/core"
:uiop
:usocket
:cl-protobufs
:websocket-driver
:log4cl
:bordeaux-threads
(:version :local-time "1.0.6")
:unix-opts))
|
10683
|
#-asdf3.1 (error "CLSC requires ASDF 3.1 or later. Please upgrade your ASDF.")
;;;; clsc.asd
;; (when (asdf:find-system :ql nil))
(let ((third-path #P"thirdparty/"))
(when (not (find third-path ql:*local-project-directories* :test #'pathname-match-p))
(setf ql:*local-project-directories* (cons third-path ql:*local-project-directories*))))
(asdf:defsystem #:clsc
:description "clsc"
:author "zeldacl <<EMAIL>>"
:license "Specify license here"
:version (:read-file-form "version.text")
;; :pathname "src/"
:components
((:module "s2-proto"
:serial t
:pathname "protocol/sc2/"
;; :search-path "proto"
:components
(
;; (:protobuf-file "s2clientprotocol/common")
;; (:protobuf-file "s2clientprotocol/debug" search-path (#p"protocol/sc2/"))
(:protobuf-file "s2clientprotocol/sc2api" :search-path (#p""))
)))
;; :protobuf-file "proto"
:class :package-inferred-system
;; :serial t
;; :components (
;; (:module framework
;; :components ((:file "package")
;; (:file "network")))
;; (:file "package")
;; (:file "clsc"))
:defsystem-depends-on ((:version :cl-protobufs "1.0"))
:depends-on ("clsc/lab/dx/sc2/s2client/core"
:uiop
:usocket
:cl-protobufs
:websocket-driver
:log4cl
:bordeaux-threads
(:version :local-time "1.0.6")
:unix-opts))
| true |
#-asdf3.1 (error "CLSC requires ASDF 3.1 or later. Please upgrade your ASDF.")
;;;; clsc.asd
;; (when (asdf:find-system :ql nil))
(let ((third-path #P"thirdparty/"))
(when (not (find third-path ql:*local-project-directories* :test #'pathname-match-p))
(setf ql:*local-project-directories* (cons third-path ql:*local-project-directories*))))
(asdf:defsystem #:clsc
:description "clsc"
:author "zeldacl <PI:EMAIL:<EMAIL>END_PI>"
:license "Specify license here"
:version (:read-file-form "version.text")
;; :pathname "src/"
:components
((:module "s2-proto"
:serial t
:pathname "protocol/sc2/"
;; :search-path "proto"
:components
(
;; (:protobuf-file "s2clientprotocol/common")
;; (:protobuf-file "s2clientprotocol/debug" search-path (#p"protocol/sc2/"))
(:protobuf-file "s2clientprotocol/sc2api" :search-path (#p""))
)))
;; :protobuf-file "proto"
:class :package-inferred-system
;; :serial t
;; :components (
;; (:module framework
;; :components ((:file "package")
;; (:file "network")))
;; (:file "package")
;; (:file "clsc"))
:defsystem-depends-on ((:version :cl-protobufs "1.0"))
:depends-on ("clsc/lab/dx/sc2/s2client/core"
:uiop
:usocket
:cl-protobufs
:websocket-driver
:log4cl
:bordeaux-threads
(:version :local-time "1.0.6")
:unix-opts))
|
[
{
"context": "CENSE file distributed with ACL2.\n;\n; Authors:\n; Alessandro Coglio ([email protected])\n; Eric Smith (eric.smith@k",
"end": 273,
"score": 0.999854326248169,
"start": 256,
"tag": "NAME",
"value": "Alessandro Coglio"
},
{
"context": "ed with ACL2.\n;\n; Authors:\n; Alessandro Coglio ([email protected])\n; Eric Smith ([email protected])\n; Matt",
"end": 293,
"score": 0.9999293088912964,
"start": 275,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "rs:\n; Alessandro Coglio ([email protected])\n; Eric Smith ([email protected])\n; Matt Kaufmann (kaufm",
"end": 309,
"score": 0.9998171925544739,
"start": 299,
"tag": "NAME",
"value": "Eric Smith"
},
{
"context": "andro Coglio ([email protected])\n; Eric Smith ([email protected])\n; Matt Kaufmann ([email protected])\n\n;;;;",
"end": 333,
"score": 0.9999344348907471,
"start": 311,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "l.edu)\n; Eric Smith ([email protected])\n; Matt Kaufmann ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;",
"end": 352,
"score": 0.9998204708099365,
"start": 339,
"tag": "NAME",
"value": "Matt Kaufmann"
},
{
"context": "Smith ([email protected])\n; Matt Kaufmann ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 376,
"score": 0.9999338388442993,
"start": 354,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/kestrel/utilities/system/world-queries.lisp
|
MattKaufmann/acl2
| 1 |
; System Utilities -- World Queries
;
; Copyright (C) 2018 Kestrel Institute (http://www.kestrel.edu)
; Copyright (C) 2018 Regents of the University of Texas
;
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;
; Authors:
; Alessandro Coglio ([email protected])
; Eric Smith ([email protected])
; Matt Kaufmann ([email protected])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(include-book "xdoc/constructors" :dir :system)
(include-book "std/util/deflist" :dir :system)
(include-book "std/util/defrule" :dir :system)
(include-book "system/kestrel" :dir :system)
(include-book "system/pseudo-good-worldp" :dir :system)
(include-book "term-function-recognizers")
(local (include-book "std/typed-lists/symbol-listp" :dir :system))
(local (include-book "arglistp-theorems"))
(local (include-book "world-theorems"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc world-queries
:parents (system-utilities-non-built-in)
:short "Utilities to query @(see world)s."
:long
"<p>
These complement the world query utilities
in the <see topic='@(url system-utilities)'>built-in system utilities</see>.
</p>
<p>
Many of these world query utilities come in two variants:
a ``fast'' one and a ``logic-friendly'' one.
The former has relatively weak and no (strong) return type theorems;
the latter has stronger guards and some run-time checks
that are believed to never fail
and that enable the proof of (stronger) return type theorems
without having to assume stronger properties in the guard
of the @(see world) arguments.
The logic-friendly variants are helpful
to prove properties (including verifying guards)
of logic-mode code that calls them,
but the fast variants avoid the performance penalty
of the always-satisfied run-time checks,
when proving properties of the code that calls them is not a focus
(e.g. in program-mode code).
</p>
<p>
The built-in world query utilities
have the characteristics of the fast variants.
Below we provide logic-friendly variants of
some built-in world query utilities.
</p>
<p>
The fast variants provided below are named in a way
that is ``consistent'' with the built-in world query utilities.
The logic-friendly world query utilities are named by adding @('+')
after the name of the corresponding fast world query utilities
(both built-in and provided below).
</p>")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define theorem-symbolp ((sym symbolp) (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Check if a symbol names a theorem,
i.e. it has a @('theorem') property."
:long
"<p>
This function is named in analogy to
the @(tsee function-symbolp) built-in system utility.
</p>"
(not (eq t (getpropc sym 'theorem t wrld))))
(define macro-symbolp ((sym symbolp) (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Check if a symbol names a macro,
i.e. it has a @('macro-args') property."
:long
"<p>
This function is named in analogy to
the @(tsee function-symbolp) built-in system utility.
</p>"
(not (eq t (getpropc sym 'macro-args t wrld))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(std::deflist function-symbol-listp (x wrld)
(function-symbolp x wrld)
:guard (and (symbol-listp x)
(plist-worldp wrld))
:parents (world-queries)
:short "Check if all the symbols in a list name functions."
:true-listp t)
(std::deflist theorem-symbol-listp (x wrld)
(theorem-symbolp x wrld)
:guard (and (symbol-listp x)
(plist-worldp wrld))
:parents (world-queries)
:short "Check if all the symbols in a list name theorems."
:true-listp t)
(std::deflist macro-symbol-listp (x wrld)
(macro-symbolp x wrld)
:guard (and (symbol-listp x)
(plist-worldp wrld))
:parents (world-queries)
:short "Check if all the symbols in a list name macros."
:true-listp t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define function-namep (x (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Recognize symbols that name functions."
:long
"<p>
This function is enabled because it is meant as an abbreviation.
Thus, theorems triggered by this function should be avoided.
</p>"
(and (symbolp x)
(function-symbolp x wrld))
:enabled t)
(define theorem-namep (x (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Recognize symbols that name theorems."
:long
"<p>
This function is enabled because it is meant as an abbreviation.
Thus, theorems triggered by this function should be avoided.
</p>"
(and (symbolp x)
(theorem-symbolp x wrld))
:enabled t)
(define macro-namep (x (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Recognize symbols that name macros."
:long
"<p>
This function is enabled because it is meant as an abbreviation.
Thus, theorems triggered by this function should be avoided.
</p>"
(and (symbolp x)
(macro-symbolp x wrld))
:enabled t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(std::deflist function-name-listp (x wrld)
(function-namep x wrld)
:guard (plist-worldp wrld)
:parents (world-queries)
:short "Recognize true lists of symbols that name functions."
:true-listp t)
(std::deflist theorem-name-listp (x wrld)
(theorem-namep x wrld)
:guard (plist-worldp wrld)
:parents (world-queries)
:short "Recognize true lists of symbols that name theorems."
:true-listp t)
(std::deflist macro-name-listp (x wrld)
(macro-namep x wrld)
:guard (plist-worldp wrld)
:parents (world-queries)
:short "Recognize true lists of symbols that name macros."
:true-listp t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define logical-name-listp (names (wrld plist-worldp))
;; we cannot use STD::DEFLIST to define LOGICAL-NAME-LISTP
;; because STD::DEFLIST attempts to prove that LOGICAL-NAMEP is boolean,
;; but it is not
:returns (yes/no booleanp)
:verify-guards nil
:parents (world-queries)
:short "Recognize true lists of logical names."
:long
"<p>
See @('logical-namep') in the ACL2 source code.
</p>"
(cond ((atom names) (null names))
(t (and (logical-namep (car names) wrld)
(logical-name-listp (cdr names) wrld)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define logic-function-namep (x (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Recognize symbols that name logic-mode functions."
:long
"<p>
This function is enabled because it is meant as an abbreviation.
Thus, theorems triggered by this function should be avoided.
</p>"
(and (function-namep x wrld)
(logicp x wrld))
:enabled t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define formals+ ((fn (or (function-namep fn wrld)
(pseudo-lambdap fn)))
(wrld plist-worldp-with-formals))
:returns (formals symbol-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee formals)."
:long
"<p>
This returns the same result as @(tsee formals) on named functions,
but it has a stronger guard for named functions
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>
<p>
This utility also operates on lambda expressions, unlike @(tsee formals).
</p>"
(b* ((result (cond ((symbolp fn) (formals fn wrld))
(t (lambda-formals fn)))))
(if (symbol-listp result)
result
(raise "Internal error: ~
the formals ~x0 of ~x1 are not a true list of symbols."
result fn)))
:guard-hints (("Goal" :in-theory (enable pseudo-lambdap))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define arity+ ((fn (or (function-namep fn wrld)
(pseudo-lambdap fn)))
(wrld plist-worldp-with-formals))
:returns (result natp
:hyp (or (function-namep fn wrld) (pseudo-lambdap fn))
:hints (("Goal" :in-theory (enable arity pseudo-lambdap))))
:parents (world-queries)
:short "Logic-friendly variant of @(tsee arity)."
:long
"<p>
This returns the same result as @(tsee arity),
but it has a stronger guard.
</p>"
(arity fn wrld)
:guard-hints (("Goal" :in-theory (enable pseudo-lambdap))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define stobjs-in+ ((fn (function-namep fn wrld))
(wrld plist-worldp))
:returns (result symbol-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee stobjs-in)."
:long
"<p>
This returns the same result as @(tsee stobjs-in),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (stobjs-in fn wrld)))
(if (symbol-listp result)
result
(raise "Internal error: ~
the STOBJS-IN property ~x0 of ~x1 is not a true list of symbols."
result fn))))
(define stobjs-out+ ((fn (function-namep fn wrld))
(wrld plist-worldp))
:guard (not (member-eq fn *stobjs-out-invalid*))
:returns (result symbol-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee stobjs-out)."
:long
"<p>
This returns the same result as @(tsee stobjs-out),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>
<p>
The function must not be in @('*stobjs-out-invalid*'),
because in that case its output stobjs depend on how it is called.
</p>"
(b* ((result (stobjs-out fn wrld)))
(if (symbol-listp result)
result
(raise "Internal error: ~
the STOBJS-OUT property ~x0 of ~x1 is not a true list of symbols."
result fn))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define macro-args+ ((mac (macro-namep mac wrld))
(wrld plist-worldp))
:returns (result true-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee macro-args)."
:long
"<p>
This returns the same result as the built-in system utility @('macro-args')
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (macro-args mac wrld)))
(if (true-listp result)
result
(raise "Internal error: ~
the MACRO-ARGS property ~x0 of ~x1 is not a true list."
result mac))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define definedp ((fn symbolp) (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Check if a named logic-mode function is defined."
:long
"<p>
We check if the function symbol has an @('unnormalized-body') property.
</p>
<p>
Note that some program-mode functions may be defined
but not have an @('unnormalized-body') property.
</p>
<p>
See @(tsee definedp+) for a logic-friendly variant of this utility.
</p>"
(if (getpropc fn 'unnormalized-body nil wrld) t nil))
(define definedp+ ((fn (logic-function-namep fn wrld)) (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee definedp)."
:long
"<p>
This returns the same result as @(tsee definedp),
but it has a stronger guard.
</p>"
(definedp fn wrld))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define primitivep ((fn symbolp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Check if a named function is @(see primitive)."
:long
"<p>
See @(tsee primitivep+) for a logic-friendly variant of this utility.
</p>"
(and (member-eq fn (strip-cars *primitive-formals-and-guards*)) t))
(define primitivep+ ((fn (function-namep fn wrld)) (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee primitivep)."
:long
"<p>
This returns the same result as @(tsee guard-verified-p),
but it has a stronger guard.
The guard requires an extra @(see world) argument,
which is usually available when doing system programming.
</p>"
(declare (ignore wrld))
(primitivep fn))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define guard-verified-p ((fn/thm symbolp) (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Check if a named function or theorem is @(tsee guard)-verified."
:long
"<p>
See @(tsee guard-verified-p+) for a logic-friendly variant of this utility.
</p>"
(eq (symbol-class fn/thm wrld) :common-lisp-compliant))
(define guard-verified-p+ ((fn/thm (or (function-namep fn/thm wrld)
(theorem-namep fn/thm wrld)))
(wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee guard-verified-p)."
:long
"<p>
This returns the same result as @(tsee guard-verified-p),
but it has a stronger guard.
</p>"
(guard-verified-p fn/thm wrld))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define ubody ((fn pseudo-termfnp) (wrld plist-worldp))
:returns (body "A @(tsee pseudo-termp).")
:parents (world-queries)
:short "Unnormalized body of a named logic-mode function,
or body of a lambda expression."
:long
"<p>
This is a specialization of @(tsee body)
with @('nil') as the second argument.
Since @(tsee body) is not guard-verified only because of
the code that handles the case in which the second argument is non-@('nil'),
we avoid calling @(tsee body) and instead replicate
the code that handles the case in which the second argument is @('nil');
thus, this utility is guard-verified.
</p>
<p>
If the argument named function is not defined, this utility returns @('nil').
</p>
<p>
Not that some program-mode functions may be defined
but not have an @('unnormalized-body') property.
</p>
<p>
See @(tsee ubody+) for a logic-friendly variant of this utility.
</p>"
(cond ((symbolp fn) (getpropc fn 'unnormalized-body nil wrld))
(t (lambda-body fn)))
:guard-hints (("Goal" :in-theory (enable pseudo-termfnp pseudo-lambdap))))
(define ubody+ ((fn (or (and (logic-function-namep fn wrld)
(definedp fn wrld))
(pseudo-lambdap fn)))
(wrld plist-worldp))
:returns (body pseudo-termp
:hyp (or (symbolp fn) (pseudo-lambdap fn))
:hints (("Goal" :in-theory (enable pseudo-lambdap))))
:parents (world-queries)
:short "Logic-friendly variant of @(tsee ubody)."
:long
"<p>
This returns the same result as @(tsee ubody),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (ubody fn wrld)))
(if (pseudo-termp result)
result
(raise "Internal error: ~
the unnormalized body ~x0 of ~x1 is not a pseudo-term."
result fn)))
:guard-hints (("Goal" :in-theory (enable pseudo-termfnp))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define uguard ((fn pseudo-termfnp) (wrld plist-worldp))
:returns (guard "A @(tsee pseudo-termp).")
:parents (world-queries)
:short "Unoptimized guard of a named function or of a lambda expression."
:long
"<p>
This is a specialization of
<see topic='@(url system-utilities)'>@('guard')</see>
with @('nil') as the second argument.
Since @(tsee body) is in program mode only because of
the code that handles the case in which the second argument is non-@('nil'),
we avoid calling @(tsee guard) and instead replicate
the code that handles the case in which the second argument is @('nil');
thus, this utility is in logic mode and guard-verified.
</p>
<p>
See @(tsee uguard+) for a logic-friendly variant of this utility.
</p>"
(cond ((symbolp fn) (getpropc fn 'guard *t* wrld))
(t *t*)))
(define uguard+ ((fn (or (function-namep fn wrld)
(pseudo-lambdap fn)))
(wrld plist-worldp))
:returns (guard pseudo-termp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee uguard)."
:long
"<p>
This returns the same result as @(tsee uguard),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (uguard fn wrld)))
(if (pseudo-termp result)
result
(raise "Internal error: ~
the guard ~x0 of ~x1 is not a pseudo-term."
result fn)))
:guard-hints (("Goal" :in-theory (enable pseudo-termfnp))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define non-executablep ((fn symbolp) (wrld plist-worldp))
:returns (status "@('t'), @('nil'), or @(':program').")
:parents (world-queries)
:short "@(see Non-executable) status of a named logic-mode defined function."
:long
"<p>
See @(tsee non-executablep+) for a logic-friendly variant of this utility.
</p>"
(getpropc fn 'non-executablep nil wrld))
(define non-executablep+ ((fn (function-namep fn wrld))
(wrld plist-worldp))
:returns (nonexec (or (booleanp nonexec) (eq nonexec :program)))
:parents (world-queries)
:short "Logic-friendly variant of @(tsee non-executablep)."
:long
"<p>
This returns the same result as @(tsee non-executablep),
but it has a stronger guard
and includes run-time checks (which should always succeed) on the result
that allow us to prove the return type theorems
without strengthening the guard on @('wrld').
</p>"
(b* ((result (non-executablep fn wrld))
((unless (or (booleanp result)
(eq result :program)))
(raise "Internal error: ~
the non-executable status ~x0 of ~x1 is not ~
T, NIL, or :PROGRAM."
result fn))
((when (and (logicp fn wrld)
(eq result :program)))
(raise "Internal error: ~
the non-executable status of the logic-mode function ~x0 ~
is :PROGRAM instead of T or NIL."
fn)))
result)
///
(more-returns
(nonexec booleanp
:hyp (logicp fn wrld)
:name booleanp-of-non-executablep+-when-logicp)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define unwrapped-nonexec-body ((fn symbolp) (wrld plist-worldp))
:returns (unwrapped-body "A @(tsee pseudo-termp).")
:verify-guards nil
:parents (world-queries)
:short "Body of a named logic-mode defined non-executable function,
without the ``non-executable wrapper''."
:long
"<p>
@(tsee defun-nx) generates
a logic-mode function whose body is wrapped as follows:
</p>
@({
(return-last 'progn
(throw-nonexec-error 'fn
(cons arg1 ... (cons argN 'nil)...))
body)
})
<p>
If @(tsee defun) is used for a logic-mode function with
<see topic='@(url non-executable)'>@(':non-executable')</see> set to @('t'),
the submitted body (once translated) must be wrapped as above.
</p>
<p>
This utility returns
the unwrapped body of a logic-mode non-executable function @('fn'),
by removing the wrapper shown above.
</p>
<p>
See @(tsee unwrapped-nonexec-body+) for
a logic-friendly variant of this utility.
</p>"
(fourth (ubody fn wrld)))
(define unwrapped-nonexec-body+ ((fn (and (logic-function-namep fn wrld)
(definedp fn wrld)
(non-executablep fn wrld)))
(wrld plist-worldp-with-formals))
:returns (unwrapped-body pseudo-termp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee unwrapped-nonexec-body)."
:long
"<p>
This returns the same result as @(tsee unwrapped-nonexec-body),
but it has a stronger guard,
is guard-verified,
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
This utility also includes a run-time check (which should always succeed)
that the wrapper around the body has the expected form,
via the built-in function @('throw-nonexec-error-p');
this allows us to verify the guards
without strengthening the guard of @('wrld').
</p>"
(b* ((body (ubody+ fn wrld))
((unless (and (throw-nonexec-error-p body fn (formals+ fn wrld))
(consp (cdddr body))))
(raise "Internal error: ~
the body ~x0 of the non-executable function ~x1 ~
does not have the expected wrapper."
body fn))
(unwrapped-body (fourth body))
((unless (pseudo-termp unwrapped-body))
(raise "Internal error: ~
the unwrapped body ~x0 of the non-executable function ~x1 ~
is not a pseudo-term."
unwrapped-body fn)))
unwrapped-body))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define number-of-results ((fn symbolp) (wrld plist-worldp))
:guard (not (member-eq fn *stobjs-out-invalid*))
:returns (n natp "Actually a @(tsee posp).")
:parents (world-queries)
:short "Number of values returned by a named function."
:long
"<p>
This is 1, unless the function uses @(tsee mv)
(directly, or indirectly by calling another function that does)
to return multiple values.
</p>
<p>
The number of results of the function
is the length of its @(tsee stobjs-out) list.
</p>
<p>
The function must not be in @('*stobjs-out-invalid*'),
because in that case the number of its results depends on how it is called.
</p>
<p>
See @(tsee number-of-results+) for a logic-friendly variant of this utility.
</p>"
(len (stobjs-out fn wrld)))
(define number-of-results+ ((fn (function-namep fn wrld))
(wrld plist-worldp))
:guard (not (member-eq fn *stobjs-out-invalid*))
:returns (n posp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee number-of-results)."
:long
"<p>
This returns the same result as @(tsee number-of-results),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (number-of-results fn wrld)))
(if (posp result)
result
(prog2$
(raise "Internal error: ~
the STOBJS-OUT property of ~x0 is empty."
fn)
1)))) ; any POSP could be used here
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define no-stobjs-p ((fn symbolp) (wrld plist-worldp))
:guard (not (member-eq fn *stobjs-out-invalid*))
:returns (yes/no booleanp)
:verify-guards nil
:parents (world-queries)
:short "Check if a named function has no input or output @(see stobj)s."
:long
"<p>
The function must not be in @('*stobjs-out-invalid*'),
because in that case its (output) stobjs depend on how it is called.
</p>
<p>
See @(tsee no-stobjs-p+) for a logic-friendly variant of this utility.
</p>"
(and (all-nils (stobjs-in fn wrld))
(all-nils (stobjs-out fn wrld))))
(define no-stobjs-p+ ((fn (function-namep fn wrld))
(wrld plist-worldp))
:guard (not (member-eq fn *stobjs-out-invalid*))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee no-stobjs-p)."
:long
"<p>
This returns the same result as @(tsee no-stobjs-p),
but it has a stronger guard and is guard-verified.
</p>"
(and (all-nils (stobjs-in+ fn wrld))
(all-nils (stobjs-out+ fn wrld))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define irecursivep ((fn symbolp) (wrld plist-worldp))
:returns (clique "A @(tsee symbol-listp).")
:parents (world-queries)
:short "List of mutually recursive functions of which
the specified named function is a member,
based on the @(tsee defun) form that introduced this function,
or @('nil') if the specified function is not recursive."
:long
"<p>
This is a specialization of @(tsee recursivep)
with @('nil') as the second argument:
the @('i') that starts the name of @('irecursivep') conveys that
the result is based on the @(tsee defun) form that <i>introduced</i> @('fn').
</p>
<p>
See @(tsee irecursivep+) for a logic-friendly variant of this utility.
</p>"
(recursivep fn nil wrld))
(define irecursivep+ ((fn (logic-function-namep fn wrld))
(wrld plist-worldp))
:returns (clique symbol-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee irecursivep)."
:long
"<p>
This returns the same result as @(tsee irecursivep),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (irecursivep fn wrld)))
(if (symbol-listp result)
result
(raise "Internal error: ~
the RECURSIVEP property ~x0 of ~x1 is not a true list of symbols."
result fn))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define measure ((fn symbolp) (wrld plist-worldp))
:returns (measure "A @(tsee pseudo-termp).")
:verify-guards nil
:parents (world-queries)
:short "Measure expression of a named logic-mode recursive function."
:long
"<p>
See @(see xargs) for a discussion of the @(':measure') keyword.
</p>
<p>
See @(tsee measure+) for a logic-friendly variant of this utility.
</p>"
(b* ((justification (getpropc fn 'justification nil wrld)))
(access justification justification :measure)))
(define measure+ ((fn (and (logic-function-namep fn wrld)
(recursivep fn nil wrld)))
(wrld plist-worldp))
:returns (measure pseudo-termp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee measure)."
:long
"<p>
This returns the same result as @(tsee measure),
but it has a stronger guard,
is guard-verified,
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
This utility also includes a run-time check (which should always succeed)
on the form of the @('justification') property of the function
that allows us to verify the guards
without strengthening the guard of @('wrld').
</p>"
(b* ((justification (getpropc fn 'justification nil wrld))
((unless (weak-justification-p justification))
(raise "Internal error: ~
the JUSTIFICATION property ~x0 of ~x1 is not well-formed."
justification fn))
(measure (access justification justification :measure))
((unless (pseudo-termp measure))
(raise "Internal error: ~
the measure ~x0 of ~x1 is not a pseudo-term."
measure fn)))
measure))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define measured-subset ((fn symbolp) (wrld plist-worldp))
:returns (measured-subset "A @(tsee symbol-listp).")
:verify-guards nil
:parents (world-queries)
:short "Subset of the formal arguments
of a named logic-mode recursive function
that occur in its @(see measure) expression."
:long
"<p>
See @(tsee measured-subset+) for a logic-friendly variant of this utility.
</p>"
(b* ((justification (getpropc fn 'justification nil wrld)))
(access justification justification :subset)))
(define measured-subset+ ((fn (and (logic-function-namep fn wrld)
(recursivep fn nil wrld)))
(wrld plist-worldp))
:returns (measured-subset symbol-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee measured-subset)."
:long
"<p>
This returns the same result as @(tsee measured-subset),
but it has a stronger guard,
is guard-verified,
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
This utility also includes a run-time check (which should always succeed)
on the form of the @('justification') property of the function
that allows us to verify the guards
without strengthening the guard of @('wrld').
</p>"
(b* ((justification (getpropc fn 'justification nil wrld))
((unless (weak-justification-p justification))
(raise "Internal error: ~
the JUSTIFICATION property ~x0 of ~x1 is not well-formed."
justification fn))
(measured-subset (access justification justification :subset))
((unless (symbol-listp measured-subset))
(raise "Internal error: ~
the measured subset ~x0 of ~x1 is not a true list of symbols."
measured-subset fn)))
measured-subset))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define well-founded-relation ((fn symbolp) (wrld plist-worldp))
:returns (well-founded-relation "A @(tsee symbolp).")
:verify-guards nil
:parents (world-queries)
:short "Well-founded relation of a named logic-mode recursive function."
:long
"<p>
See @(see well-founded-relation-rule)
for a discussion of well-founded relations in ACL2,
including the @(':well-founded-relation') rule class.
</p>
<p>
See @(tsee well-founded-relation+) for
a logic-friendly variant of this utility.
</p>"
(b* ((justification (getpropc fn 'justification nil wrld)))
(access justification justification :rel)))
(define well-founded-relation+ ((fn (and (logic-function-namep fn wrld)
(recursivep fn nil wrld)))
(wrld plist-worldp))
:returns (well-founded-relation symbolp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee well-founded-relation)."
:long
"<p>
This returns the same result as @(tsee well-founded-relation),
but it has a stronger guard,
is guard-verified,
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
This utility also includes a run-time check (which should always succeed)
on the form of the @('justification') property of the function
that allows us to verify the guards
without strengthening the guard of @('wrld').
</p>"
(b* ((justification (getpropc fn 'justification nil wrld))
((unless (weak-justification-p justification))
(raise "Internal error: ~
the justification ~x0 of ~x1 is not well-formed."
justification fn))
(well-founded-relation (access justification justification :rel))
((unless (symbolp well-founded-relation))
(raise "Internal error: ~
the well-founded relation ~x0 of ~x1 is not a symbol."
well-founded-relation fn)))
well-founded-relation))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define ruler-extenders ((fn symbolp) (wrld plist-worldp))
:returns (ruler-extenders "A @(tsee symbol-listp) of @(':all').")
:verify-guards nil
:parents (world-queries)
:short "Ruler-extenders of a named logic-mode recursive function."
:long
"<p>
See @(see rulers) for background.
</p>
<p>
See @(tsee ruler-extenders+) for a logic-friendly variant of this utility.
</p>"
(b* ((justification (getpropc fn 'justification nil wrld)))
(access justification justification :ruler-extenders)))
(define ruler-extenders+ ((fn (and (logic-function-namep fn wrld)
(recursivep fn nil wrld)))
(wrld plist-worldp))
:returns (ruler-extenders (or (symbol-listp ruler-extenders)
(equal ruler-extenders :all)))
:parents (world-queries)
:short "Logic-friendly variant of @(tsee ruler-extenders)."
:long
"<p>
This returns the same result as @(tsee ruler-extenders),
but it has a stronger guard,
is guard-verified,
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
This utility also includes a run-time check (which should always succeed)
on the form of the @('justification') property of the function
that allows us to verify the guards
without strengthening the guard of @('wrld').
</p>"
(b* ((justification (getpropc fn 'justification nil wrld))
((unless (weak-justification-p justification))
(raise "Internal error: ~
the 'JUSTIFICATION property ~x0 of ~x1 is not well-formed."
justification fn))
(ruler-extenders (access justification justification :ruler-extenders))
((unless (or (symbol-listp ruler-extenders)
(eq ruler-extenders :all)))
(raise "Internal error: ~
the well-founded relation ~x0 of ~x1 ~
is neither a true list of symbols nor :ALL."
ruler-extenders fn)))
ruler-extenders))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define macro-required-args ((mac symbolp) (wrld plist-worldp))
:returns (required-args "A @(tsee symbol-listp).")
:verify-guards nil
:parents (world-queries)
:short "Required arguments of a macro, in order."
:long
"<p>
The arguments of a macro form a list that
optionally starts with @('&whole') followed by another symbol,
continues with zero or more symbols that do not start with @('&')
which are the required arguments,
and possibly ends with
a symbol starting with @('&') followed by more things.
</p>
<p>
After removing @('&whole') and the symbol following it
(if the list of arguments starts with @('&whole')),
we collect all the arguments until
either the end of the list is reached
or a symbol starting with @('&') is encountered.
</p>
<p>
See @(tsee macro-required-args+) for
a logic-friendly variant of this utility.
</p>"
(b* ((all-args (macro-args mac wrld)))
(if (null all-args)
nil
(if (eq (car all-args) '&whole)
(macro-required-args-aux (cddr all-args) nil)
(macro-required-args-aux all-args nil))))
:prepwork
((define macro-required-args-aux ((args true-listp)
(rev-result symbol-listp))
:returns (final-result) ; SYMBOL-LISTP
:verify-guards nil
(if (endp args)
(reverse rev-result)
(b* ((arg (car args)))
(if (lambda-keywordp arg)
(reverse rev-result)
(macro-required-args-aux (cdr args)
(cons arg rev-result))))))))
(define macro-required-args+ ((mac (macro-namep mac wrld))
(wrld plist-worldp))
:returns (required-args symbol-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee macro-required-args)."
:long
"<p>
This returns the same result as @(tsee macro-required-args),
but it has a stronger guard,
is guard-verified,
and includes run-time checks (which should always succeed)
that allows us to prove the return type theorem and to verify guards
without strengthening the guard on @('wrld').
</p>"
(b* ((all-args (macro-args+ mac wrld)))
(if (null all-args)
nil
(if (eq (car all-args) '&whole)
(macro-required-args+-aux mac (cddr all-args) nil)
(macro-required-args+-aux mac all-args nil))))
:prepwork
((define macro-required-args+-aux ((mac symbolp)
(args true-listp)
(rev-result symbol-listp))
:returns (final-result symbol-listp
:hyp (symbol-listp rev-result))
(if (endp args)
(reverse rev-result)
(b* ((arg (car args)))
(if (lambda-keywordp arg)
(reverse rev-result)
(if (symbolp arg)
(macro-required-args+-aux mac
(cdr args)
(cons arg rev-result))
(raise "Internal error: ~
the required macro argument ~x0 of ~x1 is not a symbol."
arg mac))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define macro-keyword-args ((mac symbolp) (wrld plist-worldp))
:returns (keyword-args "A @(tsee symbol-alistp).")
:verify-guards nil
:parents (world-queries)
:short "Keyword arguments of a macro, in order, with their default values."
:long
(xdoc::topstring
(xdoc::p
"Starting from the full argument list of the macro,
first we find @('&key') in the list;
if not found, we return @('nil') (i.e. no keyword arguments).
Otherwise, we scan and collect information from the remaining arguments,
until we reach either the end of the macro argument list
or a symbol starting with @('&...').")
(xdoc::p
"Keyword arguments have one of the forms
@('name'), @('(name \'default)'), @('(name \'default predicate)'),
where @('name') is the argument name (a symbol)
@('default') its default value (quoted),
and @('predicate') is another symbol.
When we scan a keyword argument,
we put name and default value as a pair into an alist.")
(xdoc::p
"See @(tsee macro-keyword-args) for
a logic-friendly variant of this utility."))
(b* ((all-args (macro-args mac wrld))
(args-after-&key (cdr (member-eq '&key all-args)))
(keyword-args (macro-keyword-args-aux args-after-&key)))
keyword-args)
:prepwork
((define macro-keyword-args-aux ((args true-listp))
:returns keyword-args ; SYMBOL-ALISTP
:verify-guards nil
:parents nil
(b* (((when (endp args)) nil)
(arg (car args))
((when (lambda-keywordp arg)) nil)
(name (if (atom arg) arg (first arg)))
(default (if (atom arg) nil (unquote (second arg)))))
(acons name default (macro-keyword-args-aux (cdr args)))))))
(define macro-keyword-args+ ((mac (macro-namep mac wrld))
(wrld plist-worldp))
:returns (keyword-args symbol-alistp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee macro-keyword-args)."
:long
(xdoc::topstring-p
"This returns the same result as @(tsee macro-keyword-args),
but it has a stronger guard,
is guard-verified,
and includes run-time checks (which should always succeed)
that allow us to prove the return type theorem and to verify the guards
without strengthening the guard on @('wrld').")
(b* ((all-args (macro-args+ mac wrld))
(args-after-&key (cdr (member-eq '&key all-args)))
(keyword-args (macro-keyword-args+-aux mac args-after-&key)))
keyword-args)
:prepwork
((define macro-keyword-args+-aux ((mac symbolp) args)
:returns (keyword-args symbol-alistp)
:verify-guards :after-returns
:parents nil ; override default
(b* (((when (atom args)) nil)
(arg (car args))
((when (lambda-keywordp arg)) nil)
((when (symbolp arg))
(acons arg nil (macro-keyword-args+-aux mac (cdr args))))
((unless (and (consp arg)
(symbolp (first arg))
(consp (cdr arg))
(consp (second arg))
(eq (car (second arg)) 'quote)
(consp (cdr (second arg)))))
(raise "Internal error: ~
the keyword macro argument ~x0 of ~x1 ~
does not have the expected form."
arg mac)))
(acons (first arg)
(unquote (second arg))
(macro-keyword-args+-aux mac (cdr args)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define thm-formula ((thm symbolp) (wrld plist-worldp))
:returns (formula "A @(tsee pseudo-termp).")
:parents (world-queries)
:short "Formula of a named theorem."
:long
"<p>
This is a specialization of @(tsee formula) to named theorems,
for which the second argument of @(tsee formula) is immaterial.
Since @(tsee formula) is in program mode only because of
the code that handles the cases in which the first argument
is not the name of a theorem,
we avoid calling @(tsee formula) and instead replicate
the code that handles the case in which
the first argument is the name of a theorem;
thus, this utility is in logic mode and guard-verified.
</p>
<p>
See @(tsee thm-formula+) for a logic-friendly variant of this utility.
</p>"
(getpropc thm 'theorem nil wrld))
(define thm-formula+ ((thm (theorem-namep thm wrld))
(wrld plist-worldp))
:returns (formula pseudo-termp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee thm-formula)."
:long
"<p>
This returns the same result as @(tsee thm-formula),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (thm-formula thm wrld)))
(if (pseudo-termp result)
result
(raise "Internal error: ~
the FORMULA property ~x0 of ~x1 is not a pseudo-term."
result thm))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define classes ((thm symbolp) (wrld plist-worldp))
:returns (classes "An @(tsee alistp)
from @(tsee keywordp) to @(tsee keyword-value-listp).")
:parents (world-queries)
:short "Rule classes of a theorem."
:long
"<p>
These form a value of type @('keyword-to-keyword-value-list-alistp'),
which is defined in @('[books]/system/pseudo-good-worldp.lisp').
</p>
<p>
See @(tsee classes+) for a logic-friendly variant of this utility.
</p>"
(getpropc thm 'classes nil wrld))
(define classes+ ((thm (theorem-namep thm wrld))
(wrld plist-worldp))
:returns (classes keyword-to-keyword-value-list-alistp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee classes)."
:long
"<p>
This returns the same result as @(tsee classes),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (classes thm wrld)))
(if (keyword-to-keyword-value-list-alistp result)
result
(raise "Internal error: ~
the rule classes ~x0 of ~x1 are not an alist
from keywords to keyword-value lists."
result thm))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define induction-machine ((fn symbolp) (wrld plist-worldp))
:returns (result "A @('pseudo-induction-machinep').")
:parents (world-queries)
:short "Induction machine of a named logic-mode (singly) recursive function."
:long
"<p>
This is a list of @('tests-and-calls') records
(see the ACL2 source code for information on these records),
each of which contains zero or more recursive calls
along with the tests that lead to them.
The induction machine is a value of type @('pseudo-induction-machinep'),
which is defined in @('[books]/system/pseudo-good-worldp.lisp').
</p>
<p>
Note that
induction is not directly supported for mutually recursive functions.
</p>
<p>
See @(tsee induction-machine+) for a logic-friendly variant of this utility.
</p>"
(getpropc fn 'induction-machine nil wrld))
(define induction-machine+ ((fn (and (logic-function-namep fn wrld)
(= 1 (len (irecursivep+ fn wrld)))))
(wrld plist-worldp))
:returns (result (pseudo-induction-machinep fn result))
:parents (world-queries)
:short "Logic-friendly variant of @(tsee induction-machine)."
:long
"<p>
This returns the same result as @(tsee induction-machine),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (induction-machine fn wrld)))
(if (pseudo-induction-machinep fn result)
result
(raise "Internal error: ~
the INDUCTION-MACHINE property ~x0 of ~x1 ~
does not have the expected form."
result fn))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define pseudo-tests-and-callp (x)
:returns (yes/no booleanp)
:parents (world-queries)
:short "Recognize well-formed @('tests-and-call') records."
:long
"<p>
A @('tests-and-call') record is defined as
</p>
@({
(defrec tests-and-call (tests call) nil)
})
<p>
(see the ACL2 source code).
</p>
<p>
In a well-formed @('tests-and-call') record,
@('tests') must be a list of terms and
@('call') must be a term.
</p>
<p>
This recognizer is analogous to @('pseudo-tests-and-callsp')
in @('[books]/system/pseudo-good-worldp.lisp')
for @('tests-and-calls') records.
</p>"
(case-match x
(('tests-and-call tests call)
(and (pseudo-term-listp tests)
(pseudo-termp call)))
(& nil))
///
(defrule weak-tests-and-call-p-when-pseudo-tests-and-callp
(implies (pseudo-tests-and-callp x)
(weak-tests-and-call-p x))))
(std::deflist pseudo-tests-and-call-listp (x)
(pseudo-tests-and-callp x)
:parents (world-queries)
:short "Recognize true lists of well-formed @('tests-and-call') records."
:true-listp t
:elementp-of-nil nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define recursive-calls ((fn symbolp) (wrld plist-worldp))
:returns (calls-with-tests "A @(tsee pseudo-tests-and-call-listp).")
:mode :program
:parents (world-queries)
:short "Recursive calls of a named non-mutually-recursive function,
along with the controlling tests."
:long
"<p>
For singly recursive logic-mode functions,
this is similar to the result of @(tsee induction-machine),
but each record has one recursive call (instead of zero or more),
and there is exactly one record for each recursive call.
</p>
<p>
This utility works on both logic-mode and program-mode functions
(if the program-mode functions have an @('unnormalized-body') property).
This utility should not be called on a function that is
mutually recursive with other functions;
it must be called only on singly recursive functions,
or on non-recursive functions (the result is @('nil') in this case).
</p>
<p>
This utility may be extended to handle also mutually recursive functions.
</p>
<p>
If the function is in logic mode and recursive,
we obtain its ruler extenders and pass them to
the built-in function @('termination-machine').
Otherwise, we pass the default ruler extenders.
</p>"
(b* ((ruler-extenders (if (and (logicp fn wrld)
(irecursivep fn wrld))
(ruler-extenders fn wrld)
(default-ruler-extenders wrld))))
(termination-machine
(list fn) (ubody fn wrld) nil nil ruler-extenders)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define fundef-disabledp ((fn (function-namep fn (w state))) state)
:returns (yes/no "A @(tsee booleanp).")
:mode :program
:parents (world-queries)
:short "Check if the definition of a named function is disabled."
(if (member-equal `(:definition ,fn) (disabledp fn)) t nil))
(define fundef-enabledp ((fn (function-namep fn (w state))) state)
:returns (yes/no "A @(tsee booleanp).")
:mode :program
:parents (world-queries)
:short "Check if the definition of a named function is enabled."
(not (fundef-disabledp fn state)))
(define rune-disabledp ((rune (runep rune (w state))) state)
:returns (yes/no "A @(tsee booleanp).")
:mode :program
:parents (world-queries)
:short "Check if a @(see rune) is disabled."
(if (member-equal rune (disabledp (cadr rune))) t nil))
(define rune-enabledp ((rune (runep rune (w state))) state)
:returns (yes/no "A @(tsee booleanp).")
:mode :program
:parents (world-queries)
:short "Check if a @(see rune) is enabled."
(not (rune-disabledp rune state)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define known-packages (state)
:returns (pkg-names "A @(tsee string-listp).")
:parents (world-queries)
:short "List of names of the known packages, in chronological order."
:long
"<p>
See @(tsee known-packages+) for a logic-friendly variant of this utility.
</p>"
(reverse (strip-cars (known-package-alist state))))
(define known-packages+ (state)
:returns (pkg-names string-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee known-packages)."
:long
"<p>
This returns the same result as @(tsee known-packages),
but it includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('state').
</p>"
(b* ((result (known-packages state)))
(if (string-listp result)
result
(raise "Internal error: ~
the list of keys ~x0 of the alist of known packages ~
is not a true list of strings."
result))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define included-books ((wrld plist-worldp))
:returns (result "A @(tsee string-listp).")
:verify-guards nil
:parents (world-queries)
:short "List of full pathnames of all books currently included
(directly or indirectly)."
(strip-cars (global-val 'include-book-alist wrld)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(std::deflist pseudo-event-landmark-listp (x)
(pseudo-event-landmarkp x)
:parents (world-queries)
:short "Recognize true lists of event landmarks."
:long
"<p>
See @('pseudo-event-landmarkp')
in @('[books]/system/pseudo-good-worldp.lisp').
</p>"
:true-listp t
:elementp-of-nil nil)
(std::deflist pseudo-command-landmark-listp (x)
(pseudo-command-landmarkp x)
:parents (world-queries)
:short "Recognize true lists of command landmarks."
:long
"<p>
See @('pseudo-command-landmarkp')
in @('[books]/system/pseudo-good-worldp.lisp').
</p>"
:true-listp t
:elementp-of-nil nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define event-landmark-names ((event pseudo-event-landmarkp))
:returns (names "A @('string-or-symbol-listp').")
:verify-guards nil
:parents (world-queries)
:short "Names introduced by an event landmark."
:long
"<p>
Each event landmark introduces zero or more names into the @(see world).
See @('pseudo-event-landmarkp')
in @('[books]/system/pseudo-good-worldp.lisp'),
and the description of event tuples in the ACL2 source code.
</p>"
(let ((namex (access-event-tuple-namex event)))
(cond ((equal namex 0) nil) ; no names
((consp namex) namex) ; list of names
(t (list namex))))) ; single name
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define fresh-namep-msg-weak ((name symbolp) type (wrld plist-worldp))
:guard (member-eq type
'(function macro const stobj constrained-function nil))
:returns (msg/nil "A message (see @(tsee msg)) or @('nil').")
:mode :program
:parents (world-queries)
:short "Return either @('nil') or a message indicating why the name is not
a legal new name."
:long
"<p>
This helper function for @(tsee fresh-namep-msg) avoids the ``virginity''
check ensuring that the name is not already defined in raw Lisp. See @(tsee
fresh-namep-msg).
</p>"
(flet ((not-new-namep-msg (name wrld)
;; It is tempting to report that the properties
;; 'global-value, 'table-alist, 'table-guard are
;; not relevant for this check. But that would
;; probably make the message confusing.
(let ((old-type (logical-name-type name wrld t)))
(cond
(old-type
(msg "~x0 is already the name for a ~s1."
name
(case old-type
(function "function")
(macro "macro")
(const "constant")
(stobj "stobj")
(constrained-function
"constrained function"))))
(t
(msg "~x0 has properties in the world; it is ~
not a new name."
name))))))
(cond
((mv-let (ctx msg)
(chk-all-but-new-name-cmp name 'fresh-namep-msg type wrld)
(and ctx ; it's an error
msg)))
((not (new-namep name wrld))
(not-new-namep-msg name wrld))
(t (case type
(const
(and (not (legal-constantp name))
;; A somewhat more informative error message is produced by
;; chk-legal-defconst-name, but I think the following suffices.
(msg "~x0 is not a legal constant name."
name)))
(stobj
(and (not (new-namep (the-live-var name) wrld))
(not-new-namep-msg (the-live-var name) wrld)))
(t nil))))))
(define fresh-namep-msg ((name symbolp) type (wrld plist-worldp) state)
:guard (member-eq type
'(function macro const stobj constrained-function nil))
:returns (mv (erp "Always @('nil').")
(msg/nil "A message (see @(tsee msg)) or @('nil').")
state)
:mode :program
:parents (world-queries)
:short "Return either @('nil') or a message indicating why the name is not
a legal new name."
:long
"<p>
Returns an <see topic='@(url error-triple)'>error triple</see>
@('(mv nil msg/nil state)'), where @('msg/nil')
is either @('nil') or a message (see @(tsee msg)) indicating why the given
name is not legal for a definition of the given type: @('function') for
@(tsee defun), @('macro') for @(tsee defmacro), @('const') for @(tsee
defconst), @('stobj') for @(tsee defstobj), @('constrained-function') for
@(tsee defchoose), and otherwise @('nil') (for other kinds of @(see events),
for example @(tsee defthm) and @(tsee deflabel)). See @(see name).
</p>
<p>
WARNING: This is an incomplete check in the case of a stobj name, because
the field names required for a more complete check are not supplied as
inputs.
</p>
<p>
Implementation Note. This function modifies @(see state), because the check
for legality of new definitions (carried out by ACL2 source function
@('chk-virgin-msg')) modifies state. That modification is necessary because
for all we know, raw Lisp is adding or removing function definitions that we
don't know about without our having modified state; so logically, we pop the
oracle when making this check. End of Implementation Note.
</p>"
(let ((msg (fresh-namep-msg-weak name type wrld)))
(cond (msg (value msg))
(t (mv-let (msg state)
(chk-virgin-msg name type wrld state)
(value msg))))))
(define chk-fresh-namep ((name symbolp) type ctx (wrld plist-worldp) state)
:guard (member-eq type
'(function macro const stobj constrained-function nil))
:returns (mv erp val state)
:mode :program
:parents (world-queries)
:short "Check whether name is a legal new name."
:long
"<p>
Returns an <see topic='@(url error-triple)'>error triple</see>
@('(mv erp val state)') where @('erp') is
@('nil') if and only if name is a legal new name, and @('val') is
irrelevant. If @('erp') is not nil, then an explanatory error message is
printed.
</p>
<p>
For more information about legality of new names see @(tsee fresh-namep-msg),
which returns an <see topic='@(url error-triple)'>error triple</see>,
@('(mv nil msg/nil state)'). When
non-@('nil'), the value @('msg/nil') provides the message printed by
@('chk-fresh-namep').
</p>"
(er-let* ((msg (fresh-namep-msg name type wrld state))) ; never an error
(cond (msg (er soft ctx "~@0" msg))
(t (value nil)))))
|
16781
|
; System Utilities -- World Queries
;
; Copyright (C) 2018 Kestrel Institute (http://www.kestrel.edu)
; Copyright (C) 2018 Regents of the University of Texas
;
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;
; Authors:
; <NAME> (<EMAIL>)
; <NAME> (<EMAIL>)
; <NAME> (<EMAIL>)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(include-book "xdoc/constructors" :dir :system)
(include-book "std/util/deflist" :dir :system)
(include-book "std/util/defrule" :dir :system)
(include-book "system/kestrel" :dir :system)
(include-book "system/pseudo-good-worldp" :dir :system)
(include-book "term-function-recognizers")
(local (include-book "std/typed-lists/symbol-listp" :dir :system))
(local (include-book "arglistp-theorems"))
(local (include-book "world-theorems"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc world-queries
:parents (system-utilities-non-built-in)
:short "Utilities to query @(see world)s."
:long
"<p>
These complement the world query utilities
in the <see topic='@(url system-utilities)'>built-in system utilities</see>.
</p>
<p>
Many of these world query utilities come in two variants:
a ``fast'' one and a ``logic-friendly'' one.
The former has relatively weak and no (strong) return type theorems;
the latter has stronger guards and some run-time checks
that are believed to never fail
and that enable the proof of (stronger) return type theorems
without having to assume stronger properties in the guard
of the @(see world) arguments.
The logic-friendly variants are helpful
to prove properties (including verifying guards)
of logic-mode code that calls them,
but the fast variants avoid the performance penalty
of the always-satisfied run-time checks,
when proving properties of the code that calls them is not a focus
(e.g. in program-mode code).
</p>
<p>
The built-in world query utilities
have the characteristics of the fast variants.
Below we provide logic-friendly variants of
some built-in world query utilities.
</p>
<p>
The fast variants provided below are named in a way
that is ``consistent'' with the built-in world query utilities.
The logic-friendly world query utilities are named by adding @('+')
after the name of the corresponding fast world query utilities
(both built-in and provided below).
</p>")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define theorem-symbolp ((sym symbolp) (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Check if a symbol names a theorem,
i.e. it has a @('theorem') property."
:long
"<p>
This function is named in analogy to
the @(tsee function-symbolp) built-in system utility.
</p>"
(not (eq t (getpropc sym 'theorem t wrld))))
(define macro-symbolp ((sym symbolp) (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Check if a symbol names a macro,
i.e. it has a @('macro-args') property."
:long
"<p>
This function is named in analogy to
the @(tsee function-symbolp) built-in system utility.
</p>"
(not (eq t (getpropc sym 'macro-args t wrld))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(std::deflist function-symbol-listp (x wrld)
(function-symbolp x wrld)
:guard (and (symbol-listp x)
(plist-worldp wrld))
:parents (world-queries)
:short "Check if all the symbols in a list name functions."
:true-listp t)
(std::deflist theorem-symbol-listp (x wrld)
(theorem-symbolp x wrld)
:guard (and (symbol-listp x)
(plist-worldp wrld))
:parents (world-queries)
:short "Check if all the symbols in a list name theorems."
:true-listp t)
(std::deflist macro-symbol-listp (x wrld)
(macro-symbolp x wrld)
:guard (and (symbol-listp x)
(plist-worldp wrld))
:parents (world-queries)
:short "Check if all the symbols in a list name macros."
:true-listp t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define function-namep (x (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Recognize symbols that name functions."
:long
"<p>
This function is enabled because it is meant as an abbreviation.
Thus, theorems triggered by this function should be avoided.
</p>"
(and (symbolp x)
(function-symbolp x wrld))
:enabled t)
(define theorem-namep (x (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Recognize symbols that name theorems."
:long
"<p>
This function is enabled because it is meant as an abbreviation.
Thus, theorems triggered by this function should be avoided.
</p>"
(and (symbolp x)
(theorem-symbolp x wrld))
:enabled t)
(define macro-namep (x (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Recognize symbols that name macros."
:long
"<p>
This function is enabled because it is meant as an abbreviation.
Thus, theorems triggered by this function should be avoided.
</p>"
(and (symbolp x)
(macro-symbolp x wrld))
:enabled t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(std::deflist function-name-listp (x wrld)
(function-namep x wrld)
:guard (plist-worldp wrld)
:parents (world-queries)
:short "Recognize true lists of symbols that name functions."
:true-listp t)
(std::deflist theorem-name-listp (x wrld)
(theorem-namep x wrld)
:guard (plist-worldp wrld)
:parents (world-queries)
:short "Recognize true lists of symbols that name theorems."
:true-listp t)
(std::deflist macro-name-listp (x wrld)
(macro-namep x wrld)
:guard (plist-worldp wrld)
:parents (world-queries)
:short "Recognize true lists of symbols that name macros."
:true-listp t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define logical-name-listp (names (wrld plist-worldp))
;; we cannot use STD::DEFLIST to define LOGICAL-NAME-LISTP
;; because STD::DEFLIST attempts to prove that LOGICAL-NAMEP is boolean,
;; but it is not
:returns (yes/no booleanp)
:verify-guards nil
:parents (world-queries)
:short "Recognize true lists of logical names."
:long
"<p>
See @('logical-namep') in the ACL2 source code.
</p>"
(cond ((atom names) (null names))
(t (and (logical-namep (car names) wrld)
(logical-name-listp (cdr names) wrld)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define logic-function-namep (x (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Recognize symbols that name logic-mode functions."
:long
"<p>
This function is enabled because it is meant as an abbreviation.
Thus, theorems triggered by this function should be avoided.
</p>"
(and (function-namep x wrld)
(logicp x wrld))
:enabled t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define formals+ ((fn (or (function-namep fn wrld)
(pseudo-lambdap fn)))
(wrld plist-worldp-with-formals))
:returns (formals symbol-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee formals)."
:long
"<p>
This returns the same result as @(tsee formals) on named functions,
but it has a stronger guard for named functions
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>
<p>
This utility also operates on lambda expressions, unlike @(tsee formals).
</p>"
(b* ((result (cond ((symbolp fn) (formals fn wrld))
(t (lambda-formals fn)))))
(if (symbol-listp result)
result
(raise "Internal error: ~
the formals ~x0 of ~x1 are not a true list of symbols."
result fn)))
:guard-hints (("Goal" :in-theory (enable pseudo-lambdap))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define arity+ ((fn (or (function-namep fn wrld)
(pseudo-lambdap fn)))
(wrld plist-worldp-with-formals))
:returns (result natp
:hyp (or (function-namep fn wrld) (pseudo-lambdap fn))
:hints (("Goal" :in-theory (enable arity pseudo-lambdap))))
:parents (world-queries)
:short "Logic-friendly variant of @(tsee arity)."
:long
"<p>
This returns the same result as @(tsee arity),
but it has a stronger guard.
</p>"
(arity fn wrld)
:guard-hints (("Goal" :in-theory (enable pseudo-lambdap))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define stobjs-in+ ((fn (function-namep fn wrld))
(wrld plist-worldp))
:returns (result symbol-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee stobjs-in)."
:long
"<p>
This returns the same result as @(tsee stobjs-in),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (stobjs-in fn wrld)))
(if (symbol-listp result)
result
(raise "Internal error: ~
the STOBJS-IN property ~x0 of ~x1 is not a true list of symbols."
result fn))))
(define stobjs-out+ ((fn (function-namep fn wrld))
(wrld plist-worldp))
:guard (not (member-eq fn *stobjs-out-invalid*))
:returns (result symbol-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee stobjs-out)."
:long
"<p>
This returns the same result as @(tsee stobjs-out),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>
<p>
The function must not be in @('*stobjs-out-invalid*'),
because in that case its output stobjs depend on how it is called.
</p>"
(b* ((result (stobjs-out fn wrld)))
(if (symbol-listp result)
result
(raise "Internal error: ~
the STOBJS-OUT property ~x0 of ~x1 is not a true list of symbols."
result fn))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define macro-args+ ((mac (macro-namep mac wrld))
(wrld plist-worldp))
:returns (result true-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee macro-args)."
:long
"<p>
This returns the same result as the built-in system utility @('macro-args')
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (macro-args mac wrld)))
(if (true-listp result)
result
(raise "Internal error: ~
the MACRO-ARGS property ~x0 of ~x1 is not a true list."
result mac))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define definedp ((fn symbolp) (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Check if a named logic-mode function is defined."
:long
"<p>
We check if the function symbol has an @('unnormalized-body') property.
</p>
<p>
Note that some program-mode functions may be defined
but not have an @('unnormalized-body') property.
</p>
<p>
See @(tsee definedp+) for a logic-friendly variant of this utility.
</p>"
(if (getpropc fn 'unnormalized-body nil wrld) t nil))
(define definedp+ ((fn (logic-function-namep fn wrld)) (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee definedp)."
:long
"<p>
This returns the same result as @(tsee definedp),
but it has a stronger guard.
</p>"
(definedp fn wrld))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define primitivep ((fn symbolp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Check if a named function is @(see primitive)."
:long
"<p>
See @(tsee primitivep+) for a logic-friendly variant of this utility.
</p>"
(and (member-eq fn (strip-cars *primitive-formals-and-guards*)) t))
(define primitivep+ ((fn (function-namep fn wrld)) (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee primitivep)."
:long
"<p>
This returns the same result as @(tsee guard-verified-p),
but it has a stronger guard.
The guard requires an extra @(see world) argument,
which is usually available when doing system programming.
</p>"
(declare (ignore wrld))
(primitivep fn))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define guard-verified-p ((fn/thm symbolp) (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Check if a named function or theorem is @(tsee guard)-verified."
:long
"<p>
See @(tsee guard-verified-p+) for a logic-friendly variant of this utility.
</p>"
(eq (symbol-class fn/thm wrld) :common-lisp-compliant))
(define guard-verified-p+ ((fn/thm (or (function-namep fn/thm wrld)
(theorem-namep fn/thm wrld)))
(wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee guard-verified-p)."
:long
"<p>
This returns the same result as @(tsee guard-verified-p),
but it has a stronger guard.
</p>"
(guard-verified-p fn/thm wrld))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define ubody ((fn pseudo-termfnp) (wrld plist-worldp))
:returns (body "A @(tsee pseudo-termp).")
:parents (world-queries)
:short "Unnormalized body of a named logic-mode function,
or body of a lambda expression."
:long
"<p>
This is a specialization of @(tsee body)
with @('nil') as the second argument.
Since @(tsee body) is not guard-verified only because of
the code that handles the case in which the second argument is non-@('nil'),
we avoid calling @(tsee body) and instead replicate
the code that handles the case in which the second argument is @('nil');
thus, this utility is guard-verified.
</p>
<p>
If the argument named function is not defined, this utility returns @('nil').
</p>
<p>
Not that some program-mode functions may be defined
but not have an @('unnormalized-body') property.
</p>
<p>
See @(tsee ubody+) for a logic-friendly variant of this utility.
</p>"
(cond ((symbolp fn) (getpropc fn 'unnormalized-body nil wrld))
(t (lambda-body fn)))
:guard-hints (("Goal" :in-theory (enable pseudo-termfnp pseudo-lambdap))))
(define ubody+ ((fn (or (and (logic-function-namep fn wrld)
(definedp fn wrld))
(pseudo-lambdap fn)))
(wrld plist-worldp))
:returns (body pseudo-termp
:hyp (or (symbolp fn) (pseudo-lambdap fn))
:hints (("Goal" :in-theory (enable pseudo-lambdap))))
:parents (world-queries)
:short "Logic-friendly variant of @(tsee ubody)."
:long
"<p>
This returns the same result as @(tsee ubody),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (ubody fn wrld)))
(if (pseudo-termp result)
result
(raise "Internal error: ~
the unnormalized body ~x0 of ~x1 is not a pseudo-term."
result fn)))
:guard-hints (("Goal" :in-theory (enable pseudo-termfnp))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define uguard ((fn pseudo-termfnp) (wrld plist-worldp))
:returns (guard "A @(tsee pseudo-termp).")
:parents (world-queries)
:short "Unoptimized guard of a named function or of a lambda expression."
:long
"<p>
This is a specialization of
<see topic='@(url system-utilities)'>@('guard')</see>
with @('nil') as the second argument.
Since @(tsee body) is in program mode only because of
the code that handles the case in which the second argument is non-@('nil'),
we avoid calling @(tsee guard) and instead replicate
the code that handles the case in which the second argument is @('nil');
thus, this utility is in logic mode and guard-verified.
</p>
<p>
See @(tsee uguard+) for a logic-friendly variant of this utility.
</p>"
(cond ((symbolp fn) (getpropc fn 'guard *t* wrld))
(t *t*)))
(define uguard+ ((fn (or (function-namep fn wrld)
(pseudo-lambdap fn)))
(wrld plist-worldp))
:returns (guard pseudo-termp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee uguard)."
:long
"<p>
This returns the same result as @(tsee uguard),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (uguard fn wrld)))
(if (pseudo-termp result)
result
(raise "Internal error: ~
the guard ~x0 of ~x1 is not a pseudo-term."
result fn)))
:guard-hints (("Goal" :in-theory (enable pseudo-termfnp))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define non-executablep ((fn symbolp) (wrld plist-worldp))
:returns (status "@('t'), @('nil'), or @(':program').")
:parents (world-queries)
:short "@(see Non-executable) status of a named logic-mode defined function."
:long
"<p>
See @(tsee non-executablep+) for a logic-friendly variant of this utility.
</p>"
(getpropc fn 'non-executablep nil wrld))
(define non-executablep+ ((fn (function-namep fn wrld))
(wrld plist-worldp))
:returns (nonexec (or (booleanp nonexec) (eq nonexec :program)))
:parents (world-queries)
:short "Logic-friendly variant of @(tsee non-executablep)."
:long
"<p>
This returns the same result as @(tsee non-executablep),
but it has a stronger guard
and includes run-time checks (which should always succeed) on the result
that allow us to prove the return type theorems
without strengthening the guard on @('wrld').
</p>"
(b* ((result (non-executablep fn wrld))
((unless (or (booleanp result)
(eq result :program)))
(raise "Internal error: ~
the non-executable status ~x0 of ~x1 is not ~
T, NIL, or :PROGRAM."
result fn))
((when (and (logicp fn wrld)
(eq result :program)))
(raise "Internal error: ~
the non-executable status of the logic-mode function ~x0 ~
is :PROGRAM instead of T or NIL."
fn)))
result)
///
(more-returns
(nonexec booleanp
:hyp (logicp fn wrld)
:name booleanp-of-non-executablep+-when-logicp)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define unwrapped-nonexec-body ((fn symbolp) (wrld plist-worldp))
:returns (unwrapped-body "A @(tsee pseudo-termp).")
:verify-guards nil
:parents (world-queries)
:short "Body of a named logic-mode defined non-executable function,
without the ``non-executable wrapper''."
:long
"<p>
@(tsee defun-nx) generates
a logic-mode function whose body is wrapped as follows:
</p>
@({
(return-last 'progn
(throw-nonexec-error 'fn
(cons arg1 ... (cons argN 'nil)...))
body)
})
<p>
If @(tsee defun) is used for a logic-mode function with
<see topic='@(url non-executable)'>@(':non-executable')</see> set to @('t'),
the submitted body (once translated) must be wrapped as above.
</p>
<p>
This utility returns
the unwrapped body of a logic-mode non-executable function @('fn'),
by removing the wrapper shown above.
</p>
<p>
See @(tsee unwrapped-nonexec-body+) for
a logic-friendly variant of this utility.
</p>"
(fourth (ubody fn wrld)))
(define unwrapped-nonexec-body+ ((fn (and (logic-function-namep fn wrld)
(definedp fn wrld)
(non-executablep fn wrld)))
(wrld plist-worldp-with-formals))
:returns (unwrapped-body pseudo-termp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee unwrapped-nonexec-body)."
:long
"<p>
This returns the same result as @(tsee unwrapped-nonexec-body),
but it has a stronger guard,
is guard-verified,
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
This utility also includes a run-time check (which should always succeed)
that the wrapper around the body has the expected form,
via the built-in function @('throw-nonexec-error-p');
this allows us to verify the guards
without strengthening the guard of @('wrld').
</p>"
(b* ((body (ubody+ fn wrld))
((unless (and (throw-nonexec-error-p body fn (formals+ fn wrld))
(consp (cdddr body))))
(raise "Internal error: ~
the body ~x0 of the non-executable function ~x1 ~
does not have the expected wrapper."
body fn))
(unwrapped-body (fourth body))
((unless (pseudo-termp unwrapped-body))
(raise "Internal error: ~
the unwrapped body ~x0 of the non-executable function ~x1 ~
is not a pseudo-term."
unwrapped-body fn)))
unwrapped-body))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define number-of-results ((fn symbolp) (wrld plist-worldp))
:guard (not (member-eq fn *stobjs-out-invalid*))
:returns (n natp "Actually a @(tsee posp).")
:parents (world-queries)
:short "Number of values returned by a named function."
:long
"<p>
This is 1, unless the function uses @(tsee mv)
(directly, or indirectly by calling another function that does)
to return multiple values.
</p>
<p>
The number of results of the function
is the length of its @(tsee stobjs-out) list.
</p>
<p>
The function must not be in @('*stobjs-out-invalid*'),
because in that case the number of its results depends on how it is called.
</p>
<p>
See @(tsee number-of-results+) for a logic-friendly variant of this utility.
</p>"
(len (stobjs-out fn wrld)))
(define number-of-results+ ((fn (function-namep fn wrld))
(wrld plist-worldp))
:guard (not (member-eq fn *stobjs-out-invalid*))
:returns (n posp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee number-of-results)."
:long
"<p>
This returns the same result as @(tsee number-of-results),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (number-of-results fn wrld)))
(if (posp result)
result
(prog2$
(raise "Internal error: ~
the STOBJS-OUT property of ~x0 is empty."
fn)
1)))) ; any POSP could be used here
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define no-stobjs-p ((fn symbolp) (wrld plist-worldp))
:guard (not (member-eq fn *stobjs-out-invalid*))
:returns (yes/no booleanp)
:verify-guards nil
:parents (world-queries)
:short "Check if a named function has no input or output @(see stobj)s."
:long
"<p>
The function must not be in @('*stobjs-out-invalid*'),
because in that case its (output) stobjs depend on how it is called.
</p>
<p>
See @(tsee no-stobjs-p+) for a logic-friendly variant of this utility.
</p>"
(and (all-nils (stobjs-in fn wrld))
(all-nils (stobjs-out fn wrld))))
(define no-stobjs-p+ ((fn (function-namep fn wrld))
(wrld plist-worldp))
:guard (not (member-eq fn *stobjs-out-invalid*))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee no-stobjs-p)."
:long
"<p>
This returns the same result as @(tsee no-stobjs-p),
but it has a stronger guard and is guard-verified.
</p>"
(and (all-nils (stobjs-in+ fn wrld))
(all-nils (stobjs-out+ fn wrld))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define irecursivep ((fn symbolp) (wrld plist-worldp))
:returns (clique "A @(tsee symbol-listp).")
:parents (world-queries)
:short "List of mutually recursive functions of which
the specified named function is a member,
based on the @(tsee defun) form that introduced this function,
or @('nil') if the specified function is not recursive."
:long
"<p>
This is a specialization of @(tsee recursivep)
with @('nil') as the second argument:
the @('i') that starts the name of @('irecursivep') conveys that
the result is based on the @(tsee defun) form that <i>introduced</i> @('fn').
</p>
<p>
See @(tsee irecursivep+) for a logic-friendly variant of this utility.
</p>"
(recursivep fn nil wrld))
(define irecursivep+ ((fn (logic-function-namep fn wrld))
(wrld plist-worldp))
:returns (clique symbol-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee irecursivep)."
:long
"<p>
This returns the same result as @(tsee irecursivep),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (irecursivep fn wrld)))
(if (symbol-listp result)
result
(raise "Internal error: ~
the RECURSIVEP property ~x0 of ~x1 is not a true list of symbols."
result fn))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define measure ((fn symbolp) (wrld plist-worldp))
:returns (measure "A @(tsee pseudo-termp).")
:verify-guards nil
:parents (world-queries)
:short "Measure expression of a named logic-mode recursive function."
:long
"<p>
See @(see xargs) for a discussion of the @(':measure') keyword.
</p>
<p>
See @(tsee measure+) for a logic-friendly variant of this utility.
</p>"
(b* ((justification (getpropc fn 'justification nil wrld)))
(access justification justification :measure)))
(define measure+ ((fn (and (logic-function-namep fn wrld)
(recursivep fn nil wrld)))
(wrld plist-worldp))
:returns (measure pseudo-termp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee measure)."
:long
"<p>
This returns the same result as @(tsee measure),
but it has a stronger guard,
is guard-verified,
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
This utility also includes a run-time check (which should always succeed)
on the form of the @('justification') property of the function
that allows us to verify the guards
without strengthening the guard of @('wrld').
</p>"
(b* ((justification (getpropc fn 'justification nil wrld))
((unless (weak-justification-p justification))
(raise "Internal error: ~
the JUSTIFICATION property ~x0 of ~x1 is not well-formed."
justification fn))
(measure (access justification justification :measure))
((unless (pseudo-termp measure))
(raise "Internal error: ~
the measure ~x0 of ~x1 is not a pseudo-term."
measure fn)))
measure))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define measured-subset ((fn symbolp) (wrld plist-worldp))
:returns (measured-subset "A @(tsee symbol-listp).")
:verify-guards nil
:parents (world-queries)
:short "Subset of the formal arguments
of a named logic-mode recursive function
that occur in its @(see measure) expression."
:long
"<p>
See @(tsee measured-subset+) for a logic-friendly variant of this utility.
</p>"
(b* ((justification (getpropc fn 'justification nil wrld)))
(access justification justification :subset)))
(define measured-subset+ ((fn (and (logic-function-namep fn wrld)
(recursivep fn nil wrld)))
(wrld plist-worldp))
:returns (measured-subset symbol-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee measured-subset)."
:long
"<p>
This returns the same result as @(tsee measured-subset),
but it has a stronger guard,
is guard-verified,
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
This utility also includes a run-time check (which should always succeed)
on the form of the @('justification') property of the function
that allows us to verify the guards
without strengthening the guard of @('wrld').
</p>"
(b* ((justification (getpropc fn 'justification nil wrld))
((unless (weak-justification-p justification))
(raise "Internal error: ~
the JUSTIFICATION property ~x0 of ~x1 is not well-formed."
justification fn))
(measured-subset (access justification justification :subset))
((unless (symbol-listp measured-subset))
(raise "Internal error: ~
the measured subset ~x0 of ~x1 is not a true list of symbols."
measured-subset fn)))
measured-subset))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define well-founded-relation ((fn symbolp) (wrld plist-worldp))
:returns (well-founded-relation "A @(tsee symbolp).")
:verify-guards nil
:parents (world-queries)
:short "Well-founded relation of a named logic-mode recursive function."
:long
"<p>
See @(see well-founded-relation-rule)
for a discussion of well-founded relations in ACL2,
including the @(':well-founded-relation') rule class.
</p>
<p>
See @(tsee well-founded-relation+) for
a logic-friendly variant of this utility.
</p>"
(b* ((justification (getpropc fn 'justification nil wrld)))
(access justification justification :rel)))
(define well-founded-relation+ ((fn (and (logic-function-namep fn wrld)
(recursivep fn nil wrld)))
(wrld plist-worldp))
:returns (well-founded-relation symbolp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee well-founded-relation)."
:long
"<p>
This returns the same result as @(tsee well-founded-relation),
but it has a stronger guard,
is guard-verified,
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
This utility also includes a run-time check (which should always succeed)
on the form of the @('justification') property of the function
that allows us to verify the guards
without strengthening the guard of @('wrld').
</p>"
(b* ((justification (getpropc fn 'justification nil wrld))
((unless (weak-justification-p justification))
(raise "Internal error: ~
the justification ~x0 of ~x1 is not well-formed."
justification fn))
(well-founded-relation (access justification justification :rel))
((unless (symbolp well-founded-relation))
(raise "Internal error: ~
the well-founded relation ~x0 of ~x1 is not a symbol."
well-founded-relation fn)))
well-founded-relation))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define ruler-extenders ((fn symbolp) (wrld plist-worldp))
:returns (ruler-extenders "A @(tsee symbol-listp) of @(':all').")
:verify-guards nil
:parents (world-queries)
:short "Ruler-extenders of a named logic-mode recursive function."
:long
"<p>
See @(see rulers) for background.
</p>
<p>
See @(tsee ruler-extenders+) for a logic-friendly variant of this utility.
</p>"
(b* ((justification (getpropc fn 'justification nil wrld)))
(access justification justification :ruler-extenders)))
(define ruler-extenders+ ((fn (and (logic-function-namep fn wrld)
(recursivep fn nil wrld)))
(wrld plist-worldp))
:returns (ruler-extenders (or (symbol-listp ruler-extenders)
(equal ruler-extenders :all)))
:parents (world-queries)
:short "Logic-friendly variant of @(tsee ruler-extenders)."
:long
"<p>
This returns the same result as @(tsee ruler-extenders),
but it has a stronger guard,
is guard-verified,
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
This utility also includes a run-time check (which should always succeed)
on the form of the @('justification') property of the function
that allows us to verify the guards
without strengthening the guard of @('wrld').
</p>"
(b* ((justification (getpropc fn 'justification nil wrld))
((unless (weak-justification-p justification))
(raise "Internal error: ~
the 'JUSTIFICATION property ~x0 of ~x1 is not well-formed."
justification fn))
(ruler-extenders (access justification justification :ruler-extenders))
((unless (or (symbol-listp ruler-extenders)
(eq ruler-extenders :all)))
(raise "Internal error: ~
the well-founded relation ~x0 of ~x1 ~
is neither a true list of symbols nor :ALL."
ruler-extenders fn)))
ruler-extenders))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define macro-required-args ((mac symbolp) (wrld plist-worldp))
:returns (required-args "A @(tsee symbol-listp).")
:verify-guards nil
:parents (world-queries)
:short "Required arguments of a macro, in order."
:long
"<p>
The arguments of a macro form a list that
optionally starts with @('&whole') followed by another symbol,
continues with zero or more symbols that do not start with @('&')
which are the required arguments,
and possibly ends with
a symbol starting with @('&') followed by more things.
</p>
<p>
After removing @('&whole') and the symbol following it
(if the list of arguments starts with @('&whole')),
we collect all the arguments until
either the end of the list is reached
or a symbol starting with @('&') is encountered.
</p>
<p>
See @(tsee macro-required-args+) for
a logic-friendly variant of this utility.
</p>"
(b* ((all-args (macro-args mac wrld)))
(if (null all-args)
nil
(if (eq (car all-args) '&whole)
(macro-required-args-aux (cddr all-args) nil)
(macro-required-args-aux all-args nil))))
:prepwork
((define macro-required-args-aux ((args true-listp)
(rev-result symbol-listp))
:returns (final-result) ; SYMBOL-LISTP
:verify-guards nil
(if (endp args)
(reverse rev-result)
(b* ((arg (car args)))
(if (lambda-keywordp arg)
(reverse rev-result)
(macro-required-args-aux (cdr args)
(cons arg rev-result))))))))
(define macro-required-args+ ((mac (macro-namep mac wrld))
(wrld plist-worldp))
:returns (required-args symbol-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee macro-required-args)."
:long
"<p>
This returns the same result as @(tsee macro-required-args),
but it has a stronger guard,
is guard-verified,
and includes run-time checks (which should always succeed)
that allows us to prove the return type theorem and to verify guards
without strengthening the guard on @('wrld').
</p>"
(b* ((all-args (macro-args+ mac wrld)))
(if (null all-args)
nil
(if (eq (car all-args) '&whole)
(macro-required-args+-aux mac (cddr all-args) nil)
(macro-required-args+-aux mac all-args nil))))
:prepwork
((define macro-required-args+-aux ((mac symbolp)
(args true-listp)
(rev-result symbol-listp))
:returns (final-result symbol-listp
:hyp (symbol-listp rev-result))
(if (endp args)
(reverse rev-result)
(b* ((arg (car args)))
(if (lambda-keywordp arg)
(reverse rev-result)
(if (symbolp arg)
(macro-required-args+-aux mac
(cdr args)
(cons arg rev-result))
(raise "Internal error: ~
the required macro argument ~x0 of ~x1 is not a symbol."
arg mac))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define macro-keyword-args ((mac symbolp) (wrld plist-worldp))
:returns (keyword-args "A @(tsee symbol-alistp).")
:verify-guards nil
:parents (world-queries)
:short "Keyword arguments of a macro, in order, with their default values."
:long
(xdoc::topstring
(xdoc::p
"Starting from the full argument list of the macro,
first we find @('&key') in the list;
if not found, we return @('nil') (i.e. no keyword arguments).
Otherwise, we scan and collect information from the remaining arguments,
until we reach either the end of the macro argument list
or a symbol starting with @('&...').")
(xdoc::p
"Keyword arguments have one of the forms
@('name'), @('(name \'default)'), @('(name \'default predicate)'),
where @('name') is the argument name (a symbol)
@('default') its default value (quoted),
and @('predicate') is another symbol.
When we scan a keyword argument,
we put name and default value as a pair into an alist.")
(xdoc::p
"See @(tsee macro-keyword-args) for
a logic-friendly variant of this utility."))
(b* ((all-args (macro-args mac wrld))
(args-after-&key (cdr (member-eq '&key all-args)))
(keyword-args (macro-keyword-args-aux args-after-&key)))
keyword-args)
:prepwork
((define macro-keyword-args-aux ((args true-listp))
:returns keyword-args ; SYMBOL-ALISTP
:verify-guards nil
:parents nil
(b* (((when (endp args)) nil)
(arg (car args))
((when (lambda-keywordp arg)) nil)
(name (if (atom arg) arg (first arg)))
(default (if (atom arg) nil (unquote (second arg)))))
(acons name default (macro-keyword-args-aux (cdr args)))))))
(define macro-keyword-args+ ((mac (macro-namep mac wrld))
(wrld plist-worldp))
:returns (keyword-args symbol-alistp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee macro-keyword-args)."
:long
(xdoc::topstring-p
"This returns the same result as @(tsee macro-keyword-args),
but it has a stronger guard,
is guard-verified,
and includes run-time checks (which should always succeed)
that allow us to prove the return type theorem and to verify the guards
without strengthening the guard on @('wrld').")
(b* ((all-args (macro-args+ mac wrld))
(args-after-&key (cdr (member-eq '&key all-args)))
(keyword-args (macro-keyword-args+-aux mac args-after-&key)))
keyword-args)
:prepwork
((define macro-keyword-args+-aux ((mac symbolp) args)
:returns (keyword-args symbol-alistp)
:verify-guards :after-returns
:parents nil ; override default
(b* (((when (atom args)) nil)
(arg (car args))
((when (lambda-keywordp arg)) nil)
((when (symbolp arg))
(acons arg nil (macro-keyword-args+-aux mac (cdr args))))
((unless (and (consp arg)
(symbolp (first arg))
(consp (cdr arg))
(consp (second arg))
(eq (car (second arg)) 'quote)
(consp (cdr (second arg)))))
(raise "Internal error: ~
the keyword macro argument ~x0 of ~x1 ~
does not have the expected form."
arg mac)))
(acons (first arg)
(unquote (second arg))
(macro-keyword-args+-aux mac (cdr args)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define thm-formula ((thm symbolp) (wrld plist-worldp))
:returns (formula "A @(tsee pseudo-termp).")
:parents (world-queries)
:short "Formula of a named theorem."
:long
"<p>
This is a specialization of @(tsee formula) to named theorems,
for which the second argument of @(tsee formula) is immaterial.
Since @(tsee formula) is in program mode only because of
the code that handles the cases in which the first argument
is not the name of a theorem,
we avoid calling @(tsee formula) and instead replicate
the code that handles the case in which
the first argument is the name of a theorem;
thus, this utility is in logic mode and guard-verified.
</p>
<p>
See @(tsee thm-formula+) for a logic-friendly variant of this utility.
</p>"
(getpropc thm 'theorem nil wrld))
(define thm-formula+ ((thm (theorem-namep thm wrld))
(wrld plist-worldp))
:returns (formula pseudo-termp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee thm-formula)."
:long
"<p>
This returns the same result as @(tsee thm-formula),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (thm-formula thm wrld)))
(if (pseudo-termp result)
result
(raise "Internal error: ~
the FORMULA property ~x0 of ~x1 is not a pseudo-term."
result thm))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define classes ((thm symbolp) (wrld plist-worldp))
:returns (classes "An @(tsee alistp)
from @(tsee keywordp) to @(tsee keyword-value-listp).")
:parents (world-queries)
:short "Rule classes of a theorem."
:long
"<p>
These form a value of type @('keyword-to-keyword-value-list-alistp'),
which is defined in @('[books]/system/pseudo-good-worldp.lisp').
</p>
<p>
See @(tsee classes+) for a logic-friendly variant of this utility.
</p>"
(getpropc thm 'classes nil wrld))
(define classes+ ((thm (theorem-namep thm wrld))
(wrld plist-worldp))
:returns (classes keyword-to-keyword-value-list-alistp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee classes)."
:long
"<p>
This returns the same result as @(tsee classes),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (classes thm wrld)))
(if (keyword-to-keyword-value-list-alistp result)
result
(raise "Internal error: ~
the rule classes ~x0 of ~x1 are not an alist
from keywords to keyword-value lists."
result thm))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define induction-machine ((fn symbolp) (wrld plist-worldp))
:returns (result "A @('pseudo-induction-machinep').")
:parents (world-queries)
:short "Induction machine of a named logic-mode (singly) recursive function."
:long
"<p>
This is a list of @('tests-and-calls') records
(see the ACL2 source code for information on these records),
each of which contains zero or more recursive calls
along with the tests that lead to them.
The induction machine is a value of type @('pseudo-induction-machinep'),
which is defined in @('[books]/system/pseudo-good-worldp.lisp').
</p>
<p>
Note that
induction is not directly supported for mutually recursive functions.
</p>
<p>
See @(tsee induction-machine+) for a logic-friendly variant of this utility.
</p>"
(getpropc fn 'induction-machine nil wrld))
(define induction-machine+ ((fn (and (logic-function-namep fn wrld)
(= 1 (len (irecursivep+ fn wrld)))))
(wrld plist-worldp))
:returns (result (pseudo-induction-machinep fn result))
:parents (world-queries)
:short "Logic-friendly variant of @(tsee induction-machine)."
:long
"<p>
This returns the same result as @(tsee induction-machine),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (induction-machine fn wrld)))
(if (pseudo-induction-machinep fn result)
result
(raise "Internal error: ~
the INDUCTION-MACHINE property ~x0 of ~x1 ~
does not have the expected form."
result fn))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define pseudo-tests-and-callp (x)
:returns (yes/no booleanp)
:parents (world-queries)
:short "Recognize well-formed @('tests-and-call') records."
:long
"<p>
A @('tests-and-call') record is defined as
</p>
@({
(defrec tests-and-call (tests call) nil)
})
<p>
(see the ACL2 source code).
</p>
<p>
In a well-formed @('tests-and-call') record,
@('tests') must be a list of terms and
@('call') must be a term.
</p>
<p>
This recognizer is analogous to @('pseudo-tests-and-callsp')
in @('[books]/system/pseudo-good-worldp.lisp')
for @('tests-and-calls') records.
</p>"
(case-match x
(('tests-and-call tests call)
(and (pseudo-term-listp tests)
(pseudo-termp call)))
(& nil))
///
(defrule weak-tests-and-call-p-when-pseudo-tests-and-callp
(implies (pseudo-tests-and-callp x)
(weak-tests-and-call-p x))))
(std::deflist pseudo-tests-and-call-listp (x)
(pseudo-tests-and-callp x)
:parents (world-queries)
:short "Recognize true lists of well-formed @('tests-and-call') records."
:true-listp t
:elementp-of-nil nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define recursive-calls ((fn symbolp) (wrld plist-worldp))
:returns (calls-with-tests "A @(tsee pseudo-tests-and-call-listp).")
:mode :program
:parents (world-queries)
:short "Recursive calls of a named non-mutually-recursive function,
along with the controlling tests."
:long
"<p>
For singly recursive logic-mode functions,
this is similar to the result of @(tsee induction-machine),
but each record has one recursive call (instead of zero or more),
and there is exactly one record for each recursive call.
</p>
<p>
This utility works on both logic-mode and program-mode functions
(if the program-mode functions have an @('unnormalized-body') property).
This utility should not be called on a function that is
mutually recursive with other functions;
it must be called only on singly recursive functions,
or on non-recursive functions (the result is @('nil') in this case).
</p>
<p>
This utility may be extended to handle also mutually recursive functions.
</p>
<p>
If the function is in logic mode and recursive,
we obtain its ruler extenders and pass them to
the built-in function @('termination-machine').
Otherwise, we pass the default ruler extenders.
</p>"
(b* ((ruler-extenders (if (and (logicp fn wrld)
(irecursivep fn wrld))
(ruler-extenders fn wrld)
(default-ruler-extenders wrld))))
(termination-machine
(list fn) (ubody fn wrld) nil nil ruler-extenders)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define fundef-disabledp ((fn (function-namep fn (w state))) state)
:returns (yes/no "A @(tsee booleanp).")
:mode :program
:parents (world-queries)
:short "Check if the definition of a named function is disabled."
(if (member-equal `(:definition ,fn) (disabledp fn)) t nil))
(define fundef-enabledp ((fn (function-namep fn (w state))) state)
:returns (yes/no "A @(tsee booleanp).")
:mode :program
:parents (world-queries)
:short "Check if the definition of a named function is enabled."
(not (fundef-disabledp fn state)))
(define rune-disabledp ((rune (runep rune (w state))) state)
:returns (yes/no "A @(tsee booleanp).")
:mode :program
:parents (world-queries)
:short "Check if a @(see rune) is disabled."
(if (member-equal rune (disabledp (cadr rune))) t nil))
(define rune-enabledp ((rune (runep rune (w state))) state)
:returns (yes/no "A @(tsee booleanp).")
:mode :program
:parents (world-queries)
:short "Check if a @(see rune) is enabled."
(not (rune-disabledp rune state)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define known-packages (state)
:returns (pkg-names "A @(tsee string-listp).")
:parents (world-queries)
:short "List of names of the known packages, in chronological order."
:long
"<p>
See @(tsee known-packages+) for a logic-friendly variant of this utility.
</p>"
(reverse (strip-cars (known-package-alist state))))
(define known-packages+ (state)
:returns (pkg-names string-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee known-packages)."
:long
"<p>
This returns the same result as @(tsee known-packages),
but it includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('state').
</p>"
(b* ((result (known-packages state)))
(if (string-listp result)
result
(raise "Internal error: ~
the list of keys ~x0 of the alist of known packages ~
is not a true list of strings."
result))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define included-books ((wrld plist-worldp))
:returns (result "A @(tsee string-listp).")
:verify-guards nil
:parents (world-queries)
:short "List of full pathnames of all books currently included
(directly or indirectly)."
(strip-cars (global-val 'include-book-alist wrld)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(std::deflist pseudo-event-landmark-listp (x)
(pseudo-event-landmarkp x)
:parents (world-queries)
:short "Recognize true lists of event landmarks."
:long
"<p>
See @('pseudo-event-landmarkp')
in @('[books]/system/pseudo-good-worldp.lisp').
</p>"
:true-listp t
:elementp-of-nil nil)
(std::deflist pseudo-command-landmark-listp (x)
(pseudo-command-landmarkp x)
:parents (world-queries)
:short "Recognize true lists of command landmarks."
:long
"<p>
See @('pseudo-command-landmarkp')
in @('[books]/system/pseudo-good-worldp.lisp').
</p>"
:true-listp t
:elementp-of-nil nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define event-landmark-names ((event pseudo-event-landmarkp))
:returns (names "A @('string-or-symbol-listp').")
:verify-guards nil
:parents (world-queries)
:short "Names introduced by an event landmark."
:long
"<p>
Each event landmark introduces zero or more names into the @(see world).
See @('pseudo-event-landmarkp')
in @('[books]/system/pseudo-good-worldp.lisp'),
and the description of event tuples in the ACL2 source code.
</p>"
(let ((namex (access-event-tuple-namex event)))
(cond ((equal namex 0) nil) ; no names
((consp namex) namex) ; list of names
(t (list namex))))) ; single name
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define fresh-namep-msg-weak ((name symbolp) type (wrld plist-worldp))
:guard (member-eq type
'(function macro const stobj constrained-function nil))
:returns (msg/nil "A message (see @(tsee msg)) or @('nil').")
:mode :program
:parents (world-queries)
:short "Return either @('nil') or a message indicating why the name is not
a legal new name."
:long
"<p>
This helper function for @(tsee fresh-namep-msg) avoids the ``virginity''
check ensuring that the name is not already defined in raw Lisp. See @(tsee
fresh-namep-msg).
</p>"
(flet ((not-new-namep-msg (name wrld)
;; It is tempting to report that the properties
;; 'global-value, 'table-alist, 'table-guard are
;; not relevant for this check. But that would
;; probably make the message confusing.
(let ((old-type (logical-name-type name wrld t)))
(cond
(old-type
(msg "~x0 is already the name for a ~s1."
name
(case old-type
(function "function")
(macro "macro")
(const "constant")
(stobj "stobj")
(constrained-function
"constrained function"))))
(t
(msg "~x0 has properties in the world; it is ~
not a new name."
name))))))
(cond
((mv-let (ctx msg)
(chk-all-but-new-name-cmp name 'fresh-namep-msg type wrld)
(and ctx ; it's an error
msg)))
((not (new-namep name wrld))
(not-new-namep-msg name wrld))
(t (case type
(const
(and (not (legal-constantp name))
;; A somewhat more informative error message is produced by
;; chk-legal-defconst-name, but I think the following suffices.
(msg "~x0 is not a legal constant name."
name)))
(stobj
(and (not (new-namep (the-live-var name) wrld))
(not-new-namep-msg (the-live-var name) wrld)))
(t nil))))))
(define fresh-namep-msg ((name symbolp) type (wrld plist-worldp) state)
:guard (member-eq type
'(function macro const stobj constrained-function nil))
:returns (mv (erp "Always @('nil').")
(msg/nil "A message (see @(tsee msg)) or @('nil').")
state)
:mode :program
:parents (world-queries)
:short "Return either @('nil') or a message indicating why the name is not
a legal new name."
:long
"<p>
Returns an <see topic='@(url error-triple)'>error triple</see>
@('(mv nil msg/nil state)'), where @('msg/nil')
is either @('nil') or a message (see @(tsee msg)) indicating why the given
name is not legal for a definition of the given type: @('function') for
@(tsee defun), @('macro') for @(tsee defmacro), @('const') for @(tsee
defconst), @('stobj') for @(tsee defstobj), @('constrained-function') for
@(tsee defchoose), and otherwise @('nil') (for other kinds of @(see events),
for example @(tsee defthm) and @(tsee deflabel)). See @(see name).
</p>
<p>
WARNING: This is an incomplete check in the case of a stobj name, because
the field names required for a more complete check are not supplied as
inputs.
</p>
<p>
Implementation Note. This function modifies @(see state), because the check
for legality of new definitions (carried out by ACL2 source function
@('chk-virgin-msg')) modifies state. That modification is necessary because
for all we know, raw Lisp is adding or removing function definitions that we
don't know about without our having modified state; so logically, we pop the
oracle when making this check. End of Implementation Note.
</p>"
(let ((msg (fresh-namep-msg-weak name type wrld)))
(cond (msg (value msg))
(t (mv-let (msg state)
(chk-virgin-msg name type wrld state)
(value msg))))))
(define chk-fresh-namep ((name symbolp) type ctx (wrld plist-worldp) state)
:guard (member-eq type
'(function macro const stobj constrained-function nil))
:returns (mv erp val state)
:mode :program
:parents (world-queries)
:short "Check whether name is a legal new name."
:long
"<p>
Returns an <see topic='@(url error-triple)'>error triple</see>
@('(mv erp val state)') where @('erp') is
@('nil') if and only if name is a legal new name, and @('val') is
irrelevant. If @('erp') is not nil, then an explanatory error message is
printed.
</p>
<p>
For more information about legality of new names see @(tsee fresh-namep-msg),
which returns an <see topic='@(url error-triple)'>error triple</see>,
@('(mv nil msg/nil state)'). When
non-@('nil'), the value @('msg/nil') provides the message printed by
@('chk-fresh-namep').
</p>"
(er-let* ((msg (fresh-namep-msg name type wrld state))) ; never an error
(cond (msg (er soft ctx "~@0" msg))
(t (value nil)))))
| true |
; System Utilities -- World Queries
;
; Copyright (C) 2018 Kestrel Institute (http://www.kestrel.edu)
; Copyright (C) 2018 Regents of the University of Texas
;
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;
; Authors:
; PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
; PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
; PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(include-book "xdoc/constructors" :dir :system)
(include-book "std/util/deflist" :dir :system)
(include-book "std/util/defrule" :dir :system)
(include-book "system/kestrel" :dir :system)
(include-book "system/pseudo-good-worldp" :dir :system)
(include-book "term-function-recognizers")
(local (include-book "std/typed-lists/symbol-listp" :dir :system))
(local (include-book "arglistp-theorems"))
(local (include-book "world-theorems"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc world-queries
:parents (system-utilities-non-built-in)
:short "Utilities to query @(see world)s."
:long
"<p>
These complement the world query utilities
in the <see topic='@(url system-utilities)'>built-in system utilities</see>.
</p>
<p>
Many of these world query utilities come in two variants:
a ``fast'' one and a ``logic-friendly'' one.
The former has relatively weak and no (strong) return type theorems;
the latter has stronger guards and some run-time checks
that are believed to never fail
and that enable the proof of (stronger) return type theorems
without having to assume stronger properties in the guard
of the @(see world) arguments.
The logic-friendly variants are helpful
to prove properties (including verifying guards)
of logic-mode code that calls them,
but the fast variants avoid the performance penalty
of the always-satisfied run-time checks,
when proving properties of the code that calls them is not a focus
(e.g. in program-mode code).
</p>
<p>
The built-in world query utilities
have the characteristics of the fast variants.
Below we provide logic-friendly variants of
some built-in world query utilities.
</p>
<p>
The fast variants provided below are named in a way
that is ``consistent'' with the built-in world query utilities.
The logic-friendly world query utilities are named by adding @('+')
after the name of the corresponding fast world query utilities
(both built-in and provided below).
</p>")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define theorem-symbolp ((sym symbolp) (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Check if a symbol names a theorem,
i.e. it has a @('theorem') property."
:long
"<p>
This function is named in analogy to
the @(tsee function-symbolp) built-in system utility.
</p>"
(not (eq t (getpropc sym 'theorem t wrld))))
(define macro-symbolp ((sym symbolp) (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Check if a symbol names a macro,
i.e. it has a @('macro-args') property."
:long
"<p>
This function is named in analogy to
the @(tsee function-symbolp) built-in system utility.
</p>"
(not (eq t (getpropc sym 'macro-args t wrld))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(std::deflist function-symbol-listp (x wrld)
(function-symbolp x wrld)
:guard (and (symbol-listp x)
(plist-worldp wrld))
:parents (world-queries)
:short "Check if all the symbols in a list name functions."
:true-listp t)
(std::deflist theorem-symbol-listp (x wrld)
(theorem-symbolp x wrld)
:guard (and (symbol-listp x)
(plist-worldp wrld))
:parents (world-queries)
:short "Check if all the symbols in a list name theorems."
:true-listp t)
(std::deflist macro-symbol-listp (x wrld)
(macro-symbolp x wrld)
:guard (and (symbol-listp x)
(plist-worldp wrld))
:parents (world-queries)
:short "Check if all the symbols in a list name macros."
:true-listp t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define function-namep (x (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Recognize symbols that name functions."
:long
"<p>
This function is enabled because it is meant as an abbreviation.
Thus, theorems triggered by this function should be avoided.
</p>"
(and (symbolp x)
(function-symbolp x wrld))
:enabled t)
(define theorem-namep (x (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Recognize symbols that name theorems."
:long
"<p>
This function is enabled because it is meant as an abbreviation.
Thus, theorems triggered by this function should be avoided.
</p>"
(and (symbolp x)
(theorem-symbolp x wrld))
:enabled t)
(define macro-namep (x (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Recognize symbols that name macros."
:long
"<p>
This function is enabled because it is meant as an abbreviation.
Thus, theorems triggered by this function should be avoided.
</p>"
(and (symbolp x)
(macro-symbolp x wrld))
:enabled t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(std::deflist function-name-listp (x wrld)
(function-namep x wrld)
:guard (plist-worldp wrld)
:parents (world-queries)
:short "Recognize true lists of symbols that name functions."
:true-listp t)
(std::deflist theorem-name-listp (x wrld)
(theorem-namep x wrld)
:guard (plist-worldp wrld)
:parents (world-queries)
:short "Recognize true lists of symbols that name theorems."
:true-listp t)
(std::deflist macro-name-listp (x wrld)
(macro-namep x wrld)
:guard (plist-worldp wrld)
:parents (world-queries)
:short "Recognize true lists of symbols that name macros."
:true-listp t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define logical-name-listp (names (wrld plist-worldp))
;; we cannot use STD::DEFLIST to define LOGICAL-NAME-LISTP
;; because STD::DEFLIST attempts to prove that LOGICAL-NAMEP is boolean,
;; but it is not
:returns (yes/no booleanp)
:verify-guards nil
:parents (world-queries)
:short "Recognize true lists of logical names."
:long
"<p>
See @('logical-namep') in the ACL2 source code.
</p>"
(cond ((atom names) (null names))
(t (and (logical-namep (car names) wrld)
(logical-name-listp (cdr names) wrld)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define logic-function-namep (x (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Recognize symbols that name logic-mode functions."
:long
"<p>
This function is enabled because it is meant as an abbreviation.
Thus, theorems triggered by this function should be avoided.
</p>"
(and (function-namep x wrld)
(logicp x wrld))
:enabled t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define formals+ ((fn (or (function-namep fn wrld)
(pseudo-lambdap fn)))
(wrld plist-worldp-with-formals))
:returns (formals symbol-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee formals)."
:long
"<p>
This returns the same result as @(tsee formals) on named functions,
but it has a stronger guard for named functions
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>
<p>
This utility also operates on lambda expressions, unlike @(tsee formals).
</p>"
(b* ((result (cond ((symbolp fn) (formals fn wrld))
(t (lambda-formals fn)))))
(if (symbol-listp result)
result
(raise "Internal error: ~
the formals ~x0 of ~x1 are not a true list of symbols."
result fn)))
:guard-hints (("Goal" :in-theory (enable pseudo-lambdap))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define arity+ ((fn (or (function-namep fn wrld)
(pseudo-lambdap fn)))
(wrld plist-worldp-with-formals))
:returns (result natp
:hyp (or (function-namep fn wrld) (pseudo-lambdap fn))
:hints (("Goal" :in-theory (enable arity pseudo-lambdap))))
:parents (world-queries)
:short "Logic-friendly variant of @(tsee arity)."
:long
"<p>
This returns the same result as @(tsee arity),
but it has a stronger guard.
</p>"
(arity fn wrld)
:guard-hints (("Goal" :in-theory (enable pseudo-lambdap))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define stobjs-in+ ((fn (function-namep fn wrld))
(wrld plist-worldp))
:returns (result symbol-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee stobjs-in)."
:long
"<p>
This returns the same result as @(tsee stobjs-in),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (stobjs-in fn wrld)))
(if (symbol-listp result)
result
(raise "Internal error: ~
the STOBJS-IN property ~x0 of ~x1 is not a true list of symbols."
result fn))))
(define stobjs-out+ ((fn (function-namep fn wrld))
(wrld plist-worldp))
:guard (not (member-eq fn *stobjs-out-invalid*))
:returns (result symbol-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee stobjs-out)."
:long
"<p>
This returns the same result as @(tsee stobjs-out),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>
<p>
The function must not be in @('*stobjs-out-invalid*'),
because in that case its output stobjs depend on how it is called.
</p>"
(b* ((result (stobjs-out fn wrld)))
(if (symbol-listp result)
result
(raise "Internal error: ~
the STOBJS-OUT property ~x0 of ~x1 is not a true list of symbols."
result fn))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define macro-args+ ((mac (macro-namep mac wrld))
(wrld plist-worldp))
:returns (result true-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee macro-args)."
:long
"<p>
This returns the same result as the built-in system utility @('macro-args')
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (macro-args mac wrld)))
(if (true-listp result)
result
(raise "Internal error: ~
the MACRO-ARGS property ~x0 of ~x1 is not a true list."
result mac))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define definedp ((fn symbolp) (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Check if a named logic-mode function is defined."
:long
"<p>
We check if the function symbol has an @('unnormalized-body') property.
</p>
<p>
Note that some program-mode functions may be defined
but not have an @('unnormalized-body') property.
</p>
<p>
See @(tsee definedp+) for a logic-friendly variant of this utility.
</p>"
(if (getpropc fn 'unnormalized-body nil wrld) t nil))
(define definedp+ ((fn (logic-function-namep fn wrld)) (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee definedp)."
:long
"<p>
This returns the same result as @(tsee definedp),
but it has a stronger guard.
</p>"
(definedp fn wrld))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define primitivep ((fn symbolp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Check if a named function is @(see primitive)."
:long
"<p>
See @(tsee primitivep+) for a logic-friendly variant of this utility.
</p>"
(and (member-eq fn (strip-cars *primitive-formals-and-guards*)) t))
(define primitivep+ ((fn (function-namep fn wrld)) (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee primitivep)."
:long
"<p>
This returns the same result as @(tsee guard-verified-p),
but it has a stronger guard.
The guard requires an extra @(see world) argument,
which is usually available when doing system programming.
</p>"
(declare (ignore wrld))
(primitivep fn))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define guard-verified-p ((fn/thm symbolp) (wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Check if a named function or theorem is @(tsee guard)-verified."
:long
"<p>
See @(tsee guard-verified-p+) for a logic-friendly variant of this utility.
</p>"
(eq (symbol-class fn/thm wrld) :common-lisp-compliant))
(define guard-verified-p+ ((fn/thm (or (function-namep fn/thm wrld)
(theorem-namep fn/thm wrld)))
(wrld plist-worldp))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee guard-verified-p)."
:long
"<p>
This returns the same result as @(tsee guard-verified-p),
but it has a stronger guard.
</p>"
(guard-verified-p fn/thm wrld))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define ubody ((fn pseudo-termfnp) (wrld plist-worldp))
:returns (body "A @(tsee pseudo-termp).")
:parents (world-queries)
:short "Unnormalized body of a named logic-mode function,
or body of a lambda expression."
:long
"<p>
This is a specialization of @(tsee body)
with @('nil') as the second argument.
Since @(tsee body) is not guard-verified only because of
the code that handles the case in which the second argument is non-@('nil'),
we avoid calling @(tsee body) and instead replicate
the code that handles the case in which the second argument is @('nil');
thus, this utility is guard-verified.
</p>
<p>
If the argument named function is not defined, this utility returns @('nil').
</p>
<p>
Not that some program-mode functions may be defined
but not have an @('unnormalized-body') property.
</p>
<p>
See @(tsee ubody+) for a logic-friendly variant of this utility.
</p>"
(cond ((symbolp fn) (getpropc fn 'unnormalized-body nil wrld))
(t (lambda-body fn)))
:guard-hints (("Goal" :in-theory (enable pseudo-termfnp pseudo-lambdap))))
(define ubody+ ((fn (or (and (logic-function-namep fn wrld)
(definedp fn wrld))
(pseudo-lambdap fn)))
(wrld plist-worldp))
:returns (body pseudo-termp
:hyp (or (symbolp fn) (pseudo-lambdap fn))
:hints (("Goal" :in-theory (enable pseudo-lambdap))))
:parents (world-queries)
:short "Logic-friendly variant of @(tsee ubody)."
:long
"<p>
This returns the same result as @(tsee ubody),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (ubody fn wrld)))
(if (pseudo-termp result)
result
(raise "Internal error: ~
the unnormalized body ~x0 of ~x1 is not a pseudo-term."
result fn)))
:guard-hints (("Goal" :in-theory (enable pseudo-termfnp))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define uguard ((fn pseudo-termfnp) (wrld plist-worldp))
:returns (guard "A @(tsee pseudo-termp).")
:parents (world-queries)
:short "Unoptimized guard of a named function or of a lambda expression."
:long
"<p>
This is a specialization of
<see topic='@(url system-utilities)'>@('guard')</see>
with @('nil') as the second argument.
Since @(tsee body) is in program mode only because of
the code that handles the case in which the second argument is non-@('nil'),
we avoid calling @(tsee guard) and instead replicate
the code that handles the case in which the second argument is @('nil');
thus, this utility is in logic mode and guard-verified.
</p>
<p>
See @(tsee uguard+) for a logic-friendly variant of this utility.
</p>"
(cond ((symbolp fn) (getpropc fn 'guard *t* wrld))
(t *t*)))
(define uguard+ ((fn (or (function-namep fn wrld)
(pseudo-lambdap fn)))
(wrld plist-worldp))
:returns (guard pseudo-termp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee uguard)."
:long
"<p>
This returns the same result as @(tsee uguard),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (uguard fn wrld)))
(if (pseudo-termp result)
result
(raise "Internal error: ~
the guard ~x0 of ~x1 is not a pseudo-term."
result fn)))
:guard-hints (("Goal" :in-theory (enable pseudo-termfnp))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define non-executablep ((fn symbolp) (wrld plist-worldp))
:returns (status "@('t'), @('nil'), or @(':program').")
:parents (world-queries)
:short "@(see Non-executable) status of a named logic-mode defined function."
:long
"<p>
See @(tsee non-executablep+) for a logic-friendly variant of this utility.
</p>"
(getpropc fn 'non-executablep nil wrld))
(define non-executablep+ ((fn (function-namep fn wrld))
(wrld plist-worldp))
:returns (nonexec (or (booleanp nonexec) (eq nonexec :program)))
:parents (world-queries)
:short "Logic-friendly variant of @(tsee non-executablep)."
:long
"<p>
This returns the same result as @(tsee non-executablep),
but it has a stronger guard
and includes run-time checks (which should always succeed) on the result
that allow us to prove the return type theorems
without strengthening the guard on @('wrld').
</p>"
(b* ((result (non-executablep fn wrld))
((unless (or (booleanp result)
(eq result :program)))
(raise "Internal error: ~
the non-executable status ~x0 of ~x1 is not ~
T, NIL, or :PROGRAM."
result fn))
((when (and (logicp fn wrld)
(eq result :program)))
(raise "Internal error: ~
the non-executable status of the logic-mode function ~x0 ~
is :PROGRAM instead of T or NIL."
fn)))
result)
///
(more-returns
(nonexec booleanp
:hyp (logicp fn wrld)
:name booleanp-of-non-executablep+-when-logicp)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define unwrapped-nonexec-body ((fn symbolp) (wrld plist-worldp))
:returns (unwrapped-body "A @(tsee pseudo-termp).")
:verify-guards nil
:parents (world-queries)
:short "Body of a named logic-mode defined non-executable function,
without the ``non-executable wrapper''."
:long
"<p>
@(tsee defun-nx) generates
a logic-mode function whose body is wrapped as follows:
</p>
@({
(return-last 'progn
(throw-nonexec-error 'fn
(cons arg1 ... (cons argN 'nil)...))
body)
})
<p>
If @(tsee defun) is used for a logic-mode function with
<see topic='@(url non-executable)'>@(':non-executable')</see> set to @('t'),
the submitted body (once translated) must be wrapped as above.
</p>
<p>
This utility returns
the unwrapped body of a logic-mode non-executable function @('fn'),
by removing the wrapper shown above.
</p>
<p>
See @(tsee unwrapped-nonexec-body+) for
a logic-friendly variant of this utility.
</p>"
(fourth (ubody fn wrld)))
(define unwrapped-nonexec-body+ ((fn (and (logic-function-namep fn wrld)
(definedp fn wrld)
(non-executablep fn wrld)))
(wrld plist-worldp-with-formals))
:returns (unwrapped-body pseudo-termp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee unwrapped-nonexec-body)."
:long
"<p>
This returns the same result as @(tsee unwrapped-nonexec-body),
but it has a stronger guard,
is guard-verified,
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
This utility also includes a run-time check (which should always succeed)
that the wrapper around the body has the expected form,
via the built-in function @('throw-nonexec-error-p');
this allows us to verify the guards
without strengthening the guard of @('wrld').
</p>"
(b* ((body (ubody+ fn wrld))
((unless (and (throw-nonexec-error-p body fn (formals+ fn wrld))
(consp (cdddr body))))
(raise "Internal error: ~
the body ~x0 of the non-executable function ~x1 ~
does not have the expected wrapper."
body fn))
(unwrapped-body (fourth body))
((unless (pseudo-termp unwrapped-body))
(raise "Internal error: ~
the unwrapped body ~x0 of the non-executable function ~x1 ~
is not a pseudo-term."
unwrapped-body fn)))
unwrapped-body))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define number-of-results ((fn symbolp) (wrld plist-worldp))
:guard (not (member-eq fn *stobjs-out-invalid*))
:returns (n natp "Actually a @(tsee posp).")
:parents (world-queries)
:short "Number of values returned by a named function."
:long
"<p>
This is 1, unless the function uses @(tsee mv)
(directly, or indirectly by calling another function that does)
to return multiple values.
</p>
<p>
The number of results of the function
is the length of its @(tsee stobjs-out) list.
</p>
<p>
The function must not be in @('*stobjs-out-invalid*'),
because in that case the number of its results depends on how it is called.
</p>
<p>
See @(tsee number-of-results+) for a logic-friendly variant of this utility.
</p>"
(len (stobjs-out fn wrld)))
(define number-of-results+ ((fn (function-namep fn wrld))
(wrld plist-worldp))
:guard (not (member-eq fn *stobjs-out-invalid*))
:returns (n posp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee number-of-results)."
:long
"<p>
This returns the same result as @(tsee number-of-results),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (number-of-results fn wrld)))
(if (posp result)
result
(prog2$
(raise "Internal error: ~
the STOBJS-OUT property of ~x0 is empty."
fn)
1)))) ; any POSP could be used here
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define no-stobjs-p ((fn symbolp) (wrld plist-worldp))
:guard (not (member-eq fn *stobjs-out-invalid*))
:returns (yes/no booleanp)
:verify-guards nil
:parents (world-queries)
:short "Check if a named function has no input or output @(see stobj)s."
:long
"<p>
The function must not be in @('*stobjs-out-invalid*'),
because in that case its (output) stobjs depend on how it is called.
</p>
<p>
See @(tsee no-stobjs-p+) for a logic-friendly variant of this utility.
</p>"
(and (all-nils (stobjs-in fn wrld))
(all-nils (stobjs-out fn wrld))))
(define no-stobjs-p+ ((fn (function-namep fn wrld))
(wrld plist-worldp))
:guard (not (member-eq fn *stobjs-out-invalid*))
:returns (yes/no booleanp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee no-stobjs-p)."
:long
"<p>
This returns the same result as @(tsee no-stobjs-p),
but it has a stronger guard and is guard-verified.
</p>"
(and (all-nils (stobjs-in+ fn wrld))
(all-nils (stobjs-out+ fn wrld))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define irecursivep ((fn symbolp) (wrld plist-worldp))
:returns (clique "A @(tsee symbol-listp).")
:parents (world-queries)
:short "List of mutually recursive functions of which
the specified named function is a member,
based on the @(tsee defun) form that introduced this function,
or @('nil') if the specified function is not recursive."
:long
"<p>
This is a specialization of @(tsee recursivep)
with @('nil') as the second argument:
the @('i') that starts the name of @('irecursivep') conveys that
the result is based on the @(tsee defun) form that <i>introduced</i> @('fn').
</p>
<p>
See @(tsee irecursivep+) for a logic-friendly variant of this utility.
</p>"
(recursivep fn nil wrld))
(define irecursivep+ ((fn (logic-function-namep fn wrld))
(wrld plist-worldp))
:returns (clique symbol-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee irecursivep)."
:long
"<p>
This returns the same result as @(tsee irecursivep),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (irecursivep fn wrld)))
(if (symbol-listp result)
result
(raise "Internal error: ~
the RECURSIVEP property ~x0 of ~x1 is not a true list of symbols."
result fn))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define measure ((fn symbolp) (wrld plist-worldp))
:returns (measure "A @(tsee pseudo-termp).")
:verify-guards nil
:parents (world-queries)
:short "Measure expression of a named logic-mode recursive function."
:long
"<p>
See @(see xargs) for a discussion of the @(':measure') keyword.
</p>
<p>
See @(tsee measure+) for a logic-friendly variant of this utility.
</p>"
(b* ((justification (getpropc fn 'justification nil wrld)))
(access justification justification :measure)))
(define measure+ ((fn (and (logic-function-namep fn wrld)
(recursivep fn nil wrld)))
(wrld plist-worldp))
:returns (measure pseudo-termp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee measure)."
:long
"<p>
This returns the same result as @(tsee measure),
but it has a stronger guard,
is guard-verified,
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
This utility also includes a run-time check (which should always succeed)
on the form of the @('justification') property of the function
that allows us to verify the guards
without strengthening the guard of @('wrld').
</p>"
(b* ((justification (getpropc fn 'justification nil wrld))
((unless (weak-justification-p justification))
(raise "Internal error: ~
the JUSTIFICATION property ~x0 of ~x1 is not well-formed."
justification fn))
(measure (access justification justification :measure))
((unless (pseudo-termp measure))
(raise "Internal error: ~
the measure ~x0 of ~x1 is not a pseudo-term."
measure fn)))
measure))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define measured-subset ((fn symbolp) (wrld plist-worldp))
:returns (measured-subset "A @(tsee symbol-listp).")
:verify-guards nil
:parents (world-queries)
:short "Subset of the formal arguments
of a named logic-mode recursive function
that occur in its @(see measure) expression."
:long
"<p>
See @(tsee measured-subset+) for a logic-friendly variant of this utility.
</p>"
(b* ((justification (getpropc fn 'justification nil wrld)))
(access justification justification :subset)))
(define measured-subset+ ((fn (and (logic-function-namep fn wrld)
(recursivep fn nil wrld)))
(wrld plist-worldp))
:returns (measured-subset symbol-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee measured-subset)."
:long
"<p>
This returns the same result as @(tsee measured-subset),
but it has a stronger guard,
is guard-verified,
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
This utility also includes a run-time check (which should always succeed)
on the form of the @('justification') property of the function
that allows us to verify the guards
without strengthening the guard of @('wrld').
</p>"
(b* ((justification (getpropc fn 'justification nil wrld))
((unless (weak-justification-p justification))
(raise "Internal error: ~
the JUSTIFICATION property ~x0 of ~x1 is not well-formed."
justification fn))
(measured-subset (access justification justification :subset))
((unless (symbol-listp measured-subset))
(raise "Internal error: ~
the measured subset ~x0 of ~x1 is not a true list of symbols."
measured-subset fn)))
measured-subset))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define well-founded-relation ((fn symbolp) (wrld plist-worldp))
:returns (well-founded-relation "A @(tsee symbolp).")
:verify-guards nil
:parents (world-queries)
:short "Well-founded relation of a named logic-mode recursive function."
:long
"<p>
See @(see well-founded-relation-rule)
for a discussion of well-founded relations in ACL2,
including the @(':well-founded-relation') rule class.
</p>
<p>
See @(tsee well-founded-relation+) for
a logic-friendly variant of this utility.
</p>"
(b* ((justification (getpropc fn 'justification nil wrld)))
(access justification justification :rel)))
(define well-founded-relation+ ((fn (and (logic-function-namep fn wrld)
(recursivep fn nil wrld)))
(wrld plist-worldp))
:returns (well-founded-relation symbolp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee well-founded-relation)."
:long
"<p>
This returns the same result as @(tsee well-founded-relation),
but it has a stronger guard,
is guard-verified,
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
This utility also includes a run-time check (which should always succeed)
on the form of the @('justification') property of the function
that allows us to verify the guards
without strengthening the guard of @('wrld').
</p>"
(b* ((justification (getpropc fn 'justification nil wrld))
((unless (weak-justification-p justification))
(raise "Internal error: ~
the justification ~x0 of ~x1 is not well-formed."
justification fn))
(well-founded-relation (access justification justification :rel))
((unless (symbolp well-founded-relation))
(raise "Internal error: ~
the well-founded relation ~x0 of ~x1 is not a symbol."
well-founded-relation fn)))
well-founded-relation))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define ruler-extenders ((fn symbolp) (wrld plist-worldp))
:returns (ruler-extenders "A @(tsee symbol-listp) of @(':all').")
:verify-guards nil
:parents (world-queries)
:short "Ruler-extenders of a named logic-mode recursive function."
:long
"<p>
See @(see rulers) for background.
</p>
<p>
See @(tsee ruler-extenders+) for a logic-friendly variant of this utility.
</p>"
(b* ((justification (getpropc fn 'justification nil wrld)))
(access justification justification :ruler-extenders)))
(define ruler-extenders+ ((fn (and (logic-function-namep fn wrld)
(recursivep fn nil wrld)))
(wrld plist-worldp))
:returns (ruler-extenders (or (symbol-listp ruler-extenders)
(equal ruler-extenders :all)))
:parents (world-queries)
:short "Logic-friendly variant of @(tsee ruler-extenders)."
:long
"<p>
This returns the same result as @(tsee ruler-extenders),
but it has a stronger guard,
is guard-verified,
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
This utility also includes a run-time check (which should always succeed)
on the form of the @('justification') property of the function
that allows us to verify the guards
without strengthening the guard of @('wrld').
</p>"
(b* ((justification (getpropc fn 'justification nil wrld))
((unless (weak-justification-p justification))
(raise "Internal error: ~
the 'JUSTIFICATION property ~x0 of ~x1 is not well-formed."
justification fn))
(ruler-extenders (access justification justification :ruler-extenders))
((unless (or (symbol-listp ruler-extenders)
(eq ruler-extenders :all)))
(raise "Internal error: ~
the well-founded relation ~x0 of ~x1 ~
is neither a true list of symbols nor :ALL."
ruler-extenders fn)))
ruler-extenders))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define macro-required-args ((mac symbolp) (wrld plist-worldp))
:returns (required-args "A @(tsee symbol-listp).")
:verify-guards nil
:parents (world-queries)
:short "Required arguments of a macro, in order."
:long
"<p>
The arguments of a macro form a list that
optionally starts with @('&whole') followed by another symbol,
continues with zero or more symbols that do not start with @('&')
which are the required arguments,
and possibly ends with
a symbol starting with @('&') followed by more things.
</p>
<p>
After removing @('&whole') and the symbol following it
(if the list of arguments starts with @('&whole')),
we collect all the arguments until
either the end of the list is reached
or a symbol starting with @('&') is encountered.
</p>
<p>
See @(tsee macro-required-args+) for
a logic-friendly variant of this utility.
</p>"
(b* ((all-args (macro-args mac wrld)))
(if (null all-args)
nil
(if (eq (car all-args) '&whole)
(macro-required-args-aux (cddr all-args) nil)
(macro-required-args-aux all-args nil))))
:prepwork
((define macro-required-args-aux ((args true-listp)
(rev-result symbol-listp))
:returns (final-result) ; SYMBOL-LISTP
:verify-guards nil
(if (endp args)
(reverse rev-result)
(b* ((arg (car args)))
(if (lambda-keywordp arg)
(reverse rev-result)
(macro-required-args-aux (cdr args)
(cons arg rev-result))))))))
(define macro-required-args+ ((mac (macro-namep mac wrld))
(wrld plist-worldp))
:returns (required-args symbol-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee macro-required-args)."
:long
"<p>
This returns the same result as @(tsee macro-required-args),
but it has a stronger guard,
is guard-verified,
and includes run-time checks (which should always succeed)
that allows us to prove the return type theorem and to verify guards
without strengthening the guard on @('wrld').
</p>"
(b* ((all-args (macro-args+ mac wrld)))
(if (null all-args)
nil
(if (eq (car all-args) '&whole)
(macro-required-args+-aux mac (cddr all-args) nil)
(macro-required-args+-aux mac all-args nil))))
:prepwork
((define macro-required-args+-aux ((mac symbolp)
(args true-listp)
(rev-result symbol-listp))
:returns (final-result symbol-listp
:hyp (symbol-listp rev-result))
(if (endp args)
(reverse rev-result)
(b* ((arg (car args)))
(if (lambda-keywordp arg)
(reverse rev-result)
(if (symbolp arg)
(macro-required-args+-aux mac
(cdr args)
(cons arg rev-result))
(raise "Internal error: ~
the required macro argument ~x0 of ~x1 is not a symbol."
arg mac))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define macro-keyword-args ((mac symbolp) (wrld plist-worldp))
:returns (keyword-args "A @(tsee symbol-alistp).")
:verify-guards nil
:parents (world-queries)
:short "Keyword arguments of a macro, in order, with their default values."
:long
(xdoc::topstring
(xdoc::p
"Starting from the full argument list of the macro,
first we find @('&key') in the list;
if not found, we return @('nil') (i.e. no keyword arguments).
Otherwise, we scan and collect information from the remaining arguments,
until we reach either the end of the macro argument list
or a symbol starting with @('&...').")
(xdoc::p
"Keyword arguments have one of the forms
@('name'), @('(name \'default)'), @('(name \'default predicate)'),
where @('name') is the argument name (a symbol)
@('default') its default value (quoted),
and @('predicate') is another symbol.
When we scan a keyword argument,
we put name and default value as a pair into an alist.")
(xdoc::p
"See @(tsee macro-keyword-args) for
a logic-friendly variant of this utility."))
(b* ((all-args (macro-args mac wrld))
(args-after-&key (cdr (member-eq '&key all-args)))
(keyword-args (macro-keyword-args-aux args-after-&key)))
keyword-args)
:prepwork
((define macro-keyword-args-aux ((args true-listp))
:returns keyword-args ; SYMBOL-ALISTP
:verify-guards nil
:parents nil
(b* (((when (endp args)) nil)
(arg (car args))
((when (lambda-keywordp arg)) nil)
(name (if (atom arg) arg (first arg)))
(default (if (atom arg) nil (unquote (second arg)))))
(acons name default (macro-keyword-args-aux (cdr args)))))))
(define macro-keyword-args+ ((mac (macro-namep mac wrld))
(wrld plist-worldp))
:returns (keyword-args symbol-alistp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee macro-keyword-args)."
:long
(xdoc::topstring-p
"This returns the same result as @(tsee macro-keyword-args),
but it has a stronger guard,
is guard-verified,
and includes run-time checks (which should always succeed)
that allow us to prove the return type theorem and to verify the guards
without strengthening the guard on @('wrld').")
(b* ((all-args (macro-args+ mac wrld))
(args-after-&key (cdr (member-eq '&key all-args)))
(keyword-args (macro-keyword-args+-aux mac args-after-&key)))
keyword-args)
:prepwork
((define macro-keyword-args+-aux ((mac symbolp) args)
:returns (keyword-args symbol-alistp)
:verify-guards :after-returns
:parents nil ; override default
(b* (((when (atom args)) nil)
(arg (car args))
((when (lambda-keywordp arg)) nil)
((when (symbolp arg))
(acons arg nil (macro-keyword-args+-aux mac (cdr args))))
((unless (and (consp arg)
(symbolp (first arg))
(consp (cdr arg))
(consp (second arg))
(eq (car (second arg)) 'quote)
(consp (cdr (second arg)))))
(raise "Internal error: ~
the keyword macro argument ~x0 of ~x1 ~
does not have the expected form."
arg mac)))
(acons (first arg)
(unquote (second arg))
(macro-keyword-args+-aux mac (cdr args)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define thm-formula ((thm symbolp) (wrld plist-worldp))
:returns (formula "A @(tsee pseudo-termp).")
:parents (world-queries)
:short "Formula of a named theorem."
:long
"<p>
This is a specialization of @(tsee formula) to named theorems,
for which the second argument of @(tsee formula) is immaterial.
Since @(tsee formula) is in program mode only because of
the code that handles the cases in which the first argument
is not the name of a theorem,
we avoid calling @(tsee formula) and instead replicate
the code that handles the case in which
the first argument is the name of a theorem;
thus, this utility is in logic mode and guard-verified.
</p>
<p>
See @(tsee thm-formula+) for a logic-friendly variant of this utility.
</p>"
(getpropc thm 'theorem nil wrld))
(define thm-formula+ ((thm (theorem-namep thm wrld))
(wrld plist-worldp))
:returns (formula pseudo-termp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee thm-formula)."
:long
"<p>
This returns the same result as @(tsee thm-formula),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (thm-formula thm wrld)))
(if (pseudo-termp result)
result
(raise "Internal error: ~
the FORMULA property ~x0 of ~x1 is not a pseudo-term."
result thm))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define classes ((thm symbolp) (wrld plist-worldp))
:returns (classes "An @(tsee alistp)
from @(tsee keywordp) to @(tsee keyword-value-listp).")
:parents (world-queries)
:short "Rule classes of a theorem."
:long
"<p>
These form a value of type @('keyword-to-keyword-value-list-alistp'),
which is defined in @('[books]/system/pseudo-good-worldp.lisp').
</p>
<p>
See @(tsee classes+) for a logic-friendly variant of this utility.
</p>"
(getpropc thm 'classes nil wrld))
(define classes+ ((thm (theorem-namep thm wrld))
(wrld plist-worldp))
:returns (classes keyword-to-keyword-value-list-alistp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee classes)."
:long
"<p>
This returns the same result as @(tsee classes),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (classes thm wrld)))
(if (keyword-to-keyword-value-list-alistp result)
result
(raise "Internal error: ~
the rule classes ~x0 of ~x1 are not an alist
from keywords to keyword-value lists."
result thm))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define induction-machine ((fn symbolp) (wrld plist-worldp))
:returns (result "A @('pseudo-induction-machinep').")
:parents (world-queries)
:short "Induction machine of a named logic-mode (singly) recursive function."
:long
"<p>
This is a list of @('tests-and-calls') records
(see the ACL2 source code for information on these records),
each of which contains zero or more recursive calls
along with the tests that lead to them.
The induction machine is a value of type @('pseudo-induction-machinep'),
which is defined in @('[books]/system/pseudo-good-worldp.lisp').
</p>
<p>
Note that
induction is not directly supported for mutually recursive functions.
</p>
<p>
See @(tsee induction-machine+) for a logic-friendly variant of this utility.
</p>"
(getpropc fn 'induction-machine nil wrld))
(define induction-machine+ ((fn (and (logic-function-namep fn wrld)
(= 1 (len (irecursivep+ fn wrld)))))
(wrld plist-worldp))
:returns (result (pseudo-induction-machinep fn result))
:parents (world-queries)
:short "Logic-friendly variant of @(tsee induction-machine)."
:long
"<p>
This returns the same result as @(tsee induction-machine),
but it has a stronger guard
and includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('wrld').
</p>"
(b* ((result (induction-machine fn wrld)))
(if (pseudo-induction-machinep fn result)
result
(raise "Internal error: ~
the INDUCTION-MACHINE property ~x0 of ~x1 ~
does not have the expected form."
result fn))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define pseudo-tests-and-callp (x)
:returns (yes/no booleanp)
:parents (world-queries)
:short "Recognize well-formed @('tests-and-call') records."
:long
"<p>
A @('tests-and-call') record is defined as
</p>
@({
(defrec tests-and-call (tests call) nil)
})
<p>
(see the ACL2 source code).
</p>
<p>
In a well-formed @('tests-and-call') record,
@('tests') must be a list of terms and
@('call') must be a term.
</p>
<p>
This recognizer is analogous to @('pseudo-tests-and-callsp')
in @('[books]/system/pseudo-good-worldp.lisp')
for @('tests-and-calls') records.
</p>"
(case-match x
(('tests-and-call tests call)
(and (pseudo-term-listp tests)
(pseudo-termp call)))
(& nil))
///
(defrule weak-tests-and-call-p-when-pseudo-tests-and-callp
(implies (pseudo-tests-and-callp x)
(weak-tests-and-call-p x))))
(std::deflist pseudo-tests-and-call-listp (x)
(pseudo-tests-and-callp x)
:parents (world-queries)
:short "Recognize true lists of well-formed @('tests-and-call') records."
:true-listp t
:elementp-of-nil nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define recursive-calls ((fn symbolp) (wrld plist-worldp))
:returns (calls-with-tests "A @(tsee pseudo-tests-and-call-listp).")
:mode :program
:parents (world-queries)
:short "Recursive calls of a named non-mutually-recursive function,
along with the controlling tests."
:long
"<p>
For singly recursive logic-mode functions,
this is similar to the result of @(tsee induction-machine),
but each record has one recursive call (instead of zero or more),
and there is exactly one record for each recursive call.
</p>
<p>
This utility works on both logic-mode and program-mode functions
(if the program-mode functions have an @('unnormalized-body') property).
This utility should not be called on a function that is
mutually recursive with other functions;
it must be called only on singly recursive functions,
or on non-recursive functions (the result is @('nil') in this case).
</p>
<p>
This utility may be extended to handle also mutually recursive functions.
</p>
<p>
If the function is in logic mode and recursive,
we obtain its ruler extenders and pass them to
the built-in function @('termination-machine').
Otherwise, we pass the default ruler extenders.
</p>"
(b* ((ruler-extenders (if (and (logicp fn wrld)
(irecursivep fn wrld))
(ruler-extenders fn wrld)
(default-ruler-extenders wrld))))
(termination-machine
(list fn) (ubody fn wrld) nil nil ruler-extenders)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define fundef-disabledp ((fn (function-namep fn (w state))) state)
:returns (yes/no "A @(tsee booleanp).")
:mode :program
:parents (world-queries)
:short "Check if the definition of a named function is disabled."
(if (member-equal `(:definition ,fn) (disabledp fn)) t nil))
(define fundef-enabledp ((fn (function-namep fn (w state))) state)
:returns (yes/no "A @(tsee booleanp).")
:mode :program
:parents (world-queries)
:short "Check if the definition of a named function is enabled."
(not (fundef-disabledp fn state)))
(define rune-disabledp ((rune (runep rune (w state))) state)
:returns (yes/no "A @(tsee booleanp).")
:mode :program
:parents (world-queries)
:short "Check if a @(see rune) is disabled."
(if (member-equal rune (disabledp (cadr rune))) t nil))
(define rune-enabledp ((rune (runep rune (w state))) state)
:returns (yes/no "A @(tsee booleanp).")
:mode :program
:parents (world-queries)
:short "Check if a @(see rune) is enabled."
(not (rune-disabledp rune state)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define known-packages (state)
:returns (pkg-names "A @(tsee string-listp).")
:parents (world-queries)
:short "List of names of the known packages, in chronological order."
:long
"<p>
See @(tsee known-packages+) for a logic-friendly variant of this utility.
</p>"
(reverse (strip-cars (known-package-alist state))))
(define known-packages+ (state)
:returns (pkg-names string-listp)
:parents (world-queries)
:short "Logic-friendly variant of @(tsee known-packages)."
:long
"<p>
This returns the same result as @(tsee known-packages),
but it includes a run-time check (which should always succeed) on the result
that allows us to prove the return type theorem
without strengthening the guard on @('state').
</p>"
(b* ((result (known-packages state)))
(if (string-listp result)
result
(raise "Internal error: ~
the list of keys ~x0 of the alist of known packages ~
is not a true list of strings."
result))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define included-books ((wrld plist-worldp))
:returns (result "A @(tsee string-listp).")
:verify-guards nil
:parents (world-queries)
:short "List of full pathnames of all books currently included
(directly or indirectly)."
(strip-cars (global-val 'include-book-alist wrld)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(std::deflist pseudo-event-landmark-listp (x)
(pseudo-event-landmarkp x)
:parents (world-queries)
:short "Recognize true lists of event landmarks."
:long
"<p>
See @('pseudo-event-landmarkp')
in @('[books]/system/pseudo-good-worldp.lisp').
</p>"
:true-listp t
:elementp-of-nil nil)
(std::deflist pseudo-command-landmark-listp (x)
(pseudo-command-landmarkp x)
:parents (world-queries)
:short "Recognize true lists of command landmarks."
:long
"<p>
See @('pseudo-command-landmarkp')
in @('[books]/system/pseudo-good-worldp.lisp').
</p>"
:true-listp t
:elementp-of-nil nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define event-landmark-names ((event pseudo-event-landmarkp))
:returns (names "A @('string-or-symbol-listp').")
:verify-guards nil
:parents (world-queries)
:short "Names introduced by an event landmark."
:long
"<p>
Each event landmark introduces zero or more names into the @(see world).
See @('pseudo-event-landmarkp')
in @('[books]/system/pseudo-good-worldp.lisp'),
and the description of event tuples in the ACL2 source code.
</p>"
(let ((namex (access-event-tuple-namex event)))
(cond ((equal namex 0) nil) ; no names
((consp namex) namex) ; list of names
(t (list namex))))) ; single name
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define fresh-namep-msg-weak ((name symbolp) type (wrld plist-worldp))
:guard (member-eq type
'(function macro const stobj constrained-function nil))
:returns (msg/nil "A message (see @(tsee msg)) or @('nil').")
:mode :program
:parents (world-queries)
:short "Return either @('nil') or a message indicating why the name is not
a legal new name."
:long
"<p>
This helper function for @(tsee fresh-namep-msg) avoids the ``virginity''
check ensuring that the name is not already defined in raw Lisp. See @(tsee
fresh-namep-msg).
</p>"
(flet ((not-new-namep-msg (name wrld)
;; It is tempting to report that the properties
;; 'global-value, 'table-alist, 'table-guard are
;; not relevant for this check. But that would
;; probably make the message confusing.
(let ((old-type (logical-name-type name wrld t)))
(cond
(old-type
(msg "~x0 is already the name for a ~s1."
name
(case old-type
(function "function")
(macro "macro")
(const "constant")
(stobj "stobj")
(constrained-function
"constrained function"))))
(t
(msg "~x0 has properties in the world; it is ~
not a new name."
name))))))
(cond
((mv-let (ctx msg)
(chk-all-but-new-name-cmp name 'fresh-namep-msg type wrld)
(and ctx ; it's an error
msg)))
((not (new-namep name wrld))
(not-new-namep-msg name wrld))
(t (case type
(const
(and (not (legal-constantp name))
;; A somewhat more informative error message is produced by
;; chk-legal-defconst-name, but I think the following suffices.
(msg "~x0 is not a legal constant name."
name)))
(stobj
(and (not (new-namep (the-live-var name) wrld))
(not-new-namep-msg (the-live-var name) wrld)))
(t nil))))))
(define fresh-namep-msg ((name symbolp) type (wrld plist-worldp) state)
:guard (member-eq type
'(function macro const stobj constrained-function nil))
:returns (mv (erp "Always @('nil').")
(msg/nil "A message (see @(tsee msg)) or @('nil').")
state)
:mode :program
:parents (world-queries)
:short "Return either @('nil') or a message indicating why the name is not
a legal new name."
:long
"<p>
Returns an <see topic='@(url error-triple)'>error triple</see>
@('(mv nil msg/nil state)'), where @('msg/nil')
is either @('nil') or a message (see @(tsee msg)) indicating why the given
name is not legal for a definition of the given type: @('function') for
@(tsee defun), @('macro') for @(tsee defmacro), @('const') for @(tsee
defconst), @('stobj') for @(tsee defstobj), @('constrained-function') for
@(tsee defchoose), and otherwise @('nil') (for other kinds of @(see events),
for example @(tsee defthm) and @(tsee deflabel)). See @(see name).
</p>
<p>
WARNING: This is an incomplete check in the case of a stobj name, because
the field names required for a more complete check are not supplied as
inputs.
</p>
<p>
Implementation Note. This function modifies @(see state), because the check
for legality of new definitions (carried out by ACL2 source function
@('chk-virgin-msg')) modifies state. That modification is necessary because
for all we know, raw Lisp is adding or removing function definitions that we
don't know about without our having modified state; so logically, we pop the
oracle when making this check. End of Implementation Note.
</p>"
(let ((msg (fresh-namep-msg-weak name type wrld)))
(cond (msg (value msg))
(t (mv-let (msg state)
(chk-virgin-msg name type wrld state)
(value msg))))))
(define chk-fresh-namep ((name symbolp) type ctx (wrld plist-worldp) state)
:guard (member-eq type
'(function macro const stobj constrained-function nil))
:returns (mv erp val state)
:mode :program
:parents (world-queries)
:short "Check whether name is a legal new name."
:long
"<p>
Returns an <see topic='@(url error-triple)'>error triple</see>
@('(mv erp val state)') where @('erp') is
@('nil') if and only if name is a legal new name, and @('val') is
irrelevant. If @('erp') is not nil, then an explanatory error message is
printed.
</p>
<p>
For more information about legality of new names see @(tsee fresh-namep-msg),
which returns an <see topic='@(url error-triple)'>error triple</see>,
@('(mv nil msg/nil state)'). When
non-@('nil'), the value @('msg/nil') provides the message printed by
@('chk-fresh-namep').
</p>"
(er-let* ((msg (fresh-namep-msg name type wrld state))) ; never an error
(cond (msg (er soft ctx "~@0" msg))
(t (value nil)))))
|
[
{
"context": "g in the development of OGMS, please send email to [email protected]. Be sure to include a google-account username wit",
"end": 2137,
"score": 0.9999291896820068,
"start": 2113,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " to change.\")\n\t (ontology-annotation !dc:creator \"Richard Scheuermann\")\n\t (ontology-annotation !dc:creator \"Barry Smith",
"end": 2420,
"score": 0.9997252821922302,
"start": 2401,
"tag": "NAME",
"value": "Richard Scheuermann"
},
{
"context": "Scheuermann\")\n\t (ontology-annotation !dc:creator \"Barry Smith\")\n\t (ontology-annotation !dc:creator \"Werner Ceus",
"end": 2470,
"score": 0.9998540878295898,
"start": 2459,
"tag": "NAME",
"value": "Barry Smith"
},
{
"context": "Barry Smith\")\n\t (ontology-annotation !dc:creator \"Werner Ceusters\")\n\t (ontology-annotation !dc:creator \"Albert Gold",
"end": 2524,
"score": 0.999849796295166,
"start": 2509,
"tag": "NAME",
"value": "Werner Ceusters"
},
{
"context": "er Ceusters\")\n\t (ontology-annotation !dc:creator \"Albert Goldfain\")\n\t (ontology-annotation !dc:creator \"Lindsay Cow",
"end": 2578,
"score": 0.9998623132705688,
"start": 2563,
"tag": "NAME",
"value": "Albert Goldfain"
},
{
"context": "rt Goldfain\")\n\t (ontology-annotation !dc:creator \"Lindsay Cowell\")\n\t (ontology-annotation !dc:creator \"Anand Kumar",
"end": 2631,
"score": 0.9998772740364075,
"start": 2617,
"tag": "NAME",
"value": "Lindsay Cowell"
},
{
"context": "dsay Cowell\")\n\t (ontology-annotation !dc:creator \"Anand Kumar\")\n\t (ontology-annotation !dc:creator \"Cornelius R",
"end": 2681,
"score": 0.9998437762260437,
"start": 2670,
"tag": "NAME",
"value": "Anand Kumar"
},
{
"context": "Anand Kumar\")\n\t (ontology-annotation !dc:creator \"Cornelius Rosse\")\n\t (ontology-annotation !dc:creator \"Bill Hogan\"",
"end": 2735,
"score": 0.9997343420982361,
"start": 2720,
"tag": "NAME",
"value": "Cornelius Rosse"
},
{
"context": "elius Rosse\")\n\t (ontology-annotation !dc:creator \"Bill Hogan\")\n\t (ontology-annotation !dc:creator \"Sivaram Ara",
"end": 2784,
"score": 0.9998657703399658,
"start": 2774,
"tag": "NAME",
"value": "Bill Hogan"
},
{
"context": "\"Bill Hogan\")\n\t (ontology-annotation !dc:creator \"Sivaram Arabandi\")\n\t (ontology-annotation !dc:creator \"Bill Hogan\"",
"end": 2839,
"score": 0.9997353553771973,
"start": 2823,
"tag": "NAME",
"value": "Sivaram Arabandi"
},
{
"context": "am Arabandi\")\n\t (ontology-annotation !dc:creator \"Bill Hogan\")\n\t (ontology-annotation !dc:creator \"Daniel Meri",
"end": 2888,
"score": 0.9998624324798584,
"start": 2878,
"tag": "NAME",
"value": "Bill Hogan"
},
{
"context": "\"Bill Hogan\")\n\t (ontology-annotation !dc:creator \"Daniel Merico\")\n\t (ontology-annotation !dc:creator \"Alan Rutten",
"end": 2940,
"score": 0.9998563528060913,
"start": 2927,
"tag": "NAME",
"value": "Daniel Merico"
},
{
"context": "niel Merico\")\n\t (ontology-annotation !dc:creator \"Alan Ruttenberg\")\n\t (annotation-property !obo:IAO_0000115 (label ",
"end": 2994,
"score": 0.9998507499694824,
"start": 2979,
"tag": "NAME",
"value": "Alan Ruttenberg"
},
{
"context": "ation !obi:IAO_0000117 (#\"replaceAll\" created-by \"agoldfain\" \"Albert Goldfain\")))\n\t\t\t (if creation-date (an",
"end": 4283,
"score": 0.999688446521759,
"start": 4274,
"tag": "USERNAME",
"value": "agoldfain"
},
{
"context": "AO_0000117 (#\"replaceAll\" created-by \"agoldfain\" \"Albert Goldfain\")))\n\t\t\t (if creation-date (annotation !obo:IAO_",
"end": 4301,
"score": 0.9998831748962402,
"start": 4286,
"tag": "NAME",
"value": "Albert Goldfain"
}
] |
src/tools/ogms2owl.lisp
|
sbjain/ogms
| 17 |
;; another obo to owl converter
;; (setq obo (make-instance 'obo :path "~/repos/ogms/trunk/src/ontology/ogms.obo"))
;; (read-obo obo)
;; (ogms-to-owl obo) -> ~/Desktop/ogms.owl
(defun getf-multiple (plist indicator)
(loop for (key value) on plist by #'cddr when (eq indicator key) collect value))
(defun ogms-to-owl (obo &optional (dest "ogms:ontology;ogms.owl"))
(flet ((uri-ify (id)
(cond ((equal id "BFO:0000076")
!bfo:Entity)
((#"matches" id "^BFO:.*")
(make-uri (second (assoc id *bfo-map* :test 'equalp))))
((#"matches" id "^OGMS:.*")
(make-uri (#"replaceFirst" id "OGMS:" "http://purl.obolibrary.org/obo/OGMS_")))
((#"matches" id "^OBO_REL:.*")
(make-uri (#"replaceFirst" id "^OBO_REL:" "http://www.obofoundry.org/ro/ro.owl#")))
((#"matches" id "^IAO:.*")
(make-uri (#"replaceFirst" id "^IAO:" "http://purl.obolibrary.org/obo/IAO_")))
(t (error "don't know how to convert id ~a to uri" id)))))
(with-ontology ogms (:about "http://purl.obolibrary.org/obo/ogms.owl" :base "http://purl.obolibrary.org/obo/ogms.owl")
((owl-imports !<http://www.ifomis.org/bfo/1.1>)
(owl-imports !<http://purl.obolibrary.org/obo/iao/ontology-metadata.owl>)
(owl-imports !<http://protege.stanford.edu/plugins/owl/dc/protege-dc.owl>)
(ontology-annotation !rdfs:comment "The Ontology for General Medical Science (OGMS) is based on the papers Toward an Ontological Treatment of Disease and Diagnosis and On Carcinomas and Other Pathological Entities. The ontology attempts to address some of the issues raised at the Workshop on Ontology of Diseases (Dallas, TX). OGMS was formerly called the clinical phenotype ontology. Terms from OGMS hang from the Basic Formal Ontology.
The latest version of OGMS is always available at http://purl.obolibrary.org/obo/ogms.owl
This is version 2009-12-03 aka '0.3'
http://purl.obolibrary.org/obo/ogms/2009-12-09/ogms.owl
The OGMS developer site is http://code.google.com/p/ogms/
The discussion group is http://groups.google.com/group/ogms-discuss
If you are interested in participating in the development of OGMS, please send email to [email protected]. Be sure to include a google-account username with your request (this will be the username associated with a gmail address).")
(ontology-annotation !rdfs:comment "This ontology is in early development. Expect it to change.")
(ontology-annotation !dc:creator "Richard Scheuermann")
(ontology-annotation !dc:creator "Barry Smith")
(ontology-annotation !dc:creator "Werner Ceusters")
(ontology-annotation !dc:creator "Albert Goldfain")
(ontology-annotation !dc:creator "Lindsay Cowell")
(ontology-annotation !dc:creator "Anand Kumar")
(ontology-annotation !dc:creator "Cornelius Rosse")
(ontology-annotation !dc:creator "Bill Hogan")
(ontology-annotation !dc:creator "Sivaram Arabandi")
(ontology-annotation !dc:creator "Bill Hogan")
(ontology-annotation !dc:creator "Daniel Merico")
(ontology-annotation !dc:creator "Alan Ruttenberg")
(annotation-property !obo:IAO_0000115 (label "definition"))
(annotation-property !obo:IAO_0000117 (label "definition editor"))
(annotation-property !obo:IAO_0000119 (label "definition source"))
(annotation-property !obo:IAO_0000116 (label "editor note"))
(annotation-property !obo:IAO_0000232 (label "curator note"))
(ontology-annotation !dc:date (literal "2009-08-07" !xsd:date))
(loop for record in (terms obo)
for name = (getf (cdr record) :name)
for id = (getf (cdr record) :id)
for is_a = (getf-multiple (cdr record) :is_a)
for xrefs = (getf-multiple (cdr record) :xref)
for def = (getf (cdr record) :def)
for created-by = (getf (cdr record) :created_by)
for creation-date = (getf (cdr record) :creation_date)
if (equal name "undefined primitive terms") do (setq name "_undefined primitive term")
unless (or (equal id !owl:Thing) (equal id !bfo:Entity) (#"matches" id "BFO.*") (equal id "OGMS:0000072"))
collect (apply 'class (unless (#"matches" id "IAO.*") (label name)) (uri-ify id)
(if (car def) (annotation !obo:IAO_0000115 (literal (car def) :|@en|)))
(if (third def) (annotation !obo:IAO_0000119 (third def)))
(if created-by (annotation !obi:IAO_0000117 (#"replaceAll" created-by "agoldfain" "Albert Goldfain")))
(if creation-date (annotation !obo:IAO_0000232 (format nil "creation date: ~a" creation-date)))
(if (member "BFO:0000076" is_a :test 'equalp)
(annotation !obi:IAO_0000116 "note: defined class"))
(append
(if (car xrefs)
(loop for xref in xrefs collect
(annotation !oboinowl:hasDbXref (format nil "~a" xref))))
(list :partial)
(if (getf (cdr record) :is_obsolete)
(list !oboinowl:ObsoleteClass)
(mapcar #'uri-ify is_a))))))
(write-rdfxml ogms dest))))
(defun ogms-convert (&optional (source "ogms:ontology;ogms.obo") (dest "ogms:ontology;ogms.owl"))
(let ((obo (make-instance 'obo :path source)))
(read-obo obo)
(ogms-to-owl obo dest)))
(defparameter *bfo-map*
'(("BFO:0000000" "http://www.ifomis.org/bfo/1.1#Entity")
("BFO:0000001" "http://www.ifomis.org/bfo/1.1/snap#Continuant")
("BFO:0000003" "http://www.ifomis.org/bfo/1.1/snap#DependentContinuant")
("BFO:0000004" "http://www.ifomis.org/bfo/1.1/snap#IndependentContinuant")
("BFO:0000005" "http://www.ifomis.org/bfo/1.1/snap#GenericallyDependentContinuant")
("BFO:0000006" "http://www.ifomis.org/bfo/1.1/snap#SpecificallyDependentContinuant")
("BFO:0000007" "http://www.ifomis.org/bfo/1.1/snap#Quality")
("BFO:0000008" "http://www.ifomis.org/bfo/1.1/snap#RealizableEntity")
("BFO:0000009" "http://www.ifomis.org/bfo/1.1/snap#Disposition")
("BFO:0000010" "http://www.ifomis.org/bfo/1.1/snap#Role")
("BFO:0000011" "http://www.ifomis.org/bfo/1.1/snap#Function")
("BFO:0000012" "http://www.ifomis.org/bfo/1.1/snap#Capability")
("BFO:0000041" "http://www.ifomis.org/bfo/1.1/snap#MaterialEntity")
("BFO:0000042" "http://www.ifomis.org/bfo/1.1/snap#FiatObjectPart")
("BFO:0000043" "http://www.ifomis.org/bfo/1.1/snap#Object")
("BFO:0000044" "http://www.ifomis.org/bfo/1.1/snap#ObjectAggregate")
("BFO:0000002" "http://www.ifomis.org/bfo/1.1/span#Occurrent")
("BFO:0000052" "http://www.ifomis.org/bfo/1.1/span#ProcessualEntity")
("BFO:0000053" "http://www.ifomis.org/bfo/1.1/span#FiatProcessPart")
("BFO:0000058" "http://www.ifomis.org/bfo/1.1/span#Process")
("BFO:0000062" "http://www.ifomis.org/bfo/1.1/span#ProcessAggregate")))
|
96962
|
;; another obo to owl converter
;; (setq obo (make-instance 'obo :path "~/repos/ogms/trunk/src/ontology/ogms.obo"))
;; (read-obo obo)
;; (ogms-to-owl obo) -> ~/Desktop/ogms.owl
(defun getf-multiple (plist indicator)
(loop for (key value) on plist by #'cddr when (eq indicator key) collect value))
(defun ogms-to-owl (obo &optional (dest "ogms:ontology;ogms.owl"))
(flet ((uri-ify (id)
(cond ((equal id "BFO:0000076")
!bfo:Entity)
((#"matches" id "^BFO:.*")
(make-uri (second (assoc id *bfo-map* :test 'equalp))))
((#"matches" id "^OGMS:.*")
(make-uri (#"replaceFirst" id "OGMS:" "http://purl.obolibrary.org/obo/OGMS_")))
((#"matches" id "^OBO_REL:.*")
(make-uri (#"replaceFirst" id "^OBO_REL:" "http://www.obofoundry.org/ro/ro.owl#")))
((#"matches" id "^IAO:.*")
(make-uri (#"replaceFirst" id "^IAO:" "http://purl.obolibrary.org/obo/IAO_")))
(t (error "don't know how to convert id ~a to uri" id)))))
(with-ontology ogms (:about "http://purl.obolibrary.org/obo/ogms.owl" :base "http://purl.obolibrary.org/obo/ogms.owl")
((owl-imports !<http://www.ifomis.org/bfo/1.1>)
(owl-imports !<http://purl.obolibrary.org/obo/iao/ontology-metadata.owl>)
(owl-imports !<http://protege.stanford.edu/plugins/owl/dc/protege-dc.owl>)
(ontology-annotation !rdfs:comment "The Ontology for General Medical Science (OGMS) is based on the papers Toward an Ontological Treatment of Disease and Diagnosis and On Carcinomas and Other Pathological Entities. The ontology attempts to address some of the issues raised at the Workshop on Ontology of Diseases (Dallas, TX). OGMS was formerly called the clinical phenotype ontology. Terms from OGMS hang from the Basic Formal Ontology.
The latest version of OGMS is always available at http://purl.obolibrary.org/obo/ogms.owl
This is version 2009-12-03 aka '0.3'
http://purl.obolibrary.org/obo/ogms/2009-12-09/ogms.owl
The OGMS developer site is http://code.google.com/p/ogms/
The discussion group is http://groups.google.com/group/ogms-discuss
If you are interested in participating in the development of OGMS, please send email to <EMAIL>. Be sure to include a google-account username with your request (this will be the username associated with a gmail address).")
(ontology-annotation !rdfs:comment "This ontology is in early development. Expect it to change.")
(ontology-annotation !dc:creator "<NAME>")
(ontology-annotation !dc:creator "<NAME>")
(ontology-annotation !dc:creator "<NAME>")
(ontology-annotation !dc:creator "<NAME>")
(ontology-annotation !dc:creator "<NAME>")
(ontology-annotation !dc:creator "<NAME>")
(ontology-annotation !dc:creator "<NAME>")
(ontology-annotation !dc:creator "<NAME>")
(ontology-annotation !dc:creator "<NAME>")
(ontology-annotation !dc:creator "<NAME>")
(ontology-annotation !dc:creator "<NAME>")
(ontology-annotation !dc:creator "<NAME>")
(annotation-property !obo:IAO_0000115 (label "definition"))
(annotation-property !obo:IAO_0000117 (label "definition editor"))
(annotation-property !obo:IAO_0000119 (label "definition source"))
(annotation-property !obo:IAO_0000116 (label "editor note"))
(annotation-property !obo:IAO_0000232 (label "curator note"))
(ontology-annotation !dc:date (literal "2009-08-07" !xsd:date))
(loop for record in (terms obo)
for name = (getf (cdr record) :name)
for id = (getf (cdr record) :id)
for is_a = (getf-multiple (cdr record) :is_a)
for xrefs = (getf-multiple (cdr record) :xref)
for def = (getf (cdr record) :def)
for created-by = (getf (cdr record) :created_by)
for creation-date = (getf (cdr record) :creation_date)
if (equal name "undefined primitive terms") do (setq name "_undefined primitive term")
unless (or (equal id !owl:Thing) (equal id !bfo:Entity) (#"matches" id "BFO.*") (equal id "OGMS:0000072"))
collect (apply 'class (unless (#"matches" id "IAO.*") (label name)) (uri-ify id)
(if (car def) (annotation !obo:IAO_0000115 (literal (car def) :|@en|)))
(if (third def) (annotation !obo:IAO_0000119 (third def)))
(if created-by (annotation !obi:IAO_0000117 (#"replaceAll" created-by "agoldfain" "<NAME>")))
(if creation-date (annotation !obo:IAO_0000232 (format nil "creation date: ~a" creation-date)))
(if (member "BFO:0000076" is_a :test 'equalp)
(annotation !obi:IAO_0000116 "note: defined class"))
(append
(if (car xrefs)
(loop for xref in xrefs collect
(annotation !oboinowl:hasDbXref (format nil "~a" xref))))
(list :partial)
(if (getf (cdr record) :is_obsolete)
(list !oboinowl:ObsoleteClass)
(mapcar #'uri-ify is_a))))))
(write-rdfxml ogms dest))))
(defun ogms-convert (&optional (source "ogms:ontology;ogms.obo") (dest "ogms:ontology;ogms.owl"))
(let ((obo (make-instance 'obo :path source)))
(read-obo obo)
(ogms-to-owl obo dest)))
(defparameter *bfo-map*
'(("BFO:0000000" "http://www.ifomis.org/bfo/1.1#Entity")
("BFO:0000001" "http://www.ifomis.org/bfo/1.1/snap#Continuant")
("BFO:0000003" "http://www.ifomis.org/bfo/1.1/snap#DependentContinuant")
("BFO:0000004" "http://www.ifomis.org/bfo/1.1/snap#IndependentContinuant")
("BFO:0000005" "http://www.ifomis.org/bfo/1.1/snap#GenericallyDependentContinuant")
("BFO:0000006" "http://www.ifomis.org/bfo/1.1/snap#SpecificallyDependentContinuant")
("BFO:0000007" "http://www.ifomis.org/bfo/1.1/snap#Quality")
("BFO:0000008" "http://www.ifomis.org/bfo/1.1/snap#RealizableEntity")
("BFO:0000009" "http://www.ifomis.org/bfo/1.1/snap#Disposition")
("BFO:0000010" "http://www.ifomis.org/bfo/1.1/snap#Role")
("BFO:0000011" "http://www.ifomis.org/bfo/1.1/snap#Function")
("BFO:0000012" "http://www.ifomis.org/bfo/1.1/snap#Capability")
("BFO:0000041" "http://www.ifomis.org/bfo/1.1/snap#MaterialEntity")
("BFO:0000042" "http://www.ifomis.org/bfo/1.1/snap#FiatObjectPart")
("BFO:0000043" "http://www.ifomis.org/bfo/1.1/snap#Object")
("BFO:0000044" "http://www.ifomis.org/bfo/1.1/snap#ObjectAggregate")
("BFO:0000002" "http://www.ifomis.org/bfo/1.1/span#Occurrent")
("BFO:0000052" "http://www.ifomis.org/bfo/1.1/span#ProcessualEntity")
("BFO:0000053" "http://www.ifomis.org/bfo/1.1/span#FiatProcessPart")
("BFO:0000058" "http://www.ifomis.org/bfo/1.1/span#Process")
("BFO:0000062" "http://www.ifomis.org/bfo/1.1/span#ProcessAggregate")))
| true |
;; another obo to owl converter
;; (setq obo (make-instance 'obo :path "~/repos/ogms/trunk/src/ontology/ogms.obo"))
;; (read-obo obo)
;; (ogms-to-owl obo) -> ~/Desktop/ogms.owl
(defun getf-multiple (plist indicator)
(loop for (key value) on plist by #'cddr when (eq indicator key) collect value))
(defun ogms-to-owl (obo &optional (dest "ogms:ontology;ogms.owl"))
(flet ((uri-ify (id)
(cond ((equal id "BFO:0000076")
!bfo:Entity)
((#"matches" id "^BFO:.*")
(make-uri (second (assoc id *bfo-map* :test 'equalp))))
((#"matches" id "^OGMS:.*")
(make-uri (#"replaceFirst" id "OGMS:" "http://purl.obolibrary.org/obo/OGMS_")))
((#"matches" id "^OBO_REL:.*")
(make-uri (#"replaceFirst" id "^OBO_REL:" "http://www.obofoundry.org/ro/ro.owl#")))
((#"matches" id "^IAO:.*")
(make-uri (#"replaceFirst" id "^IAO:" "http://purl.obolibrary.org/obo/IAO_")))
(t (error "don't know how to convert id ~a to uri" id)))))
(with-ontology ogms (:about "http://purl.obolibrary.org/obo/ogms.owl" :base "http://purl.obolibrary.org/obo/ogms.owl")
((owl-imports !<http://www.ifomis.org/bfo/1.1>)
(owl-imports !<http://purl.obolibrary.org/obo/iao/ontology-metadata.owl>)
(owl-imports !<http://protege.stanford.edu/plugins/owl/dc/protege-dc.owl>)
(ontology-annotation !rdfs:comment "The Ontology for General Medical Science (OGMS) is based on the papers Toward an Ontological Treatment of Disease and Diagnosis and On Carcinomas and Other Pathological Entities. The ontology attempts to address some of the issues raised at the Workshop on Ontology of Diseases (Dallas, TX). OGMS was formerly called the clinical phenotype ontology. Terms from OGMS hang from the Basic Formal Ontology.
The latest version of OGMS is always available at http://purl.obolibrary.org/obo/ogms.owl
This is version 2009-12-03 aka '0.3'
http://purl.obolibrary.org/obo/ogms/2009-12-09/ogms.owl
The OGMS developer site is http://code.google.com/p/ogms/
The discussion group is http://groups.google.com/group/ogms-discuss
If you are interested in participating in the development of OGMS, please send email to PI:EMAIL:<EMAIL>END_PI. Be sure to include a google-account username with your request (this will be the username associated with a gmail address).")
(ontology-annotation !rdfs:comment "This ontology is in early development. Expect it to change.")
(ontology-annotation !dc:creator "PI:NAME:<NAME>END_PI")
(ontology-annotation !dc:creator "PI:NAME:<NAME>END_PI")
(ontology-annotation !dc:creator "PI:NAME:<NAME>END_PI")
(ontology-annotation !dc:creator "PI:NAME:<NAME>END_PI")
(ontology-annotation !dc:creator "PI:NAME:<NAME>END_PI")
(ontology-annotation !dc:creator "PI:NAME:<NAME>END_PI")
(ontology-annotation !dc:creator "PI:NAME:<NAME>END_PI")
(ontology-annotation !dc:creator "PI:NAME:<NAME>END_PI")
(ontology-annotation !dc:creator "PI:NAME:<NAME>END_PI")
(ontology-annotation !dc:creator "PI:NAME:<NAME>END_PI")
(ontology-annotation !dc:creator "PI:NAME:<NAME>END_PI")
(ontology-annotation !dc:creator "PI:NAME:<NAME>END_PI")
(annotation-property !obo:IAO_0000115 (label "definition"))
(annotation-property !obo:IAO_0000117 (label "definition editor"))
(annotation-property !obo:IAO_0000119 (label "definition source"))
(annotation-property !obo:IAO_0000116 (label "editor note"))
(annotation-property !obo:IAO_0000232 (label "curator note"))
(ontology-annotation !dc:date (literal "2009-08-07" !xsd:date))
(loop for record in (terms obo)
for name = (getf (cdr record) :name)
for id = (getf (cdr record) :id)
for is_a = (getf-multiple (cdr record) :is_a)
for xrefs = (getf-multiple (cdr record) :xref)
for def = (getf (cdr record) :def)
for created-by = (getf (cdr record) :created_by)
for creation-date = (getf (cdr record) :creation_date)
if (equal name "undefined primitive terms") do (setq name "_undefined primitive term")
unless (or (equal id !owl:Thing) (equal id !bfo:Entity) (#"matches" id "BFO.*") (equal id "OGMS:0000072"))
collect (apply 'class (unless (#"matches" id "IAO.*") (label name)) (uri-ify id)
(if (car def) (annotation !obo:IAO_0000115 (literal (car def) :|@en|)))
(if (third def) (annotation !obo:IAO_0000119 (third def)))
(if created-by (annotation !obi:IAO_0000117 (#"replaceAll" created-by "agoldfain" "PI:NAME:<NAME>END_PI")))
(if creation-date (annotation !obo:IAO_0000232 (format nil "creation date: ~a" creation-date)))
(if (member "BFO:0000076" is_a :test 'equalp)
(annotation !obi:IAO_0000116 "note: defined class"))
(append
(if (car xrefs)
(loop for xref in xrefs collect
(annotation !oboinowl:hasDbXref (format nil "~a" xref))))
(list :partial)
(if (getf (cdr record) :is_obsolete)
(list !oboinowl:ObsoleteClass)
(mapcar #'uri-ify is_a))))))
(write-rdfxml ogms dest))))
(defun ogms-convert (&optional (source "ogms:ontology;ogms.obo") (dest "ogms:ontology;ogms.owl"))
(let ((obo (make-instance 'obo :path source)))
(read-obo obo)
(ogms-to-owl obo dest)))
(defparameter *bfo-map*
'(("BFO:0000000" "http://www.ifomis.org/bfo/1.1#Entity")
("BFO:0000001" "http://www.ifomis.org/bfo/1.1/snap#Continuant")
("BFO:0000003" "http://www.ifomis.org/bfo/1.1/snap#DependentContinuant")
("BFO:0000004" "http://www.ifomis.org/bfo/1.1/snap#IndependentContinuant")
("BFO:0000005" "http://www.ifomis.org/bfo/1.1/snap#GenericallyDependentContinuant")
("BFO:0000006" "http://www.ifomis.org/bfo/1.1/snap#SpecificallyDependentContinuant")
("BFO:0000007" "http://www.ifomis.org/bfo/1.1/snap#Quality")
("BFO:0000008" "http://www.ifomis.org/bfo/1.1/snap#RealizableEntity")
("BFO:0000009" "http://www.ifomis.org/bfo/1.1/snap#Disposition")
("BFO:0000010" "http://www.ifomis.org/bfo/1.1/snap#Role")
("BFO:0000011" "http://www.ifomis.org/bfo/1.1/snap#Function")
("BFO:0000012" "http://www.ifomis.org/bfo/1.1/snap#Capability")
("BFO:0000041" "http://www.ifomis.org/bfo/1.1/snap#MaterialEntity")
("BFO:0000042" "http://www.ifomis.org/bfo/1.1/snap#FiatObjectPart")
("BFO:0000043" "http://www.ifomis.org/bfo/1.1/snap#Object")
("BFO:0000044" "http://www.ifomis.org/bfo/1.1/snap#ObjectAggregate")
("BFO:0000002" "http://www.ifomis.org/bfo/1.1/span#Occurrent")
("BFO:0000052" "http://www.ifomis.org/bfo/1.1/span#ProcessualEntity")
("BFO:0000053" "http://www.ifomis.org/bfo/1.1/span#FiatProcessPart")
("BFO:0000058" "http://www.ifomis.org/bfo/1.1/span#Process")
("BFO:0000062" "http://www.ifomis.org/bfo/1.1/span#ProcessAggregate")))
|
[
{
"context": ";;;;; Grupo 30 Taguspark - 77213 Rui Silva, 82134 Jorge Almeida\n\n(load \"exemplos.fas\")\n\n;;;;",
"end": 42,
"score": 0.999494194984436,
"start": 33,
"tag": "NAME",
"value": "Rui Silva"
},
{
"context": ";;;;; Grupo 30 Taguspark - 77213 Rui Silva, 82134 Jorge Almeida\n\n(load \"exemplos.fas\")\n\n;;;; 2.1.1 Tipo Restricao",
"end": 63,
"score": 0.9998109936714172,
"start": 50,
"tag": "NAME",
"value": "Jorge Almeida"
}
] |
projeto.lisp
|
ruimams/fill-a-pix-solver
| 0 |
;;;;; Grupo 30 Taguspark - 77213 Rui Silva, 82134 Jorge Almeida
(load "exemplos.fas")
;;;; 2.1.1 Tipo Restricao
;;; cria-restricao: lista de variaveis x predicado -> restricao
(defstruct (restricao (:constructor cria-restricao (variaveis funcao-validacao)))
"Tipo restricao caracterizado por uma lista das variaveis envolvidas na restricao, e uma funcao
que verifica a restricao."
variaveis ; lista de variaveis
funcao-validacao) ; predicado
;;; restricao-variaveis: restricao -> lista de variaveis
;;; restricao-funcao-validacao: restricao -> predicado
;;;; 2.1.2 Tipo PSR
(defstruct psr
"Tipo PSR (Problema de Satisfacao de Restricoes)"
variaveis-todas ; lista com todas as variaveis por ordem
restricoes ; lista de restricoes
hash-d ; hashtable dominio (variavel->dominio)
hash-a ; hatribuicoes (variavel->valor)
hash-r) ; restricoes (variavel->lista de restricoes)
;;; cria-psr: lista variaveis x lista de dominios x lista de restricoes -> PSR
(defun cria-psr (variaveis dominios restricoes)
""
(let ((hash-d (make-hash-table :test 'equal))
(hash-a (make-hash-table :test 'equal))
(hash-r (make-hash-table :test 'equal)))
(mapcar #'(lambda (v d) (setf (gethash v hash-d) d)) variaveis dominios)
(dolist (r restricoes)
(dolist (v (restricao-variaveis r) v)
(push r (gethash v hash-r))))
(maphash #'(lambda (v r) (declare (ignore v)) (nreverse r)) hash-r)
(make-psr :variaveis-todas variaveis
:restricoes restricoes
:hash-d hash-d
:hash-a hash-a
:hash-r hash-r)))
;;; psr-atribuicoes: PSR -> lista atribuicoes
(defun psr-atribuicoes (p)
"Retorna uma lista com todas as atribuicoes - pares (variavel . valor) - do PSR."
(loop for variavel being the hash-keys in (psr-hash-a p) using (hash-value valor)
collect (cons variavel valor)))
;;; psr-variaveis-todas: PSR -> lista variaveis
;;; psr-variaveis-nao-atribuidas: PSR -> lista de variaveis
(defun psr-variaveis-nao-atribuidas (p)
"Devolve lista de variaveis nao atribuidas (pela ordem inicial)."
(loop for v in (psr-variaveis-todas p) when (not (psr-variavel-atribuida-p p v)) collect v))
;;; psr-variavel-valor: PSR x variavel -> objecto
(defun psr-variavel-valor (p v)
"Devolve o valor atribuido a variavel (caso nao exista atribuicao devolve nil)."
(nth-value 0 (gethash v (psr-hash-a p))))
;;; psr-variavel-dominio: PSR x variavel -> dominio
(defun psr-variavel-dominio (p v)
"Devolve o dominio associado a uma variavel."
(if (psr-variavel-atribuida-p p v)
(list (psr-variavel-valor p v))
(nth-value 0 (gethash v (psr-hash-d p)))))
(defun psr-variavel-atribuida-p (p v)
"Devolve booleano que indica se a variavel esta ou nao atribuida."
(psr-variavel-valor p v))
;;; psr-variavel-restricoes: PSR x variavel -> lista restricoes
(defun psr-variavel-restricoes (p v)
"Devolve uma lista com todas as restricoes aplicaveis a uma variavel."
(nth-value 0 (gethash v (psr-hash-r p))))
;;; psr-adiciona-atribuicao!: PSR x variavel x valor -> {}
(defun psr-adiciona-atribuicao! (p v valor)
""
(setf (gethash v (psr-hash-a p)) valor))
;;; psr-remove-atribuicao!: PSR x variavel -> {}
(defun psr-remove-atribuicao! (p v)
""
(remhash v (psr-hash-a p)))
;;; psr-altera-dominio!: PSR x variavel x dominio {}
(defun psr-altera-dominio! (p v d)
""
(setf (gethash v (psr-hash-d p)) d))
;;; psr-completo-p: PSR -> logico
(defun psr-completo-p (p)
""
(null (psr-variaveis-nao-atribuidas p)))
;;; AUXILIAR
(defun psr-testa-restricoes (p restricoes)
"Testa uma lista de restricoes e devolve dois valores. O primeiro, um boleano que indica se todas
as restricoes se verificam e o segundo indica o numero de testes realizados."
(let ((testes 0))
(dolist (r restricoes (values t testes))
(incf testes)
(when (null (funcall (restricao-funcao-validacao r) p)) (return (values nil testes))))))
;;; psr-consistente-p: PSR -> logico, inteiro
(defun psr-consistente-p (p)
"Testa todas as restricoes do psr."
(psr-testa-restricoes p (psr-restricoes p)))
;;; psr-variavel-consistente-p: PSR x variavel -> logico, inteiro
(defun psr-variavel-consistente-p (p v)
"Testa as restricoes associadas a variavel 'v'."
(psr-testa-restricoes p (psr-variavel-restricoes p v)))
;;; psr-atribuicao-consistente-p: PSR x variavel x valor -> logico, inteiro
(defun psr-atribuicao-consistente-p (p v valor)
""
(let ((atribuicao (psr-variavel-valor p v))
(consistente t)
(testes 0))
(psr-adiciona-atribuicao! p v valor)
(setf (values consistente testes) (psr-variavel-consistente-p p v))
(if atribuicao (psr-adiciona-atribuicao! p v atribuicao) (psr-remove-atribuicao! p v))
(values consistente testes)))
;;; psr-atribuicoes-consistentes-arco-p: PSR x variavel x valor x variavel x valor -> logico, inteiro
(defun psr-atribuicoes-consistentes-arco-p (p v1 valor1 v2 valor2)
""
(let ((atribuicao1 (psr-variavel-valor p v1))
(atribuicao2 (psr-variavel-valor p v2))
(consistente t)
(testes 0))
(psr-adiciona-atribuicao! p v1 valor1)
(psr-adiciona-atribuicao! p v2 valor2)
(dolist (r (psr-variavel-restricoes p v1))
(when (find v2 (restricao-variaveis r) :test 'equal)
(incf testes)
(when (null (funcall (restricao-funcao-validacao r) p))
(setf consistente nil)
(return))))
(if atribuicao1 (psr-adiciona-atribuicao! p v1 atribuicao1) (psr-remove-atribuicao! p v1))
(if atribuicao2 (psr-adiciona-atribuicao! p v2 atribuicao2) (psr-remove-atribuicao! p v2))
(values consistente testes)))
;;;; 2.2.1 Funcoes de conversao
(defun variaveis-a-volta (linha coluna max-linha max-coluna)
"Devolve uma lista com as coordenadas, em formato string '(linha . coluna)', a volta da coordenada
fornecida tendo em conta as dimensoes do tabuleiro (0 <= linhas < max-linha e
0 <= colunas < max-coluna)."
(let ((variaveis (list)))
(loop for delta-l from -1 to 1 do
(loop for delta-c from -1 to 1 do
(let ((l (+ linha delta-l)) (c (+ coluna delta-c)))
(when (and (>= l 0) (< l max-linha) (>= c 0) (< c max-coluna))
(push (write-to-string (cons l c)) variaveis)))))
(nreverse variaveis)))
(defun psr-conta-valor (p variaveis valor)
"Devolve o numero de variaveis (do argumento) que tem como valor o 'valor'."
(count valor variaveis :key #'(lambda (v) (psr-variavel-valor p v)) :test 'eql))
;;; fill-a-pix->psr: array -> PSR
(defun fill-a-pix->psr (tab) ; tab de tabuleiro
""
(let ((variaveis (list)) (dominios (list)) (restricoes (list)))
(dotimes (l (array-dimension tab 0)) ; linha
(dotimes (c (array-dimension tab 1)) ; coluna
(push (write-to-string (cons l c)) variaveis)
(push (list 0 1) dominios)
(when (numberp (aref tab l c))
(let ((vav (variaveis-a-volta l c (array-dimension tab 0) (array-dimension tab 1)))
(numero (aref tab l c)))
(push
(cria-restricao
vav
#'(lambda (p) (let ((pretas (psr-conta-valor p vav 1))
(brancas (psr-conta-valor p vav 0)))
(and (<= pretas numero) (<= brancas (- (length vav) numero))))))
restricoes)))))
(cria-psr (nreverse variaveis) (nreverse dominios) (nreverse restricoes))))
(defun lista->lista2d (lista linhas colunas)
"Recebe uma lista de listas e devolve uma nova lista em formato de matriz."
(loop for l below linhas
collect (loop for c below colunas
append (nth (+ (* l colunas) c) lista))))
;;; psr->fill-a-pix: PSR x inteiro x inteiro -> array
(defun psr->fill-a-pix (p linhas colunas)
""
(let ((tab (make-array (list linhas colunas)))
(i 0))
(dolist (v (psr-variaveis-todas p) tab)
(setf (aref tab (floor i colunas) (mod i colunas)) (psr-variavel-valor p v))
(incf i))))
;;;; 2.2.2
;;; procura-retrocesso-simples: PSR -> PSR, inteiro
(defun procura-retrocesso-simples (p)
""
(let ((testes-total 0))
(if (psr-completo-p p)
(return-from procura-retrocesso-simples (values p testes-total))
(let* ((v (first (psr-variaveis-nao-atribuidas p)))
(d (psr-variavel-dominio p v)))
(dolist (valor d)
(multiple-value-bind (consistente testes) (psr-atribuicao-consistente-p p v valor)
(incf testes-total testes)
(when consistente
(psr-adiciona-atribuicao! p v valor)
(multiple-value-bind (recurs-consistente recurs-testes) (procura-retrocesso-simples p)
(incf testes-total recurs-testes)
(when (not (null recurs-consistente))
(return-from procura-retrocesso-simples (values p testes-total))))
(psr-remove-atribuicao! p v))))
(return-from procura-retrocesso-simples (values nil testes-total))))))
;;; resolve-simples: array -> array
(defun resolve-simples (tab)
""
(multiple-value-bind (p) (procura-retrocesso-simples (fill-a-pix->psr tab))
(if (null p) nil (psr->fill-a-pix p (array-dimension tab 0) (array-dimension tab 1)))))
;;; resolve-simples: array -> array
(defun resolve-grau (tab)
""
(multiple-value-bind (p) (procura-retrocesso-grau (fill-a-pix->psr tab))
(if (null p) nil (psr->fill-a-pix p (array-dimension tab 0) (array-dimension tab 1)))))
;;; resolve-simples: array -> array
(defun resolve-fc-mrv (tab)
""
(multiple-value-bind (p) (procura-retrocesso-fc-mrv (fill-a-pix->psr tab))
(if (null p) nil (psr->fill-a-pix p (array-dimension tab 0) (array-dimension tab 1)))))
;;; resolve-simples: array -> array
(defun resolve-mac-mrv (tab)
""
(multiple-value-bind (p) (procura-retrocesso-mac-mrv (fill-a-pix->psr tab))
(if (null p) nil (psr->fill-a-pix p (array-dimension tab 0) (array-dimension tab 1)))))
(defun n-restricoes-c-natribuidas (p v)
""
(count-if #'(lambda (r) (some #'(lambda (v1) (and (not (equal v1 v))
(null (psr-variavel-atribuida-p p v1))))
(restricao-variaveis r)))
(psr-variavel-restricoes p v)))
(defun psr-var-maior-grau (p)
""
(first (sort (psr-variaveis-nao-atribuidas p)
#'>
:key #'(lambda (v) (n-restricoes-c-natribuidas p v)))))
;;; procura-retrocesso-grau: PSR -> PSR, inteiro
(defun procura-retrocesso-grau (p)
""
(let ((testes-total 0))
(if (psr-completo-p p)
(return-from procura-retrocesso-grau (values p testes-total))
(let* ((v (psr-var-maior-grau p))
(d (psr-variavel-dominio p v)))
(dolist (valor d)
(multiple-value-bind (consistente testes) (psr-atribuicao-consistente-p p v valor)
(incf testes-total testes)
(when consistente
(psr-adiciona-atribuicao! p v valor)
(multiple-value-bind (recurs-consistente recurs-testes) (procura-retrocesso-grau p)
(incf testes-total recurs-testes)
(when (not (null recurs-consistente))
(return-from procura-retrocesso-grau (values p testes-total))))
(psr-remove-atribuicao! p v))))
(return-from procura-retrocesso-grau (values nil testes-total))))))
(defun psr-mrv (p)
""
(let* ((lista-vna (psr-variaveis-nao-atribuidas p))
(min-v (first lista-vna))
(min-length (length (psr-variavel-dominio p min-v))))
(dolist (v lista-vna)
(let ((d-length (length (psr-variavel-dominio p v))))
(when (< d-length min-length)
(setf min-length d-length)
(setf min-v v))))
min-v))
;;; procura-retrocesso-fc-mrv: PSR -> PSR, inteiro
(defun procura-retrocesso-fc-mrv (p)
""
(let ((testes-totais 0))
(when (psr-completo-p p) (return-from procura-retrocesso-fc-mrv (values p testes-totais)))
(let ((v (psr-mrv p)))
(dolist (valor (psr-variavel-dominio p v))
(multiple-value-bind (consistente testes) (psr-atribuicao-consistente-p p v valor)
(incf testes-totais testes)
(when consistente
(psr-adiciona-atribuicao! p v valor)
(multiple-value-bind (inferencias testes) (psr-forward-checking p v)
(incf testes-totais testes)
(when inferencias
(let ((backup (make-hash-table :test 'equal)))
(maphash #'(lambda (iv id)
(setf (gethash iv backup) (psr-variavel-dominio p iv))
(psr-altera-dominio! p iv id))
inferencias)
(multiple-value-bind (resultado testes) (procura-retrocesso-fc-mrv p)
(incf testes-totais testes)
(when resultado
(return-from procura-retrocesso-fc-mrv (values resultado testes-totais))))
(maphash #'(lambda (bv bd)
(psr-altera-dominio! p bv bd))
backup)))
(psr-remove-atribuicao! p v))))))
(return-from procura-retrocesso-fc-mrv (values nil testes-totais))))
(defun psr-forward-checking (p v)
""
(let ((testes-totais 0)
(inferencias (make-hash-table :test 'equal))
(lista-arcos (psr-arcos-vizinhos-nao-atribuidos2 p v)))
(dolist (arco lista-arcos)
(let ((v2 (first arco))
(v1 (rest arco)))
(multiple-value-bind (revise testes) (psr-revise2 p v2 v1 inferencias)
(incf testes-totais testes)
(when revise
(multiple-value-bind (d exists) (gethash v2 inferencias)
(when exists
(when (= (length d) 0)
(return-from psr-forward-checking (values nil testes-totais)))))))))
(return-from psr-forward-checking (values inferencias testes-totais))))
(defun psr-arcos-vizinhos-nao-atribuidos2 (p v)
""
(let ((lista-arcos (list))
(envolvidas (remove-duplicates (reduce #'append (psr-variavel-restricoes p v)
:key 'restricao-variaveis)
:test 'equal)))
(dolist (v-na (psr-variaveis-nao-atribuidas p))
(when (not (equal v v-na))
(when (find v-na envolvidas :test 'equal)
(push (cons v-na v) lista-arcos))))
(nreverse lista-arcos)))
(defun psr-revise2 (p x y inferencias)
""
(let* ((testes-totais 0)
(revised nil)
(dominio-x (gethash x inferencias (psr-variavel-dominio p x)))
(novo-dominio-x dominio-x)
(dominio-y (if (psr-variavel-atribuida-p p y)
(list (psr-variavel-valor p y))
(gethash y inferencias (psr-variavel-dominio p y)))))
(dolist (valor-x dominio-x)
(let ((found-consistent-value nil))
(dolist (valor-y dominio-y)
(multiple-value-bind (consistente testes) (psr-atribuicoes-consistentes-arco-p p x valor-x y valor-y)
(incf testes-totais testes)
(when consistente
(setf found-consistent-value t)
(return))))
(when (null found-consistent-value)
(setf revised t)
(setf novo-dominio-x (remove valor-x novo-dominio-x)))))
(when revised
(setf (gethash x inferencias) novo-dominio-x))
(values revised testes-totais)))
;;; procura-retrocesso-mac-mrv: PSR -> PSR, inteiro
(defun procura-retrocesso-mac-mrv (p)
""
(let ((testes-totais 0))
(when (psr-completo-p p) (return-from procura-retrocesso-mac-mrv (values p testes-totais)))
(let* ((v (psr-mrv p)))
(dolist (valor (psr-variavel-dominio p v))
(multiple-value-bind (consistente testes) (psr-atribuicao-consistente-p p v valor)
(incf testes-totais testes)
(when consistente
(psr-adiciona-atribuicao! p v valor)
(multiple-value-bind (inferencias testes) (psr-mac p v)
(incf testes-totais testes)
(when inferencias
(let ((backup (make-hash-table :test 'equal)))
(maphash #'(lambda (iv id)
(setf (gethash iv backup) (psr-variavel-dominio p iv))
(psr-altera-dominio! p iv id))
inferencias)
(multiple-value-bind (resultado testes) (procura-retrocesso-mac-mrv p)
(incf testes-totais testes)
(when resultado
(return-from procura-retrocesso-mac-mrv (values resultado testes-totais))))
(maphash #'(lambda (bv bd)
(psr-altera-dominio! p bv bd))
backup)))
(psr-remove-atribuicao! p v))))))
(return-from procura-retrocesso-mac-mrv (values nil testes-totais))))
(defun psr-mac (p v)
""
(let ((testes-totais 0)
(inferencias (make-hash-table :test 'equal))
(lista-arcos (psr-arcos-vizinhos-nao-atribuidos2 p v)))
(dolist (arco lista-arcos)
(let ((v2 (first arco))
(v1 (rest arco)))
(multiple-value-bind (revise testes) (psr-revise2 p v2 v1 inferencias)
(incf testes-totais testes)
(when revise
(multiple-value-bind (d exists) (gethash v2 inferencias)
(when exists
(when (= (length d) 0)
(return-from psr-mac (values nil testes-totais)))))
(nconc lista-arcos (remove (cons v1 v2)
(psr-arcos-vizinhos-nao-atribuidos2 p v2)
:test 'equal))))))
(return-from psr-mac (values inferencias testes-totais))))
;;; -----------------------------------------------------------------------
(defstruct restricao-fapix
""
ipixs
funcao-validacao)
(defstruct fapix
""
linhas ; numero de linhas do tabuleiro
colunas ; numero de colunas do tabuleiro
max-ipix ; numero posicoes do tabuleiro
dominio ; array: dominio de cada pix
atribuicao ; array: atribuicao de cada pix
restricoes ; array: lista de restricoes associadas a cada pix
a-volta ; array: lista de indices de pixs a volta de cada pix
relacionados ; array: lista de pixs relacionados por uma restricao de cada pix
natribuidos ; lista: indices de pixs nao atribuidos
solucionavel ; valor logico: auxiliar para tabuleiros impossiveis
dominio-len ; array: listas com indices de pixs por comprimento de dominio
pix ; array: numero da casa no tabuleiro de cada pix (nil quando nao tem numero)
hv) ; array: valor da heuristica de valor (acabou por nao ser usado visto nao se ter encontrado
; calculo util e eficiente)
(defun cria-restricao-fapix (ipixs pix a-volta-len)
""
(make-restricao-fapix :ipixs ipixs
:funcao-validacao #'(lambda (f) (multiple-value-bind (brancos pretos)
(fapix-conta-cores f ipixs)
(and (<= pretos pix)
(<= brancos (- a-volta-len pix)))))))
(defun fapix-ipixs-nao-atribuidos (f)
"Recebe um `fapix' e devolve a lista de ipixs nao atribuidos desse fapix."
(fapix-natribuidos f))
(defun fapix-pix-cor (f ipix)
"Recebe um `fapix' e um indice de um pix e devolve a cor (atribuicao) associada ao pix ou nil caso
nao tenha atribuicao."
(aref (fapix-atribuicao f) ipix))
(defun fapix-pix-dominio (f ipix)
"Recebe um `fapix' e um indice de um pix e devolve o dominio associado ao pix."
(let ((cor (fapix-pix-cor f ipix)))
(if cor
(list cor)
(aref (fapix-dominio f) ipix))))
(defun fapix-pix-restricoes (f ipix)
"Recebe um `fapix' e um indice de um pix e devolve uma lista com todas as restricoes aplicaveis ao
pix."
(aref (fapix-restricoes f) ipix))
(defun fapix-adiciona-atribuicao! (f ipix cor)
"Recebe um `fapix', um indice de um pix e uma cor (0 para branco e 1 para preto) e atribui a cor
ao pix."
(setf (aref (fapix-atribuicao f) ipix) cor))
(defun fapix-remove-atribuicao! (f ipix)
"Recebe um `fapix' e um indice de um pix e remove a atribuicao de cor do pix."
(fapix-adiciona-atribuicao! f ipix nil))
(defun fapix-altera-dominio! (f ipix d)
"Recebe um `fapix', um indice de um pix e um dominio (lista de cores), atribui esse dominio ao pix
e atualiza as listas de comprimento de dominio."
(setf (aref (fapix-dominio-len f) (length (fapix-pix-dominio f ipix)))
(remove ipix (aref (fapix-dominio-len f) (length (fapix-pix-dominio f ipix)))))
(setf (aref (fapix-dominio f) ipix) d)
(push ipix (aref (fapix-dominio-len f) (length d))))
(defun fapix-completo-p (f)
"Recebe um `fapix' e testa se o fapix esta completo (se nao tem variaveis sem atribuicao). Retorna
T se estiver completo e nil caso contrario."
(null (fapix-ipixs-nao-atribuidos f)))
(defun fapix-testa-restricoes (f restricoes)
"Recebe um `fapix' e uma lista de `restricao-fapix' e testa todas as restricoes. Retorna dois
valores. O primeiro e um valor logico que indica se todas as restricoes se verificam. O segundo e
a ultima restricao a ser testada caso nem todas as restricoes se verifiquem e NIL caso contrario. Se
a lista de restricoes estiver vazia e devolvido T e NIL."
(dolist (r restricoes (values t nil))
(when (null (funcall (restricao-fapix-funcao-validacao r) f))
(return (values nil r)))))
(defun fapix-consistente-p (f)
"Recebe um `fapix' e testa todas as retricoes do mesmo. Retorna o mesmo que
`fapix-testa-restricoes'"
(fapix-testa-restricoes f (fapix-restricoes f)))
(defun fapix-pix-consistente-p (f ipix)
"Recebe um `fapix' e um indice de um pix e testa as restricoes associadas ao pix. Retorna o mesmo
que `fapix-testa-restricoes'."
(fapix-testa-restricoes f (fapix-pix-restricoes f ipix)))
(defun fapix-atribuicao-consistente-p (f ipix cor)
"Recebe um `fapix', um indice de um pix e uma cor. Testa se a atribuicao da cor ao pix e
consistente com as restricoes associadas ao pix. Retorna o mesmo que `fapix-testa-restricoes'."
(let ((atribuicao (fapix-pix-cor f ipix))
(consistente t)
(falhou nil))
(fapix-adiciona-atribuicao! f ipix cor)
(setf (values consistente falhou) (fapix-pix-consistente-p f ipix))
(if atribuicao (fapix-adiciona-atribuicao! f ipix atribuicao) (fapix-remove-atribuicao! f ipix))
(values consistente falhou)))
(defun fapix-atribuicoes-consistentes-p (f ipix1 cor1 ipix2 cor2)
"Recebe um `fapix', dois indices de pixs e duas cores. Testa se a atribuicao da cor1 ao pix1 e da
cor2 ao pix2 e consistente com as restricoes associadas a ambos os pix (testa as restricoes de forma
sequencial - primeiro as do pix1 e depois as do pix2). Retorna o mesmo que `fapix-testa-restricoes'
."
(let ((atribuicao1 (fapix-pix-cor f ipix1))
(atribuicao2 (fapix-pix-cor f ipix2))
(consistente t))
(fapix-adiciona-atribuicao! f ipix1 cor1)
(fapix-adiciona-atribuicao! f ipix2 cor2)
(block testes
(when (fapix-testa-restricoes f (fapix-pix-restricoes f ipix1))
(when (fapix-testa-restricoes f (fapix-pix-restricoes f ipix2))
(return-from testes)))
(setf consistente nil))
(if atribuicao1 (fapix-adiciona-atribuicao! f ipix1 atribuicao1) (fapix-remove-atribuicao! f ipix1))
(if atribuicao2 (fapix-adiciona-atribuicao! f ipix2 atribuicao2) (fapix-remove-atribuicao! f ipix2))
(values consistente 0)))
(defun fapix-conta-cores (f ipixs)
"Recebe um `fapix' e uma lista de indices de pixs. Retorna dois valores: quantos pixs brancos e
pretos ha na lista."
(let ((brancos 0)
(pretos 0))
(dolist (ipix ipixs (values brancos pretos))
(let ((cor (fapix-pix-cor f ipix)))
(when cor
(if (= cor 0)
(incf brancos)
(incf pretos)))))))
(defun linha (ipix colunas)
"Devolve a linha em que se encontra o pix correspondente ao indice fornecido."
(nth-value 0 (floor ipix colunas)))
(defun coluna (ipix colunas)
"Devolve a coluna em que se encontra o pix correspondente ao indice fornecido."
(nth-value 1 (floor ipix colunas)))
(defun pix-a-volta (ipix colunas max-ipix)
"Devolve uma lista com os indices dos pix a volta do pix cujo o indice fornecido."
(loop for l from (- ipix colunas) to (+ ipix colunas) by colunas when (< -1 l max-ipix)
append (loop for c from (- l 1) to (+ l 1) when (= (linha c colunas) (linha l colunas))
collect c)))
(defun fill-a-pix->fapix (tab) ; tab de tabuleiro
"Converte um tabuleiro fill-a-pix para um `fapix'."
(let* ((linhas (array-dimension tab 0))
(colunas (array-dimension tab 1))
(max-ipix (* linhas colunas))
(pix-dominio (make-array max-ipix :initial-element (list 0 1)))
(pix-atribuicoes (make-array max-ipix :initial-element nil))
(pix-restricoes (make-array max-ipix :initial-element nil))
(pix-a-volta (make-array max-ipix :initial-element nil))
(pix-relacionados (make-array max-ipix :initial-element nil))
(pix-natribuidos (list))
(pix-solucionavel t) ; t de talvez
(dominio-len (make-array 3 :initial-element nil))
(pix-dominio-len-p (make-array max-ipix :initial-element nil))
(pix-pix (make-array max-ipix :initial-element nil))
(pix-hv (make-array max-ipix :initial-element 0))
(ipix 0))
(block ciclos
(dotimes (l linhas)
(dotimes (c colunas)
(let* ((pix (aref tab l c))
(a-volta (pix-a-volta ipix colunas max-ipix))
(a-volta-len (length a-volta)))
(setf (aref pix-a-volta ipix) a-volta)
(push ipix pix-natribuidos)
(when (numberp pix)
(when (> pix a-volta-len) (setf pix-solucionavel nil) (return-from ciclos))
(setf (aref pix-pix ipix) pix)
(let* ((restricao (cria-restricao-fapix a-volta pix a-volta-len))
(dominio (if (= pix 0) (list 0) (if (= pix a-volta-len) (list 1) nil))))
(dolist (ipix-av a-volta)
(push restricao (aref pix-restricoes ipix-av))
(setf (aref pix-relacionados ipix-av) (merge 'list
(aref pix-relacionados ipix-av)
(remove ipix-av a-volta :test '=)
#'<))
(when dominio
(setf (aref pix-dominio ipix-av) dominio)
(push ipix-av (aref dominio-len 1))
(setf (aref pix-dominio-len-p ipix-av) t)))))
(let* ((soma 0)
(numero 0))
(dolist (ipix-av a-volta)
(let ((pix-av (aref tab (linha ipix-av colunas) (coluna ipix-av colunas))))
(when pix-av
(incf soma pix-av)
(incf numero))))
;; (when (and (not (= numero 0)) (>= (round (round soma numero) a-volta-len) 1))
;; (setf (aref pix-hv ipix) 1)
;; ))
)
(incf ipix)))))
(dotimes (i max-ipix)
(when (not (aref pix-dominio-len-p i))
(push i (aref dominio-len 2)))
(delete-duplicates (aref pix-relacionados i)))
(make-fapix :linhas linhas
:colunas colunas
:max-ipix max-ipix
:dominio pix-dominio
:atribuicao pix-atribuicoes
:restricoes pix-restricoes
:a-volta pix-a-volta
:relacionados pix-relacionados
:natribuidos pix-natribuidos
:solucionavel pix-solucionavel
:dominio-len dominio-len
:pix pix-pix
:hv pix-hv)))
(defun fapix->fill-a-pix (f)
"Converte um `fapix' para um tabuleiro fill-a-pix."
(let* ((colunas (fapix-colunas f))
(tab (make-array (list (fapix-linhas f) colunas))))
(dotimes (ipix (fapix-max-ipix f) tab)
(setf (aref tab (linha ipix colunas) (coluna ipix colunas)) (fapix-pix-cor f ipix)))))
(defun algoritmo (f)
""
(when (not (fapix-solucionavel f)) (return-from algoritmo nil))
(procura-retrocesso-mac-mrv-fapix f))
(defun resolve-best (tab)
""
(fapix->fill-a-pix (algoritmo (fill-a-pix->fapix tab))))
(defun fapix-mrv-modificado (f)
""
(dolist (ipix (aref (fapix-dominio-len f) 1))
(return-from fapix-mrv-modificado ipix))
;; criterio de desempate para quando o comprimento do dominio e 2
(let* ((max-ipix (first (aref (fapix-dominio-len f) 2)))
(a-volta (aref (fapix-a-volta f) max-ipix))
(max-atrib-a-volta (count-if #'(lambda (ipix-av) (fapix-pix-cor f ipix-av)) a-volta))
(max-natrib-a-volta (- (length a-volta) max-atrib-a-volta)))
(dolist (ipix (aref (fapix-dominio-len f) 2) max-ipix)
(setf a-volta (aref (fapix-a-volta f) ipix))
(let* ((atrib-a-volta (count-if #'(lambda (ipix-av) (fapix-pix-cor f ipix-av)) a-volta))
(natrib-a-volta (- (length a-volta) atrib-a-volta)))
(when (or (> atrib-a-volta max-atrib-a-volta)
(and (= atrib-a-volta max-atrib-a-volta) (< natrib-a-volta max-natrib-a-volta)))
(setf max-atrib-a-volta atrib-a-volta)
(setf max-natrib-a-volta natrib-a-volta)
(setf max-ipix ipix))))))
(defun procura-retrocesso-fc-mrv-fapix (f)
""
(when (fapix-completo-p f)
(return-from procura-retrocesso-fc-mrv-fapix (values f 0)))
(let* ((ipix (fapix-mrv-modificado f))
(d (fapix-pix-dominio f ipix)))
;; (when (= (length d) 2)
;; (when (= (aref (fapix-hv f) ipix) 1)
;; (setf d (reverse d))))
(dolist (cor d)
(fapix-adiciona-atribuicao! f ipix cor)
(setf (fapix-natribuidos f) (remove ipix (fapix-natribuidos f)))
(setf (aref (fapix-dominio-len f) (length d))
(remove ipix (aref (fapix-dominio-len f) (length d))))
(let ((inferencias (fapix-forward-checking f ipix)))
(when inferencias
(let ((backup (make-hash-table :test 'eql)))
(maphash #'(lambda (iipix id)
(setf (gethash iipix backup) (fapix-pix-dominio f iipix))
(fapix-altera-dominio! f iipix id))
inferencias)
(multiple-value-bind (resultado) (procura-retrocesso-fc-mrv-fapix f)
(when resultado
(return-from procura-retrocesso-fc-mrv-fapix (values resultado 0))))
(maphash #'(lambda (bipix bd)
(fapix-altera-dominio! f bipix bd))
backup)))
(fapix-remove-atribuicao! f ipix)
(push ipix (fapix-natribuidos f))
(push ipix (aref (fapix-dominio-len f) (length d))))))
(return-from procura-retrocesso-fc-mrv-fapix (values nil 0)))
(defun procura-retrocesso-mac-mrv-fapix (f)
""
(when (fapix-completo-p f)
(return-from procura-retrocesso-mac-mrv-fapix (values f 0)))
(let* ((ipix (fapix-mrv-modificado f))
(d (fapix-pix-dominio f ipix)))
;; (when (= (length d) 2)
;; (when (= (aref (fapix-hv f) ipix) 1)
;; (setf d (reverse d))))
(dolist (cor d)
(fapix-adiciona-atribuicao! f ipix cor)
(setf (fapix-natribuidos f) (remove ipix (fapix-natribuidos f)))
(setf (aref (fapix-dominio-len f) (length d))
(remove ipix (aref (fapix-dominio-len f) (length d))))
(let ((inferencias (fapix-mac f ipix)))
(when inferencias
(let ((backup (make-hash-table :test 'eql)))
(maphash #'(lambda (iipix id)
(setf (gethash iipix backup) (fapix-pix-dominio f iipix))
(fapix-altera-dominio! f iipix id))
inferencias)
(multiple-value-bind (resultado) (procura-retrocesso-mac-mrv-fapix f)
(when resultado
(return-from procura-retrocesso-mac-mrv-fapix (values resultado 0))))
(maphash #'(lambda (bipix bd)
(fapix-altera-dominio! f bipix bd))
backup)))
(fapix-remove-atribuicao! f ipix)
(push ipix (fapix-natribuidos f))
(push ipix (aref (fapix-dominio-len f) (length d))))))
(return-from procura-retrocesso-mac-mrv-fapix (values nil 0)))
(defun fapix-forward-checking (f ipix)
""
(let ((inferencias (make-hash-table :test 'eql)))
(dolist (v2 (aref (fapix-relacionados f) ipix))
(when (not (fapix-pix-cor f v2))
(dolist (cor2 (gethash v2 inferencias (fapix-pix-dominio f v2)))
(multiple-value-bind (consistente r-falhou) (fapix-atribuicao-consistente-p f v2 cor2)
(when (not consistente)
(dolist (ipix3 (restricao-fapix-ipixs r-falhou))
(when (not (fapix-pix-cor f ipix3))
(when (null (setf (gethash ipix3 inferencias)
(remove cor2
(gethash ipix3 inferencias (fapix-pix-dominio f ipix3)))))
(return-from fapix-forward-checking (values nil 0))))))))))
(return-from fapix-forward-checking (values inferencias 0))))
(defun fapix-mac (f ipix)
""
(let ((inferencias (make-hash-table :test 'eql))
(lista-arcos (fapix-arcos-vizinhos-nao-atribuidos f ipix)))
(dolist (arco lista-arcos)
(let ((v2 (first arco))
(v1 (rest arco)))
(dolist (cor2 (gethash v2 inferencias (fapix-pix-dominio f v2)))
(dolist (cor1 (gethash v1 inferencias (fapix-pix-dominio f v1)))
(let ((cor1-backup (fapix-pix-cor f v1)))
(fapix-adiciona-atribuicao! f v1 cor1)
(multiple-value-bind (consistente r-falhou) (fapix-atribuicao-consistente-p f v2 cor2)
(when (not consistente)
(dolist (ipix3 (restricao-fapix-ipixs r-falhou))
(when (not (fapix-pix-cor f ipix3))
(when (null (setf (gethash ipix3 inferencias)
(remove cor2 (gethash ipix3 inferencias (fapix-pix-dominio f ipix3)))))
(fapix-adiciona-atribuicao! f v1 cor1-backup)
(return-from fapix-mac (values nil 0)))))
(nconc lista-arcos (remove (cons v1 v2)
(fapix-arcos-vizinhos-nao-atribuidos f v2)
:test 'equal))))
(fapix-adiciona-atribuicao! f v1 cor1-backup))))))
(return-from fapix-mac (values inferencias 0))))
(defun fapix-arcos-vizinhos-nao-atribuidos (f ipix)
""
(loop for ipix-rel in (aref (fapix-relacionados f) ipix) unless (fapix-pix-cor f ipix-rel)
collect (cons ipix-rel ipix)))
|
74348
|
;;;;; Grupo 30 Taguspark - 77213 <NAME>, 82134 <NAME>
(load "exemplos.fas")
;;;; 2.1.1 Tipo Restricao
;;; cria-restricao: lista de variaveis x predicado -> restricao
(defstruct (restricao (:constructor cria-restricao (variaveis funcao-validacao)))
"Tipo restricao caracterizado por uma lista das variaveis envolvidas na restricao, e uma funcao
que verifica a restricao."
variaveis ; lista de variaveis
funcao-validacao) ; predicado
;;; restricao-variaveis: restricao -> lista de variaveis
;;; restricao-funcao-validacao: restricao -> predicado
;;;; 2.1.2 Tipo PSR
(defstruct psr
"Tipo PSR (Problema de Satisfacao de Restricoes)"
variaveis-todas ; lista com todas as variaveis por ordem
restricoes ; lista de restricoes
hash-d ; hashtable dominio (variavel->dominio)
hash-a ; hatribuicoes (variavel->valor)
hash-r) ; restricoes (variavel->lista de restricoes)
;;; cria-psr: lista variaveis x lista de dominios x lista de restricoes -> PSR
(defun cria-psr (variaveis dominios restricoes)
""
(let ((hash-d (make-hash-table :test 'equal))
(hash-a (make-hash-table :test 'equal))
(hash-r (make-hash-table :test 'equal)))
(mapcar #'(lambda (v d) (setf (gethash v hash-d) d)) variaveis dominios)
(dolist (r restricoes)
(dolist (v (restricao-variaveis r) v)
(push r (gethash v hash-r))))
(maphash #'(lambda (v r) (declare (ignore v)) (nreverse r)) hash-r)
(make-psr :variaveis-todas variaveis
:restricoes restricoes
:hash-d hash-d
:hash-a hash-a
:hash-r hash-r)))
;;; psr-atribuicoes: PSR -> lista atribuicoes
(defun psr-atribuicoes (p)
"Retorna uma lista com todas as atribuicoes - pares (variavel . valor) - do PSR."
(loop for variavel being the hash-keys in (psr-hash-a p) using (hash-value valor)
collect (cons variavel valor)))
;;; psr-variaveis-todas: PSR -> lista variaveis
;;; psr-variaveis-nao-atribuidas: PSR -> lista de variaveis
(defun psr-variaveis-nao-atribuidas (p)
"Devolve lista de variaveis nao atribuidas (pela ordem inicial)."
(loop for v in (psr-variaveis-todas p) when (not (psr-variavel-atribuida-p p v)) collect v))
;;; psr-variavel-valor: PSR x variavel -> objecto
(defun psr-variavel-valor (p v)
"Devolve o valor atribuido a variavel (caso nao exista atribuicao devolve nil)."
(nth-value 0 (gethash v (psr-hash-a p))))
;;; psr-variavel-dominio: PSR x variavel -> dominio
(defun psr-variavel-dominio (p v)
"Devolve o dominio associado a uma variavel."
(if (psr-variavel-atribuida-p p v)
(list (psr-variavel-valor p v))
(nth-value 0 (gethash v (psr-hash-d p)))))
(defun psr-variavel-atribuida-p (p v)
"Devolve booleano que indica se a variavel esta ou nao atribuida."
(psr-variavel-valor p v))
;;; psr-variavel-restricoes: PSR x variavel -> lista restricoes
(defun psr-variavel-restricoes (p v)
"Devolve uma lista com todas as restricoes aplicaveis a uma variavel."
(nth-value 0 (gethash v (psr-hash-r p))))
;;; psr-adiciona-atribuicao!: PSR x variavel x valor -> {}
(defun psr-adiciona-atribuicao! (p v valor)
""
(setf (gethash v (psr-hash-a p)) valor))
;;; psr-remove-atribuicao!: PSR x variavel -> {}
(defun psr-remove-atribuicao! (p v)
""
(remhash v (psr-hash-a p)))
;;; psr-altera-dominio!: PSR x variavel x dominio {}
(defun psr-altera-dominio! (p v d)
""
(setf (gethash v (psr-hash-d p)) d))
;;; psr-completo-p: PSR -> logico
(defun psr-completo-p (p)
""
(null (psr-variaveis-nao-atribuidas p)))
;;; AUXILIAR
(defun psr-testa-restricoes (p restricoes)
"Testa uma lista de restricoes e devolve dois valores. O primeiro, um boleano que indica se todas
as restricoes se verificam e o segundo indica o numero de testes realizados."
(let ((testes 0))
(dolist (r restricoes (values t testes))
(incf testes)
(when (null (funcall (restricao-funcao-validacao r) p)) (return (values nil testes))))))
;;; psr-consistente-p: PSR -> logico, inteiro
(defun psr-consistente-p (p)
"Testa todas as restricoes do psr."
(psr-testa-restricoes p (psr-restricoes p)))
;;; psr-variavel-consistente-p: PSR x variavel -> logico, inteiro
(defun psr-variavel-consistente-p (p v)
"Testa as restricoes associadas a variavel 'v'."
(psr-testa-restricoes p (psr-variavel-restricoes p v)))
;;; psr-atribuicao-consistente-p: PSR x variavel x valor -> logico, inteiro
(defun psr-atribuicao-consistente-p (p v valor)
""
(let ((atribuicao (psr-variavel-valor p v))
(consistente t)
(testes 0))
(psr-adiciona-atribuicao! p v valor)
(setf (values consistente testes) (psr-variavel-consistente-p p v))
(if atribuicao (psr-adiciona-atribuicao! p v atribuicao) (psr-remove-atribuicao! p v))
(values consistente testes)))
;;; psr-atribuicoes-consistentes-arco-p: PSR x variavel x valor x variavel x valor -> logico, inteiro
(defun psr-atribuicoes-consistentes-arco-p (p v1 valor1 v2 valor2)
""
(let ((atribuicao1 (psr-variavel-valor p v1))
(atribuicao2 (psr-variavel-valor p v2))
(consistente t)
(testes 0))
(psr-adiciona-atribuicao! p v1 valor1)
(psr-adiciona-atribuicao! p v2 valor2)
(dolist (r (psr-variavel-restricoes p v1))
(when (find v2 (restricao-variaveis r) :test 'equal)
(incf testes)
(when (null (funcall (restricao-funcao-validacao r) p))
(setf consistente nil)
(return))))
(if atribuicao1 (psr-adiciona-atribuicao! p v1 atribuicao1) (psr-remove-atribuicao! p v1))
(if atribuicao2 (psr-adiciona-atribuicao! p v2 atribuicao2) (psr-remove-atribuicao! p v2))
(values consistente testes)))
;;;; 2.2.1 Funcoes de conversao
(defun variaveis-a-volta (linha coluna max-linha max-coluna)
"Devolve uma lista com as coordenadas, em formato string '(linha . coluna)', a volta da coordenada
fornecida tendo em conta as dimensoes do tabuleiro (0 <= linhas < max-linha e
0 <= colunas < max-coluna)."
(let ((variaveis (list)))
(loop for delta-l from -1 to 1 do
(loop for delta-c from -1 to 1 do
(let ((l (+ linha delta-l)) (c (+ coluna delta-c)))
(when (and (>= l 0) (< l max-linha) (>= c 0) (< c max-coluna))
(push (write-to-string (cons l c)) variaveis)))))
(nreverse variaveis)))
(defun psr-conta-valor (p variaveis valor)
"Devolve o numero de variaveis (do argumento) que tem como valor o 'valor'."
(count valor variaveis :key #'(lambda (v) (psr-variavel-valor p v)) :test 'eql))
;;; fill-a-pix->psr: array -> PSR
(defun fill-a-pix->psr (tab) ; tab de tabuleiro
""
(let ((variaveis (list)) (dominios (list)) (restricoes (list)))
(dotimes (l (array-dimension tab 0)) ; linha
(dotimes (c (array-dimension tab 1)) ; coluna
(push (write-to-string (cons l c)) variaveis)
(push (list 0 1) dominios)
(when (numberp (aref tab l c))
(let ((vav (variaveis-a-volta l c (array-dimension tab 0) (array-dimension tab 1)))
(numero (aref tab l c)))
(push
(cria-restricao
vav
#'(lambda (p) (let ((pretas (psr-conta-valor p vav 1))
(brancas (psr-conta-valor p vav 0)))
(and (<= pretas numero) (<= brancas (- (length vav) numero))))))
restricoes)))))
(cria-psr (nreverse variaveis) (nreverse dominios) (nreverse restricoes))))
(defun lista->lista2d (lista linhas colunas)
"Recebe uma lista de listas e devolve uma nova lista em formato de matriz."
(loop for l below linhas
collect (loop for c below colunas
append (nth (+ (* l colunas) c) lista))))
;;; psr->fill-a-pix: PSR x inteiro x inteiro -> array
(defun psr->fill-a-pix (p linhas colunas)
""
(let ((tab (make-array (list linhas colunas)))
(i 0))
(dolist (v (psr-variaveis-todas p) tab)
(setf (aref tab (floor i colunas) (mod i colunas)) (psr-variavel-valor p v))
(incf i))))
;;;; 2.2.2
;;; procura-retrocesso-simples: PSR -> PSR, inteiro
(defun procura-retrocesso-simples (p)
""
(let ((testes-total 0))
(if (psr-completo-p p)
(return-from procura-retrocesso-simples (values p testes-total))
(let* ((v (first (psr-variaveis-nao-atribuidas p)))
(d (psr-variavel-dominio p v)))
(dolist (valor d)
(multiple-value-bind (consistente testes) (psr-atribuicao-consistente-p p v valor)
(incf testes-total testes)
(when consistente
(psr-adiciona-atribuicao! p v valor)
(multiple-value-bind (recurs-consistente recurs-testes) (procura-retrocesso-simples p)
(incf testes-total recurs-testes)
(when (not (null recurs-consistente))
(return-from procura-retrocesso-simples (values p testes-total))))
(psr-remove-atribuicao! p v))))
(return-from procura-retrocesso-simples (values nil testes-total))))))
;;; resolve-simples: array -> array
(defun resolve-simples (tab)
""
(multiple-value-bind (p) (procura-retrocesso-simples (fill-a-pix->psr tab))
(if (null p) nil (psr->fill-a-pix p (array-dimension tab 0) (array-dimension tab 1)))))
;;; resolve-simples: array -> array
(defun resolve-grau (tab)
""
(multiple-value-bind (p) (procura-retrocesso-grau (fill-a-pix->psr tab))
(if (null p) nil (psr->fill-a-pix p (array-dimension tab 0) (array-dimension tab 1)))))
;;; resolve-simples: array -> array
(defun resolve-fc-mrv (tab)
""
(multiple-value-bind (p) (procura-retrocesso-fc-mrv (fill-a-pix->psr tab))
(if (null p) nil (psr->fill-a-pix p (array-dimension tab 0) (array-dimension tab 1)))))
;;; resolve-simples: array -> array
(defun resolve-mac-mrv (tab)
""
(multiple-value-bind (p) (procura-retrocesso-mac-mrv (fill-a-pix->psr tab))
(if (null p) nil (psr->fill-a-pix p (array-dimension tab 0) (array-dimension tab 1)))))
(defun n-restricoes-c-natribuidas (p v)
""
(count-if #'(lambda (r) (some #'(lambda (v1) (and (not (equal v1 v))
(null (psr-variavel-atribuida-p p v1))))
(restricao-variaveis r)))
(psr-variavel-restricoes p v)))
(defun psr-var-maior-grau (p)
""
(first (sort (psr-variaveis-nao-atribuidas p)
#'>
:key #'(lambda (v) (n-restricoes-c-natribuidas p v)))))
;;; procura-retrocesso-grau: PSR -> PSR, inteiro
(defun procura-retrocesso-grau (p)
""
(let ((testes-total 0))
(if (psr-completo-p p)
(return-from procura-retrocesso-grau (values p testes-total))
(let* ((v (psr-var-maior-grau p))
(d (psr-variavel-dominio p v)))
(dolist (valor d)
(multiple-value-bind (consistente testes) (psr-atribuicao-consistente-p p v valor)
(incf testes-total testes)
(when consistente
(psr-adiciona-atribuicao! p v valor)
(multiple-value-bind (recurs-consistente recurs-testes) (procura-retrocesso-grau p)
(incf testes-total recurs-testes)
(when (not (null recurs-consistente))
(return-from procura-retrocesso-grau (values p testes-total))))
(psr-remove-atribuicao! p v))))
(return-from procura-retrocesso-grau (values nil testes-total))))))
(defun psr-mrv (p)
""
(let* ((lista-vna (psr-variaveis-nao-atribuidas p))
(min-v (first lista-vna))
(min-length (length (psr-variavel-dominio p min-v))))
(dolist (v lista-vna)
(let ((d-length (length (psr-variavel-dominio p v))))
(when (< d-length min-length)
(setf min-length d-length)
(setf min-v v))))
min-v))
;;; procura-retrocesso-fc-mrv: PSR -> PSR, inteiro
(defun procura-retrocesso-fc-mrv (p)
""
(let ((testes-totais 0))
(when (psr-completo-p p) (return-from procura-retrocesso-fc-mrv (values p testes-totais)))
(let ((v (psr-mrv p)))
(dolist (valor (psr-variavel-dominio p v))
(multiple-value-bind (consistente testes) (psr-atribuicao-consistente-p p v valor)
(incf testes-totais testes)
(when consistente
(psr-adiciona-atribuicao! p v valor)
(multiple-value-bind (inferencias testes) (psr-forward-checking p v)
(incf testes-totais testes)
(when inferencias
(let ((backup (make-hash-table :test 'equal)))
(maphash #'(lambda (iv id)
(setf (gethash iv backup) (psr-variavel-dominio p iv))
(psr-altera-dominio! p iv id))
inferencias)
(multiple-value-bind (resultado testes) (procura-retrocesso-fc-mrv p)
(incf testes-totais testes)
(when resultado
(return-from procura-retrocesso-fc-mrv (values resultado testes-totais))))
(maphash #'(lambda (bv bd)
(psr-altera-dominio! p bv bd))
backup)))
(psr-remove-atribuicao! p v))))))
(return-from procura-retrocesso-fc-mrv (values nil testes-totais))))
(defun psr-forward-checking (p v)
""
(let ((testes-totais 0)
(inferencias (make-hash-table :test 'equal))
(lista-arcos (psr-arcos-vizinhos-nao-atribuidos2 p v)))
(dolist (arco lista-arcos)
(let ((v2 (first arco))
(v1 (rest arco)))
(multiple-value-bind (revise testes) (psr-revise2 p v2 v1 inferencias)
(incf testes-totais testes)
(when revise
(multiple-value-bind (d exists) (gethash v2 inferencias)
(when exists
(when (= (length d) 0)
(return-from psr-forward-checking (values nil testes-totais)))))))))
(return-from psr-forward-checking (values inferencias testes-totais))))
(defun psr-arcos-vizinhos-nao-atribuidos2 (p v)
""
(let ((lista-arcos (list))
(envolvidas (remove-duplicates (reduce #'append (psr-variavel-restricoes p v)
:key 'restricao-variaveis)
:test 'equal)))
(dolist (v-na (psr-variaveis-nao-atribuidas p))
(when (not (equal v v-na))
(when (find v-na envolvidas :test 'equal)
(push (cons v-na v) lista-arcos))))
(nreverse lista-arcos)))
(defun psr-revise2 (p x y inferencias)
""
(let* ((testes-totais 0)
(revised nil)
(dominio-x (gethash x inferencias (psr-variavel-dominio p x)))
(novo-dominio-x dominio-x)
(dominio-y (if (psr-variavel-atribuida-p p y)
(list (psr-variavel-valor p y))
(gethash y inferencias (psr-variavel-dominio p y)))))
(dolist (valor-x dominio-x)
(let ((found-consistent-value nil))
(dolist (valor-y dominio-y)
(multiple-value-bind (consistente testes) (psr-atribuicoes-consistentes-arco-p p x valor-x y valor-y)
(incf testes-totais testes)
(when consistente
(setf found-consistent-value t)
(return))))
(when (null found-consistent-value)
(setf revised t)
(setf novo-dominio-x (remove valor-x novo-dominio-x)))))
(when revised
(setf (gethash x inferencias) novo-dominio-x))
(values revised testes-totais)))
;;; procura-retrocesso-mac-mrv: PSR -> PSR, inteiro
(defun procura-retrocesso-mac-mrv (p)
""
(let ((testes-totais 0))
(when (psr-completo-p p) (return-from procura-retrocesso-mac-mrv (values p testes-totais)))
(let* ((v (psr-mrv p)))
(dolist (valor (psr-variavel-dominio p v))
(multiple-value-bind (consistente testes) (psr-atribuicao-consistente-p p v valor)
(incf testes-totais testes)
(when consistente
(psr-adiciona-atribuicao! p v valor)
(multiple-value-bind (inferencias testes) (psr-mac p v)
(incf testes-totais testes)
(when inferencias
(let ((backup (make-hash-table :test 'equal)))
(maphash #'(lambda (iv id)
(setf (gethash iv backup) (psr-variavel-dominio p iv))
(psr-altera-dominio! p iv id))
inferencias)
(multiple-value-bind (resultado testes) (procura-retrocesso-mac-mrv p)
(incf testes-totais testes)
(when resultado
(return-from procura-retrocesso-mac-mrv (values resultado testes-totais))))
(maphash #'(lambda (bv bd)
(psr-altera-dominio! p bv bd))
backup)))
(psr-remove-atribuicao! p v))))))
(return-from procura-retrocesso-mac-mrv (values nil testes-totais))))
(defun psr-mac (p v)
""
(let ((testes-totais 0)
(inferencias (make-hash-table :test 'equal))
(lista-arcos (psr-arcos-vizinhos-nao-atribuidos2 p v)))
(dolist (arco lista-arcos)
(let ((v2 (first arco))
(v1 (rest arco)))
(multiple-value-bind (revise testes) (psr-revise2 p v2 v1 inferencias)
(incf testes-totais testes)
(when revise
(multiple-value-bind (d exists) (gethash v2 inferencias)
(when exists
(when (= (length d) 0)
(return-from psr-mac (values nil testes-totais)))))
(nconc lista-arcos (remove (cons v1 v2)
(psr-arcos-vizinhos-nao-atribuidos2 p v2)
:test 'equal))))))
(return-from psr-mac (values inferencias testes-totais))))
;;; -----------------------------------------------------------------------
(defstruct restricao-fapix
""
ipixs
funcao-validacao)
(defstruct fapix
""
linhas ; numero de linhas do tabuleiro
colunas ; numero de colunas do tabuleiro
max-ipix ; numero posicoes do tabuleiro
dominio ; array: dominio de cada pix
atribuicao ; array: atribuicao de cada pix
restricoes ; array: lista de restricoes associadas a cada pix
a-volta ; array: lista de indices de pixs a volta de cada pix
relacionados ; array: lista de pixs relacionados por uma restricao de cada pix
natribuidos ; lista: indices de pixs nao atribuidos
solucionavel ; valor logico: auxiliar para tabuleiros impossiveis
dominio-len ; array: listas com indices de pixs por comprimento de dominio
pix ; array: numero da casa no tabuleiro de cada pix (nil quando nao tem numero)
hv) ; array: valor da heuristica de valor (acabou por nao ser usado visto nao se ter encontrado
; calculo util e eficiente)
(defun cria-restricao-fapix (ipixs pix a-volta-len)
""
(make-restricao-fapix :ipixs ipixs
:funcao-validacao #'(lambda (f) (multiple-value-bind (brancos pretos)
(fapix-conta-cores f ipixs)
(and (<= pretos pix)
(<= brancos (- a-volta-len pix)))))))
(defun fapix-ipixs-nao-atribuidos (f)
"Recebe um `fapix' e devolve a lista de ipixs nao atribuidos desse fapix."
(fapix-natribuidos f))
(defun fapix-pix-cor (f ipix)
"Recebe um `fapix' e um indice de um pix e devolve a cor (atribuicao) associada ao pix ou nil caso
nao tenha atribuicao."
(aref (fapix-atribuicao f) ipix))
(defun fapix-pix-dominio (f ipix)
"Recebe um `fapix' e um indice de um pix e devolve o dominio associado ao pix."
(let ((cor (fapix-pix-cor f ipix)))
(if cor
(list cor)
(aref (fapix-dominio f) ipix))))
(defun fapix-pix-restricoes (f ipix)
"Recebe um `fapix' e um indice de um pix e devolve uma lista com todas as restricoes aplicaveis ao
pix."
(aref (fapix-restricoes f) ipix))
(defun fapix-adiciona-atribuicao! (f ipix cor)
"Recebe um `fapix', um indice de um pix e uma cor (0 para branco e 1 para preto) e atribui a cor
ao pix."
(setf (aref (fapix-atribuicao f) ipix) cor))
(defun fapix-remove-atribuicao! (f ipix)
"Recebe um `fapix' e um indice de um pix e remove a atribuicao de cor do pix."
(fapix-adiciona-atribuicao! f ipix nil))
(defun fapix-altera-dominio! (f ipix d)
"Recebe um `fapix', um indice de um pix e um dominio (lista de cores), atribui esse dominio ao pix
e atualiza as listas de comprimento de dominio."
(setf (aref (fapix-dominio-len f) (length (fapix-pix-dominio f ipix)))
(remove ipix (aref (fapix-dominio-len f) (length (fapix-pix-dominio f ipix)))))
(setf (aref (fapix-dominio f) ipix) d)
(push ipix (aref (fapix-dominio-len f) (length d))))
(defun fapix-completo-p (f)
"Recebe um `fapix' e testa se o fapix esta completo (se nao tem variaveis sem atribuicao). Retorna
T se estiver completo e nil caso contrario."
(null (fapix-ipixs-nao-atribuidos f)))
(defun fapix-testa-restricoes (f restricoes)
"Recebe um `fapix' e uma lista de `restricao-fapix' e testa todas as restricoes. Retorna dois
valores. O primeiro e um valor logico que indica se todas as restricoes se verificam. O segundo e
a ultima restricao a ser testada caso nem todas as restricoes se verifiquem e NIL caso contrario. Se
a lista de restricoes estiver vazia e devolvido T e NIL."
(dolist (r restricoes (values t nil))
(when (null (funcall (restricao-fapix-funcao-validacao r) f))
(return (values nil r)))))
(defun fapix-consistente-p (f)
"Recebe um `fapix' e testa todas as retricoes do mesmo. Retorna o mesmo que
`fapix-testa-restricoes'"
(fapix-testa-restricoes f (fapix-restricoes f)))
(defun fapix-pix-consistente-p (f ipix)
"Recebe um `fapix' e um indice de um pix e testa as restricoes associadas ao pix. Retorna o mesmo
que `fapix-testa-restricoes'."
(fapix-testa-restricoes f (fapix-pix-restricoes f ipix)))
(defun fapix-atribuicao-consistente-p (f ipix cor)
"Recebe um `fapix', um indice de um pix e uma cor. Testa se a atribuicao da cor ao pix e
consistente com as restricoes associadas ao pix. Retorna o mesmo que `fapix-testa-restricoes'."
(let ((atribuicao (fapix-pix-cor f ipix))
(consistente t)
(falhou nil))
(fapix-adiciona-atribuicao! f ipix cor)
(setf (values consistente falhou) (fapix-pix-consistente-p f ipix))
(if atribuicao (fapix-adiciona-atribuicao! f ipix atribuicao) (fapix-remove-atribuicao! f ipix))
(values consistente falhou)))
(defun fapix-atribuicoes-consistentes-p (f ipix1 cor1 ipix2 cor2)
"Recebe um `fapix', dois indices de pixs e duas cores. Testa se a atribuicao da cor1 ao pix1 e da
cor2 ao pix2 e consistente com as restricoes associadas a ambos os pix (testa as restricoes de forma
sequencial - primeiro as do pix1 e depois as do pix2). Retorna o mesmo que `fapix-testa-restricoes'
."
(let ((atribuicao1 (fapix-pix-cor f ipix1))
(atribuicao2 (fapix-pix-cor f ipix2))
(consistente t))
(fapix-adiciona-atribuicao! f ipix1 cor1)
(fapix-adiciona-atribuicao! f ipix2 cor2)
(block testes
(when (fapix-testa-restricoes f (fapix-pix-restricoes f ipix1))
(when (fapix-testa-restricoes f (fapix-pix-restricoes f ipix2))
(return-from testes)))
(setf consistente nil))
(if atribuicao1 (fapix-adiciona-atribuicao! f ipix1 atribuicao1) (fapix-remove-atribuicao! f ipix1))
(if atribuicao2 (fapix-adiciona-atribuicao! f ipix2 atribuicao2) (fapix-remove-atribuicao! f ipix2))
(values consistente 0)))
(defun fapix-conta-cores (f ipixs)
"Recebe um `fapix' e uma lista de indices de pixs. Retorna dois valores: quantos pixs brancos e
pretos ha na lista."
(let ((brancos 0)
(pretos 0))
(dolist (ipix ipixs (values brancos pretos))
(let ((cor (fapix-pix-cor f ipix)))
(when cor
(if (= cor 0)
(incf brancos)
(incf pretos)))))))
(defun linha (ipix colunas)
"Devolve a linha em que se encontra o pix correspondente ao indice fornecido."
(nth-value 0 (floor ipix colunas)))
(defun coluna (ipix colunas)
"Devolve a coluna em que se encontra o pix correspondente ao indice fornecido."
(nth-value 1 (floor ipix colunas)))
(defun pix-a-volta (ipix colunas max-ipix)
"Devolve uma lista com os indices dos pix a volta do pix cujo o indice fornecido."
(loop for l from (- ipix colunas) to (+ ipix colunas) by colunas when (< -1 l max-ipix)
append (loop for c from (- l 1) to (+ l 1) when (= (linha c colunas) (linha l colunas))
collect c)))
(defun fill-a-pix->fapix (tab) ; tab de tabuleiro
"Converte um tabuleiro fill-a-pix para um `fapix'."
(let* ((linhas (array-dimension tab 0))
(colunas (array-dimension tab 1))
(max-ipix (* linhas colunas))
(pix-dominio (make-array max-ipix :initial-element (list 0 1)))
(pix-atribuicoes (make-array max-ipix :initial-element nil))
(pix-restricoes (make-array max-ipix :initial-element nil))
(pix-a-volta (make-array max-ipix :initial-element nil))
(pix-relacionados (make-array max-ipix :initial-element nil))
(pix-natribuidos (list))
(pix-solucionavel t) ; t de talvez
(dominio-len (make-array 3 :initial-element nil))
(pix-dominio-len-p (make-array max-ipix :initial-element nil))
(pix-pix (make-array max-ipix :initial-element nil))
(pix-hv (make-array max-ipix :initial-element 0))
(ipix 0))
(block ciclos
(dotimes (l linhas)
(dotimes (c colunas)
(let* ((pix (aref tab l c))
(a-volta (pix-a-volta ipix colunas max-ipix))
(a-volta-len (length a-volta)))
(setf (aref pix-a-volta ipix) a-volta)
(push ipix pix-natribuidos)
(when (numberp pix)
(when (> pix a-volta-len) (setf pix-solucionavel nil) (return-from ciclos))
(setf (aref pix-pix ipix) pix)
(let* ((restricao (cria-restricao-fapix a-volta pix a-volta-len))
(dominio (if (= pix 0) (list 0) (if (= pix a-volta-len) (list 1) nil))))
(dolist (ipix-av a-volta)
(push restricao (aref pix-restricoes ipix-av))
(setf (aref pix-relacionados ipix-av) (merge 'list
(aref pix-relacionados ipix-av)
(remove ipix-av a-volta :test '=)
#'<))
(when dominio
(setf (aref pix-dominio ipix-av) dominio)
(push ipix-av (aref dominio-len 1))
(setf (aref pix-dominio-len-p ipix-av) t)))))
(let* ((soma 0)
(numero 0))
(dolist (ipix-av a-volta)
(let ((pix-av (aref tab (linha ipix-av colunas) (coluna ipix-av colunas))))
(when pix-av
(incf soma pix-av)
(incf numero))))
;; (when (and (not (= numero 0)) (>= (round (round soma numero) a-volta-len) 1))
;; (setf (aref pix-hv ipix) 1)
;; ))
)
(incf ipix)))))
(dotimes (i max-ipix)
(when (not (aref pix-dominio-len-p i))
(push i (aref dominio-len 2)))
(delete-duplicates (aref pix-relacionados i)))
(make-fapix :linhas linhas
:colunas colunas
:max-ipix max-ipix
:dominio pix-dominio
:atribuicao pix-atribuicoes
:restricoes pix-restricoes
:a-volta pix-a-volta
:relacionados pix-relacionados
:natribuidos pix-natribuidos
:solucionavel pix-solucionavel
:dominio-len dominio-len
:pix pix-pix
:hv pix-hv)))
(defun fapix->fill-a-pix (f)
"Converte um `fapix' para um tabuleiro fill-a-pix."
(let* ((colunas (fapix-colunas f))
(tab (make-array (list (fapix-linhas f) colunas))))
(dotimes (ipix (fapix-max-ipix f) tab)
(setf (aref tab (linha ipix colunas) (coluna ipix colunas)) (fapix-pix-cor f ipix)))))
(defun algoritmo (f)
""
(when (not (fapix-solucionavel f)) (return-from algoritmo nil))
(procura-retrocesso-mac-mrv-fapix f))
(defun resolve-best (tab)
""
(fapix->fill-a-pix (algoritmo (fill-a-pix->fapix tab))))
(defun fapix-mrv-modificado (f)
""
(dolist (ipix (aref (fapix-dominio-len f) 1))
(return-from fapix-mrv-modificado ipix))
;; criterio de desempate para quando o comprimento do dominio e 2
(let* ((max-ipix (first (aref (fapix-dominio-len f) 2)))
(a-volta (aref (fapix-a-volta f) max-ipix))
(max-atrib-a-volta (count-if #'(lambda (ipix-av) (fapix-pix-cor f ipix-av)) a-volta))
(max-natrib-a-volta (- (length a-volta) max-atrib-a-volta)))
(dolist (ipix (aref (fapix-dominio-len f) 2) max-ipix)
(setf a-volta (aref (fapix-a-volta f) ipix))
(let* ((atrib-a-volta (count-if #'(lambda (ipix-av) (fapix-pix-cor f ipix-av)) a-volta))
(natrib-a-volta (- (length a-volta) atrib-a-volta)))
(when (or (> atrib-a-volta max-atrib-a-volta)
(and (= atrib-a-volta max-atrib-a-volta) (< natrib-a-volta max-natrib-a-volta)))
(setf max-atrib-a-volta atrib-a-volta)
(setf max-natrib-a-volta natrib-a-volta)
(setf max-ipix ipix))))))
(defun procura-retrocesso-fc-mrv-fapix (f)
""
(when (fapix-completo-p f)
(return-from procura-retrocesso-fc-mrv-fapix (values f 0)))
(let* ((ipix (fapix-mrv-modificado f))
(d (fapix-pix-dominio f ipix)))
;; (when (= (length d) 2)
;; (when (= (aref (fapix-hv f) ipix) 1)
;; (setf d (reverse d))))
(dolist (cor d)
(fapix-adiciona-atribuicao! f ipix cor)
(setf (fapix-natribuidos f) (remove ipix (fapix-natribuidos f)))
(setf (aref (fapix-dominio-len f) (length d))
(remove ipix (aref (fapix-dominio-len f) (length d))))
(let ((inferencias (fapix-forward-checking f ipix)))
(when inferencias
(let ((backup (make-hash-table :test 'eql)))
(maphash #'(lambda (iipix id)
(setf (gethash iipix backup) (fapix-pix-dominio f iipix))
(fapix-altera-dominio! f iipix id))
inferencias)
(multiple-value-bind (resultado) (procura-retrocesso-fc-mrv-fapix f)
(when resultado
(return-from procura-retrocesso-fc-mrv-fapix (values resultado 0))))
(maphash #'(lambda (bipix bd)
(fapix-altera-dominio! f bipix bd))
backup)))
(fapix-remove-atribuicao! f ipix)
(push ipix (fapix-natribuidos f))
(push ipix (aref (fapix-dominio-len f) (length d))))))
(return-from procura-retrocesso-fc-mrv-fapix (values nil 0)))
(defun procura-retrocesso-mac-mrv-fapix (f)
""
(when (fapix-completo-p f)
(return-from procura-retrocesso-mac-mrv-fapix (values f 0)))
(let* ((ipix (fapix-mrv-modificado f))
(d (fapix-pix-dominio f ipix)))
;; (when (= (length d) 2)
;; (when (= (aref (fapix-hv f) ipix) 1)
;; (setf d (reverse d))))
(dolist (cor d)
(fapix-adiciona-atribuicao! f ipix cor)
(setf (fapix-natribuidos f) (remove ipix (fapix-natribuidos f)))
(setf (aref (fapix-dominio-len f) (length d))
(remove ipix (aref (fapix-dominio-len f) (length d))))
(let ((inferencias (fapix-mac f ipix)))
(when inferencias
(let ((backup (make-hash-table :test 'eql)))
(maphash #'(lambda (iipix id)
(setf (gethash iipix backup) (fapix-pix-dominio f iipix))
(fapix-altera-dominio! f iipix id))
inferencias)
(multiple-value-bind (resultado) (procura-retrocesso-mac-mrv-fapix f)
(when resultado
(return-from procura-retrocesso-mac-mrv-fapix (values resultado 0))))
(maphash #'(lambda (bipix bd)
(fapix-altera-dominio! f bipix bd))
backup)))
(fapix-remove-atribuicao! f ipix)
(push ipix (fapix-natribuidos f))
(push ipix (aref (fapix-dominio-len f) (length d))))))
(return-from procura-retrocesso-mac-mrv-fapix (values nil 0)))
(defun fapix-forward-checking (f ipix)
""
(let ((inferencias (make-hash-table :test 'eql)))
(dolist (v2 (aref (fapix-relacionados f) ipix))
(when (not (fapix-pix-cor f v2))
(dolist (cor2 (gethash v2 inferencias (fapix-pix-dominio f v2)))
(multiple-value-bind (consistente r-falhou) (fapix-atribuicao-consistente-p f v2 cor2)
(when (not consistente)
(dolist (ipix3 (restricao-fapix-ipixs r-falhou))
(when (not (fapix-pix-cor f ipix3))
(when (null (setf (gethash ipix3 inferencias)
(remove cor2
(gethash ipix3 inferencias (fapix-pix-dominio f ipix3)))))
(return-from fapix-forward-checking (values nil 0))))))))))
(return-from fapix-forward-checking (values inferencias 0))))
(defun fapix-mac (f ipix)
""
(let ((inferencias (make-hash-table :test 'eql))
(lista-arcos (fapix-arcos-vizinhos-nao-atribuidos f ipix)))
(dolist (arco lista-arcos)
(let ((v2 (first arco))
(v1 (rest arco)))
(dolist (cor2 (gethash v2 inferencias (fapix-pix-dominio f v2)))
(dolist (cor1 (gethash v1 inferencias (fapix-pix-dominio f v1)))
(let ((cor1-backup (fapix-pix-cor f v1)))
(fapix-adiciona-atribuicao! f v1 cor1)
(multiple-value-bind (consistente r-falhou) (fapix-atribuicao-consistente-p f v2 cor2)
(when (not consistente)
(dolist (ipix3 (restricao-fapix-ipixs r-falhou))
(when (not (fapix-pix-cor f ipix3))
(when (null (setf (gethash ipix3 inferencias)
(remove cor2 (gethash ipix3 inferencias (fapix-pix-dominio f ipix3)))))
(fapix-adiciona-atribuicao! f v1 cor1-backup)
(return-from fapix-mac (values nil 0)))))
(nconc lista-arcos (remove (cons v1 v2)
(fapix-arcos-vizinhos-nao-atribuidos f v2)
:test 'equal))))
(fapix-adiciona-atribuicao! f v1 cor1-backup))))))
(return-from fapix-mac (values inferencias 0))))
(defun fapix-arcos-vizinhos-nao-atribuidos (f ipix)
""
(loop for ipix-rel in (aref (fapix-relacionados f) ipix) unless (fapix-pix-cor f ipix-rel)
collect (cons ipix-rel ipix)))
| true |
;;;;; Grupo 30 Taguspark - 77213 PI:NAME:<NAME>END_PI, 82134 PI:NAME:<NAME>END_PI
(load "exemplos.fas")
;;;; 2.1.1 Tipo Restricao
;;; cria-restricao: lista de variaveis x predicado -> restricao
(defstruct (restricao (:constructor cria-restricao (variaveis funcao-validacao)))
"Tipo restricao caracterizado por uma lista das variaveis envolvidas na restricao, e uma funcao
que verifica a restricao."
variaveis ; lista de variaveis
funcao-validacao) ; predicado
;;; restricao-variaveis: restricao -> lista de variaveis
;;; restricao-funcao-validacao: restricao -> predicado
;;;; 2.1.2 Tipo PSR
(defstruct psr
"Tipo PSR (Problema de Satisfacao de Restricoes)"
variaveis-todas ; lista com todas as variaveis por ordem
restricoes ; lista de restricoes
hash-d ; hashtable dominio (variavel->dominio)
hash-a ; hatribuicoes (variavel->valor)
hash-r) ; restricoes (variavel->lista de restricoes)
;;; cria-psr: lista variaveis x lista de dominios x lista de restricoes -> PSR
(defun cria-psr (variaveis dominios restricoes)
""
(let ((hash-d (make-hash-table :test 'equal))
(hash-a (make-hash-table :test 'equal))
(hash-r (make-hash-table :test 'equal)))
(mapcar #'(lambda (v d) (setf (gethash v hash-d) d)) variaveis dominios)
(dolist (r restricoes)
(dolist (v (restricao-variaveis r) v)
(push r (gethash v hash-r))))
(maphash #'(lambda (v r) (declare (ignore v)) (nreverse r)) hash-r)
(make-psr :variaveis-todas variaveis
:restricoes restricoes
:hash-d hash-d
:hash-a hash-a
:hash-r hash-r)))
;;; psr-atribuicoes: PSR -> lista atribuicoes
(defun psr-atribuicoes (p)
"Retorna uma lista com todas as atribuicoes - pares (variavel . valor) - do PSR."
(loop for variavel being the hash-keys in (psr-hash-a p) using (hash-value valor)
collect (cons variavel valor)))
;;; psr-variaveis-todas: PSR -> lista variaveis
;;; psr-variaveis-nao-atribuidas: PSR -> lista de variaveis
(defun psr-variaveis-nao-atribuidas (p)
"Devolve lista de variaveis nao atribuidas (pela ordem inicial)."
(loop for v in (psr-variaveis-todas p) when (not (psr-variavel-atribuida-p p v)) collect v))
;;; psr-variavel-valor: PSR x variavel -> objecto
(defun psr-variavel-valor (p v)
"Devolve o valor atribuido a variavel (caso nao exista atribuicao devolve nil)."
(nth-value 0 (gethash v (psr-hash-a p))))
;;; psr-variavel-dominio: PSR x variavel -> dominio
(defun psr-variavel-dominio (p v)
"Devolve o dominio associado a uma variavel."
(if (psr-variavel-atribuida-p p v)
(list (psr-variavel-valor p v))
(nth-value 0 (gethash v (psr-hash-d p)))))
(defun psr-variavel-atribuida-p (p v)
"Devolve booleano que indica se a variavel esta ou nao atribuida."
(psr-variavel-valor p v))
;;; psr-variavel-restricoes: PSR x variavel -> lista restricoes
(defun psr-variavel-restricoes (p v)
"Devolve uma lista com todas as restricoes aplicaveis a uma variavel."
(nth-value 0 (gethash v (psr-hash-r p))))
;;; psr-adiciona-atribuicao!: PSR x variavel x valor -> {}
(defun psr-adiciona-atribuicao! (p v valor)
""
(setf (gethash v (psr-hash-a p)) valor))
;;; psr-remove-atribuicao!: PSR x variavel -> {}
(defun psr-remove-atribuicao! (p v)
""
(remhash v (psr-hash-a p)))
;;; psr-altera-dominio!: PSR x variavel x dominio {}
(defun psr-altera-dominio! (p v d)
""
(setf (gethash v (psr-hash-d p)) d))
;;; psr-completo-p: PSR -> logico
(defun psr-completo-p (p)
""
(null (psr-variaveis-nao-atribuidas p)))
;;; AUXILIAR
(defun psr-testa-restricoes (p restricoes)
"Testa uma lista de restricoes e devolve dois valores. O primeiro, um boleano que indica se todas
as restricoes se verificam e o segundo indica o numero de testes realizados."
(let ((testes 0))
(dolist (r restricoes (values t testes))
(incf testes)
(when (null (funcall (restricao-funcao-validacao r) p)) (return (values nil testes))))))
;;; psr-consistente-p: PSR -> logico, inteiro
(defun psr-consistente-p (p)
"Testa todas as restricoes do psr."
(psr-testa-restricoes p (psr-restricoes p)))
;;; psr-variavel-consistente-p: PSR x variavel -> logico, inteiro
(defun psr-variavel-consistente-p (p v)
"Testa as restricoes associadas a variavel 'v'."
(psr-testa-restricoes p (psr-variavel-restricoes p v)))
;;; psr-atribuicao-consistente-p: PSR x variavel x valor -> logico, inteiro
(defun psr-atribuicao-consistente-p (p v valor)
""
(let ((atribuicao (psr-variavel-valor p v))
(consistente t)
(testes 0))
(psr-adiciona-atribuicao! p v valor)
(setf (values consistente testes) (psr-variavel-consistente-p p v))
(if atribuicao (psr-adiciona-atribuicao! p v atribuicao) (psr-remove-atribuicao! p v))
(values consistente testes)))
;;; psr-atribuicoes-consistentes-arco-p: PSR x variavel x valor x variavel x valor -> logico, inteiro
(defun psr-atribuicoes-consistentes-arco-p (p v1 valor1 v2 valor2)
""
(let ((atribuicao1 (psr-variavel-valor p v1))
(atribuicao2 (psr-variavel-valor p v2))
(consistente t)
(testes 0))
(psr-adiciona-atribuicao! p v1 valor1)
(psr-adiciona-atribuicao! p v2 valor2)
(dolist (r (psr-variavel-restricoes p v1))
(when (find v2 (restricao-variaveis r) :test 'equal)
(incf testes)
(when (null (funcall (restricao-funcao-validacao r) p))
(setf consistente nil)
(return))))
(if atribuicao1 (psr-adiciona-atribuicao! p v1 atribuicao1) (psr-remove-atribuicao! p v1))
(if atribuicao2 (psr-adiciona-atribuicao! p v2 atribuicao2) (psr-remove-atribuicao! p v2))
(values consistente testes)))
;;;; 2.2.1 Funcoes de conversao
(defun variaveis-a-volta (linha coluna max-linha max-coluna)
"Devolve uma lista com as coordenadas, em formato string '(linha . coluna)', a volta da coordenada
fornecida tendo em conta as dimensoes do tabuleiro (0 <= linhas < max-linha e
0 <= colunas < max-coluna)."
(let ((variaveis (list)))
(loop for delta-l from -1 to 1 do
(loop for delta-c from -1 to 1 do
(let ((l (+ linha delta-l)) (c (+ coluna delta-c)))
(when (and (>= l 0) (< l max-linha) (>= c 0) (< c max-coluna))
(push (write-to-string (cons l c)) variaveis)))))
(nreverse variaveis)))
(defun psr-conta-valor (p variaveis valor)
"Devolve o numero de variaveis (do argumento) que tem como valor o 'valor'."
(count valor variaveis :key #'(lambda (v) (psr-variavel-valor p v)) :test 'eql))
;;; fill-a-pix->psr: array -> PSR
(defun fill-a-pix->psr (tab) ; tab de tabuleiro
""
(let ((variaveis (list)) (dominios (list)) (restricoes (list)))
(dotimes (l (array-dimension tab 0)) ; linha
(dotimes (c (array-dimension tab 1)) ; coluna
(push (write-to-string (cons l c)) variaveis)
(push (list 0 1) dominios)
(when (numberp (aref tab l c))
(let ((vav (variaveis-a-volta l c (array-dimension tab 0) (array-dimension tab 1)))
(numero (aref tab l c)))
(push
(cria-restricao
vav
#'(lambda (p) (let ((pretas (psr-conta-valor p vav 1))
(brancas (psr-conta-valor p vav 0)))
(and (<= pretas numero) (<= brancas (- (length vav) numero))))))
restricoes)))))
(cria-psr (nreverse variaveis) (nreverse dominios) (nreverse restricoes))))
(defun lista->lista2d (lista linhas colunas)
"Recebe uma lista de listas e devolve uma nova lista em formato de matriz."
(loop for l below linhas
collect (loop for c below colunas
append (nth (+ (* l colunas) c) lista))))
;;; psr->fill-a-pix: PSR x inteiro x inteiro -> array
(defun psr->fill-a-pix (p linhas colunas)
""
(let ((tab (make-array (list linhas colunas)))
(i 0))
(dolist (v (psr-variaveis-todas p) tab)
(setf (aref tab (floor i colunas) (mod i colunas)) (psr-variavel-valor p v))
(incf i))))
;;;; 2.2.2
;;; procura-retrocesso-simples: PSR -> PSR, inteiro
(defun procura-retrocesso-simples (p)
""
(let ((testes-total 0))
(if (psr-completo-p p)
(return-from procura-retrocesso-simples (values p testes-total))
(let* ((v (first (psr-variaveis-nao-atribuidas p)))
(d (psr-variavel-dominio p v)))
(dolist (valor d)
(multiple-value-bind (consistente testes) (psr-atribuicao-consistente-p p v valor)
(incf testes-total testes)
(when consistente
(psr-adiciona-atribuicao! p v valor)
(multiple-value-bind (recurs-consistente recurs-testes) (procura-retrocesso-simples p)
(incf testes-total recurs-testes)
(when (not (null recurs-consistente))
(return-from procura-retrocesso-simples (values p testes-total))))
(psr-remove-atribuicao! p v))))
(return-from procura-retrocesso-simples (values nil testes-total))))))
;;; resolve-simples: array -> array
(defun resolve-simples (tab)
""
(multiple-value-bind (p) (procura-retrocesso-simples (fill-a-pix->psr tab))
(if (null p) nil (psr->fill-a-pix p (array-dimension tab 0) (array-dimension tab 1)))))
;;; resolve-simples: array -> array
(defun resolve-grau (tab)
""
(multiple-value-bind (p) (procura-retrocesso-grau (fill-a-pix->psr tab))
(if (null p) nil (psr->fill-a-pix p (array-dimension tab 0) (array-dimension tab 1)))))
;;; resolve-simples: array -> array
(defun resolve-fc-mrv (tab)
""
(multiple-value-bind (p) (procura-retrocesso-fc-mrv (fill-a-pix->psr tab))
(if (null p) nil (psr->fill-a-pix p (array-dimension tab 0) (array-dimension tab 1)))))
;;; resolve-simples: array -> array
(defun resolve-mac-mrv (tab)
""
(multiple-value-bind (p) (procura-retrocesso-mac-mrv (fill-a-pix->psr tab))
(if (null p) nil (psr->fill-a-pix p (array-dimension tab 0) (array-dimension tab 1)))))
(defun n-restricoes-c-natribuidas (p v)
""
(count-if #'(lambda (r) (some #'(lambda (v1) (and (not (equal v1 v))
(null (psr-variavel-atribuida-p p v1))))
(restricao-variaveis r)))
(psr-variavel-restricoes p v)))
(defun psr-var-maior-grau (p)
""
(first (sort (psr-variaveis-nao-atribuidas p)
#'>
:key #'(lambda (v) (n-restricoes-c-natribuidas p v)))))
;;; procura-retrocesso-grau: PSR -> PSR, inteiro
(defun procura-retrocesso-grau (p)
""
(let ((testes-total 0))
(if (psr-completo-p p)
(return-from procura-retrocesso-grau (values p testes-total))
(let* ((v (psr-var-maior-grau p))
(d (psr-variavel-dominio p v)))
(dolist (valor d)
(multiple-value-bind (consistente testes) (psr-atribuicao-consistente-p p v valor)
(incf testes-total testes)
(when consistente
(psr-adiciona-atribuicao! p v valor)
(multiple-value-bind (recurs-consistente recurs-testes) (procura-retrocesso-grau p)
(incf testes-total recurs-testes)
(when (not (null recurs-consistente))
(return-from procura-retrocesso-grau (values p testes-total))))
(psr-remove-atribuicao! p v))))
(return-from procura-retrocesso-grau (values nil testes-total))))))
(defun psr-mrv (p)
""
(let* ((lista-vna (psr-variaveis-nao-atribuidas p))
(min-v (first lista-vna))
(min-length (length (psr-variavel-dominio p min-v))))
(dolist (v lista-vna)
(let ((d-length (length (psr-variavel-dominio p v))))
(when (< d-length min-length)
(setf min-length d-length)
(setf min-v v))))
min-v))
;;; procura-retrocesso-fc-mrv: PSR -> PSR, inteiro
(defun procura-retrocesso-fc-mrv (p)
""
(let ((testes-totais 0))
(when (psr-completo-p p) (return-from procura-retrocesso-fc-mrv (values p testes-totais)))
(let ((v (psr-mrv p)))
(dolist (valor (psr-variavel-dominio p v))
(multiple-value-bind (consistente testes) (psr-atribuicao-consistente-p p v valor)
(incf testes-totais testes)
(when consistente
(psr-adiciona-atribuicao! p v valor)
(multiple-value-bind (inferencias testes) (psr-forward-checking p v)
(incf testes-totais testes)
(when inferencias
(let ((backup (make-hash-table :test 'equal)))
(maphash #'(lambda (iv id)
(setf (gethash iv backup) (psr-variavel-dominio p iv))
(psr-altera-dominio! p iv id))
inferencias)
(multiple-value-bind (resultado testes) (procura-retrocesso-fc-mrv p)
(incf testes-totais testes)
(when resultado
(return-from procura-retrocesso-fc-mrv (values resultado testes-totais))))
(maphash #'(lambda (bv bd)
(psr-altera-dominio! p bv bd))
backup)))
(psr-remove-atribuicao! p v))))))
(return-from procura-retrocesso-fc-mrv (values nil testes-totais))))
(defun psr-forward-checking (p v)
""
(let ((testes-totais 0)
(inferencias (make-hash-table :test 'equal))
(lista-arcos (psr-arcos-vizinhos-nao-atribuidos2 p v)))
(dolist (arco lista-arcos)
(let ((v2 (first arco))
(v1 (rest arco)))
(multiple-value-bind (revise testes) (psr-revise2 p v2 v1 inferencias)
(incf testes-totais testes)
(when revise
(multiple-value-bind (d exists) (gethash v2 inferencias)
(when exists
(when (= (length d) 0)
(return-from psr-forward-checking (values nil testes-totais)))))))))
(return-from psr-forward-checking (values inferencias testes-totais))))
(defun psr-arcos-vizinhos-nao-atribuidos2 (p v)
""
(let ((lista-arcos (list))
(envolvidas (remove-duplicates (reduce #'append (psr-variavel-restricoes p v)
:key 'restricao-variaveis)
:test 'equal)))
(dolist (v-na (psr-variaveis-nao-atribuidas p))
(when (not (equal v v-na))
(when (find v-na envolvidas :test 'equal)
(push (cons v-na v) lista-arcos))))
(nreverse lista-arcos)))
(defun psr-revise2 (p x y inferencias)
""
(let* ((testes-totais 0)
(revised nil)
(dominio-x (gethash x inferencias (psr-variavel-dominio p x)))
(novo-dominio-x dominio-x)
(dominio-y (if (psr-variavel-atribuida-p p y)
(list (psr-variavel-valor p y))
(gethash y inferencias (psr-variavel-dominio p y)))))
(dolist (valor-x dominio-x)
(let ((found-consistent-value nil))
(dolist (valor-y dominio-y)
(multiple-value-bind (consistente testes) (psr-atribuicoes-consistentes-arco-p p x valor-x y valor-y)
(incf testes-totais testes)
(when consistente
(setf found-consistent-value t)
(return))))
(when (null found-consistent-value)
(setf revised t)
(setf novo-dominio-x (remove valor-x novo-dominio-x)))))
(when revised
(setf (gethash x inferencias) novo-dominio-x))
(values revised testes-totais)))
;;; procura-retrocesso-mac-mrv: PSR -> PSR, inteiro
(defun procura-retrocesso-mac-mrv (p)
""
(let ((testes-totais 0))
(when (psr-completo-p p) (return-from procura-retrocesso-mac-mrv (values p testes-totais)))
(let* ((v (psr-mrv p)))
(dolist (valor (psr-variavel-dominio p v))
(multiple-value-bind (consistente testes) (psr-atribuicao-consistente-p p v valor)
(incf testes-totais testes)
(when consistente
(psr-adiciona-atribuicao! p v valor)
(multiple-value-bind (inferencias testes) (psr-mac p v)
(incf testes-totais testes)
(when inferencias
(let ((backup (make-hash-table :test 'equal)))
(maphash #'(lambda (iv id)
(setf (gethash iv backup) (psr-variavel-dominio p iv))
(psr-altera-dominio! p iv id))
inferencias)
(multiple-value-bind (resultado testes) (procura-retrocesso-mac-mrv p)
(incf testes-totais testes)
(when resultado
(return-from procura-retrocesso-mac-mrv (values resultado testes-totais))))
(maphash #'(lambda (bv bd)
(psr-altera-dominio! p bv bd))
backup)))
(psr-remove-atribuicao! p v))))))
(return-from procura-retrocesso-mac-mrv (values nil testes-totais))))
(defun psr-mac (p v)
""
(let ((testes-totais 0)
(inferencias (make-hash-table :test 'equal))
(lista-arcos (psr-arcos-vizinhos-nao-atribuidos2 p v)))
(dolist (arco lista-arcos)
(let ((v2 (first arco))
(v1 (rest arco)))
(multiple-value-bind (revise testes) (psr-revise2 p v2 v1 inferencias)
(incf testes-totais testes)
(when revise
(multiple-value-bind (d exists) (gethash v2 inferencias)
(when exists
(when (= (length d) 0)
(return-from psr-mac (values nil testes-totais)))))
(nconc lista-arcos (remove (cons v1 v2)
(psr-arcos-vizinhos-nao-atribuidos2 p v2)
:test 'equal))))))
(return-from psr-mac (values inferencias testes-totais))))
;;; -----------------------------------------------------------------------
(defstruct restricao-fapix
""
ipixs
funcao-validacao)
(defstruct fapix
""
linhas ; numero de linhas do tabuleiro
colunas ; numero de colunas do tabuleiro
max-ipix ; numero posicoes do tabuleiro
dominio ; array: dominio de cada pix
atribuicao ; array: atribuicao de cada pix
restricoes ; array: lista de restricoes associadas a cada pix
a-volta ; array: lista de indices de pixs a volta de cada pix
relacionados ; array: lista de pixs relacionados por uma restricao de cada pix
natribuidos ; lista: indices de pixs nao atribuidos
solucionavel ; valor logico: auxiliar para tabuleiros impossiveis
dominio-len ; array: listas com indices de pixs por comprimento de dominio
pix ; array: numero da casa no tabuleiro de cada pix (nil quando nao tem numero)
hv) ; array: valor da heuristica de valor (acabou por nao ser usado visto nao se ter encontrado
; calculo util e eficiente)
(defun cria-restricao-fapix (ipixs pix a-volta-len)
""
(make-restricao-fapix :ipixs ipixs
:funcao-validacao #'(lambda (f) (multiple-value-bind (brancos pretos)
(fapix-conta-cores f ipixs)
(and (<= pretos pix)
(<= brancos (- a-volta-len pix)))))))
(defun fapix-ipixs-nao-atribuidos (f)
"Recebe um `fapix' e devolve a lista de ipixs nao atribuidos desse fapix."
(fapix-natribuidos f))
(defun fapix-pix-cor (f ipix)
"Recebe um `fapix' e um indice de um pix e devolve a cor (atribuicao) associada ao pix ou nil caso
nao tenha atribuicao."
(aref (fapix-atribuicao f) ipix))
(defun fapix-pix-dominio (f ipix)
"Recebe um `fapix' e um indice de um pix e devolve o dominio associado ao pix."
(let ((cor (fapix-pix-cor f ipix)))
(if cor
(list cor)
(aref (fapix-dominio f) ipix))))
(defun fapix-pix-restricoes (f ipix)
"Recebe um `fapix' e um indice de um pix e devolve uma lista com todas as restricoes aplicaveis ao
pix."
(aref (fapix-restricoes f) ipix))
(defun fapix-adiciona-atribuicao! (f ipix cor)
"Recebe um `fapix', um indice de um pix e uma cor (0 para branco e 1 para preto) e atribui a cor
ao pix."
(setf (aref (fapix-atribuicao f) ipix) cor))
(defun fapix-remove-atribuicao! (f ipix)
"Recebe um `fapix' e um indice de um pix e remove a atribuicao de cor do pix."
(fapix-adiciona-atribuicao! f ipix nil))
(defun fapix-altera-dominio! (f ipix d)
"Recebe um `fapix', um indice de um pix e um dominio (lista de cores), atribui esse dominio ao pix
e atualiza as listas de comprimento de dominio."
(setf (aref (fapix-dominio-len f) (length (fapix-pix-dominio f ipix)))
(remove ipix (aref (fapix-dominio-len f) (length (fapix-pix-dominio f ipix)))))
(setf (aref (fapix-dominio f) ipix) d)
(push ipix (aref (fapix-dominio-len f) (length d))))
(defun fapix-completo-p (f)
"Recebe um `fapix' e testa se o fapix esta completo (se nao tem variaveis sem atribuicao). Retorna
T se estiver completo e nil caso contrario."
(null (fapix-ipixs-nao-atribuidos f)))
(defun fapix-testa-restricoes (f restricoes)
"Recebe um `fapix' e uma lista de `restricao-fapix' e testa todas as restricoes. Retorna dois
valores. O primeiro e um valor logico que indica se todas as restricoes se verificam. O segundo e
a ultima restricao a ser testada caso nem todas as restricoes se verifiquem e NIL caso contrario. Se
a lista de restricoes estiver vazia e devolvido T e NIL."
(dolist (r restricoes (values t nil))
(when (null (funcall (restricao-fapix-funcao-validacao r) f))
(return (values nil r)))))
(defun fapix-consistente-p (f)
"Recebe um `fapix' e testa todas as retricoes do mesmo. Retorna o mesmo que
`fapix-testa-restricoes'"
(fapix-testa-restricoes f (fapix-restricoes f)))
(defun fapix-pix-consistente-p (f ipix)
"Recebe um `fapix' e um indice de um pix e testa as restricoes associadas ao pix. Retorna o mesmo
que `fapix-testa-restricoes'."
(fapix-testa-restricoes f (fapix-pix-restricoes f ipix)))
(defun fapix-atribuicao-consistente-p (f ipix cor)
"Recebe um `fapix', um indice de um pix e uma cor. Testa se a atribuicao da cor ao pix e
consistente com as restricoes associadas ao pix. Retorna o mesmo que `fapix-testa-restricoes'."
(let ((atribuicao (fapix-pix-cor f ipix))
(consistente t)
(falhou nil))
(fapix-adiciona-atribuicao! f ipix cor)
(setf (values consistente falhou) (fapix-pix-consistente-p f ipix))
(if atribuicao (fapix-adiciona-atribuicao! f ipix atribuicao) (fapix-remove-atribuicao! f ipix))
(values consistente falhou)))
(defun fapix-atribuicoes-consistentes-p (f ipix1 cor1 ipix2 cor2)
"Recebe um `fapix', dois indices de pixs e duas cores. Testa se a atribuicao da cor1 ao pix1 e da
cor2 ao pix2 e consistente com as restricoes associadas a ambos os pix (testa as restricoes de forma
sequencial - primeiro as do pix1 e depois as do pix2). Retorna o mesmo que `fapix-testa-restricoes'
."
(let ((atribuicao1 (fapix-pix-cor f ipix1))
(atribuicao2 (fapix-pix-cor f ipix2))
(consistente t))
(fapix-adiciona-atribuicao! f ipix1 cor1)
(fapix-adiciona-atribuicao! f ipix2 cor2)
(block testes
(when (fapix-testa-restricoes f (fapix-pix-restricoes f ipix1))
(when (fapix-testa-restricoes f (fapix-pix-restricoes f ipix2))
(return-from testes)))
(setf consistente nil))
(if atribuicao1 (fapix-adiciona-atribuicao! f ipix1 atribuicao1) (fapix-remove-atribuicao! f ipix1))
(if atribuicao2 (fapix-adiciona-atribuicao! f ipix2 atribuicao2) (fapix-remove-atribuicao! f ipix2))
(values consistente 0)))
(defun fapix-conta-cores (f ipixs)
"Recebe um `fapix' e uma lista de indices de pixs. Retorna dois valores: quantos pixs brancos e
pretos ha na lista."
(let ((brancos 0)
(pretos 0))
(dolist (ipix ipixs (values brancos pretos))
(let ((cor (fapix-pix-cor f ipix)))
(when cor
(if (= cor 0)
(incf brancos)
(incf pretos)))))))
(defun linha (ipix colunas)
"Devolve a linha em que se encontra o pix correspondente ao indice fornecido."
(nth-value 0 (floor ipix colunas)))
(defun coluna (ipix colunas)
"Devolve a coluna em que se encontra o pix correspondente ao indice fornecido."
(nth-value 1 (floor ipix colunas)))
(defun pix-a-volta (ipix colunas max-ipix)
"Devolve uma lista com os indices dos pix a volta do pix cujo o indice fornecido."
(loop for l from (- ipix colunas) to (+ ipix colunas) by colunas when (< -1 l max-ipix)
append (loop for c from (- l 1) to (+ l 1) when (= (linha c colunas) (linha l colunas))
collect c)))
(defun fill-a-pix->fapix (tab) ; tab de tabuleiro
"Converte um tabuleiro fill-a-pix para um `fapix'."
(let* ((linhas (array-dimension tab 0))
(colunas (array-dimension tab 1))
(max-ipix (* linhas colunas))
(pix-dominio (make-array max-ipix :initial-element (list 0 1)))
(pix-atribuicoes (make-array max-ipix :initial-element nil))
(pix-restricoes (make-array max-ipix :initial-element nil))
(pix-a-volta (make-array max-ipix :initial-element nil))
(pix-relacionados (make-array max-ipix :initial-element nil))
(pix-natribuidos (list))
(pix-solucionavel t) ; t de talvez
(dominio-len (make-array 3 :initial-element nil))
(pix-dominio-len-p (make-array max-ipix :initial-element nil))
(pix-pix (make-array max-ipix :initial-element nil))
(pix-hv (make-array max-ipix :initial-element 0))
(ipix 0))
(block ciclos
(dotimes (l linhas)
(dotimes (c colunas)
(let* ((pix (aref tab l c))
(a-volta (pix-a-volta ipix colunas max-ipix))
(a-volta-len (length a-volta)))
(setf (aref pix-a-volta ipix) a-volta)
(push ipix pix-natribuidos)
(when (numberp pix)
(when (> pix a-volta-len) (setf pix-solucionavel nil) (return-from ciclos))
(setf (aref pix-pix ipix) pix)
(let* ((restricao (cria-restricao-fapix a-volta pix a-volta-len))
(dominio (if (= pix 0) (list 0) (if (= pix a-volta-len) (list 1) nil))))
(dolist (ipix-av a-volta)
(push restricao (aref pix-restricoes ipix-av))
(setf (aref pix-relacionados ipix-av) (merge 'list
(aref pix-relacionados ipix-av)
(remove ipix-av a-volta :test '=)
#'<))
(when dominio
(setf (aref pix-dominio ipix-av) dominio)
(push ipix-av (aref dominio-len 1))
(setf (aref pix-dominio-len-p ipix-av) t)))))
(let* ((soma 0)
(numero 0))
(dolist (ipix-av a-volta)
(let ((pix-av (aref tab (linha ipix-av colunas) (coluna ipix-av colunas))))
(when pix-av
(incf soma pix-av)
(incf numero))))
;; (when (and (not (= numero 0)) (>= (round (round soma numero) a-volta-len) 1))
;; (setf (aref pix-hv ipix) 1)
;; ))
)
(incf ipix)))))
(dotimes (i max-ipix)
(when (not (aref pix-dominio-len-p i))
(push i (aref dominio-len 2)))
(delete-duplicates (aref pix-relacionados i)))
(make-fapix :linhas linhas
:colunas colunas
:max-ipix max-ipix
:dominio pix-dominio
:atribuicao pix-atribuicoes
:restricoes pix-restricoes
:a-volta pix-a-volta
:relacionados pix-relacionados
:natribuidos pix-natribuidos
:solucionavel pix-solucionavel
:dominio-len dominio-len
:pix pix-pix
:hv pix-hv)))
(defun fapix->fill-a-pix (f)
"Converte um `fapix' para um tabuleiro fill-a-pix."
(let* ((colunas (fapix-colunas f))
(tab (make-array (list (fapix-linhas f) colunas))))
(dotimes (ipix (fapix-max-ipix f) tab)
(setf (aref tab (linha ipix colunas) (coluna ipix colunas)) (fapix-pix-cor f ipix)))))
(defun algoritmo (f)
""
(when (not (fapix-solucionavel f)) (return-from algoritmo nil))
(procura-retrocesso-mac-mrv-fapix f))
(defun resolve-best (tab)
""
(fapix->fill-a-pix (algoritmo (fill-a-pix->fapix tab))))
(defun fapix-mrv-modificado (f)
""
(dolist (ipix (aref (fapix-dominio-len f) 1))
(return-from fapix-mrv-modificado ipix))
;; criterio de desempate para quando o comprimento do dominio e 2
(let* ((max-ipix (first (aref (fapix-dominio-len f) 2)))
(a-volta (aref (fapix-a-volta f) max-ipix))
(max-atrib-a-volta (count-if #'(lambda (ipix-av) (fapix-pix-cor f ipix-av)) a-volta))
(max-natrib-a-volta (- (length a-volta) max-atrib-a-volta)))
(dolist (ipix (aref (fapix-dominio-len f) 2) max-ipix)
(setf a-volta (aref (fapix-a-volta f) ipix))
(let* ((atrib-a-volta (count-if #'(lambda (ipix-av) (fapix-pix-cor f ipix-av)) a-volta))
(natrib-a-volta (- (length a-volta) atrib-a-volta)))
(when (or (> atrib-a-volta max-atrib-a-volta)
(and (= atrib-a-volta max-atrib-a-volta) (< natrib-a-volta max-natrib-a-volta)))
(setf max-atrib-a-volta atrib-a-volta)
(setf max-natrib-a-volta natrib-a-volta)
(setf max-ipix ipix))))))
(defun procura-retrocesso-fc-mrv-fapix (f)
""
(when (fapix-completo-p f)
(return-from procura-retrocesso-fc-mrv-fapix (values f 0)))
(let* ((ipix (fapix-mrv-modificado f))
(d (fapix-pix-dominio f ipix)))
;; (when (= (length d) 2)
;; (when (= (aref (fapix-hv f) ipix) 1)
;; (setf d (reverse d))))
(dolist (cor d)
(fapix-adiciona-atribuicao! f ipix cor)
(setf (fapix-natribuidos f) (remove ipix (fapix-natribuidos f)))
(setf (aref (fapix-dominio-len f) (length d))
(remove ipix (aref (fapix-dominio-len f) (length d))))
(let ((inferencias (fapix-forward-checking f ipix)))
(when inferencias
(let ((backup (make-hash-table :test 'eql)))
(maphash #'(lambda (iipix id)
(setf (gethash iipix backup) (fapix-pix-dominio f iipix))
(fapix-altera-dominio! f iipix id))
inferencias)
(multiple-value-bind (resultado) (procura-retrocesso-fc-mrv-fapix f)
(when resultado
(return-from procura-retrocesso-fc-mrv-fapix (values resultado 0))))
(maphash #'(lambda (bipix bd)
(fapix-altera-dominio! f bipix bd))
backup)))
(fapix-remove-atribuicao! f ipix)
(push ipix (fapix-natribuidos f))
(push ipix (aref (fapix-dominio-len f) (length d))))))
(return-from procura-retrocesso-fc-mrv-fapix (values nil 0)))
(defun procura-retrocesso-mac-mrv-fapix (f)
""
(when (fapix-completo-p f)
(return-from procura-retrocesso-mac-mrv-fapix (values f 0)))
(let* ((ipix (fapix-mrv-modificado f))
(d (fapix-pix-dominio f ipix)))
;; (when (= (length d) 2)
;; (when (= (aref (fapix-hv f) ipix) 1)
;; (setf d (reverse d))))
(dolist (cor d)
(fapix-adiciona-atribuicao! f ipix cor)
(setf (fapix-natribuidos f) (remove ipix (fapix-natribuidos f)))
(setf (aref (fapix-dominio-len f) (length d))
(remove ipix (aref (fapix-dominio-len f) (length d))))
(let ((inferencias (fapix-mac f ipix)))
(when inferencias
(let ((backup (make-hash-table :test 'eql)))
(maphash #'(lambda (iipix id)
(setf (gethash iipix backup) (fapix-pix-dominio f iipix))
(fapix-altera-dominio! f iipix id))
inferencias)
(multiple-value-bind (resultado) (procura-retrocesso-mac-mrv-fapix f)
(when resultado
(return-from procura-retrocesso-mac-mrv-fapix (values resultado 0))))
(maphash #'(lambda (bipix bd)
(fapix-altera-dominio! f bipix bd))
backup)))
(fapix-remove-atribuicao! f ipix)
(push ipix (fapix-natribuidos f))
(push ipix (aref (fapix-dominio-len f) (length d))))))
(return-from procura-retrocesso-mac-mrv-fapix (values nil 0)))
(defun fapix-forward-checking (f ipix)
""
(let ((inferencias (make-hash-table :test 'eql)))
(dolist (v2 (aref (fapix-relacionados f) ipix))
(when (not (fapix-pix-cor f v2))
(dolist (cor2 (gethash v2 inferencias (fapix-pix-dominio f v2)))
(multiple-value-bind (consistente r-falhou) (fapix-atribuicao-consistente-p f v2 cor2)
(when (not consistente)
(dolist (ipix3 (restricao-fapix-ipixs r-falhou))
(when (not (fapix-pix-cor f ipix3))
(when (null (setf (gethash ipix3 inferencias)
(remove cor2
(gethash ipix3 inferencias (fapix-pix-dominio f ipix3)))))
(return-from fapix-forward-checking (values nil 0))))))))))
(return-from fapix-forward-checking (values inferencias 0))))
(defun fapix-mac (f ipix)
""
(let ((inferencias (make-hash-table :test 'eql))
(lista-arcos (fapix-arcos-vizinhos-nao-atribuidos f ipix)))
(dolist (arco lista-arcos)
(let ((v2 (first arco))
(v1 (rest arco)))
(dolist (cor2 (gethash v2 inferencias (fapix-pix-dominio f v2)))
(dolist (cor1 (gethash v1 inferencias (fapix-pix-dominio f v1)))
(let ((cor1-backup (fapix-pix-cor f v1)))
(fapix-adiciona-atribuicao! f v1 cor1)
(multiple-value-bind (consistente r-falhou) (fapix-atribuicao-consistente-p f v2 cor2)
(when (not consistente)
(dolist (ipix3 (restricao-fapix-ipixs r-falhou))
(when (not (fapix-pix-cor f ipix3))
(when (null (setf (gethash ipix3 inferencias)
(remove cor2 (gethash ipix3 inferencias (fapix-pix-dominio f ipix3)))))
(fapix-adiciona-atribuicao! f v1 cor1-backup)
(return-from fapix-mac (values nil 0)))))
(nconc lista-arcos (remove (cons v1 v2)
(fapix-arcos-vizinhos-nao-atribuidos f v2)
:test 'equal))))
(fapix-adiciona-atribuicao! f v1 cor1-backup))))))
(return-from fapix-mac (values inferencias 0))))
(defun fapix-arcos-vizinhos-nao-atribuidos (f ipix)
""
(loop for ipix-rel in (aref (fapix-relacionados f) ipix) unless (fapix-pix-cor f ipix-rel)
collect (cons ipix-rel ipix)))
|
[
{
"context": "m \"parmesan\"\n\t:serial t\n\t:version \"0.1\"\n\t:author \"Dylan Ball <[email protected]>\"\n\t:maintainer \"Dylan Ball <a",
"end": 74,
"score": 0.9998855590820312,
"start": 64,
"tag": "NAME",
"value": "Dylan Ball"
},
{
"context": "\n\t:serial t\n\t:version \"0.1\"\n\t:author \"Dylan Ball <[email protected]>\"\n\t:maintainer \"Dylan Ball <[email protected]>\"\n",
"end": 94,
"score": 0.9999268651008606,
"start": 76,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "r \"Dylan Ball <[email protected]>\"\n\t:maintainer \"Dylan Ball <[email protected]>\"\n\t:description \"Parmesan\"\n\t:",
"end": 121,
"score": 0.9998907446861267,
"start": 111,
"tag": "NAME",
"value": "Dylan Ball"
},
{
"context": "l <[email protected]>\"\n\t:maintainer \"Dylan Ball <[email protected]>\"\n\t:description \"Parmesan\"\n\t:long-description \"pa",
"end": 141,
"score": 0.9999260306358337,
"start": 123,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
parmesan.asd
|
arathnim/parmesan
| 20 |
(asdf:defsystem "parmesan"
:serial t
:version "0.1"
:author "Dylan Ball <[email protected]>"
:maintainer "Dylan Ball <[email protected]>"
:description "Parmesan"
:long-description "parser combinators, lisp-style"
:depends-on (alexandria iterate wernicke)
:components ((:file "parmesan")))
|
56456
|
(asdf:defsystem "parmesan"
:serial t
:version "0.1"
:author "<NAME> <<EMAIL>>"
:maintainer "<NAME> <<EMAIL>>"
:description "Parmesan"
:long-description "parser combinators, lisp-style"
:depends-on (alexandria iterate wernicke)
:components ((:file "parmesan")))
| true |
(asdf:defsystem "parmesan"
:serial t
:version "0.1"
:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:maintainer "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:description "Parmesan"
:long-description "parser combinators, lisp-style"
:depends-on (alexandria iterate wernicke)
:components ((:file "parmesan")))
|
[
{
"context": "#|\n Copyright (C) 2019 Gnuxie <[email protected]>\n|#\n\n(in-package #:json-",
"end": 30,
"score": 0.5374901294708252,
"start": 26,
"tag": "USERNAME",
"value": "Gnux"
},
{
"context": "#|\n Copyright (C) 2019 Gnuxie <[email protected]>\n|#\n\n(in-package #:json-sc",
"end": 32,
"score": 0.575616717338562,
"start": 30,
"tag": "NAME",
"value": "ie"
},
{
"context": "#|\n Copyright (C) 2019 Gnuxie <[email protected]>\n|#\n\n(in-package #:json-schema)\n\n(defun cl-type<-",
"end": 55,
"score": 0.999927282333374,
"start": 34,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
code/generation-protocol.lisp
|
lisp-mirror/cl-json-schema
| 1 |
#|
Copyright (C) 2019 Gnuxie <[email protected]>
|#
(in-package #:json-schema)
(defun cl-type<-json-schema-type (type)
(etypecase type
(null 'null)
(list
`(or ,@ (mapcar #'cl-type<-json-schema-type type)))
(string
(alexandria:switch (type :test #'string=)
("string" 'string)
("integer" 'integer)
("number" 'number)
("object" '(or json-schema:json-serializable string))
("array" 'list)
("boolean" 'boolean)
("null" 'null)))))
(defgeneric produce-schema (schema option)
(:documentation "This is the top generic you all to get everything
A class for the schema named by name. The method impls needed to use json-schema.
The option is used to determine whether to use the mop impl or something else,
like generating specific methods for this class.")
(:method (schema (option mop-option))
(let ((output `(progn ,(class<-object schema option)
,(find-inner-classes schema option))))
(v:debug :produce-schema "~%~%~w" output)
output)))
(defgeneric direct-slots<-schema (schema option)
(:documentation "The will return a list of both direct-slots
for this schema definition.")
(:method ((schema schema) (option mop-option))
(with-hash-keys (("properties")) (object schema)
(when properties
(loop :for key :being :the :hash-key :using
(hash-value property) :of properties :collect
(slot<-property key property schema option))))))
(defun find-inner-classes (schema option)
(with-hash-keys (("properties")) (object schema)
`(progn
,@ (when properties
(loop :for key :being :the :hash-key :using
(hash-value property) :of properties :collect
(let* ((inner-properties (gethash "properties" property))
(inner-schema
(and inner-properties
(make-instance 'inner-schema
:name (format nil "~a-~a"
(internal-name schema option)
key)
:parent-key key
:parent schema))))
(unless (null inner-schema)
(produce-schema inner-schema option))))))))
(defgeneric class<-object (schema option)
(:documentation "Produce a class from a json-schema object.")
(:method ((schema schema) (option mop-option))
(multiple-value-bind (parents slots inner-schemas)
(resolve-references schema option)
`(progn
,(unless (null parents) ; avoid style-warning for unused option.
`(let ((option ,option))
,@(mapcar (lambda (schema) `(ensure-schema-class ,schema option))
parents)))
(defclass ,(internal-name schema option)
,(mapcar (lambda (schema)
(internal-name schema option))
parents)
,slots
,@ (class-options<-schema schema option))
;; this is because our constructors need the c-p-l before make-instance.
(c2mop:finalize-inheritance (find-class ',(internal-name schema option)))
,inner-schemas))))
(defgeneric slot<-property (name property parent-schema option)
(:documentation "produce a slot definition for the property")
(:method (name property parent-schema (option mop-option))
(with-hash-keys (("type")) property
(let ((target-package (target-package option)))
`(,(symbol<-key name target-package) :initarg ,(keyword<-key name)
:accessor ,(symbol<-key name target-package)
:type ,(cl-type<-json-schema-type type)
:json-key ,name)))))
(defgeneric class-options<-schema (schema option)
(:documentation "a list of the class options for the class definition.")
(:method (schema (option mop-option))
(declare (ignore schema option))
'((:metaclass json-schema:json-serializable-class))))
(defun ensure-inherit (symbol target-package)
"ensure that the symbol is imported into the target-package
and also exported from the target package."
(defpackage+-1:inherit-from (symbol-package symbol)
(list (symbol-name symbol))
target-package))
(defgeneric resolve-references (schema option)
(:documentation "Resolve the references in the schema
returns (values parents slots) as determined by the overrides
specified in the schema")
(:method (schema (option mop-option))
(let ((parents '())
(slots (direct-slots<-schema schema option))
(inner-schemas '(progn)))
(labels ((update-slot (slot)
(let ((association
(assoc (car slot) slots :test #'string-equal)))
(if association
(loop :for (key value) :on (rest slot):by #'cddr :do
(let ((existing-option (getf (rest association) key)))
(unless existing-option
(setf (getf existing-option key) value))))
(push slot slots))))
(add-slots (more-slots)
(mapc #'update-slot more-slots))
(add-parents (new-parents)
(setf parents (append parents new-parents)))
(add-inner-schemas (next-inner-schemas)
(setf inner-schemas
(append inner-schemas
(list next-inner-schemas)))))
(do-referenced-schemas referenced-schema schema
(cond
((inherit-schema-p referenced-schema option)
(push referenced-schema parents))
(t
(add-inner-schemas
(find-inner-classes referenced-schema option))
(multiple-value-bind (next-parents next-slots next-inner-schemas)
(resolve-references referenced-schema option)
(add-parents next-parents)
(add-slots next-slots)
(add-inner-schemas next-inner-schemas)
(mapc (lambda (slot-option)
(ensure-inherit (car slot-option)
(target-package option)))
next-slots))))))
(values
parents
slots
inner-schemas))))
(defgeneric ensure-schema-class (schema option)
(:method (schema (option mop-option))
(let ((class-name (internal-name schema option)))
(or (find-class class-name nil)
(progn (eval (produce-schema schema option))
(find-class class-name))))))
|
29651
|
#|
Copyright (C) 2019 Gnux<NAME> <<EMAIL>>
|#
(in-package #:json-schema)
(defun cl-type<-json-schema-type (type)
(etypecase type
(null 'null)
(list
`(or ,@ (mapcar #'cl-type<-json-schema-type type)))
(string
(alexandria:switch (type :test #'string=)
("string" 'string)
("integer" 'integer)
("number" 'number)
("object" '(or json-schema:json-serializable string))
("array" 'list)
("boolean" 'boolean)
("null" 'null)))))
(defgeneric produce-schema (schema option)
(:documentation "This is the top generic you all to get everything
A class for the schema named by name. The method impls needed to use json-schema.
The option is used to determine whether to use the mop impl or something else,
like generating specific methods for this class.")
(:method (schema (option mop-option))
(let ((output `(progn ,(class<-object schema option)
,(find-inner-classes schema option))))
(v:debug :produce-schema "~%~%~w" output)
output)))
(defgeneric direct-slots<-schema (schema option)
(:documentation "The will return a list of both direct-slots
for this schema definition.")
(:method ((schema schema) (option mop-option))
(with-hash-keys (("properties")) (object schema)
(when properties
(loop :for key :being :the :hash-key :using
(hash-value property) :of properties :collect
(slot<-property key property schema option))))))
(defun find-inner-classes (schema option)
(with-hash-keys (("properties")) (object schema)
`(progn
,@ (when properties
(loop :for key :being :the :hash-key :using
(hash-value property) :of properties :collect
(let* ((inner-properties (gethash "properties" property))
(inner-schema
(and inner-properties
(make-instance 'inner-schema
:name (format nil "~a-~a"
(internal-name schema option)
key)
:parent-key key
:parent schema))))
(unless (null inner-schema)
(produce-schema inner-schema option))))))))
(defgeneric class<-object (schema option)
(:documentation "Produce a class from a json-schema object.")
(:method ((schema schema) (option mop-option))
(multiple-value-bind (parents slots inner-schemas)
(resolve-references schema option)
`(progn
,(unless (null parents) ; avoid style-warning for unused option.
`(let ((option ,option))
,@(mapcar (lambda (schema) `(ensure-schema-class ,schema option))
parents)))
(defclass ,(internal-name schema option)
,(mapcar (lambda (schema)
(internal-name schema option))
parents)
,slots
,@ (class-options<-schema schema option))
;; this is because our constructors need the c-p-l before make-instance.
(c2mop:finalize-inheritance (find-class ',(internal-name schema option)))
,inner-schemas))))
(defgeneric slot<-property (name property parent-schema option)
(:documentation "produce a slot definition for the property")
(:method (name property parent-schema (option mop-option))
(with-hash-keys (("type")) property
(let ((target-package (target-package option)))
`(,(symbol<-key name target-package) :initarg ,(keyword<-key name)
:accessor ,(symbol<-key name target-package)
:type ,(cl-type<-json-schema-type type)
:json-key ,name)))))
(defgeneric class-options<-schema (schema option)
(:documentation "a list of the class options for the class definition.")
(:method (schema (option mop-option))
(declare (ignore schema option))
'((:metaclass json-schema:json-serializable-class))))
(defun ensure-inherit (symbol target-package)
"ensure that the symbol is imported into the target-package
and also exported from the target package."
(defpackage+-1:inherit-from (symbol-package symbol)
(list (symbol-name symbol))
target-package))
(defgeneric resolve-references (schema option)
(:documentation "Resolve the references in the schema
returns (values parents slots) as determined by the overrides
specified in the schema")
(:method (schema (option mop-option))
(let ((parents '())
(slots (direct-slots<-schema schema option))
(inner-schemas '(progn)))
(labels ((update-slot (slot)
(let ((association
(assoc (car slot) slots :test #'string-equal)))
(if association
(loop :for (key value) :on (rest slot):by #'cddr :do
(let ((existing-option (getf (rest association) key)))
(unless existing-option
(setf (getf existing-option key) value))))
(push slot slots))))
(add-slots (more-slots)
(mapc #'update-slot more-slots))
(add-parents (new-parents)
(setf parents (append parents new-parents)))
(add-inner-schemas (next-inner-schemas)
(setf inner-schemas
(append inner-schemas
(list next-inner-schemas)))))
(do-referenced-schemas referenced-schema schema
(cond
((inherit-schema-p referenced-schema option)
(push referenced-schema parents))
(t
(add-inner-schemas
(find-inner-classes referenced-schema option))
(multiple-value-bind (next-parents next-slots next-inner-schemas)
(resolve-references referenced-schema option)
(add-parents next-parents)
(add-slots next-slots)
(add-inner-schemas next-inner-schemas)
(mapc (lambda (slot-option)
(ensure-inherit (car slot-option)
(target-package option)))
next-slots))))))
(values
parents
slots
inner-schemas))))
(defgeneric ensure-schema-class (schema option)
(:method (schema (option mop-option))
(let ((class-name (internal-name schema option)))
(or (find-class class-name nil)
(progn (eval (produce-schema schema option))
(find-class class-name))))))
| true |
#|
Copyright (C) 2019 GnuxPI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
|#
(in-package #:json-schema)
(defun cl-type<-json-schema-type (type)
(etypecase type
(null 'null)
(list
`(or ,@ (mapcar #'cl-type<-json-schema-type type)))
(string
(alexandria:switch (type :test #'string=)
("string" 'string)
("integer" 'integer)
("number" 'number)
("object" '(or json-schema:json-serializable string))
("array" 'list)
("boolean" 'boolean)
("null" 'null)))))
(defgeneric produce-schema (schema option)
(:documentation "This is the top generic you all to get everything
A class for the schema named by name. The method impls needed to use json-schema.
The option is used to determine whether to use the mop impl or something else,
like generating specific methods for this class.")
(:method (schema (option mop-option))
(let ((output `(progn ,(class<-object schema option)
,(find-inner-classes schema option))))
(v:debug :produce-schema "~%~%~w" output)
output)))
(defgeneric direct-slots<-schema (schema option)
(:documentation "The will return a list of both direct-slots
for this schema definition.")
(:method ((schema schema) (option mop-option))
(with-hash-keys (("properties")) (object schema)
(when properties
(loop :for key :being :the :hash-key :using
(hash-value property) :of properties :collect
(slot<-property key property schema option))))))
(defun find-inner-classes (schema option)
(with-hash-keys (("properties")) (object schema)
`(progn
,@ (when properties
(loop :for key :being :the :hash-key :using
(hash-value property) :of properties :collect
(let* ((inner-properties (gethash "properties" property))
(inner-schema
(and inner-properties
(make-instance 'inner-schema
:name (format nil "~a-~a"
(internal-name schema option)
key)
:parent-key key
:parent schema))))
(unless (null inner-schema)
(produce-schema inner-schema option))))))))
(defgeneric class<-object (schema option)
(:documentation "Produce a class from a json-schema object.")
(:method ((schema schema) (option mop-option))
(multiple-value-bind (parents slots inner-schemas)
(resolve-references schema option)
`(progn
,(unless (null parents) ; avoid style-warning for unused option.
`(let ((option ,option))
,@(mapcar (lambda (schema) `(ensure-schema-class ,schema option))
parents)))
(defclass ,(internal-name schema option)
,(mapcar (lambda (schema)
(internal-name schema option))
parents)
,slots
,@ (class-options<-schema schema option))
;; this is because our constructors need the c-p-l before make-instance.
(c2mop:finalize-inheritance (find-class ',(internal-name schema option)))
,inner-schemas))))
(defgeneric slot<-property (name property parent-schema option)
(:documentation "produce a slot definition for the property")
(:method (name property parent-schema (option mop-option))
(with-hash-keys (("type")) property
(let ((target-package (target-package option)))
`(,(symbol<-key name target-package) :initarg ,(keyword<-key name)
:accessor ,(symbol<-key name target-package)
:type ,(cl-type<-json-schema-type type)
:json-key ,name)))))
(defgeneric class-options<-schema (schema option)
(:documentation "a list of the class options for the class definition.")
(:method (schema (option mop-option))
(declare (ignore schema option))
'((:metaclass json-schema:json-serializable-class))))
(defun ensure-inherit (symbol target-package)
"ensure that the symbol is imported into the target-package
and also exported from the target package."
(defpackage+-1:inherit-from (symbol-package symbol)
(list (symbol-name symbol))
target-package))
(defgeneric resolve-references (schema option)
(:documentation "Resolve the references in the schema
returns (values parents slots) as determined by the overrides
specified in the schema")
(:method (schema (option mop-option))
(let ((parents '())
(slots (direct-slots<-schema schema option))
(inner-schemas '(progn)))
(labels ((update-slot (slot)
(let ((association
(assoc (car slot) slots :test #'string-equal)))
(if association
(loop :for (key value) :on (rest slot):by #'cddr :do
(let ((existing-option (getf (rest association) key)))
(unless existing-option
(setf (getf existing-option key) value))))
(push slot slots))))
(add-slots (more-slots)
(mapc #'update-slot more-slots))
(add-parents (new-parents)
(setf parents (append parents new-parents)))
(add-inner-schemas (next-inner-schemas)
(setf inner-schemas
(append inner-schemas
(list next-inner-schemas)))))
(do-referenced-schemas referenced-schema schema
(cond
((inherit-schema-p referenced-schema option)
(push referenced-schema parents))
(t
(add-inner-schemas
(find-inner-classes referenced-schema option))
(multiple-value-bind (next-parents next-slots next-inner-schemas)
(resolve-references referenced-schema option)
(add-parents next-parents)
(add-slots next-slots)
(add-inner-schemas next-inner-schemas)
(mapc (lambda (slot-option)
(ensure-inherit (car slot-option)
(target-package option)))
next-slots))))))
(values
parents
slots
inner-schemas))))
(defgeneric ensure-schema-class (schema option)
(:method (schema (option mop-option))
(let ((class-name (internal-name schema option)))
(or (find-class class-name nil)
(progn (eval (produce-schema schema option))
(find-class class-name))))))
|
[
{
"context": "ser-based applications.\n;; \n;; Copyright (c) 2011, Patrick D. Logan\n;; All rights reserved.\n;;\n;; See COPYING for mor",
"end": 269,
"score": 0.9998698234558105,
"start": 253,
"tag": "NAME",
"value": "Patrick D. Logan"
}
] |
workspace.lisp
|
patrickdlogan/abcl-webdriver
| 1 |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; This file is a collection of 'workspace' code for exploring Armed
;; Bear Common Lisp, lisp-unit, and WebDriver for testing
;; browser-based applications.
;;
;; Copyright (c) 2011, Patrick D. Logan
;; All rights reserved.
;;
;; See COPYING for more information. The license is the "new and
;; simplified BSD license" See
;; http://www.opensource.org/licenses/bsd-license
(ql:quickload "lisp-unit")
(use-package 'lisp-unit)
(defun make-html-unit-driver ()
"Return a new instance of org.openqa.selenium.HtmlUnitDriver"
(jnew "org.openqa.selenium.htmlunit.HtmlUnitDriver"))
(defun load-page (driver url)
"Use the given driver to HTTP GET the url. The result is loaded into the driver's browser."
(jcall "get" driver url))
(defun find-element-by-tag (driver tag)
"Return an element with the given HTML tag name on the driver's current page."
(jcall "findElement" driver (jstatic "tagName" "org.openqa.selenium.By" tag)))
(defun get-text (elem)
"Return the inner text of the given element."
(jcall "getText" elem))
(define-test test-my-max
(assert-equal "Moo Foo" (let* ((driver (make-html-unit-driver))
(elem (progn (load-page driver "http://localhost:8000")
(find-element-by-tag driver "h1"))))
(get-text elem))))
;(run-tests)
|
67598
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; This file is a collection of 'workspace' code for exploring Armed
;; Bear Common Lisp, lisp-unit, and WebDriver for testing
;; browser-based applications.
;;
;; Copyright (c) 2011, <NAME>
;; All rights reserved.
;;
;; See COPYING for more information. The license is the "new and
;; simplified BSD license" See
;; http://www.opensource.org/licenses/bsd-license
(ql:quickload "lisp-unit")
(use-package 'lisp-unit)
(defun make-html-unit-driver ()
"Return a new instance of org.openqa.selenium.HtmlUnitDriver"
(jnew "org.openqa.selenium.htmlunit.HtmlUnitDriver"))
(defun load-page (driver url)
"Use the given driver to HTTP GET the url. The result is loaded into the driver's browser."
(jcall "get" driver url))
(defun find-element-by-tag (driver tag)
"Return an element with the given HTML tag name on the driver's current page."
(jcall "findElement" driver (jstatic "tagName" "org.openqa.selenium.By" tag)))
(defun get-text (elem)
"Return the inner text of the given element."
(jcall "getText" elem))
(define-test test-my-max
(assert-equal "Moo Foo" (let* ((driver (make-html-unit-driver))
(elem (progn (load-page driver "http://localhost:8000")
(find-element-by-tag driver "h1"))))
(get-text elem))))
;(run-tests)
| true |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; This file is a collection of 'workspace' code for exploring Armed
;; Bear Common Lisp, lisp-unit, and WebDriver for testing
;; browser-based applications.
;;
;; Copyright (c) 2011, PI:NAME:<NAME>END_PI
;; All rights reserved.
;;
;; See COPYING for more information. The license is the "new and
;; simplified BSD license" See
;; http://www.opensource.org/licenses/bsd-license
(ql:quickload "lisp-unit")
(use-package 'lisp-unit)
(defun make-html-unit-driver ()
"Return a new instance of org.openqa.selenium.HtmlUnitDriver"
(jnew "org.openqa.selenium.htmlunit.HtmlUnitDriver"))
(defun load-page (driver url)
"Use the given driver to HTTP GET the url. The result is loaded into the driver's browser."
(jcall "get" driver url))
(defun find-element-by-tag (driver tag)
"Return an element with the given HTML tag name on the driver's current page."
(jcall "findElement" driver (jstatic "tagName" "org.openqa.selenium.By" tag)))
(defun get-text (elem)
"Return the inner text of the given element."
(jcall "getText" elem))
(define-test test-my-max
(assert-equal "Moo Foo" (let* ((driver (make-html-unit-driver))
(elem (progn (load-page driver "http://localhost:8000")
(find-element-by-tag driver "h1"))))
(get-text elem))))
;(run-tests)
|
[
{
"context": "; Modified by Robert Krug from John Cowles's book bad-def.lisp.\n\n(in-packag",
"end": 25,
"score": 0.9998928904533386,
"start": 14,
"tag": "NAME",
"value": "Robert Krug"
},
{
"context": "; Modified by Robert Krug from John Cowles's book bad-def.lisp.\n\n(in-package \"ACL2\")\n\n(defst",
"end": 42,
"score": 0.9998926520347595,
"start": 31,
"tag": "NAME",
"value": "John Cowles"
}
] |
books/workshops/2002/cowles-primrec/support/bad-def1.lisp
|
mayankmanj/acl2
| 305 |
; Modified by Robert Krug from John Cowles's book bad-def.lisp.
(in-package "ACL2")
(defstub
g (*) => *)
(defaxiom g-thm
(implies (syntaxp (variablep n))
(equal (g n)
(if (equal n 0)
nil
(cons nil (g (- n 1)))))))
(defthm
len-cons
(equal (len (cons x y))(+ 1 (len y))))
(set-irrelevant-formals-ok :warn)
(defun
induct-hint (k n)
(if (zp k)
t
(induct-hint (- k 1)(- n 1))))
(defthm
g-at-neg-input
(implies (and (< n 0)
(integerp k))
(> (len (g n)) k))
:rule-classes nil
:hints (("goal"
:induct (induct-hint k n))))
(defthm
contradiction!!
nil
:rule-classes nil
:hints (("Goal"
:use (:instance
g-at-neg-input
(n -1)
(k (len (g -1)))))))
|
74151
|
; Modified by <NAME> from <NAME>'s book bad-def.lisp.
(in-package "ACL2")
(defstub
g (*) => *)
(defaxiom g-thm
(implies (syntaxp (variablep n))
(equal (g n)
(if (equal n 0)
nil
(cons nil (g (- n 1)))))))
(defthm
len-cons
(equal (len (cons x y))(+ 1 (len y))))
(set-irrelevant-formals-ok :warn)
(defun
induct-hint (k n)
(if (zp k)
t
(induct-hint (- k 1)(- n 1))))
(defthm
g-at-neg-input
(implies (and (< n 0)
(integerp k))
(> (len (g n)) k))
:rule-classes nil
:hints (("goal"
:induct (induct-hint k n))))
(defthm
contradiction!!
nil
:rule-classes nil
:hints (("Goal"
:use (:instance
g-at-neg-input
(n -1)
(k (len (g -1)))))))
| true |
; Modified by PI:NAME:<NAME>END_PI from PI:NAME:<NAME>END_PI's book bad-def.lisp.
(in-package "ACL2")
(defstub
g (*) => *)
(defaxiom g-thm
(implies (syntaxp (variablep n))
(equal (g n)
(if (equal n 0)
nil
(cons nil (g (- n 1)))))))
(defthm
len-cons
(equal (len (cons x y))(+ 1 (len y))))
(set-irrelevant-formals-ok :warn)
(defun
induct-hint (k n)
(if (zp k)
t
(induct-hint (- k 1)(- n 1))))
(defthm
g-at-neg-input
(implies (and (< n 0)
(integerp k))
(> (len (g n)) k))
:rule-classes nil
:hints (("goal"
:induct (induct-hint k n))))
(defthm
contradiction!!
nil
:rule-classes nil
:hints (("Goal"
:use (:instance
g-at-neg-input
(n -1)
(k (len (g -1)))))))
|
[
{
"context": ";;;; The MIT License\n\n;;;; Copyright (c) 2003-2008 Aneil Mallavarapu\n\n;;;; Permission is hereby granted, free of charg",
"end": 105,
"score": 0.9998996257781982,
"start": 88,
"tag": "NAME",
"value": "Aneil Mallavarapu"
}
] |
libraries/b/biochem/location.lisp
|
aneilbaboo/littleb
| 6 |
;;;; This file is part of little b.
;;;; The MIT License
;;;; Copyright (c) 2003-2008 Aneil Mallavarapu
;;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;;; of this software and associated documentation files (the "Software"), to deal
;;;; in the Software without restriction, including without limitation the rights
;;;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;;;; copies of the Software, and to permit persons to whom the Software is
;;;; furnished to do so, subject to the following conditions:
;;;; The above copyright notice and this permission notice shall be included in
;;;; all copies or substantial portions of the Software.
;;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
;;;; THE SOFTWARE.
;;; File: location
;;; Description: locations where species-types may reside.
;;; $Id: location.lisp,v 1.15 2008/09/06 00:23:08 amallavarapu Exp $
(in-package #I@FOLDER)
(include @/dimensionalization :use)
;;; has-sublocation is a helper concept:
(defcon has-sublocation (:notrace)
(location field sublocation))
;;;
;;; LOCATION:
;;;
(defcon location (:notrace :abstract)
(&property
(size :#= (let ((lclass (class-of object)))
[[reference-var] :dimension (location-class-dimension lclass)
:value (default-location-size lclass)])
:relevance t)))
(defun default-location-size (lclass)
{1 * (location-class-dimension lclass).unit})
(defun location-class-p (o)
(and (typep o 'standard-class)
(subtypep o location)))
(deftype location-class ()
`(satisfies location-class-p))
(defrule compute-has-sublocations-for-name-fields
(?loc location)
=>
(let* ((lclass (class-of ?loc)))
[has-sublocation ?loc nil ?loc] ; the nil sublocation of a location is itself
(loop for fi in lclass._fieldinfos
when (and (id-fieldinfo-p fi) fi.type (subtypep fi.type 'location))
do [has-sublocation ?loc fi.symbol ?loc.,fi.symbol])))
(defrule compute-has-sublocations-for-properties
(:and (?prop [|LOCATION.PROPERTY| ?loc ?subloc])
(:test (location-p ?subloc)))
=>
(let* ((fld (class-of ?prop).field-symbol))
[has-sublocation ?loc fld ?subloc]))
(defield location.sublocation (subloc)
(if subloc object.,subloc
object))
(defun location-class-is-sublocation (loc-class &rest subloc-fields)
(let* ((next (first subloc-fields))
(fi (find next loc-class._fieldinfos :key ?.symbol))
(rest (rest subloc-fields)))
(and (typep fi 'fieldinfo)
(subtypep (if (mutils:allow-type-p fi.type)
(mutils:allow-type-type fi.type) fi.type)
'location)
(or (null rest)
(apply #'location-class-is-sublocation (find-class fi.type) rest)))))
(define-function location-class-sublocations (lclass)
(remove-if-not (lambda (fi)
(subtypep (if (mutils:allow-type-p fi.type)
(mutils:allow-type-type fi.type)
fi.type)
'location))
lclass._fieldinfos))
(define-function containing-location-class (&rest loc-classes)
"Given one or more location-class objects, returns the one which has all of the others as sublocations"
(reduce (lambda (x y)
(let ((xsubloctypes (mapcar ?.type (location-class-sublocations x)))
(ysubloctypes (mapcar ?.type (location-class-sublocations y))))
(cond
((eq x y) x)
((subtypep (class-name y) `(or ,@xsubloctypes)) x)
((subtypep (class-name x) `(or ,@ysubloctypes)) y)
(t (b-error "Locations of type ~S and ~S cannot be associated with each other"
x y)))))
loc-classes))
;;;; ;; simple, atomic locations
(defcon compartment (:notrace location)
(&optional (id := *name*)
&property (adjacent-compartments)))
(defcon membrane (:notrace location)
(&optional (id := *name*)
&property (outer (allow compartment) :relevance t)
(inner (allow compartment) :relevance t)))
(defield membrane.c1 ()
(b-warn "~S.c1: MEMBRANE.C1 is deprecated use MEMBRANE.OUTER instead." object)
.outer)
(defield (setf membrane.c1) (value)
(b-warn "~S.c1: MEMBRANE.C1 is deprecated use MEMBRANE.OUTER instead." object)
(setf .outer value))
(defield membrane.c2 ()
(b-warn "~S.c2: MEMBRANE.C2 is deprecated use MEMBRANE.INNER instead." object)
.inner)
(defield (setf membrane.c2) (value)
(b-warn "~S.c2: MEMBRANE.C2 is deprecated use MEMBRANE.INNER instead." object)
(setf .inner value))
(defun membrane-id-inverse-p (id)
(and (consp id)
(eq (first id) :inverse)))
(defun membrane-get-non-inverse-membrane (m)
(if (membrane-id-inverse-p m.id) m.inverse m))
(defield membrane.inverse ()
(if (membrane-id-inverse-p .id)
(second .id)
(let ((outer .outer)
(inner .inner))
{object.inverse :#
[[membrane (list :inverse object)]
:inner inner :outer outer]})))
(defcon membrane-enclosure ()
(&optional (inner :#= [compartment])
(membrane :#= [membrane]))
(with-relevance t {.membrane.inner := .inner}))
(defield (setf membrane-enclosure.outer) (value)
{.membrane.outer := value})
(defield membrane-enclosure.outer ()
.membrane.outer)
(defcon spherical-cell (membrane-enclosure)
(&optional (inner :#= [compartment])
(membrane :#= [membrane]))
(super inner membrane))
(defield spherical-cell.radius ()
{{.membrane.size.value / {2 pi}} ^ 1/2})
(defield (setf spherical-cell.radius) (value)
{.membrane.size :@= 2 * pi value ^ 2}
{.inner.size :@= 4/3 * pi value ^ 3})
;;;
;;; LOCATION DIMENSIONALITY: compartment size dimensionality
;;;
(define-generic location-class-dimensionality (lclass)
(:method (lc) 1)
(:method ((lc (eql compartment))) *compartment-dimensionality*)
(:method ((lc (eql membrane))) (1- *compartment-dimensionality*)))
(defun location-dimensionality (o)
(location-class-dimensionality (class-of o)))
(define-function location-class-dimension (lclass)
{*distance-dimension* ^ (location-class-dimensionality lclass) })
;;;
;;; DEF-LOCATION-CLASS
;;;
(define-macro def-location-class (name &optional superclass &body sublocations)
(let ((subloc-fields (mapcar #'first sublocations)))
(labels ((dot-field (x) (intern (concatenate 'string "." (symbol-name x))))
(dot-field-symbol-macro-def (x) `(,(dot-field x) object.,(key x)))
(process-deflocclass-subloc (x)
(destructuring-bind (name def &rest prop-def) x
(if (and (symbolp def) (ignore-errors (subtypep def 'location)))
`(,name :#= [[,def] ,@prop-def])
`(,name := [,def ,@prop-def])))))
`(symbol-macrolet ,(mapcar #'dot-field-symbol-macro-def subloc-fields)
(defcon ,name ,superclass
(&optional (id := *name*)
&property ,@(mapcar #'process-deflocclass-subloc sublocations)))))))
|
79835
|
;;;; This file is part of little b.
;;;; The MIT License
;;;; Copyright (c) 2003-2008 <NAME>
;;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;;; of this software and associated documentation files (the "Software"), to deal
;;;; in the Software without restriction, including without limitation the rights
;;;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;;;; copies of the Software, and to permit persons to whom the Software is
;;;; furnished to do so, subject to the following conditions:
;;;; The above copyright notice and this permission notice shall be included in
;;;; all copies or substantial portions of the Software.
;;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
;;;; THE SOFTWARE.
;;; File: location
;;; Description: locations where species-types may reside.
;;; $Id: location.lisp,v 1.15 2008/09/06 00:23:08 amallavarapu Exp $
(in-package #I@FOLDER)
(include @/dimensionalization :use)
;;; has-sublocation is a helper concept:
(defcon has-sublocation (:notrace)
(location field sublocation))
;;;
;;; LOCATION:
;;;
(defcon location (:notrace :abstract)
(&property
(size :#= (let ((lclass (class-of object)))
[[reference-var] :dimension (location-class-dimension lclass)
:value (default-location-size lclass)])
:relevance t)))
(defun default-location-size (lclass)
{1 * (location-class-dimension lclass).unit})
(defun location-class-p (o)
(and (typep o 'standard-class)
(subtypep o location)))
(deftype location-class ()
`(satisfies location-class-p))
(defrule compute-has-sublocations-for-name-fields
(?loc location)
=>
(let* ((lclass (class-of ?loc)))
[has-sublocation ?loc nil ?loc] ; the nil sublocation of a location is itself
(loop for fi in lclass._fieldinfos
when (and (id-fieldinfo-p fi) fi.type (subtypep fi.type 'location))
do [has-sublocation ?loc fi.symbol ?loc.,fi.symbol])))
(defrule compute-has-sublocations-for-properties
(:and (?prop [|LOCATION.PROPERTY| ?loc ?subloc])
(:test (location-p ?subloc)))
=>
(let* ((fld (class-of ?prop).field-symbol))
[has-sublocation ?loc fld ?subloc]))
(defield location.sublocation (subloc)
(if subloc object.,subloc
object))
(defun location-class-is-sublocation (loc-class &rest subloc-fields)
(let* ((next (first subloc-fields))
(fi (find next loc-class._fieldinfos :key ?.symbol))
(rest (rest subloc-fields)))
(and (typep fi 'fieldinfo)
(subtypep (if (mutils:allow-type-p fi.type)
(mutils:allow-type-type fi.type) fi.type)
'location)
(or (null rest)
(apply #'location-class-is-sublocation (find-class fi.type) rest)))))
(define-function location-class-sublocations (lclass)
(remove-if-not (lambda (fi)
(subtypep (if (mutils:allow-type-p fi.type)
(mutils:allow-type-type fi.type)
fi.type)
'location))
lclass._fieldinfos))
(define-function containing-location-class (&rest loc-classes)
"Given one or more location-class objects, returns the one which has all of the others as sublocations"
(reduce (lambda (x y)
(let ((xsubloctypes (mapcar ?.type (location-class-sublocations x)))
(ysubloctypes (mapcar ?.type (location-class-sublocations y))))
(cond
((eq x y) x)
((subtypep (class-name y) `(or ,@xsubloctypes)) x)
((subtypep (class-name x) `(or ,@ysubloctypes)) y)
(t (b-error "Locations of type ~S and ~S cannot be associated with each other"
x y)))))
loc-classes))
;;;; ;; simple, atomic locations
(defcon compartment (:notrace location)
(&optional (id := *name*)
&property (adjacent-compartments)))
(defcon membrane (:notrace location)
(&optional (id := *name*)
&property (outer (allow compartment) :relevance t)
(inner (allow compartment) :relevance t)))
(defield membrane.c1 ()
(b-warn "~S.c1: MEMBRANE.C1 is deprecated use MEMBRANE.OUTER instead." object)
.outer)
(defield (setf membrane.c1) (value)
(b-warn "~S.c1: MEMBRANE.C1 is deprecated use MEMBRANE.OUTER instead." object)
(setf .outer value))
(defield membrane.c2 ()
(b-warn "~S.c2: MEMBRANE.C2 is deprecated use MEMBRANE.INNER instead." object)
.inner)
(defield (setf membrane.c2) (value)
(b-warn "~S.c2: MEMBRANE.C2 is deprecated use MEMBRANE.INNER instead." object)
(setf .inner value))
(defun membrane-id-inverse-p (id)
(and (consp id)
(eq (first id) :inverse)))
(defun membrane-get-non-inverse-membrane (m)
(if (membrane-id-inverse-p m.id) m.inverse m))
(defield membrane.inverse ()
(if (membrane-id-inverse-p .id)
(second .id)
(let ((outer .outer)
(inner .inner))
{object.inverse :#
[[membrane (list :inverse object)]
:inner inner :outer outer]})))
(defcon membrane-enclosure ()
(&optional (inner :#= [compartment])
(membrane :#= [membrane]))
(with-relevance t {.membrane.inner := .inner}))
(defield (setf membrane-enclosure.outer) (value)
{.membrane.outer := value})
(defield membrane-enclosure.outer ()
.membrane.outer)
(defcon spherical-cell (membrane-enclosure)
(&optional (inner :#= [compartment])
(membrane :#= [membrane]))
(super inner membrane))
(defield spherical-cell.radius ()
{{.membrane.size.value / {2 pi}} ^ 1/2})
(defield (setf spherical-cell.radius) (value)
{.membrane.size :@= 2 * pi value ^ 2}
{.inner.size :@= 4/3 * pi value ^ 3})
;;;
;;; LOCATION DIMENSIONALITY: compartment size dimensionality
;;;
(define-generic location-class-dimensionality (lclass)
(:method (lc) 1)
(:method ((lc (eql compartment))) *compartment-dimensionality*)
(:method ((lc (eql membrane))) (1- *compartment-dimensionality*)))
(defun location-dimensionality (o)
(location-class-dimensionality (class-of o)))
(define-function location-class-dimension (lclass)
{*distance-dimension* ^ (location-class-dimensionality lclass) })
;;;
;;; DEF-LOCATION-CLASS
;;;
(define-macro def-location-class (name &optional superclass &body sublocations)
(let ((subloc-fields (mapcar #'first sublocations)))
(labels ((dot-field (x) (intern (concatenate 'string "." (symbol-name x))))
(dot-field-symbol-macro-def (x) `(,(dot-field x) object.,(key x)))
(process-deflocclass-subloc (x)
(destructuring-bind (name def &rest prop-def) x
(if (and (symbolp def) (ignore-errors (subtypep def 'location)))
`(,name :#= [[,def] ,@prop-def])
`(,name := [,def ,@prop-def])))))
`(symbol-macrolet ,(mapcar #'dot-field-symbol-macro-def subloc-fields)
(defcon ,name ,superclass
(&optional (id := *name*)
&property ,@(mapcar #'process-deflocclass-subloc sublocations)))))))
| true |
;;;; This file is part of little b.
;;;; The MIT License
;;;; Copyright (c) 2003-2008 PI:NAME:<NAME>END_PI
;;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;;; of this software and associated documentation files (the "Software"), to deal
;;;; in the Software without restriction, including without limitation the rights
;;;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;;;; copies of the Software, and to permit persons to whom the Software is
;;;; furnished to do so, subject to the following conditions:
;;;; The above copyright notice and this permission notice shall be included in
;;;; all copies or substantial portions of the Software.
;;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
;;;; THE SOFTWARE.
;;; File: location
;;; Description: locations where species-types may reside.
;;; $Id: location.lisp,v 1.15 2008/09/06 00:23:08 amallavarapu Exp $
(in-package #I@FOLDER)
(include @/dimensionalization :use)
;;; has-sublocation is a helper concept:
(defcon has-sublocation (:notrace)
(location field sublocation))
;;;
;;; LOCATION:
;;;
(defcon location (:notrace :abstract)
(&property
(size :#= (let ((lclass (class-of object)))
[[reference-var] :dimension (location-class-dimension lclass)
:value (default-location-size lclass)])
:relevance t)))
(defun default-location-size (lclass)
{1 * (location-class-dimension lclass).unit})
(defun location-class-p (o)
(and (typep o 'standard-class)
(subtypep o location)))
(deftype location-class ()
`(satisfies location-class-p))
(defrule compute-has-sublocations-for-name-fields
(?loc location)
=>
(let* ((lclass (class-of ?loc)))
[has-sublocation ?loc nil ?loc] ; the nil sublocation of a location is itself
(loop for fi in lclass._fieldinfos
when (and (id-fieldinfo-p fi) fi.type (subtypep fi.type 'location))
do [has-sublocation ?loc fi.symbol ?loc.,fi.symbol])))
(defrule compute-has-sublocations-for-properties
(:and (?prop [|LOCATION.PROPERTY| ?loc ?subloc])
(:test (location-p ?subloc)))
=>
(let* ((fld (class-of ?prop).field-symbol))
[has-sublocation ?loc fld ?subloc]))
(defield location.sublocation (subloc)
(if subloc object.,subloc
object))
(defun location-class-is-sublocation (loc-class &rest subloc-fields)
(let* ((next (first subloc-fields))
(fi (find next loc-class._fieldinfos :key ?.symbol))
(rest (rest subloc-fields)))
(and (typep fi 'fieldinfo)
(subtypep (if (mutils:allow-type-p fi.type)
(mutils:allow-type-type fi.type) fi.type)
'location)
(or (null rest)
(apply #'location-class-is-sublocation (find-class fi.type) rest)))))
(define-function location-class-sublocations (lclass)
(remove-if-not (lambda (fi)
(subtypep (if (mutils:allow-type-p fi.type)
(mutils:allow-type-type fi.type)
fi.type)
'location))
lclass._fieldinfos))
(define-function containing-location-class (&rest loc-classes)
"Given one or more location-class objects, returns the one which has all of the others as sublocations"
(reduce (lambda (x y)
(let ((xsubloctypes (mapcar ?.type (location-class-sublocations x)))
(ysubloctypes (mapcar ?.type (location-class-sublocations y))))
(cond
((eq x y) x)
((subtypep (class-name y) `(or ,@xsubloctypes)) x)
((subtypep (class-name x) `(or ,@ysubloctypes)) y)
(t (b-error "Locations of type ~S and ~S cannot be associated with each other"
x y)))))
loc-classes))
;;;; ;; simple, atomic locations
(defcon compartment (:notrace location)
(&optional (id := *name*)
&property (adjacent-compartments)))
(defcon membrane (:notrace location)
(&optional (id := *name*)
&property (outer (allow compartment) :relevance t)
(inner (allow compartment) :relevance t)))
(defield membrane.c1 ()
(b-warn "~S.c1: MEMBRANE.C1 is deprecated use MEMBRANE.OUTER instead." object)
.outer)
(defield (setf membrane.c1) (value)
(b-warn "~S.c1: MEMBRANE.C1 is deprecated use MEMBRANE.OUTER instead." object)
(setf .outer value))
(defield membrane.c2 ()
(b-warn "~S.c2: MEMBRANE.C2 is deprecated use MEMBRANE.INNER instead." object)
.inner)
(defield (setf membrane.c2) (value)
(b-warn "~S.c2: MEMBRANE.C2 is deprecated use MEMBRANE.INNER instead." object)
(setf .inner value))
(defun membrane-id-inverse-p (id)
(and (consp id)
(eq (first id) :inverse)))
(defun membrane-get-non-inverse-membrane (m)
(if (membrane-id-inverse-p m.id) m.inverse m))
(defield membrane.inverse ()
(if (membrane-id-inverse-p .id)
(second .id)
(let ((outer .outer)
(inner .inner))
{object.inverse :#
[[membrane (list :inverse object)]
:inner inner :outer outer]})))
(defcon membrane-enclosure ()
(&optional (inner :#= [compartment])
(membrane :#= [membrane]))
(with-relevance t {.membrane.inner := .inner}))
(defield (setf membrane-enclosure.outer) (value)
{.membrane.outer := value})
(defield membrane-enclosure.outer ()
.membrane.outer)
(defcon spherical-cell (membrane-enclosure)
(&optional (inner :#= [compartment])
(membrane :#= [membrane]))
(super inner membrane))
(defield spherical-cell.radius ()
{{.membrane.size.value / {2 pi}} ^ 1/2})
(defield (setf spherical-cell.radius) (value)
{.membrane.size :@= 2 * pi value ^ 2}
{.inner.size :@= 4/3 * pi value ^ 3})
;;;
;;; LOCATION DIMENSIONALITY: compartment size dimensionality
;;;
(define-generic location-class-dimensionality (lclass)
(:method (lc) 1)
(:method ((lc (eql compartment))) *compartment-dimensionality*)
(:method ((lc (eql membrane))) (1- *compartment-dimensionality*)))
(defun location-dimensionality (o)
(location-class-dimensionality (class-of o)))
(define-function location-class-dimension (lclass)
{*distance-dimension* ^ (location-class-dimensionality lclass) })
;;;
;;; DEF-LOCATION-CLASS
;;;
(define-macro def-location-class (name &optional superclass &body sublocations)
(let ((subloc-fields (mapcar #'first sublocations)))
(labels ((dot-field (x) (intern (concatenate 'string "." (symbol-name x))))
(dot-field-symbol-macro-def (x) `(,(dot-field x) object.,(key x)))
(process-deflocclass-subloc (x)
(destructuring-bind (name def &rest prop-def) x
(if (and (symbolp def) (ignore-errors (subtypep def 'location)))
`(,name :#= [[,def] ,@prop-def])
`(,name := [,def ,@prop-def])))))
`(symbol-macrolet ,(mapcar #'dot-field-symbol-macro-def subloc-fields)
(defcon ,name ,superclass
(&optional (id := *name*)
&property ,@(mapcar #'process-deflocclass-subloc sublocations)))))))
|
[
{
"context": "he LICENSE file distributed with ACL2.\n;\n; Author: Eric McCarthy ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 186,
"score": 0.9998582005500793,
"start": 173,
"tag": "NAME",
"value": "Eric McCarthy"
},
{
"context": "distributed with ACL2.\n;\n; Author: Eric McCarthy ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 208,
"score": 0.9999340772628784,
"start": 188,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/kestrel/yul/json/top.lisp
|
mayankmanj/acl2
| 0 |
; Yul Library
;
; Copyright (C) 2021 Kestrel Institute (http://www.kestrel.edu)
;
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;
; Author: Eric McCarthy ([email protected])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "YUL")
(include-book "parse-json")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc+ yul-json
:parents (yul)
:short "Reading Yul from JSON files."
:long
(xdoc::topstring
(xdoc::p
"We extract Yul IR from JSON files produced by the Solidity Compiler."))
:order-subtopics t)
|
39827
|
; Yul Library
;
; Copyright (C) 2021 Kestrel Institute (http://www.kestrel.edu)
;
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;
; Author: <NAME> (<EMAIL>)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "YUL")
(include-book "parse-json")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc+ yul-json
:parents (yul)
:short "Reading Yul from JSON files."
:long
(xdoc::topstring
(xdoc::p
"We extract Yul IR from JSON files produced by the Solidity Compiler."))
:order-subtopics t)
| true |
; Yul Library
;
; Copyright (C) 2021 Kestrel Institute (http://www.kestrel.edu)
;
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;
; Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "YUL")
(include-book "parse-json")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc+ yul-json
:parents (yul)
:short "Reading Yul from JSON files."
:long
(xdoc::topstring
(xdoc::p
"We extract Yul IR from JSON files produced by the Solidity Compiler."))
:order-subtopics t)
|
[
{
"context": "; The MIT License (MIT)\n;;;\n;;; Copyright (c) 2017 Michael J. Forster\n;;;\n;;; Permission is hereby granted, free of cha",
"end": 100,
"score": 0.9998241662979126,
"start": 82,
"tag": "NAME",
"value": "Michael J. Forster"
},
{
"context": "i/reference/\n(defparameter *default-customer-ip* \"255.255.255.255\")\n\n(defclass auth-capture-transaction-request (cl",
"end": 1640,
"score": 0.9997194409370422,
"start": 1625,
"tag": "IP_ADDRESS",
"value": "255.255.255.255"
}
] |
core/auth-capture.lisp
|
michaeljforster/cl-anet-api
| 0 |
;;;; core/auth-capture.lisp
;;; The MIT License (MIT)
;;;
;;; Copyright (c) 2017 Michael J. Forster
;;;
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to deal
;;; in the Software without restriction, including without limitation the rights
;;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;;; copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be included in all
;;; copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;;; SOFTWARE.
(defpackage "CL-ANET-API/CORE/AUTH-CAPTURE"
(:use "CL")
(:import-from "ALEXANDRIA")
(:import-from "WU-DECIMAL")
(:import-from "CL-JSON")
(:import-from "CL-ANET-API/CORE/REQUEST-RESPONSE")
(:export "AUTH-CAPTURE-TRANSACTION-REQUEST"
"AUTH-CAPTURE-TRANSACTION-RESPONSE"))
(in-package "CL-ANET-API/CORE/AUTH-CAPTURE")
;; See http://developer.authorize.net/api/reference/
(defparameter *default-customer-ip* "255.255.255.255")
(defclass auth-capture-transaction-request (cl-anet-api/core/request-response:transaction-request)
((amount :initarg :amount :reader cl-anet-api/core/request-response:transaction-request-amount) ; total, including tax, shipping, and other charges; 15 digits
(payment :initarg :payment :reader cl-anet-api/core/request-response:transaction-request-payment)
(order :initarg :order :reader cl-anet-api/core/request-response:transaction-request-order)
(line-items :initarg :line-items :reader cl-anet-api/core/request-response:transaction-request-line-items)
(tax :initarg :tax :reader cl-anet-api/core/request-response:transaction-request-tax)
(customer :initarg :customer :reader cl-anet-api/core/request-response:transaction-request-customer)
(bill-to :initarg :bill-to :reader cl-anet-api/core/request-response:transaction-request-bill-to)
(customer-ip :initarg :customer-ip :reader cl-anet-api/core/request-response:transaction-request-customer-ip)
(settings :initform '() :reader cl-anet-api/core/request-response:transaction-request-settings))
(:default-initargs
:amount #$0.00
:payment nil
:order nil
:line-items '()
:tax nil
:customer nil
:bill-to nil
:customer-ip *default-customer-ip*))
(defmethod cl-anet-api/core/request-response:transaction-request-type ((transaction-request auth-capture-transaction-request))
"authCaptureTransaction")
(defmethod cl-anet-api/core/request-response:transaction-request-allow-partial-auth-p ((transaction-request auth-capture-transaction-request))
(getf (slot-value transaction-request 'settings) :allow-partial-auth))
(defmethod (setf cl-anet-api/core/request-response:transaction-request-allow-partial-auth-p) (value (transaction-request auth-capture-transaction-request))
(check-type value boolean)
(setf (getf (slot-value transaction-request 'settings) :allow-partial-auth) value))
(defmethod cl-anet-api/core/request-response:transaction-request-duplicate-window ((transaction-request auth-capture-transaction-request))
(getf (slot-value transaction-request 'settings) :duplicate-window))
(defmethod (setf cl-anet-api/core/request-response:transaction-request-duplicate-window) (value (transaction-request auth-capture-transaction-request))
(check-type value integer)
(setf (getf (slot-value transaction-request 'settings) :duplicate-window) value))
(defclass auth-capture-transaction-response (cl-anet-api/core/request-response:transaction-response)
((response-code :initarg :response-code :reader cl-anet-api/core/request-response:transaction-response-response-code)
(auth-code :initarg :auth-code :reader cl-anet-api/core/request-response:transaction-response-auth-code)
(avs-result-code :initarg :avs-result-code :reader cl-anet-api/core/request-response:transaction-response-avs-result-code)
(cvv-result-code :initarg :cvv-result-code :reader cl-anet-api/core/request-response:transaction-response-cvv-result-code)
(cavv-result-code :initarg :cavv-result-code :reader cl-anet-api/core/request-response:transaction-response-cavv-result-code)
(trans-id :initarg :trans-id :reader cl-anet-api/core/request-response:transaction-response-trans-id)
;; NOTE watch JSON decode of "refTransID" as :REF-TRANS-+ID+
(ref-trans-id :initarg :ref-trans-id :reader cl-anet-api/core/request-response:transaction-response-ref-trans-id)
(trans-hash :initarg :trans-hash :reader cl-anet-api/core/request-response:transaction-response-trans-hash)
(account-number :initarg :account-number :reader cl-anet-api/core/request-response:transaction-response-account-number)
(account-type :initarg :account-type :reader cl-anet-api/core/request-response:transaction-response-account-type)
(message-code :initarg :message-code :reader cl-anet-api/core/request-response:transaction-response-message-code)
(message-description :initarg :message-description :reader cl-anet-api/core/request-response:transaction-response-message-description)
(error-code :initarg :error-code :reader cl-anet-api/core/request-response:transaction-response-error-code)
(error-text :initarg :error-text :reader cl-anet-api/core/request-response:transaction-response-error-text)
;; LATER other fields...
)
(:default-initargs
:response-code ""
:auth-code ""
:avs-result-code ""
:cvv-result-code ""
:cavv-result-code ""
:trans-id ""
:ref-trans-id ""
:trans-hash ""
:account-number ""
:account-type ""
:message-code ""
:message-description ""
:error-code ""
:error-text ""))
(defmethod cl-json:encode-json ((transaction-request auth-capture-transaction-request)
&optional (stream cl-json:*json-output*))
(with-accessors ((transaction-request-type cl-anet-api/core/request-response:transaction-request-type)
(transaction-request-amount cl-anet-api/core/request-response:transaction-request-amount)
(transaction-request-payment cl-anet-api/core/request-response:transaction-request-payment)
(transaction-request-order cl-anet-api/core/request-response:transaction-request-order)
(transaction-request-line-items cl-anet-api/core/request-response:transaction-request-line-items)
(transaction-request-tax cl-anet-api/core/request-response:transaction-request-tax)
(transaction-request-customer cl-anet-api/core/request-response:transaction-request-customer)
(transaction-request-bill-to cl-anet-api/core/request-response:transaction-request-bill-to)
(transaction-request-customer-ip cl-anet-api/core/request-response:transaction-request-customer-ip)
(transaction-request-settings cl-anet-api/core/request-response:transaction-request-settings))
transaction-request
(cl-json:with-object (stream)
(cl-json:encode-object-member :transaction-type transaction-request-type stream)
(cl-json:encode-object-member :amount (let ((wu-decimal:*print-precision-loss* :round))
(format nil "~/wu-decimal:$/" transaction-request-amount))
stream)
(unless (null transaction-request-payment)
(cl-json:encode-object-member :payment transaction-request-payment stream))
(unless (null transaction-request-order)
(cl-json:encode-object-member :order transaction-request-order stream))
(unless (null transaction-request-line-items)
(cl-json:as-object-member (:line-items stream)
(cl-json:with-object (stream)
(dolist (line-item transaction-request-line-items)
(cl-json:encode-object-member :line-item line-item stream)))))
(unless (null transaction-request-tax)
(cl-json:encode-object-member :tax transaction-request-tax stream))
(unless (null transaction-request-customer)
(cl-json:encode-object-member :customer transaction-request-customer stream))
(unless (null transaction-request-bill-to)
(cl-json:encode-object-member :bill-to transaction-request-bill-to stream))
(cl-json:encode-object-member :customer-i-p transaction-request-customer-ip stream)
(unless (null transaction-request-settings) ; assuming a list implementation
(cl-json:as-object-member (:transaction-settings stream)
(cl-json:with-object (stream)
(alexandria:doplist (key value transaction-request-settings)
(ecase key
(:allow-partial-auth
(cl-json:as-object-member (:setting stream)
(cl-json:encode-object-member :setting-name key stream)
(cl-json:encode-object-member :setting-value (if value "True" "False")
stream)))
(:duplicate-window
(cl-json:as-object-member (:setting stream)
(cl-json:encode-object-member :setting-name key stream)
(cl-json:encode-object-member :setting-value (princ-to-string value)
stream)))))))))))
(defmethod cl-anet-api/core/request-response:transaction-request-transaction-response
((transaction-request auth-capture-transaction-request)
raw-response-transaction-response)
(flet ((value (key)
(cdr (assoc key raw-response-transaction-response))))
(let ((message (cadr (assoc :messages raw-response-transaction-response)))
(err (cadr (assoc :errors raw-response-transaction-response))))
(make-instance 'auth-capture-transaction-response
:response-code (value :response-code)
:auth-code (value :auth-code)
:avs-result-code (value :avs-result-code)
:cvv-result-code (value :cvv-result-code)
:cavv-result-code (value :cavv-result-code)
:trans-id (value :trans-id)
:ref-trans-id (value :ref-trans-+id+) ; Parsed from "refTransID"!
:trans-hash (value :trans-hash)
:account-number (value :account-number)
:account-type (value :account-type)
:message-code (or (cdr (assoc :code message)) "")
:message-description (or (cdr (assoc :description message)))
:error-code (or (cdr (assoc :error-code err)) "")
:error-text (or (cdr (assoc :error-text err)) "")))))
|
87620
|
;;;; core/auth-capture.lisp
;;; The MIT License (MIT)
;;;
;;; Copyright (c) 2017 <NAME>
;;;
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to deal
;;; in the Software without restriction, including without limitation the rights
;;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;;; copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be included in all
;;; copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;;; SOFTWARE.
(defpackage "CL-ANET-API/CORE/AUTH-CAPTURE"
(:use "CL")
(:import-from "ALEXANDRIA")
(:import-from "WU-DECIMAL")
(:import-from "CL-JSON")
(:import-from "CL-ANET-API/CORE/REQUEST-RESPONSE")
(:export "AUTH-CAPTURE-TRANSACTION-REQUEST"
"AUTH-CAPTURE-TRANSACTION-RESPONSE"))
(in-package "CL-ANET-API/CORE/AUTH-CAPTURE")
;; See http://developer.authorize.net/api/reference/
(defparameter *default-customer-ip* "255.255.255.255")
(defclass auth-capture-transaction-request (cl-anet-api/core/request-response:transaction-request)
((amount :initarg :amount :reader cl-anet-api/core/request-response:transaction-request-amount) ; total, including tax, shipping, and other charges; 15 digits
(payment :initarg :payment :reader cl-anet-api/core/request-response:transaction-request-payment)
(order :initarg :order :reader cl-anet-api/core/request-response:transaction-request-order)
(line-items :initarg :line-items :reader cl-anet-api/core/request-response:transaction-request-line-items)
(tax :initarg :tax :reader cl-anet-api/core/request-response:transaction-request-tax)
(customer :initarg :customer :reader cl-anet-api/core/request-response:transaction-request-customer)
(bill-to :initarg :bill-to :reader cl-anet-api/core/request-response:transaction-request-bill-to)
(customer-ip :initarg :customer-ip :reader cl-anet-api/core/request-response:transaction-request-customer-ip)
(settings :initform '() :reader cl-anet-api/core/request-response:transaction-request-settings))
(:default-initargs
:amount #$0.00
:payment nil
:order nil
:line-items '()
:tax nil
:customer nil
:bill-to nil
:customer-ip *default-customer-ip*))
(defmethod cl-anet-api/core/request-response:transaction-request-type ((transaction-request auth-capture-transaction-request))
"authCaptureTransaction")
(defmethod cl-anet-api/core/request-response:transaction-request-allow-partial-auth-p ((transaction-request auth-capture-transaction-request))
(getf (slot-value transaction-request 'settings) :allow-partial-auth))
(defmethod (setf cl-anet-api/core/request-response:transaction-request-allow-partial-auth-p) (value (transaction-request auth-capture-transaction-request))
(check-type value boolean)
(setf (getf (slot-value transaction-request 'settings) :allow-partial-auth) value))
(defmethod cl-anet-api/core/request-response:transaction-request-duplicate-window ((transaction-request auth-capture-transaction-request))
(getf (slot-value transaction-request 'settings) :duplicate-window))
(defmethod (setf cl-anet-api/core/request-response:transaction-request-duplicate-window) (value (transaction-request auth-capture-transaction-request))
(check-type value integer)
(setf (getf (slot-value transaction-request 'settings) :duplicate-window) value))
(defclass auth-capture-transaction-response (cl-anet-api/core/request-response:transaction-response)
((response-code :initarg :response-code :reader cl-anet-api/core/request-response:transaction-response-response-code)
(auth-code :initarg :auth-code :reader cl-anet-api/core/request-response:transaction-response-auth-code)
(avs-result-code :initarg :avs-result-code :reader cl-anet-api/core/request-response:transaction-response-avs-result-code)
(cvv-result-code :initarg :cvv-result-code :reader cl-anet-api/core/request-response:transaction-response-cvv-result-code)
(cavv-result-code :initarg :cavv-result-code :reader cl-anet-api/core/request-response:transaction-response-cavv-result-code)
(trans-id :initarg :trans-id :reader cl-anet-api/core/request-response:transaction-response-trans-id)
;; NOTE watch JSON decode of "refTransID" as :REF-TRANS-+ID+
(ref-trans-id :initarg :ref-trans-id :reader cl-anet-api/core/request-response:transaction-response-ref-trans-id)
(trans-hash :initarg :trans-hash :reader cl-anet-api/core/request-response:transaction-response-trans-hash)
(account-number :initarg :account-number :reader cl-anet-api/core/request-response:transaction-response-account-number)
(account-type :initarg :account-type :reader cl-anet-api/core/request-response:transaction-response-account-type)
(message-code :initarg :message-code :reader cl-anet-api/core/request-response:transaction-response-message-code)
(message-description :initarg :message-description :reader cl-anet-api/core/request-response:transaction-response-message-description)
(error-code :initarg :error-code :reader cl-anet-api/core/request-response:transaction-response-error-code)
(error-text :initarg :error-text :reader cl-anet-api/core/request-response:transaction-response-error-text)
;; LATER other fields...
)
(:default-initargs
:response-code ""
:auth-code ""
:avs-result-code ""
:cvv-result-code ""
:cavv-result-code ""
:trans-id ""
:ref-trans-id ""
:trans-hash ""
:account-number ""
:account-type ""
:message-code ""
:message-description ""
:error-code ""
:error-text ""))
(defmethod cl-json:encode-json ((transaction-request auth-capture-transaction-request)
&optional (stream cl-json:*json-output*))
(with-accessors ((transaction-request-type cl-anet-api/core/request-response:transaction-request-type)
(transaction-request-amount cl-anet-api/core/request-response:transaction-request-amount)
(transaction-request-payment cl-anet-api/core/request-response:transaction-request-payment)
(transaction-request-order cl-anet-api/core/request-response:transaction-request-order)
(transaction-request-line-items cl-anet-api/core/request-response:transaction-request-line-items)
(transaction-request-tax cl-anet-api/core/request-response:transaction-request-tax)
(transaction-request-customer cl-anet-api/core/request-response:transaction-request-customer)
(transaction-request-bill-to cl-anet-api/core/request-response:transaction-request-bill-to)
(transaction-request-customer-ip cl-anet-api/core/request-response:transaction-request-customer-ip)
(transaction-request-settings cl-anet-api/core/request-response:transaction-request-settings))
transaction-request
(cl-json:with-object (stream)
(cl-json:encode-object-member :transaction-type transaction-request-type stream)
(cl-json:encode-object-member :amount (let ((wu-decimal:*print-precision-loss* :round))
(format nil "~/wu-decimal:$/" transaction-request-amount))
stream)
(unless (null transaction-request-payment)
(cl-json:encode-object-member :payment transaction-request-payment stream))
(unless (null transaction-request-order)
(cl-json:encode-object-member :order transaction-request-order stream))
(unless (null transaction-request-line-items)
(cl-json:as-object-member (:line-items stream)
(cl-json:with-object (stream)
(dolist (line-item transaction-request-line-items)
(cl-json:encode-object-member :line-item line-item stream)))))
(unless (null transaction-request-tax)
(cl-json:encode-object-member :tax transaction-request-tax stream))
(unless (null transaction-request-customer)
(cl-json:encode-object-member :customer transaction-request-customer stream))
(unless (null transaction-request-bill-to)
(cl-json:encode-object-member :bill-to transaction-request-bill-to stream))
(cl-json:encode-object-member :customer-i-p transaction-request-customer-ip stream)
(unless (null transaction-request-settings) ; assuming a list implementation
(cl-json:as-object-member (:transaction-settings stream)
(cl-json:with-object (stream)
(alexandria:doplist (key value transaction-request-settings)
(ecase key
(:allow-partial-auth
(cl-json:as-object-member (:setting stream)
(cl-json:encode-object-member :setting-name key stream)
(cl-json:encode-object-member :setting-value (if value "True" "False")
stream)))
(:duplicate-window
(cl-json:as-object-member (:setting stream)
(cl-json:encode-object-member :setting-name key stream)
(cl-json:encode-object-member :setting-value (princ-to-string value)
stream)))))))))))
(defmethod cl-anet-api/core/request-response:transaction-request-transaction-response
((transaction-request auth-capture-transaction-request)
raw-response-transaction-response)
(flet ((value (key)
(cdr (assoc key raw-response-transaction-response))))
(let ((message (cadr (assoc :messages raw-response-transaction-response)))
(err (cadr (assoc :errors raw-response-transaction-response))))
(make-instance 'auth-capture-transaction-response
:response-code (value :response-code)
:auth-code (value :auth-code)
:avs-result-code (value :avs-result-code)
:cvv-result-code (value :cvv-result-code)
:cavv-result-code (value :cavv-result-code)
:trans-id (value :trans-id)
:ref-trans-id (value :ref-trans-+id+) ; Parsed from "refTransID"!
:trans-hash (value :trans-hash)
:account-number (value :account-number)
:account-type (value :account-type)
:message-code (or (cdr (assoc :code message)) "")
:message-description (or (cdr (assoc :description message)))
:error-code (or (cdr (assoc :error-code err)) "")
:error-text (or (cdr (assoc :error-text err)) "")))))
| true |
;;;; core/auth-capture.lisp
;;; The MIT License (MIT)
;;;
;;; Copyright (c) 2017 PI:NAME:<NAME>END_PI
;;;
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to deal
;;; in the Software without restriction, including without limitation the rights
;;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;;; copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be included in all
;;; copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;;; SOFTWARE.
(defpackage "CL-ANET-API/CORE/AUTH-CAPTURE"
(:use "CL")
(:import-from "ALEXANDRIA")
(:import-from "WU-DECIMAL")
(:import-from "CL-JSON")
(:import-from "CL-ANET-API/CORE/REQUEST-RESPONSE")
(:export "AUTH-CAPTURE-TRANSACTION-REQUEST"
"AUTH-CAPTURE-TRANSACTION-RESPONSE"))
(in-package "CL-ANET-API/CORE/AUTH-CAPTURE")
;; See http://developer.authorize.net/api/reference/
(defparameter *default-customer-ip* "255.255.255.255")
(defclass auth-capture-transaction-request (cl-anet-api/core/request-response:transaction-request)
((amount :initarg :amount :reader cl-anet-api/core/request-response:transaction-request-amount) ; total, including tax, shipping, and other charges; 15 digits
(payment :initarg :payment :reader cl-anet-api/core/request-response:transaction-request-payment)
(order :initarg :order :reader cl-anet-api/core/request-response:transaction-request-order)
(line-items :initarg :line-items :reader cl-anet-api/core/request-response:transaction-request-line-items)
(tax :initarg :tax :reader cl-anet-api/core/request-response:transaction-request-tax)
(customer :initarg :customer :reader cl-anet-api/core/request-response:transaction-request-customer)
(bill-to :initarg :bill-to :reader cl-anet-api/core/request-response:transaction-request-bill-to)
(customer-ip :initarg :customer-ip :reader cl-anet-api/core/request-response:transaction-request-customer-ip)
(settings :initform '() :reader cl-anet-api/core/request-response:transaction-request-settings))
(:default-initargs
:amount #$0.00
:payment nil
:order nil
:line-items '()
:tax nil
:customer nil
:bill-to nil
:customer-ip *default-customer-ip*))
(defmethod cl-anet-api/core/request-response:transaction-request-type ((transaction-request auth-capture-transaction-request))
"authCaptureTransaction")
(defmethod cl-anet-api/core/request-response:transaction-request-allow-partial-auth-p ((transaction-request auth-capture-transaction-request))
(getf (slot-value transaction-request 'settings) :allow-partial-auth))
(defmethod (setf cl-anet-api/core/request-response:transaction-request-allow-partial-auth-p) (value (transaction-request auth-capture-transaction-request))
(check-type value boolean)
(setf (getf (slot-value transaction-request 'settings) :allow-partial-auth) value))
(defmethod cl-anet-api/core/request-response:transaction-request-duplicate-window ((transaction-request auth-capture-transaction-request))
(getf (slot-value transaction-request 'settings) :duplicate-window))
(defmethod (setf cl-anet-api/core/request-response:transaction-request-duplicate-window) (value (transaction-request auth-capture-transaction-request))
(check-type value integer)
(setf (getf (slot-value transaction-request 'settings) :duplicate-window) value))
(defclass auth-capture-transaction-response (cl-anet-api/core/request-response:transaction-response)
((response-code :initarg :response-code :reader cl-anet-api/core/request-response:transaction-response-response-code)
(auth-code :initarg :auth-code :reader cl-anet-api/core/request-response:transaction-response-auth-code)
(avs-result-code :initarg :avs-result-code :reader cl-anet-api/core/request-response:transaction-response-avs-result-code)
(cvv-result-code :initarg :cvv-result-code :reader cl-anet-api/core/request-response:transaction-response-cvv-result-code)
(cavv-result-code :initarg :cavv-result-code :reader cl-anet-api/core/request-response:transaction-response-cavv-result-code)
(trans-id :initarg :trans-id :reader cl-anet-api/core/request-response:transaction-response-trans-id)
;; NOTE watch JSON decode of "refTransID" as :REF-TRANS-+ID+
(ref-trans-id :initarg :ref-trans-id :reader cl-anet-api/core/request-response:transaction-response-ref-trans-id)
(trans-hash :initarg :trans-hash :reader cl-anet-api/core/request-response:transaction-response-trans-hash)
(account-number :initarg :account-number :reader cl-anet-api/core/request-response:transaction-response-account-number)
(account-type :initarg :account-type :reader cl-anet-api/core/request-response:transaction-response-account-type)
(message-code :initarg :message-code :reader cl-anet-api/core/request-response:transaction-response-message-code)
(message-description :initarg :message-description :reader cl-anet-api/core/request-response:transaction-response-message-description)
(error-code :initarg :error-code :reader cl-anet-api/core/request-response:transaction-response-error-code)
(error-text :initarg :error-text :reader cl-anet-api/core/request-response:transaction-response-error-text)
;; LATER other fields...
)
(:default-initargs
:response-code ""
:auth-code ""
:avs-result-code ""
:cvv-result-code ""
:cavv-result-code ""
:trans-id ""
:ref-trans-id ""
:trans-hash ""
:account-number ""
:account-type ""
:message-code ""
:message-description ""
:error-code ""
:error-text ""))
(defmethod cl-json:encode-json ((transaction-request auth-capture-transaction-request)
&optional (stream cl-json:*json-output*))
(with-accessors ((transaction-request-type cl-anet-api/core/request-response:transaction-request-type)
(transaction-request-amount cl-anet-api/core/request-response:transaction-request-amount)
(transaction-request-payment cl-anet-api/core/request-response:transaction-request-payment)
(transaction-request-order cl-anet-api/core/request-response:transaction-request-order)
(transaction-request-line-items cl-anet-api/core/request-response:transaction-request-line-items)
(transaction-request-tax cl-anet-api/core/request-response:transaction-request-tax)
(transaction-request-customer cl-anet-api/core/request-response:transaction-request-customer)
(transaction-request-bill-to cl-anet-api/core/request-response:transaction-request-bill-to)
(transaction-request-customer-ip cl-anet-api/core/request-response:transaction-request-customer-ip)
(transaction-request-settings cl-anet-api/core/request-response:transaction-request-settings))
transaction-request
(cl-json:with-object (stream)
(cl-json:encode-object-member :transaction-type transaction-request-type stream)
(cl-json:encode-object-member :amount (let ((wu-decimal:*print-precision-loss* :round))
(format nil "~/wu-decimal:$/" transaction-request-amount))
stream)
(unless (null transaction-request-payment)
(cl-json:encode-object-member :payment transaction-request-payment stream))
(unless (null transaction-request-order)
(cl-json:encode-object-member :order transaction-request-order stream))
(unless (null transaction-request-line-items)
(cl-json:as-object-member (:line-items stream)
(cl-json:with-object (stream)
(dolist (line-item transaction-request-line-items)
(cl-json:encode-object-member :line-item line-item stream)))))
(unless (null transaction-request-tax)
(cl-json:encode-object-member :tax transaction-request-tax stream))
(unless (null transaction-request-customer)
(cl-json:encode-object-member :customer transaction-request-customer stream))
(unless (null transaction-request-bill-to)
(cl-json:encode-object-member :bill-to transaction-request-bill-to stream))
(cl-json:encode-object-member :customer-i-p transaction-request-customer-ip stream)
(unless (null transaction-request-settings) ; assuming a list implementation
(cl-json:as-object-member (:transaction-settings stream)
(cl-json:with-object (stream)
(alexandria:doplist (key value transaction-request-settings)
(ecase key
(:allow-partial-auth
(cl-json:as-object-member (:setting stream)
(cl-json:encode-object-member :setting-name key stream)
(cl-json:encode-object-member :setting-value (if value "True" "False")
stream)))
(:duplicate-window
(cl-json:as-object-member (:setting stream)
(cl-json:encode-object-member :setting-name key stream)
(cl-json:encode-object-member :setting-value (princ-to-string value)
stream)))))))))))
(defmethod cl-anet-api/core/request-response:transaction-request-transaction-response
((transaction-request auth-capture-transaction-request)
raw-response-transaction-response)
(flet ((value (key)
(cdr (assoc key raw-response-transaction-response))))
(let ((message (cadr (assoc :messages raw-response-transaction-response)))
(err (cadr (assoc :errors raw-response-transaction-response))))
(make-instance 'auth-capture-transaction-response
:response-code (value :response-code)
:auth-code (value :auth-code)
:avs-result-code (value :avs-result-code)
:cvv-result-code (value :cvv-result-code)
:cavv-result-code (value :cavv-result-code)
:trans-id (value :trans-id)
:ref-trans-id (value :ref-trans-+id+) ; Parsed from "refTransID"!
:trans-hash (value :trans-hash)
:account-number (value :account-number)
:account-type (value :account-type)
:message-code (or (cdr (assoc :code message)) "")
:message-description (or (cdr (assoc :description message)))
:error-code (or (cdr (assoc :error-code err)) "")
:error-text (or (cdr (assoc :error-text err)) "")))))
|
[
{
"context": "e \"ACL2\")\n\n#|\n\n german.lisp \n ~~~~~~~~~~~\n\nAuthor: Sandip Ray\nDate: Wed Oct 5 01:37:01 2005\n\nThis book represe",
"end": 71,
"score": 0.9997749328613281,
"start": 61,
"tag": "NAME",
"value": "Sandip Ray"
},
{
"context": "h ACL2. \n\nPrelude\n=======\n\nBackground\n----------\n\nAnna Slobodova recently was trying to model the German protocol ",
"end": 252,
"score": 0.9989900588989258,
"start": 238,
"tag": "NAME",
"value": "Anna Slobodova"
},
{
"context": "hat revived my interest in the protocol. (Thanks, Anna.)\nI had a version of the Murphy code of the proto",
"end": 392,
"score": 0.9969584941864014,
"start": 388,
"tag": "NAME",
"value": "Anna"
},
{
"context": " a version of the Murphy code of the protocol, and Rob and I had earlier\nmodeled it very abstractly earl",
"end": 454,
"score": 0.9789479374885559,
"start": 451,
"tag": "NAME",
"value": "Rob"
},
{
"context": "wanted to see how to automate the proof. But when Anna was doing it I thought\nI might as well model th",
"end": 604,
"score": 0.5288510918617249,
"start": 602,
"tag": "NAME",
"value": "An"
},
{
"context": "t using quantifiers, in part as I plan to talk to\nMatt and J about how I believe more support should be ",
"end": 1279,
"score": 0.9970803260803223,
"start": 1275,
"tag": "NAME",
"value": "Matt"
},
{
"context": "quantifiers, in part as I plan to talk to\nMatt and J about how I believe more support should be added ",
"end": 1285,
"score": 0.9653137922286987,
"start": 1284,
"tag": "NAME",
"value": "J"
}
] |
books/projects/concurrent-programs/german-protocol/german.lisp
|
ragerdl/acl2-defthm-rc2
| 1 |
(in-package "ACL2")
#|
german.lisp
~~~~~~~~~~~
Author: Sandip Ray
Date: Wed Oct 5 01:37:01 2005
This book represents my efforts to model the German protocol and reason about
it with ACL2.
Prelude
=======
Background
----------
Anna Slobodova recently was trying to model the German protocol an use ACL2 to
prove it correct. That revived my interest in the protocol. (Thanks, Anna.)
I had a version of the Murphy code of the protocol, and Rob and I had earlier
modeled it very abstractly earlier to apply predicate abstractions. There we
wanted to see how to automate the proof. But when Anna was doing it I thought
I might as well model the protocol as close to the Murphy code as possible and
see how much effort it is to do it in ACL2.
Note on using Quantification
----------------------------
Many of the predicates necessary for the proof of coherence [including the
property of coherence itself] can be stated easily via quantification. But use
of quantification requires that we be prepared to use hints in the right
places. It is unclear whether it is better to use quantification or recursive
functions in this project. I use quantification in most places since I was
trying to get more practice at using quantifiers, in part as I plan to talk to
Matt and J about how I believe more support should be added to the use of
quantifiers. It should be noted that although the use of quantification
requires hints, the hints were extremely mechanical. [More comments at where I
do quantification proofs.] I have used recursive functions for a couple of
predicates, but I only used them when using it was natural, for example when I
was only quantifying over one process index and so I could write only one
recursive function to capture the property I posit. [I do not like to write a
number of functions defining a property if I can state the property using one
defun-sk.] The one place where I only allow recursive functions is in defining
the functions involved in the state transition of the system. I do so since I
expect that one might want to simulate [execute] the model and hence using
quantification appears to be "wrong" in the context. Either way, I do not want
to advocate anything specific but the proof shows several examples of how to do
either.
Effort
------
I started modeling the protocol on Friday September 30, 2005. I did not have
time to work on the protocol proof on Saturday. I started the proof on Sunday,
and worked about 5 hours. I then spent Monday October 3, and Tuesday October 4
on the proof, working about 8-9 hours each day, doing the proof and the
documentation in real time. I was frustrated on Tuesday evening when I saw
that I had missed one subtlety of the protocol which is listed in Section 3.23.
Then I spent the night of Tuesday, from 11:30p.m. to 1:30a.m. (Wednesday) and
finished the proof.
I wrote the documentation of the prelude (that is, this part) after the proof.
The rest of the documentation was done real time while doing the proof. The
reason I did it that way was that I wanted to document my thoughts, both so
that the script is understandable and so that if I did shelve the proof I could
get back to it easily.
After the proof was done I changed all the defthm events not involving coherent
to local so that at least including the book will work perfectly fast. To
replay the proof do (certify-book "german") at the ACL2 prompt in an empty ACL2
session. To include the book after certification, do (include-book
"german"). The latter should be very fast at least.
|#
; Here is the murphy code for the protocol that I had once gotten from Thomas
; Wahl. I suspect that it is different from the code that Anna showed me,
; since see showed me properties called ctrlpropinv and datapropinv which I
; dont see in this version. But I think possibly the basics of the two codes
; are similar in the description of the protocols.
; Const
; n: 30;
; Type
; Msg: enum { null, req_sh, req_ex, inv, inv_ack, gr_sh, gr_ex };
; State: enum { I, S, E };
; ID: Scalarset(n);
; Var
; ch1: array[ID] of Msg; /* channel 1 */
; ch2: array[ID] of Msg; /* channel 2 */
; ch3: array[ID] of Msg; /* channel 3 */
; hsl: array[ID] of boolean; /* home_shared_list */
; hil: array[ID] of boolean; /* home_invalidate_list */
; heg: boolean; /* home_exclusive_granted */
; hcm: Msg; /* home_current_command */
; hcc: ID; /* home_current_client */
; c: array[ID] of State; /* distributed cache state */
; Ruleset i: ID do
; rule "1" /* client requests shared access */
; c[i] = I & ch1[i] = null ==>
; begin
; ch1[i] := req_sh;
; end;
; rule "2" /* client requests exclusive access */
; c[i] = I & ch1[i] = null ==>
; begin
; ch1[i] := req_ex;
; end;
; rule "3" /* home picks new request */
; hcm = null & ch1[i] != null ==>
; begin
; hcm := ch1[i];
; ch1[i] := null;
; hcc := i;
; for j: ID do
; hil[j] := hsl[j];
; end;
; end;
; rule "4" /* home sends invalidate message */
; hil[i] & ch2[i] = null & ((hcm = req_sh & heg) | hcm = req_ex) ==>
; begin
; ch2[i] := inv;
; hil[i] := false;
; end;
; rule "5" /* home receives invalidate acknowledgement */
; hcm != null & ch3[i] = inv_ack ==>
; begin
; hsl[i] := false;
; heg := false;
; ch3[i] := null;
; end;
; rule "6" /* sharer invalidates cache */
; ch2[i] = inv & ch3[i] = null ==>
; begin
; ch2[i] := null;
; ch3[i] := inv_ack;
; c[i] := I;
; end;
; rule "7" /* client receives shared grant */
; ch2[i] = gr_sh ==>
; begin
; c[i] := S;
; ch2[i] := null;
; end;
; rule "8" /* client receives exclusive grant */
; ch2[i] = gr_ex ==>
; begin
; c[i] := E;
; ch2[i] := null;
; end;
; end; /* ruleset */
; rule "9" /* home grants share */
; hcm = req_sh & !heg & ch2[hcc] = null ==>
; begin
; hsl[hcc] := true;
; hcm := null;
; ch2[hcc] := gr_sh;
; end;
; rule "10" /* home grants exclusive */
; hcm = req_ex & (forall i: ID do hsl[i] = false end) & ch2[hcc] = null ==>
; begin
; hsl[hcc] := true;
; hcm := null;
; heg := true;
; ch2[hcc] := gr_ex;
; end;
; startstate
; begin
; for i: ID do
; ch1[i] := null;
; ch2[i] := null;
; ch3[i] := null;
; c[i] := I;
; hsl[i] := false;
; hil[i] := false;
; end;
; hcm := null;
; hcc := undefined;
; heg := false;
; end;
; Invariant
; forall i: ID do
; c[i] = E ->
; forall j: ID do
; j != i -> c[j] = I
; end
; end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 1: Starting Macros and Other stuff ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now let us begin. I use the records book all over the place as it allows us
;; to conveniently model states and vectors.
(include-book "misc/records" :dir :system)
;; I define the predicate memberp below since I hate the fact that ACL2's
;; member function is not a boolean, that is, does not always return T or
;; NIL. But this might not be important anyways. I am doing it more out of
;; habit than anything else.
(defun memberp (e x)
(cond ((endp x) NIL)
((equal e (first x)) T)
(t (memberp e (rest x)))))
;; I think of the input as a record of two things, namely the index of the
;; process taking the next step, and the action to be taken by the
;; process. That is, it says which process index is being processed and which
;; action is being taken on behalf of that process.
(defmacro pid (stimulus) `(g :pid ,stimulus))
(defmacro action (stimulus) `(g :action ,stimulus))
;; I have several local variables that I need to access. I hate having to write
;; g in my code, so I define some macros to hide g. This also allows me to sort
;; of "declare" variables.
(defmacro clients (st) `(g :clients ,st))
(defmacro ch1 (st) `(g :ch1 ,st))
(defmacro ch2 (st) `(g :ch2 ,st))
(defmacro ch3 (st) `(g :ch3 ,st))
(defmacro hcm (st) `(g :hcm ,st))
(defmacro hil (st) `(g :hil ,st))
(defmacro hsl (st) `(g :hsl ,st))
(defmacro heg (st) `(g :heg ,st))
(defmacro hcc (st) `(g :hcc ,st))
;; I created this macro update for specifically allowing me to write chains to
;; s. I want to be able to write such a chain and still be able to read it!!
(defun update-macro (upds result)
(declare (xargs :guard (keyword-value-listp upds)))
(if (endp upds) result
(update-macro (cddr upds)
(list 's (car upds) (cadr upds) result))))
(defmacro update (old &rest updates)
(declare (xargs :guard (keyword-value-listp updates)))
(update-macro updates old))
(defmacro >st (&rest upds) `(update st ,@upds))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 2: Modeling the German Protocol ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Here are some functions. These are used for updating all indices together
;; when that is appropriate.
(defun set-hil-hsl (keys hil hsl)
(if (endp keys) hil
(s (first keys)
(g (first keys) hsl)
(set-hil-hsl (rest keys) hil hsl))))
(defun all-false (keys hsl)
(if (endp keys) T
(and (not (g (first keys) hsl))
(all-false (rest keys) hsl))))
;; The constant constrained function (keys) below specifies the set of process
;; indices. I have left it as a constrained function so that I can conveniently
;; add hypothesis on keys as necessary (for example we might have to add that
;; keys does not contain nil, or that it is a set of natural numbers, or
;; whatever). But my goal is to prove the protocol imposing as few constraints
;; on keys as possible. To that end, whenever we need to add a constraint I
;; should add an explanatory note saying why the constraint is necessary.
(encapsulate
(((keys) => *))
(local (defun keys () nil)))
;; Here is the state transition function for the protocol. In the original
;; Murphy version (as per my understanding) there were rules which were akin to
;; guarded commands. That is, an action could be taken if the guard for the
;; action was satisfied. In ACL2 we model that as follows. I name each action
;; (the names being based on the comments in the Murphy code and somewhat
;; arbitrary). An input stimulus specifies what action is to be taken. That is,
;; it specifies the name of the action that the system should execute. If the
;; action's guards are satisfied then the action is taken. Otherwise the
;; execution of the action is identity.
(defun german-step (st stimulus)
(let* ((action (action stimulus))
(pid (pid stimulus))
(keys (keys))
(clients (clients st))
(ch1 (ch1 st))
(ch2 (ch2 st))
(ch3 (ch3 st))
(hcm (hcm st))
(hsl (hsl st))
(hil (hil st))
(heg (heg st))
(hcc (hcc st)))
(if (not (memberp pid keys))
;; The reader might be surprised by this condition. I allow the
;; external stimulus to ask *any* process to take a step. In particular
;; that means I allow "garbage" processes. But since we are not
;; modeling processes joining the protocol, I am assuming that this
;; means when I ask a garbage process to make a step then the result is
;; a no-op.
st
(cond (;; Rule 1:
(and (equal action :request-shared-access)
(equal (g pid clients) :idle)
(not ch1))
(>st :ch1
(s pid :req-shared-access ch1)))
(;; Rule 2:
(and (equal action :request-exclusive-access)
(equal (g pid clients) :idle)
(not ch1))
(>st :ch1 (s pid :req-exclusive-access ch1)))
(;; Rule 3:
(and (equal action :pick-new-request)
(not hcm)
(g pid ch1))
(>st :hcm (g pid ch1)
:ch1 (s pid NIL ch1)
:hcc pid
:hil (set-hil-hsl keys hil hsl)))
(;; Rule 4:
(and (equal action :home-sends-invalidate)
(g pid hil)
(not (g pid ch2))
(or (and (equal hcm :req-shared-access)
heg)
(equal hcm :req-exclusive-access)))
(>st :ch2 (s pid :invalidate ch2)
:hil (s pid NIL hil)))
(;; Rule 5:
(and (equal action :home-receives-invalidate)
hcm
(equal (g pid ch3) :invalidate-ack))
(>st :hsl (s pid NIL hsl)
:heg NIL
:ch3 (s pid NIL ch3)))
(;; Rule 6:
(and (equal action :sharer-invalidate-cache)
(equal (g pid ch2) :invalidate)
(not (g pid ch3)))
(>st :ch2 (s pid NIL ch2)
:ch3 (s pid :invalidate-ack ch3)
:clients (s pid :idle clients)))
(;; Rule 7:
(and (equal action :client-receives-shared)
(equal (g pid ch2) :grant-shared))
(>st :clients (s pid :shared clients)
:ch2 (s pid NIL ch2)))
(;; Rule 8:
(and (equal action :client-receives-exclusive)
(equal (g pid ch2) :grant-exclusive))
(>st :clients (s pid :exclusive clients)
:ch2 (s pid NIL ch2)))
(;; Rule 9:
(and (equal action :home-grants-shared)
(equal hcm :req-shared-access)
(not heg)
(not (g hcc ch2)))
(>st :hsl (s hcc T hsl)
:hcm NIL
:ch2 (s hcc :grant-shared ch2)))
(;; Rule 10
(and (equal action :home-grants-exclusive)
(equal hcm :req-exclusive-access)
(all-false keys hsl)
(not (g hcc ch2)))
(>st :hsl (s hcc T hsl)
:hcm nil
:heg T
:ch2 (s hcc :grant-exclusive ch2)))
(t st)))))
;; And finally the initial state (init). All state variables are nil other
;; than the clients which are all :idle. I dont know if this latter
;; restriction is important or not, but I tried to model it as per the Murphy
;; definition.
(defun initial-clients (keys)
(if (endp keys) nil
(let ((clients (initial-clients (rest keys))))
(s (first keys) :idle clients))))
(defthm initial-clients-idle
(implies (memberp i keys)
(equal (g i (initial-clients keys)) :idle)))
(defun init () (s :clients (initial-clients (keys)) nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3: The Coherence predicate and Its proof ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; OK so we have now modeled the german protocol (at least as best as I could
;; based on my interpretation of the Murphy code above). We will now prove
;; that the german protocol has coherence. To do so, I will define a predicate
;; called coherent and show that it is an invariant of the model.
;; How do we define coherent? One way might be to define recursive functions
;; and such. Since the recursive functions do not seem to provide too much
;; additional simplicity, I prefer to define it as a person doing hand-proof
;; would naturally do, namely via quantification. Note that the predicate is
;; exactly a formalization in ACL2 of the Murphy description of the invariant.
(defun-sk coherent-processes (keys clients)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(not (equal i j))
(equal (g i clients) :exclusive))
(equal (g j clients) :idle))))
(defun coherent (st) (coherent-processes (keys) (clients st)))
(local (defthm |initial state is coherent| (coherent (init))))
;; coherent as defined above is an invariant (or so I believe) but is of course
;; not an inductive invariant. For example consider rule 8. The transition
;; following rule 8 does preserve coherence, but assuming coherent for the
;; state from which the transition occurs is not sufficient. We need more.
;; Here is how I will do it. I will start with a set of predicates (initially
;; only the predicate coherent). For each predicate P, in order to prove (P
;; (german-step s i)), we probably might need to assume (and (P s) (Q s)).
;; Then I have added Q to my set of predicates. I continue this process until
;; no other predicate needs to be added to the set. My final inductive
;; invariant then is a conjunction of all the predicates I have created so far.
;; Note: When I define a predicate we immediately prove that the predicate
;; holds for the initial state init. This is a sanity check and also takes
;; care of the base cases of the inductive invariant proof on the fly.
;; For each predicate that I handle I will divide the proof of its invariance
;; in three parts. The first part is what I call "default cases". The
;; predicate holds in these cases merely since the state components which
;; govern the predicate are not modified by german-step. For example, one
;; default case for every predicate we consider is the case where the action is
;; not a legal action. Then according to the protocol above the system state
;; does not change. Thus the predicate holds after the step simply because it
;; used to hold before.
;; The second case involves some property of the predicate we are checking.
;; For example, consider the situation of coherence when the sharer invalidates
;; cache. It sets its the client to idle and hence coherence cannot change.
;; This depends on the property of coherence that setting something to :idle or
;; :shared does not change it. I will prove this property and then handle this
;; case.
;; The third case is when the predicate P holds after a step from s principally
;; because not only P but some other predicate Q holds in s. I will then
;; define Q (and show it holds for the initial state) and then prove this case.
;; This is the toughest part of all in an invariant proof and of course it is
;; possible that the predicates I come up with are not optimal and I realize
;; that later. I will try to minimize the roll-back as much as possible
;; principally because I do not want to spend too much time on this system and
;; I am doing this principally to document how such a proof is done in ACL2, so
;; that the particular predicates are possibly of less importance here.
;; All right back to work. Whenever I define something using quantification I
;; disable the definition and all associated lemmas that were introduced,
;; because I want to have control on how they are used in a proof process. For
;; example I dont want to see a "witness" until I am ready and understand what
;; the witness means in a context. So I deal with quantifiers principally via
;; :use hints.
(local (in-theory (disable coherent-processes coherent-processes-necc)))
;; default cases are pretty simple.
(local
(defthm |coherent default cases|
(implies (and (coherent st)
(not (equal (action stimulus) :sharer-invalidate-cache))
(not (equal (action stimulus) :client-receives-shared))
(not (equal (action stimulus) :client-receives-exclusive)))
(coherent (german-step st stimulus)))))
;; We are now left with 6, 7, and 8. Now 6 is easy. In 6, a client simply
;; sets itself to :idle. If the processes were coherent before then they would
;; still be coherent.
;; Note: This proof is a classic example of how (universal) quantification
;; proofs go. I assume coherence and want to show that it holds after setting
;; i to :idle. How do we do that? To understand this, let us understand
;; clearly how a (universal) quantification works. To prove a universal
;; quantification of a property I must prove that the property holds for an
;; arbitrary object called the witness of the property. Here the witness is a
;; pair of process indices, and what I must show is that if one is :exclusive
;; then the other is :idle. Thus, it is convenient to think of it this way:
;; ACL2 is presenting us with two process indices and daring us to show that
;; the above property holds after I set i to :idle. Now I of course know that
;; before setting this index coherence was holding (since I am proving an
;; implication). Thus *before setting idle* for any two processes p and q if
;; one were exclusive then the other was idle. Now I will basically do the
;; following. I will ask if the index being set, that is, i, is one of the two
;; indices that acl2 is going to present me with. If not then ACL2 is giving
;; us two other indices and thus if one is exclusive the other is shared by
;; virtue of coherence before setting. That leaves us with two cases. First,
;; ACL2 can claim that i is the index of an :exclusive process and dare us to
;; show that every other j is :idle. I can dispatch this case by saying that
;; since I have just set i to :idle, i cannot be :exclusive in the first place.
;; The second is that ACL2 can claim that there is some process which is
;; exclusive and say that show that i is :idle. This case also leaves nothing
;; to be done since I know that i is :idle.
;; The above analysis might appear to be too tedious and difficult to do every
;; time. But it is indeed pretty mechanical. I proved the theorem with the
;; hints below even before I really thought why I gave those hints. The rule
;; of the thumb is as follows. If you know that some property holds before
;; setting a process index to something then do a :cases hint on whether the
;; witness *after* the setting is the index that has been just set. If there
;; are more than one witnesses then do a case hint on each. For each of the
;; cases, just use the definition of the property as a hint and use the -necc
;; lemma for the previous state, setting the quantified variables (i and j in
;; this case) to be the corresponding witnesses for the variables after the
;; update.
(local
(defthm coherent-after-setting-idle
(implies (coherent-processes keys clients)
(coherent-processes keys (s i :idle clients)))
:hints
(("Goal"
:cases
((equal
i
(mv-nth 1
(coherent-processes-witness keys (s i :idle clients))))
(equal i (car (coherent-processes-witness keys (s i :idle clients))))))
("Subgoal 1"
:in-theory (enable coherent-processes)
:use
((:instance
coherent-processes-necc
(i (car (coherent-processes-witness keys (s i :idle clients))))
(j (mv-nth 1 (coherent-processes-witness keys (s i :idle clients)))))))
("Subgoal 2"
:in-theory (enable coherent-processes)
:use
((:instance
coherent-processes-necc
(i (car (coherent-processes-witness keys (s i :idle clients))))
(j (mv-nth 1 (coherent-processes-witness keys (s i :idle clients)))))))
("Subgoal 3"
:use
((:instance (:definition coherent-processes)
(clients (s i :idle clients)))
(:instance
coherent-processes-necc
(i (car (coherent-processes-witness keys (s i :idle clients))))
(j (mv-nth 1 (coherent-processes-witness keys
(s i :idle clients))))))))))
(local
(defthm |coherent after rule 6|
(implies (and (coherent st)
(equal (action stimulus) :sharer-invalidate-cache))
(coherent (german-step st stimulus)))))
;; So we are now left with rules 7 and 8. We need to look carefully at these
;; rules. If the action is :client-receives-shared then why is coherent
;; preserved? The reason is that in the state when a system can execute rule 7,
;; (that is, when the channel 2 has :grant-shared in it for some client), all
;; clients are either :idle or :shared (or at least I hope so). This fact can
;; be codified by the predicate ch2-client-invariant below.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk ch2-client-shared (ch2 keys clients)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(equal (g i ch2) :grant-shared))
(or (equal (g j clients) :shared)
(equal (g j clients) :idle))))))
(local
(defun ch2-client-shared-invariant (st)
(ch2-client-shared (ch2 st) (keys) (clients st))))
(local (defthm |init has ch2-shared| (ch2-client-shared-invariant (init))))
(local (in-theory (disable ch2-client-shared ch2-client-shared-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The following theorem saves us some :use hints since we would often be
;; checking if a client is :exclusive.
(local
(defthm ch2-client-shared-implies-not-exclusive
(implies (and (ch2-client-shared ch2 keys clients)
(memberp i keys)
(memberp j keys)
(equal (g i ch2) :grant-shared))
(equal (equal (g j clients) :exclusive) NIL))
:hints (("Goal"
:use ch2-client-shared-necc))))
(local
(defthm coherent-after-setting-shared
(implies (and (ch2-client-shared ch2 keys clients)
(memberp i keys)
(equal (g i ch2) :grant-shared))
(coherent-processes keys (s j :shared clients)))
:hints (("Goal"
:in-theory (enable coherent-processes)
:cases ((equal j
(car (coherent-processes-witness
keys (s j :shared clients))))))
("Subgoal 2"
:use ((:instance (:definition coherent-processes)
(clients (s j :shared clients))))))))
;; OK so now we can prove that execution of rule 7 gives us a coherent state.
(local
(defthm |coherent after rule 7|
(implies (and (ch2-client-shared-invariant st)
(coherent st)
(equal (action stimulus) :client-receives-shared))
(coherent (german-step st stimulus)))))
;; I define the similar predicate ch2-client-exclusive-invariant that lets us
;; show coherent for rule 8.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk ch2-client-exclusive (ch2 keys clients)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(equal (g i ch2) :grant-exclusive))
(equal (g j clients) :idle)))))
(local
(defun ch2-client-exclusive-invariant (st)
(ch2-client-exclusive (ch2 st) (keys) (clients st))))
(local
(defthm |init has ch2-exclusive| (ch2-client-exclusive-invariant (init))))
(local
(in-theory (disable ch2-client-exclusive ch2-client-exclusive-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm ch2-exclusive-means-idle
(implies (and (ch2-client-exclusive ch2 keys clients)
(memberp i keys)
(memberp j keys)
(equal (g i ch2) :grant-exclusive))
(equal (g j clients) :idle))
:hints (("Goal"
:use ch2-client-exclusive-necc))))
(local
(defthm ch2-exclusive-means-set-idle
(implies (and (ch2-client-exclusive ch2 keys clients)
(memberp i keys)
(memberp m keys)
(memberp n keys)
(equal (g i ch2) :grant-exclusive))
(equal (g m (s n v clients)) (if (equal m n) v :idle)))))
(local
(defthm |ch2-exclusive causes coherence|
(implies (and (ch2-client-exclusive ch2 keys clients)
(memberp i keys)
(equal (g i ch2) :grant-exclusive))
(coherent-processes keys (s j :exclusive clients)))
:hints (("Goal"
:in-theory (enable coherent-processes)
:cases
((equal
j
(car (coherent-processes-witness
keys (s j :exclusive clients)))))))))
;; Now of course rule 8 should just go through.
(local
(defthm |coherent after rule 8|
(implies (and (ch2-client-exclusive-invariant st)
(coherent st)
(equal (action stimulus) :client-receives-exclusive))
(coherent (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of Coherence ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Of course we have now done the coherence, but we now have two other
;; predicates that we need to prove as invariants. They are
;; ch2-client-shared-invariant and ch2-client-exclusive-invariant. I must now
;; prove that these persist too, and in the process add more predicates. I
;; will have a section for each predicate I prove (rather a subsection to
;; Section 3), and each proof will end with a comment "End Proof of ....".
;; This is principally so that I can efficiently search in emacs for the proofs
;; of the predicates I have done.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.1: Proof of ch2-client-shared-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The default cases as usual.
(local
(defthm |ch2 shared default cases|
(implies (and (ch2-client-shared-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(ch2-client-shared-invariant (german-step st stimulus)))))
;; Let us now first take care of sharer-invalidate-cache. This works because
;; if I set something to :idle then nothing changes in terms of what has
;; shared.
(local
(defthm ch2-shared-if-idle
(implies (and (ch2-client-shared ch2 keys clients)
(not (equal val :grant-shared)))
(ch2-client-shared (s i val ch2) keys (s j :idle clients)))
:hints
(("Goal"
:cases
((equal
i
(car (ch2-client-shared-witness
(s i val ch2) keys (s j :idle clients))))
(equal
j
(mv-nth 1 (ch2-client-shared-witness (s i val ch2) keys
(s j :idle clients))))))
("Subgoal 2"
:in-theory (enable ch2-client-shared))
("Subgoal 1"
:in-theory (enable ch2-client-shared))
("Subgoal 3"
:use
((:instance (:definition ch2-client-shared)
(clients (s j :idle clients))
(ch2 (s i val ch2)))
(:instance
ch2-client-shared-necc
(i (car (ch2-client-shared-witness (s i val ch2) keys
(s j :idle clients))))
(j (mv-nth 1 (ch2-client-shared-witness (s i val ch2)
keys
(s j :idle clients))))))))))
(local
(defthm |ch2-shared if sharer-invalidate|
(implies (and (ch2-client-shared-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(ch2-client-shared-invariant (german-step st stimulus)))))
;; Now let us take the other cases in turn. For the case
;; :home-sends-invalidate for example, we know that ch2-client-shared-invariant
;; still holds after the action if it held before. This is because if we
;; change ch2 to something other than :grant-shared the
;; ch2-client-shared-invariant does not change. Let us first prove this fact.
(local
(defthm ch2-client-shared-after-arbitrary
(implies (and (not (equal val :grant-shared))
(ch2-client-shared ch2 keys clients))
(ch2-client-shared (s pid val ch2) keys clients))
:hints (("Goal"
:cases
((equal
(car (ch2-client-shared-witness (s pid val ch2) keys clients))
pid)))
("Subgoal 2"
:use
((:instance (:definition ch2-client-shared)
(ch2 (s pid val ch2)))
(:instance
ch2-client-shared-necc
(i (car (ch2-client-shared-witness (s pid val ch2) keys
clients)))
(j (mv-nth 1 (ch2-client-shared-witness (s pid val ch2) keys
clients))))))
("Subgoal 1"
:use
((:instance (:definition ch2-client-shared)
(ch2 (s pid val ch2)))
(:instance
ch2-client-shared-necc
(i (car (ch2-client-shared-witness (s pid val ch2) keys
clients)))
(j (mv-nth 1 (ch2-client-shared-witness (s pid val ch2) keys
clients)))))))))
;; While we are at it, we might also prove that if a client is set to :shared
;; then the invariant remains.
(local
(defthm |ch2-client-shared after setting shared|
(implies (and (ch2-client-shared ch2 keys clients)
(equal (g i ch2) :grant-shared))
(ch2-client-shared ch2 keys (s j :shared clients)))
:hints (("Goal"
:cases
((equal
j
(mv-nth 1
(ch2-client-shared-witness
ch2 keys (s j :shared clients))))))
("Subgoal 2"
:use
((:instance
(:definition ch2-client-shared)
(clients (s j :shared clients)))
(:instance
ch2-client-shared-necc
(i (car (ch2-client-shared-witness
ch2 keys (s j :shared clients))))
(j (mv-nth
1 (ch2-client-shared-witness
ch2
keys (s j :shared clients)))))))
("Subgoal 1"
:use
((:instance
(:definition ch2-client-shared)
(clients (s j :shared clients)))
(:instance
ch2-client-shared-necc
(i (car (ch2-client-shared-witness
ch2 keys (s j :shared clients))))
(j (mv-nth
1 (ch2-client-shared-witness
ch2
keys (s j :shared clients))))))))))
;; OK this takes care of three of the 5 non-trivial cases of the
;; ch2-client-shared-invariant as shown below.
(local
(defthm |ch2 shared invariant after no grants-shared set|
(implies (and (ch2-client-shared-invariant st)
(memberp (action stimulus) '(:home-grants-exclusive
:client-receives-shared
:home-sends-invalidate)))
(ch2-client-shared-invariant (german-step st stimulus)))))
;; That leaves us with two cases, namely :home-grants-shared and
;; :client-receives-exclusive. Let us look at :home-grants-shared. Why is
;; this going to satisfy ch2-client-shared-invariant? The reason is that when
;; heg is nil every client has status shared or idle.
;; I add this fact as another predicate, since this is a new fact about the
;; system that is not covered by the predicates we have created so far. The
;; predicate is specified below.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk not-heg-clients-shared (heg keys clients)
(forall i
(implies (and (not heg)
(memberp i keys))
(or (equal (g i clients) :shared)
(equal (g i clients) :idle))))))
(local
(defun not-heg-clients-shared-invariant (st)
(not-heg-clients-shared (heg st) (keys) (clients st))))
(local
(defthm |init has not-heg-shared|
(not-heg-clients-shared-invariant (init))))
(local
(in-theory (disable not-heg-clients-shared not-heg-clients-shared-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; And clearly if this predicate holds then ch2-client-shared holds trivially.
(local
(defthm not-heg-clients-shared-implies-ch2-shared
(implies (and (not-heg-clients-shared heg keys clients)
(not heg))
(ch2-client-shared ch2 keys clients))
:hints (("Goal"
:use
((:instance (:definition ch2-client-shared))
(:instance
not-heg-clients-shared-necc
(i (mv-nth 1 (ch2-client-shared-witness ch2 keys clients)))))))))
(local
(defthm |ch2 shared invariant after home grants shared|
(implies (and (ch2-client-shared-invariant st)
(not-heg-clients-shared-invariant st)
(equal (action stimulus) :home-grants-shared))
(ch2-client-shared-invariant (german-step st stimulus)))))
;; The question of grant-exclusive is more interesting. What do we want in
;; this case? We want to say that in case of a :grant-exclusive all other
;; channels have nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk channel-nil-exclusive (ch2 keys)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(not (equal i j))
(equal (g i ch2) :grant-exclusive))
(equal (g j ch2) nil)))))
(local
(defun channel-nil-exclusive-invariant (st)
(channel-nil-exclusive (ch2 st) (keys))))
(local
(defthm |init has channel-nil-exclusive|
(channel-nil-exclusive-invariant (init))))
(local
(in-theory (disable channel-nil-exclusive
channel-nil-exclusive-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Why does channel-nil-invariant allow us to prove
;; ch2-client-shared-invariant? Well, the point is that if ch2-nil-invariant
;; holds then there is no channel that has value :grant-shared. Let us prove
;; this.
(local
(defthm channel-nil-for-exclusiv-implies-not-anything-else
(implies (and (channel-nil-exclusive ch2 keys)
(memberp i keys)
(equal (g i ch2) :grant-exclusive)
(memberp j keys))
(equal (g j ch2)
(if (equal i j) :grant-exclusive nil)))
:hints (("Goal"
:use channel-nil-exclusive-necc))))
(local
(defthm channel-nil-implies-ch2-client-shared
(implies (and (channel-nil-exclusive ch2 keys)
(memberp i keys)
(not (equal a :grant-shared))
(equal (g i ch2) :grant-exclusive))
(ch2-client-shared (s j a ch2)
keys
(s j b clients)))
:hints (("Goal"
:cases ((equal j (car (ch2-client-shared-witness
(s j a ch2)
keys
(s j b clients))))))
("Subgoal 1"
:in-theory (enable ch2-client-shared))
("Subgoal 2"
:in-theory (enable ch2-client-shared)))))
(local
(defthm |ch2-shared after client-receives-exclusive|
(implies (and (ch2-client-shared-invariant st)
(channel-nil-exclusive-invariant st)
(equal (action stimulus) :client-receives-exclusive))
(ch2-client-shared-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of ch2-client-shared-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.2: Proof of ch2-client-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |ch2 exclusive default cases|
(implies (and (ch2-client-exclusive-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:client-receives-shared
:client-receives-exclusive
:sharer-invalidate-cache
:home-grants-shared
:home-grants-exclusive))))
(ch2-client-exclusive-invariant (german-step st stimulus)))))
;; Now here is a property of ch2-client-exclusive. If it holds for a state
;; then I can set ch2 of any process to a value other than :grant-exclusive and
;; set any client to :idle and the predicate is still going to hold. This
;; takes care of sharer-invalidate-cache when I set ch2 to nil and the client
;; to :idle.
(local
(defthm ch2-exclusive-if-idle
(implies (and (ch2-client-exclusive ch2 keys clients)
(not (equal val :grant-exclusive)))
(ch2-client-exclusive (s i val ch2) keys (s j :idle clients)))
:hints
(("Goal"
:cases
((equal
i
(car (ch2-client-exclusive-witness
(s i val ch2) keys (s j :idle clients))))
(equal
j
(mv-nth 1 (ch2-client-exclusive-witness (s i val ch2) keys
(s j :idle clients))))))
("Subgoal 2"
:in-theory (enable ch2-client-exclusive))
("Subgoal 1"
:in-theory (enable ch2-client-exclusive))
("Subgoal 3"
:use
((:instance (:definition ch2-client-exclusive)
(clients (s j :idle clients))
(ch2 (s i val ch2)))
(:instance
ch2-client-exclusive-necc
(i (car (ch2-client-exclusive-witness (s i val ch2) keys
(s j :idle clients))))
(j (mv-nth 1 (ch2-client-exclusive-witness (s i val ch2)
keys
(s j :idle clients))))))))))
(local
(defthm |ch2-exclusive if sharer-invalidate|
(implies (and (ch2-client-exclusive-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(ch2-client-exclusive-invariant (german-step st stimulus)))))
;; Notice however, that the property above does not let us prove things for
;; (say) home-sends-invalidate. This is because in that condition the client
;; is not changed. So we will prove also the lemma that says that we are fine
;; if the client is not changed. This is in fact an easier property than the
;; one we proved before, but we need to prove it anyways. Maybe I could have
;; generalized the property above a little bit and saved myself this lemma.
;; But I dont bother since I am lazy.
(local
(defthm ch2-client-exclusive-after-arbitrary
(implies (and (not (equal val :grant-exclusive))
(ch2-client-exclusive ch2 keys clients))
(ch2-client-exclusive (s pid val ch2) keys clients))
:hints
(("Goal"
:cases
((equal
(car (ch2-client-exclusive-witness (s pid val ch2) keys clients))
pid)))
("Subgoal 2"
:use
((:instance (:definition ch2-client-exclusive)
(ch2 (s pid val ch2)))
(:instance
ch2-client-exclusive-necc
(i (car (ch2-client-exclusive-witness (s pid val ch2) keys clients)))
(j (mv-nth 1 (ch2-client-exclusive-witness
(s pid val ch2) keys clients))))))
("Subgoal 1"
:use
((:instance (:definition ch2-client-exclusive)
(ch2 (s pid val ch2)))
(:instance
ch2-client-shared-necc
(i (car (ch2-client-exclusive-witness (s pid val ch2) keys clients)))
(j (mv-nth 1 (ch2-client-exclusive-witness
(s pid val ch2) keys clients)))))))))
;; This now allows us to prove that ch2-client-exclusive-invariant holds under
;; the actions :home-grants-shared and :home-sends-invalidate.
(local
(defthm |ch2 exclusive for invalidate and shared|
(implies (and (ch2-client-exclusive-invariant st)
(memberp (action stimulus)
'(:home-grants-shared
:home-sends-invalidate)))
(ch2-client-exclusive-invariant (german-step st stimulus)))))
;; Now we are left with three cases, namely client-receives-shared,
;; client-receives-exclusive, and home-grants-exclusive. Why do these cases
;; work? For the first I will use the property that if there is a
;; :grant-exclusive in a channel then all others have nil. In other words I
;; would make use of the channel-nil-exclusive-invariant that I had already
;; defined.
;; Let us first do the case where client is getting shared. Now why does
;; ch2-client-exclusive-invariant hold in this case? Well, there are two cases.
;; Suppose that there was an index having :grant-exclusive in the channel.
;; Then I know that no other channel has :grant-shared (and thus the system
;; does not take a step) so we are done. Otherwise, there is no
;; :grant-exclusive, and thus after taking a step there is still no
;; grant-exclusive and hence we are done.
;; The analysis above suggests that we can define a predicate called
;; no-grant-exclusive to check if there is no grant-exclusive or not, and then
;; use that to prove the persistence of ch2-client-exclusive-invariant. Notice
;; that we are defining this predicate to simplify our reasoning, but this
;; predicate follows in our cases for channel-nil-exclusive. So this is not a
;; new predicate that goes in the definition of the inductive invariant.
;; Indeed, if I am willing to think harder and type more I can get rid of the
;; definition as well.
(local
(defun-sk no-grant-exclusive (keys ch2)
(forall i
(implies (memberp i keys)
(not (equal (g i ch2) :grant-exclusive))))))
(local (in-theory (disable no-grant-exclusive no-grant-exclusive-necc)))
;; Now we first prove that if there is no grant-exclusive then
;; ch2-client-exclusive-invariant holds.
(local
(defthm no-grant-exclusive-implies-ch2-exclusive
(implies (no-grant-exclusive keys ch2)
(ch2-client-exclusive ch2 keys clients))
:hints
(("Goal"
:in-theory (enable ch2-client-exclusive)
:use
((:instance
no-grant-exclusive-necc
(i (car (ch2-client-exclusive-witness ch2 keys clients)))))))))
;; Now we will show that if no-grant-exclusive does not hold that is, if there
;; is some process with :grant-exclusive and there is some other which has some
;; other value then ch2-client-exclusive-invariant does not hold.
(local
(defthm not-grant-exclusive-and-something-implies-not-invariant
(implies (and (not (no-grant-exclusive keys ch2))
(g i ch2)
(memberp i keys)
(not (equal (g i ch2) :grant-exclusive)))
(equal (channel-nil-exclusive ch2 keys) NIL))
:hints (("Goal"
:in-theory (enable no-grant-exclusive)
:use ((:instance channel-nil-exclusive-necc
(i (no-grant-exclusive-witness keys ch2))
(j i)))))))
;; Finally, no-grant-exclusive must mean that after setting a channel to NIL,
;; we still have that property.
(local
(defthm no-grant-after-setting-channel
(implies (no-grant-exclusive keys ch2)
(no-grant-exclusive keys (s i nil ch2)))
:hints
(("Goal"
:use
((:instance (:definition no-grant-exclusive)
(ch2 (s i nil ch2)))
(:instance
no-grant-exclusive-necc
(i (no-grant-exclusive-witness keys (s i nil ch2))))))
("Goal'"
:cases
((equal i (no-grant-exclusive-witness keys (s i nil ch2))))))))
;; Now of course I am done by simply splitting the two cases about whether
;; no-grants-exclusive holds or not.
(local
(defthm |ch2 exclusive for client sharing|
(implies (and (ch2-client-exclusive-invariant st)
(channel-nil-exclusive-invariant st)
(equal (action stimulus) :client-receives-shared))
(ch2-client-exclusive-invariant (german-step st stimulus)))
:hints (("Goal"
:cases ((no-grant-exclusive (keys) (ch2 st)))))))
;; Now we are down to the two cases, which are home-grants-exclusive and
;; client-receives-exclusive. I look at client-receives-exclusive first since
;; that is simpler. Now when client-receives-exclusive, it sets channel to
;; nil, and client to exclusive. We need to ensure that for all channel i if i
;; has the value :grant-exclusive then every client is :idle. But since we are
;; setting every channel to nil, there is no channel with :grant-exclusive, and
;; therefore the invariant is trivial.
(local
(defthm ch2-exclusive-after-ch2-nil
(implies (and (channel-nil-exclusive ch2 keys)
(memberp i keys)
(memberp j keys)
(equal (g i ch2) :grant-exclusive))
(equal (g j (s i nil ch2)) NIL))
:hints (("Goal"
:cases ((equal j i))))))
(local
(defthm ch2-exclusive-after-ch2-nil-2
(implies (and (channel-nil-exclusive ch2 keys)
(equal (g j ch2) :grant-exclusive)
(memberp j keys))
(ch2-client-exclusive (s j nil ch2) keys (s m val clients)))
:hints
(("Goal"
:cases
((equal
j
(car (ch2-client-exclusive-witness
(s i nil ch2) keys (s m val clients))))))
("Subgoal 2"
:in-theory (enable ch2-client-exclusive))
("Subgoal 1"
:in-theory (enable ch2-client-exclusive)))))
(local
(defthm |ch2 exclusive for client exclusive|
(implies (and (ch2-client-exclusive-invariant st)
(channel-nil-exclusive-invariant st)
(equal (action stimulus) :client-receives-exclusive))
(ch2-client-exclusive-invariant (german-step st stimulus)))))
;; The last case, namely home-grants-exclusive. To do this one, what we need
;; to decide how home can manage to send an :invalidate in channel 2. Of
;; course this means that all processes must have channel 2 NIL.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hsl-client (keys clients hsl)
(if (endp keys) T
(and (implies (not (equal (g (first keys) clients) :idle))
(equal (g (first keys) hsl) T))
(hsl-client (rest keys) clients hsl)))))
(local
(defun hsl-client-invariant (st) (hsl-client (keys) (clients st) (hsl st))))
(local
(defthm hsl-client-set
(implies (hsl-client keys clients hsl)
(hsl-client keys (s i :idle clients) hsl))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm hsl-client-initial-client
(hsl-client keys (initial-clients keys) hsl)))
(local
(defthm |init has hsl-client|
(hsl-client-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm hsl-ch2-and-all-false
(implies (and (hsl-client keys clients hsl)
(all-false keys hsl)
(memberp i keys))
(equal (g i clients) :idle))))
(local
(defthm hsl-client-implies-ch2-exclusive
(implies (and (hsl-client keys clients hsl)
(all-false keys hsl))
(ch2-client-exclusive (s i v ch2) keys clients))
:hints (("Goal"
:in-theory (enable ch2-client-exclusive)))))
(local
(defthm |ch2-exclusive for home-grants-exclusive|
(implies (and (hsl-client-invariant st)
(ch2-client-exclusive-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(ch2-client-exclusive-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of ch2-client-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right. One more gone. The next predicate is
;; not-heg-clients-shared-invariant.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.3: Proof of not-heg-clients-shared-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |not heg shared default cases|
(implies (and (not-heg-clients-shared-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-exclusive))))
(not-heg-clients-shared-invariant (german-step st stimulus)))))
;; Now comes the analysis. At home-receives-invalidate, the heg is set to nil.
;; So why is the invariant holding here? The reason is that we can claim that
;; if ch3 has invalidate-ack then all clients are either :idle or :shared.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk invalidate-ack-clients (clients ch3 keys)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(equal (g i ch3) :invalidate-ack))
(or (equal (g j clients) :idle)
(equal (g j clients) :shared))))))
(local
(defun invalidate-ack-clients-invariant (st)
(invalidate-ack-clients (clients st) (ch3 st) (keys))))
(local
(defthm |init has invariant-ack-ch3|
(invalidate-ack-clients-invariant (init))))
(local
(in-theory (disable invalidate-ack-clients invalidate-ack-clients-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now I can claim that if invalidate-ack holds then
;; not-heg-clients-shared-invariant holds.
(local
(defthm invalidate-ack-implies-not-heg
(implies (and (invalidate-ack-clients clients ch3 keys)
(memberp i keys)
(equal (g i ch3) :invalidate-ack))
(not-heg-clients-shared val keys clients))
:hints
(("Goal"
:use
((:instance (:definition not-heg-clients-shared)
(heg val))
(:instance
invalidate-ack-clients-necc
(j (not-heg-clients-shared-witness val keys clients))))))))
(local
(defthm |heg-shared after home-receives-invalidate|
(implies (and (not-heg-clients-shared-invariant st)
(invalidate-ack-clients-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(not-heg-clients-shared-invariant (german-step st stimulus)))))
;; The next case is when client receives shared. This works because client of
;; course can receive as much shared as it wants, and nothing will happen to
;; this predicate.
(local
(defthm not-heg-clients-shared-remains-with-shared
(implies (and (not-heg-clients-shared heg keys clients)
(or (equal val :shared)
(equal val :idle)))
(not-heg-clients-shared heg keys (s i val clients)))
:hints
(("Goal"
:use
((:instance (:definition not-heg-clients-shared)
(clients (s i val clients)))
(:instance
not-heg-clients-shared-necc
(i (not-heg-clients-shared-witness heg keys (s i val clients))))))
("Goal'"
:cases
((equal i
(not-heg-clients-shared-witness heg keys
(s i val clients))))))))
;; So this should give me the case of client-receives-shared.
(local
(defthm |heg-shared after client-receives-shared|
(implies (and (not-heg-clients-shared-invariant st)
(memberp (action stimulus) '(:sharer-invalidate-cache
:client-receives-shared)))
(not-heg-clients-shared-invariant (german-step st stimulus)))))
;; What happens when client-receives-exclusive? What I need here is that when
;; ch2 has grant-exclusive then heg is T
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk heg-exclusive (heg keys ch2)
(forall i
(implies (and (memberp i keys)
(equal (g i ch2) :grant-exclusive))
heg))))
(local
(defun heg-exclusive-invariant (st) (heg-exclusive (heg st) (keys) (ch2 st))))
(local
(defthm |init has heg-exclusive| (heg-exclusive-invariant (init))))
(local (in-theory (disable heg-exclusive heg-exclusive-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm heg-exclusive-and-grant-implies-not-heg
(implies (and (heg-exclusive heg keys ch2)
(memberp i keys)
(equal (g i ch2) :grant-exclusive))
(not-heg-clients-shared heg keys (s j val clients)))
:hints (("Goal"
:use ((:instance (:definition not-heg-clients-shared)
(clients (s j val clients)))
(:instance heg-exclusive-necc))))))
(local
(defthm |heg shared after client-receives-exclusive|
(implies (and (not-heg-clients-shared-invariant st)
(heg-exclusive-invariant st)
(equal (action stimulus) :client-receives-exclusive))
(not-heg-clients-shared-invariant (german-step st stimulus)))))
;; One more to go. This is when home-grants-exclusive. This is the most
;; trivial of the lot. This holds because when home-grants-exclusive it sets
;; heg to T.
(local
(defthm heg-implies-anything-fine
(implies heg
(not-heg-clients-shared heg keys clients))
:hints (("Goal"
:in-theory (enable not-heg-clients-shared)))))
(local
(defthm |heg shared after home-grants-exclusive|
(implies (and (not-heg-clients-shared-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(not-heg-clients-shared-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of ch2-client-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right so I am done with not-heg-clients-shared-invariant. Now I come to
;; channel-nil-exclusive-invariant. This says that if one of the channels has
;; grant-exclusive then all other channels must be nil. To an extent this is a
;; pretty strong statement and almost is the statement of coherence stated in
;; terms of channels. So doing this is going to take some effort.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.4: Proof of channel-nil-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |channel-nil-exclusive default cases|
(implies (and (channel-nil-exclusive-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(channel-nil-exclusive-invariant (german-step st stimulus)))))
;; The next cases to consider are those in which the channel is set to nil.
;; Obviously if a channel is set to nil then nothing can change.
(local
(defthm channel-set-to-nil-implies-channel-nil
(implies (channel-nil-exclusive ch2 keys)
(channel-nil-exclusive (s i nil ch2) keys))
:hints
(("Goal"
:cases
((equal i (car (channel-nil-exclusive-witness (s i nil ch2)
keys)))
(equal i (mv-nth 1 (channel-nil-exclusive-witness (s i nil ch2)
keys)))))
("Subgoal 2"
:in-theory (enable channel-nil-exclusive))
("Subgoal 1"
:in-theory (enable channel-nil-exclusive))
("Subgoal 3"
:use
((:instance
channel-nil-exclusive-necc
(i (car (channel-nil-exclusive-witness (s i nil ch2)
keys)))
(j (mv-nth 1 (channel-nil-exclusive-witness (s i nil ch2)
keys))))
(:instance (:definition channel-nil-exclusive)
(ch2 (s i nil ch2))))))))
(local
(defthm |channels-nil when ch2 set to nil|
(implies (and (channel-nil-exclusive-invariant st)
(memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(channel-nil-exclusive-invariant (german-step st stimulus)))))
;; Now comes the three interesting cases. First is when home-grants-exclusive.
;; I should then know that all channels are nil. This works because I know
;; that all keys are false in hsl. As a result, all channels must be nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hsl-ch2 (hsl keys ch2)
(if (endp keys) T
(and (implies (g (first keys) ch2)
(equal (g (first keys) hsl) T))
(hsl-ch2 hsl (rest keys) ch2)))))
(local
(defun hsl-ch2-invariant (st) (hsl-ch2 (hsl st) (keys) (ch2 st))))
(local
(defthm hsl-ch2-nil (hsl-ch2 nil keys nil)))
(local (defthm |init has hsl-ch2| (hsl-ch2-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm hsl-ch2-and-all-false-implies-nil
(implies (and (hsl-ch2 hsl keys ch2)
(memberp i keys)
(all-false keys hsl))
(equal (g i ch2) nil))))
(local
(defthm hsl-ch2-implies-channel-nil-exclusive
(implies (and (hsl-ch2 hsl keys ch2)
(all-false keys hsl))
(channel-nil-exclusive (s i :grant-exclusive ch2) keys))
:hints (("Goal"
:cases ((equal i (car (channel-nil-exclusive-witness
(s i :grant-exclusive ch2) keys)))))
("Subgoal 2"
:in-theory (enable channel-nil-exclusive))
("Subgoal 1"
:in-theory (enable channel-nil-exclusive)))))
(local
(defthm |channel-nil-exclusive grant-exclusive|
(implies (and (channel-nil-exclusive-invariant st)
(hsl-ch2-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(channel-nil-exclusive-invariant (german-step st stimulus)))))
;; What happens when home-grants-shared? We know (not heg). Thus we
;; automatically know that there is no :grants-exclusive. Hence we have
;; nothing to prove.
(local
(defthm heg-exclusive-and-not-heg-implies-no-exclusive
(implies (and (heg-exclusive heg keys ch2)
(not heg)
(not (equal val :grant-exclusive)))
(channel-nil-exclusive (s i val ch2) keys))
:hints (("Goal"
:cases ((equal i (car (channel-nil-exclusive-witness
(s i val ch2) keys)))))
("Subgoal 2"
:use ((:instance heg-exclusive-necc
(heg nil)
(i (car (channel-nil-exclusive-witness
(s i val ch2) keys)))))
:in-theory (enable channel-nil-exclusive))
("Subgoal 1"
:use ((:instance heg-exclusive-necc
(heg nil)
(i (car (channel-nil-exclusive-witness
(s i val ch2) keys)))))
:in-theory (enable channel-nil-exclusive)))))
(local
(defthm |channel-nil-exclusive grant-shared|
(implies (and (channel-nil-exclusive-invariant st)
(heg-exclusive-invariant st)
(equal (action stimulus) :home-grants-shared))
(channel-nil-exclusive-invariant (german-step st stimulus)))))
;; A more interesting case, and in fact the last case for this predicate, will
;; come up now. This is when home-sends-invalidate. Now I should again know
;; that if (g i hil) holds and heg is T then for all j!=i (g j ch2) = NIL.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk hil-heg (keys hil ch2 heg)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(g i hil)
(not (equal i j))
heg)
(equal (g j ch2) nil)))))
;; BTW I believe this predicate can be generalized and made prettier. But I am
;; trying to write it in the most brain-dead way possible, since I am too tired
;; to think too much about it....:->
(local
(defun hil-heg-invariant (st) (hil-heg (keys) (hil st) (ch2 st) (heg st))))
(local (defthm |init has hil-heg| (hil-heg-invariant (init))))
(local (in-theory (disable hil-heg hil-heg-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm hil-heg-set-reduction
(implies (and (hil-heg keys hil ch2 heg)
heg
(g i hil)
(memberp i keys)
(memberp j keys))
(equal (g j (s i val ch2))
(if (equal i j) val nil)))
:hints (("Goal"
:use hil-heg-necc))))
(local
(defthm hil-heg-channels-nil
(implies (and (hil-heg keys hil ch2 heg)
heg
(g i hil)
(not (equal val :grant-exclusive))
(memberp i keys))
(channel-nil-exclusive (s i val ch2) keys))
:hints (("Goal"
:cases ((equal i (car (channel-nil-exclusive-witness
(s i val ch2) keys)))))
("Subgoal 1"
:in-theory (enable channel-nil-exclusive))
("Subgoal 2"
:in-theory (enable channel-nil-exclusive)))))
;; The above takes care of invalidation when heg is T. But what do we do when
;; heg is nil? In that case we know that there is no grant-exclusive. Thus
;; there is nothing to do.
(local
(defthm |channels-nil for invalidate|
(implies (and (channel-nil-exclusive-invariant st)
(hil-heg-invariant st)
(heg-exclusive-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(channel-nil-exclusive-invariant (german-step st stimulus)))
:hints (("Goal"
:cases ((heg st))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of channel-nil-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Done with this predicate. Now we move on to hsl-client-invariant. This
;; says that for all keys if the client is not idle then hsl has the value T.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.5: Proof of hsl-client-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hsl-client default cases|
(implies (and (hsl-client-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hsl-client-invariant (german-step st stimulus)))))
;; Of course the way hsl-client has been defined it does not matter if given
;; some hsl-client we set hsl to T.
(local
(defthm hsl-set-reduction
(implies (hsl-client keys clients hsl)
(hsl-client keys clients (s i t hsl)))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
;; This takes care of cases where hsl is set to T
(local
(defthm |hsl-clients if hsl set to T|
(implies (and (hsl-client-invariant st)
(memberp (action stimulus)
'(:home-grants-shared
:home-grants-exclusive)))
(hsl-client-invariant (german-step st stimulus)))))
;; Now we come to thhe non-trivial cases. These are the cases in which either
;; hsl is being set to NIL or client is being set. In either case we require
;; more predicates to show that hsl-client-invariant holds.
;; So why does the predicate hold after home-receives-invalidate? It holds
;; because if I set client to :idle I can do anything.
(local
(defthm hsl-idle-reduction
(implies (hsl-client keys clients hsl)
(hsl-client keys (s i :idle clients) hsl))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-clients if clients idle|
(implies (and (hsl-client-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(hsl-client-invariant (german-step st stimulus)))))
;; The second about when home sets hsl to nil. Here I must carry around as
;; invariant that the corresponding client was idle. But first let us prove
;; that if some client is idle then I can set any value to hsl.
(local
(defthm hsl-idle-reduction-2
(implies (and (hsl-client keys clients hsl)
(equal (g i clients) :idle))
(hsl-client keys clients (s i v hsl)))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
;; Now I must posit a predicate that stipulates that the client is idle. Why
;; do we know that? I must know that if some process has :invalidate-ack in
;; channel 3, then that client is idle. Notice that we had previously
;; specified that *all* clients are :shared or :idle in that case.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk invalidate-ack-idle (clients keys ch3)
(forall i
(implies (and (memberp i keys)
(equal (g i ch3) :invalidate-ack))
(equal (g i clients) :idle)))))
(local
(defun invalidate-ack-idle-invariant (st)
(invalidate-ack-idle (clients st) (keys) (ch3 st))))
(local
(defthm |init has invalidate-ack-idle|
(invalidate-ack-idle-invariant (init))))
(local
(in-theory (disable invalidate-ack-idle invalidate-ack-idle-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now why do I know that the client was idle? This is specified by
;; invalidate-ack. One of the things that invalidate-ack-clients was telling
;; us is that the client which has sent invalidate-ack is :idle.
(local
(defthm invalidate-ack-hsl
(implies (and (invalidate-ack-idle clients keys ch3)
(memberp i keys)
(equal (g i ch3) :invalidate-ack)
(hsl-client keys clients hsl))
(hsl-client keys clients (s i v hsl)))
:hints (("Goal"
:use ((:instance invalidate-ack-idle-necc))))))
(local
(defthm |hsl-clients if hsl set|
(implies (and (invalidate-ack-idle-invariant st)
(hsl-client-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hsl-client-invariant (german-step st stimulus)))))
;; All right now down to two more cases for this predicate. These are cases
;; where the client receives a value either shared or exclusive. Now in these
;; cases I know that hsl-ch2 covers me.
(local
(defthm hsl-ch2-set-reduction
(implies (and (hsl-ch2 hsl keys ch2)
(memberp i keys)
(g i ch2))
(equal (g i hsl) t))))
;; I should look into this proof carefully later if time. The proof works but
;; it does double induction, and I dont like double induction. So there might
;; be something I can do about it. Need to look at subgoal *1/2.
(local
(defthm hsl-ch2-set
(implies (and (equal (g i hsl) t)
(memberp i keys)
(hsl-client keys clients hsl))
(hsl-client keys (s i v clients) hsl))
:hints (("Subgoal *1/5"
:cases ((equal i (car keys)))))))
(local
(defthm hsl-hsl-client-packaged
(implies (and (hsl-ch2 hsl keys ch2)
(hsl-client keys clients hsl)
(memberp i keys)
(g i ch2))
(hsl-client keys (s i v clients) hsl))))
(local
(defthm |hsl-client for client-receives|
(implies (and (hsl-client-invariant st)
(hsl-ch2-invariant st)
(memberp (action stimulus) '(:client-receives-shared
:client-receives-exclusive)))
(hsl-client-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hsl-client-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Done with this one. Now we move on to invalidate-ack-clients-invariant. To
;; be honest this is is a little dicey as a predicate. I probably should have
;; broken it up into two. But I give it an old college try anyways.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.6: Proof of invalidate-ack-clients-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |ch3-client default cases|
(implies (and (invalidate-ack-clients-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive))))
(invalidate-ack-clients-invariant (german-step st stimulus)))))
;; All right now back to work. What home does on receiving an invalidate-ack
;; is remove it. This activity does not change the predicate. So the first
;; case is pretty trivial.
(local
(defthm invalidate-ack-does-not-change-if-set
(implies (and (invalidate-ack-clients clients ch3 keys)
(not (equal v :invalidate-ack)))
(invalidate-ack-clients clients (s i v ch3) keys))
:hints
(("Goal"
:cases
((equal i
(car (invalidate-ack-clients-witness clients (s i v ch3) keys)))))
("Subgoal 1"
:in-theory (enable invalidate-ack-clients))
("Subgoal 2"
:use
((:instance (:definition invalidate-ack-clients)
(ch3 (s i v ch3)))
(:instance
invalidate-ack-clients-necc
(i (car (invalidate-ack-clients-witness clients (s i v ch3) keys)))
(j (mv-nth 1 (invalidate-ack-clients-witness clients (s i v ch3)
keys)))))))))
;; This lets us prove the case of home-receives-invalidate
(local
(defthm |invalidate-ack for home-receives-invalidate|
(implies (and (invalidate-ack-clients-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(invalidate-ack-clients-invariant (german-step st stimulus)))))
;; All right, now how about sharer-invalidate-cache? Well, in this case we are
;; simply setting a client to idle and hence nothing can change in terms of
;; clients. But the problem is that we are introducing an :invalidate-ack. We
;; will do this one case at a time. If there were an invalidate-ack around
;; then we would have no problem. But it is now possible that there is no
;; invalidate-ack-around, and thus someone might be exclusive. But then if I
;; do send an invalidate it should be to the exclusive guy, right? So let us
;; say that as a predicate.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun invalidate-clients (ch2 clients keys)
(if (endp keys) T
(and (implies (equal (g (first keys) ch2) :invalidate)
(or (equal (g (first keys) clients) :shared)
(equal (g (first keys) clients) :exclusive)))
(invalidate-clients ch2 clients (rest keys))))))
(local
(defun invalidate-clients-invariant (st)
(invalidate-clients (ch2 st) (clients st) (keys))))
(local
(defthm invalidate-clients-for-nil
(invalidate-clients nil clients keys)))
(local
(defthm |init has invalidate-clients|
(invalidate-clients-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now let us concentrate on what this predicate together with
;; invalidate-ack-clients tells us. It tells us that the guy to which an
;; invalidate is sent must be shared or exclusive. Let us prove this.
(local
(defthm invalidate-clients-implies-shared-or-exclusive
(implies (and (invalidate-clients ch2 clients keys)
(memberp i keys)
(equal (g i ch2) :invalidate))
(or (equal (g i clients) :shared)
(equal (g i clients) :exclusive)))
:rule-classes :forward-chaining))
(local
(defthm invalidate-and-exclusive-implies-invalidate-exclusive
(implies (and (coherent-processes keys clients)
(invalidate-clients ch2 clients keys)
(memberp i keys)
(memberp j keys)
(equal (g i clients) :exclusive)
(equal (g j ch2) :invalidate))
(equal i j))
:rule-classes :forward-chaining
:hints (("Goal"
:use ((:instance coherent-processes-necc))))))
;; Now if the guy to which invalidate is sent was exclusive then coherent will
;; kick in and show that all other processes are shared or idle. Thus when we
;; set this to anything like idle or shared I should be in great shape.
(local
(defthm invalidate-clients-and-coherent-implies-invalidate-ack
(implies (and (coherent-processes keys clients)
(equal (g i clients) :exclusive)
(memberp i keys)
(or (equal v :shared)
(equal v :idle)))
(invalidate-ack-clients (s i v clients)
(s i u ch3)
keys))
:hints
(("Goal"
:cases ((equal i (mv-nth 1 (invalidate-ack-clients-witness (s i v clients)
(s i u ch3)
keys)))))
("Subgoal 1"
:in-theory (enable invalidate-ack-clients))
("Subgoal 2"
:use
((:instance (:definition invalidate-ack-clients)
(clients (s i v clients))
(ch3 (s i u ch3)))
(:instance coherent-processes-necc
(j (mv-nth 1 (invalidate-ack-clients-witness (s i v clients)
(s i u ch3)
keys)))))))))
;; I want to now say that if invalidate-clients holds and coherent-processes
;; holds then invalidate-ack-clients holds irrespective of which client is
;; being set. This is just packaging up the previous theorems.
(local
(defthm invalidate-clients-and-coherent-for-exclusive
(implies (and (invalidate-clients ch2 clients keys)
(coherent-processes keys clients)
(memberp i keys)
(memberp j keys)
(equal (g j ch2) :invalidate)
(equal (g i clients) :exclusive)
(or (equal v :shared)
(equal v :idle)))
(invalidate-ack-clients (s j v clients)
(s j u ch3)
keys))))
;; All right, now if it is exclusive then we are done. But it can be shared.
;; If it is shared then what do I know? Well, I should know that there is no
;; exclusive at all, from coherent-processes. But that is not sufficient.
;; Because I need to say that if there is nothing that is exclusive then all
;; are shared or idle. And that is not a predicate I have defined yet. So I
;; define the predicate valid-status below to take care of that.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun valid-status (clients keys)
(if (endp keys)
T
(and (or (equal (g (first keys) clients) :idle)
(equal (g (first keys) clients) :shared)
(equal (g (first keys) clients) :exclusive))
(valid-status clients (rest keys))))))
(local
(defun valid-status-invariant (st) (valid-status (clients st) (keys))))
(local
(defthm setting-valid-does-not-change-status
(implies (and (valid-status clients keys)
(or (equal v :idle)
(equal v :shared)
(equal v :exclusive)))
(valid-status (s i v clients) keys))
:hints (("Subgoal *1/3"
:cases ((equal i (car keys)))))))
(local
(defthm valid-status-in-initial (valid-status (initial-clients keys) keys)))
(local
(defthm |init has valid status| (valid-status-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now I should know that if valid-status holds and no process has exclusive
;; then all are idle or shared. To simplify the reasoning let us define a
;; function saying that no process is exclusive. Of course this is not an
;; invariant.
(local
(defun no-exclusive (keys clients)
(if (endp keys)
T
(and (not (equal (g (first keys) clients) :exclusive))
(no-exclusive (rest keys) clients)))))
;; So no-exclusive means that all are idle or shared.
(local
(defthm no-exclusive-implies-all-idle-shared
(implies (and (no-exclusive keys clients)
(valid-status clients keys)
(memberp i keys))
(or (equal (g i clients) :shared)
(equal (g i clients) :idle)))
:rule-classes :forward-chaining))
;; And if no-exclusive does not hold then we have some process that is
;; exclusive. Notice now how we need to (and can) define a recursive function
;; that produces the corresponding witness. It is this witness that comes for
;; free if we do quantification. But I have been using quantification and
;; induction in any way whatsoever depending on my mood while quantifying over
;; only one index. So I need to "create" the witness in this case.
(local
(defun exclusive-witness (keys clients)
(if (endp keys) nil
(if (equal (g (first keys) clients) :exclusive)
(first keys)
(exclusive-witness (rest keys) clients)))))
;; This theorem shows one way of using the witness function. This is
;; essentially how we use existential quantifiers. I am saying that if
;; no-exclusive does not hold then there is an index which is exclusive, in
;; particular, exclusive-witness. This is a standard trick of simulating
;; existential quantification using recursive functions. Later we will
;; (hopefully) see a way of using recursive functions to simulate universal
;; quantification. The method is the same, namely define a witness for the
;; property (for a universal quantification we look for a negation of the
;; property). Then we say that if the witness has the property then every
;; object does. The theorem is proved using induction, and then serves to be
;; used exactly as we used the witnesses for defun-sk.
(local
(defthm exclusive-implies-exclusive-witness
(implies (not (no-exclusive keys clients))
(and (memberp (exclusive-witness keys clients) keys)
(equal (g (exclusive-witness keys clients) clients)
:exclusive)))
:rule-classes :forward-chaining))
;; Now we show that if no-exclusive holds then invalidate-ack-clients holds.
(local
(defthm no-exclusive-implies-invalidate-ack-clients
(implies (and (no-exclusive keys clients)
(valid-status clients keys)
(or (equal v :shared)
(equal v :idle)))
(invalidate-ack-clients (s i v clients)
(s i u ch3)
keys))
:hints
(("Goal"
:cases
((equal i (mv-nth 1 (invalidate-ack-clients-witness (s i v clients)
(s i u ch3)
keys)))))
("Subgoal 1"
:in-theory (enable invalidate-ack-clients))
("Subgoal 2"
:in-theory (enable invalidate-ack-clients)))))
;; And this solves it.
(local
(defthm invalidate-coherent-valid-status-invalidate-ack
(implies (and (invalidate-clients ch2 clients keys)
(equal (g j ch2) :invalidate)
(memberp j keys)
(coherent-processes keys clients)
(valid-status clients keys)
(or (equal v :idle)
(equal v :shared)))
(invalidate-ack-clients (s j v clients) (s j u ch3) keys))
:hints (("Goal"
:cases ((no-exclusive keys clients))))))
;; All right, finally done:
(local
(defthm |invalidate-ack-clients for sharer-invalidate-cache|
(implies (and (invalidate-ack-clients-invariant st)
(invalidate-clients-invariant st)
(coherent st)
(valid-status-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(invalidate-ack-clients-invariant (german-step st stimulus)))))
;; Now why does invalidate-ack-clients hold when we have a grant-shared? The
;; reason is ch2-shared-invariant which says that everybody is shared or idle
;; anyways.
(local
(defthm ch2-shared-implies-invalidate-ack-clients
(implies (and (ch2-client-shared ch2 keys clients)
(equal (g i ch2) :grant-shared)
(memberp i keys)
(or (equal v :shared)
(equal v :idle)))
(invalidate-ack-clients (s i v clients) ch3 keys))
:hints
(("Goal"
:cases
((equal i (mv-nth 1 (invalidate-ack-clients-witness (s i v clients)
ch3
keys)))))
("Subgoal 1"
:in-theory (enable invalidate-ack-clients))
("Subgoal 2"
:in-theory (enable invalidate-ack-clients)
:use
((:instance ch2-client-shared-necc
(j (mv-nth 1 (invalidate-ack-clients-witness (s i v clients)
ch3
keys)))))))))
(local
(defthm |invalidate-ack-clients for grant-shared|
(implies (and (invalidate-ack-clients-invariant st)
(ch2-client-shared-invariant st)
(equal (action stimulus) :client-receives-shared))
(invalidate-ack-clients-invariant (german-step st stimulus)))))
;; Now the last case, which is client-receives-exclusive. I dont like to think
;; about this one right now --- I am tired after doing the rest of the cases.
;; But I am pretty sure that if there is an invalidate-ack somewhere then there
;; cannot be a :grant-exclusive. So for now I posit that as a predicate and go
;; on.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk invalidate-exclusive (ch3 ch2 keys)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(equal (g i ch3) :invalidate-ack))
(not (equal (g j ch2) :grant-exclusive))))))
(local
(defun invalidate-exclusive-invariant (st)
(invalidate-exclusive (ch3 st) (ch2 st) (keys))))
(local
(defthm |init has invalidate-exclusive|
(invalidate-exclusive-invariant (init))))
(local
(in-theory (disable invalidate-exclusive invalidate-exclusive-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; And this predicate is going to throw away the remaining case. Admittedly
;; this is not something I recommend. People should analyze things carefully
;; before positing a predicate like the above. But, well, what the heck, I
;; will do it, since I am pretty confident this is an invariant.
(local
(defthm invalidate-exclusive-implies-grant-exclusive
(implies (and (invalidate-exclusive ch3 ch2 keys)
(memberp i keys)
(equal (g i ch2) :grant-exclusive))
(invalidate-ack-clients clients ch3 keys))
:hints
(("Goal"
:in-theory (enable invalidate-ack-clients)
:use
((:instance
invalidate-exclusive-necc
(j i)
(i (car (invalidate-ack-clients-witness clients ch3 keys)))))))))
(local
(defthm |invalidate-ack-clients after client-receives-exclusive|
(implies (and (invalidate-ack-clients-invariant st)
(invalidate-exclusive-invariant st)
(equal (action stimulus) :client-receives-exclusive))
(invalidate-ack-clients-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of invalidate-ack-clients-invariant
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; OK now I am just making a slight change in the order since it is night and I
;; want to do an easy predicate without thinking too much. So I will now prove
;; valid-status-invariant first. I will get back to the normal order of other
;; predicates tomorrow.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.7: Proof of valid-status-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |valid-status default cases|
(implies (and (valid-status-invariant st)
(not (memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive))))
(valid-status-invariant (german-step st stimulus)))))
;; I ought to have proven some lemma about non-default cases here, but I have
;; already proved that lemma while proving that valid-status holds for the
;; initial states. Thus the rest will go thru as well. I might as well have
;; done the whole thing in one theorem. But I am sticking to the habit of
;; splitting proofs into default and non-default cases.
(local
(defthm |valid-status non-default cases|
(implies (and (valid-status-invariant st)
(memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(valid-status-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of valid-status-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; That was really fast!! I will try one more for tonight then. Let us move on
;; now to heg-exclusive-invariant. This says that if there is a
;; :grant-exclusive in a channel then heg holds. This one is particularly
;; easy.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.8: Proof of heg-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |heg-exclusive defaults cases|
(implies (and (heg-exclusive-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(heg-exclusive-invariant (german-step st stimulus)))))
;; What happens for home-grants-exclusive? This is simple. I know that it sets
;; heg to T. Thus nothing has to be done any more.
(local
(defthm heg-exclusive-if-heg-T
(implies heg
(heg-exclusive heg keys ch2))
:hints (("Goal"
:in-theory (enable heg-exclusive)))))
(local
(defthm |heg exclusive home-grants-exclusive|
(implies (and (heg-exclusive-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(heg-exclusive-invariant (german-step st stimulus)))))
;; More interesting is the bunch of cases where ch2 is set. The good thing is
;; that when ch2 is set to anything other than grant-exclusive we can claim
;; that the predicate simply persists.
(local
(defthm heg-exclusive-if-channel-set
(implies (and (heg-exclusive heg keys ch2)
(not (equal v :grant-exclusive)))
(heg-exclusive heg keys (s i v ch2)))
:hints
(("Goal"
:cases ((equal i (heg-exclusive-witness heg keys (s i v ch2)))))
("Subgoal 1"
:in-theory (enable heg-exclusive))
("Subgoal 2"
:use
((:instance (:definition heg-exclusive)
(ch2 (s i v ch2)))
(:instance
heg-exclusive-necc
(i (heg-exclusive-witness heg keys (s i v ch2)))))))))
;; And this will take care of most of the cases for us.
(local
(defthm |heg-exclusive for ch2 set|
(implies (and (heg-exclusive-invariant st)
(memberp (action stimulus)
'(:home-sends-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive)))
(heg-exclusive-invariant (german-step st stimulus)))))
;; The only thorny case is when home actually gets an invalidate. Then it sets
;; heg to nil. Why is this ok? This is ok since we have just by serendipity
;; added the predicate invalidate-exclusive which says that there is no
;; invalidate-ack and grant-exclusive together. Let us prove that it does it.
(local
(defthm invalidate-exclusive-implies-not-heg-is-fine
(implies (and (invalidate-exclusive ch3 ch2 keys)
(memberp i keys)
(equal (g i ch3) :invalidate-ack))
(heg-exclusive heg keys ch2))
:hints (("Goal"
:in-theory (enable heg-exclusive)
:use ((:instance invalidate-exclusive-necc
(j (heg-exclusive-witness heg keys ch2))))))))
(local
(defthm |heg-exclusive for home-receives-invalidate|
(implies (and (heg-exclusive-invariant st)
(invalidate-exclusive-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(heg-exclusive-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of heg-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right, so heg-exclusive out of the way. We get to hsl-ch2.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.9: Proof of hsl-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hsl-ch2 default cases|
(implies (and (hsl-ch2-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hsl-ch2-invariant (german-step st stimulus)))))
;; Here is what one has to do when recursive functions are defined (rather than
;; quantified predicates). I am proving that hsl-ch2 holds after setting i to
;; T in clients and v in ch2. If we defined this predicate using
;; quantification we would have used the cases hint and applied the
;; instantiation of the necc lemma on the first with the witness of the second.
;; But here we prove it using induction. The cases hint we gave can be easily
;; understood by looking at the failed proof. But I dont go into that here.
(local
(defthm hsl-ch2-after-setting-hsl
(implies (hsl-ch2 hsl keys ch2)
(hsl-ch2 (s i T hsl) keys (s i v ch2)))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-ch2 after home sets|
(implies (and (hsl-ch2-invariant st)
(memberp (action stimulus)
'(:home-grants-shared
:home-grants-exclusive)))
(hsl-ch2-invariant (german-step st stimulus)))))
(local
(defthm hsl-ch2-after-ch2-nil
(implies (hsl-ch2 hsl keys ch2)
(hsl-ch2 hsl keys (s i nil ch2)))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-ch2 after client sets|
(implies (and (hsl-ch2-invariant st)
(memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(hsl-ch2-invariant (german-step st stimulus)))))
;; All right now down to the two non-trivial cases for this predicate, namely
;; that home-sends-invalidate and home-receives-invalidate. These two cases
;; involve the following consideration. In home-sends-invalidate I add a
;; :invalidate to ch2. So it must be that hsl is not nil. Why is this true?
;; The reason is that the index is in hil. So we must know that if something
;; is in hil, then it is in hsl. This is true because the hil is set from hsl,
;; and hil is reset *before* hsl.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hil-hsl (hil hsl keys)
(if (endp keys) T
(and (implies (g (first keys) hil)
(equal (g (first keys) hsl) t))
(hil-hsl hil hsl (rest keys))))))
(local
(defun hil-hsl-invariant (st) (hil-hsl (hil st) (hsl st) (keys))))
(local
(defthm hil-hsl-for-nil (hil-hsl nil nil keys)))
(local (defthm |init has hil-hsl| (hil-hsl-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; How does this work? I first know that if hil-hsl holds then every index in
;; hil must have hsl t. When home-sends-invalidate, the hil is t and hence hsl
;; is t. Since hsl is T anyways I dont have to think about what is added to
;; ch2.
(local
(defthm hil-hsl-and-hil-implies-hsl
(implies (and (hil-hsl hil hsl keys)
(g i hil)
(memberp i keys))
(equal (g i hsl) t))))
(local
(defthm hsl-hil-ch2
(implies (and (hil-hsl hil hsl keys)
(hsl-ch2 hsl keys ch2)
(memberp i keys)
(g i hil))
(hsl-ch2 hsl keys (s i v ch2)))
:hints (("Subgoal *1/6"
:cases ((equal i (car keys)))))))
;; Now I can deal with home-sends-invalidate
(local
(defthm |hsl-ch2 after home-sends-invalidate|
(implies (and (hsl-ch2-invariant st)
(hil-hsl-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hsl-ch2-invariant (german-step st stimulus)))))
;; Now I need to deal with home receives invalidate. What this amounts to is
;; the following. If home receives an invalidate-ack in ch3, that means that
;; the ch2 of that process is nil. This lets us prove this.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun invalidate-ack-ch2 (ch2 ch3 keys)
(if (endp keys) T
(and (implies (equal (g (first keys) ch3) :invalidate-ack)
(not (g (first keys) ch2)))
(invalidate-ack-ch2 ch2 ch3 (rest keys))))))
(local
(defun invalidate-ack-ch2-invariant (st)
(invalidate-ack-ch2 (ch2 st) (ch3 st) (keys))))
(local
(defthm invalidate-ack-ch2-nil (invalidate-ack-ch2 nil nil keys)))
(local
(defthm |init has invalidate-ack-ch2|
(invalidate-ack-ch2-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Notice how I am proving these theorems by induction now. I believe
;; induction and quantification really require the same thought and insight,
;; but ACL2 needs a little more support for quantifiers.
(local
(defthm invalidate-ack-ch2-implies-can-set-hsl
(implies (and (invalidate-ack-ch2 ch2 ch3 keys)
(hsl-ch2 hsl keys ch2)
(equal (g i ch3) :invalidate-ack)
(memberp i keys))
(hsl-ch2 (s i v hsl) keys ch2))
:hints (("Subgoal *1/6"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-ch2 after home receives invalidate|
(implies (and (hsl-ch2-invariant st)
(invalidate-ack-ch2-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hsl-ch2-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hsl-ch2-invariant
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now done with hsl-ch2-invariant. On to hil-heg-invariant. This says that
;; if heg holds and somebody is in the invalidate list then every other channel
;; must have nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.10: Proof of hil-heg-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hil-heg default cases|
(implies (and (hil-heg-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hil-heg-invariant (german-step st stimulus)))))
;; Now the first thing we should know is that if heg is set to nil then there
;; is nothing to prove.
(local
(defthm heg-nil-to-hil-heg
(implies (not heg)
(hil-heg keys hil ch2 heg))
:hints (("Goal"
:in-theory (enable hil-heg)))))
;; That takes care of some of the cases.
(local
(defthm |hil-heg for receive invalidate|
(implies (and (hil-heg-invariant st)
(memberp (action stimulus) '(:home-receives-invalidate
:home-grants-shared)))
(hil-heg-invariant (german-step st stimulus)))))
;; The next thing which covers a lot of cases is the statement that if I set
;; ch2 of any process to nil then hil-heg cannot be violated.
(local
(defthm hil-heg-ch2-nil
(implies (hil-heg keys hil ch2 heg)
(hil-heg keys hil (s i nil ch2) heg))
:hints
(("Goal"
:cases
((equal i (mv-nth 1 (hil-heg-witness keys hil (s i nil ch2) heg)))))
("Subgoal 1"
:in-theory (enable hil-heg))
("Subgoal 2"
:use
((:instance (:definition hil-heg)
(ch2 (s i nil ch2)))
(:instance
hil-heg-necc
(i (car (hil-heg-witness keys hil (s i nil ch2) heg)))
(j (mv-nth 1 (hil-heg-witness keys hil (s i nil ch2) heg)))))))))
;; This will let us prove many of the cases, in particular all that involve
;; client.
(local
(defthm |hil-heg for clients|
(implies (and (hil-heg-invariant st)
(memberp (action stimulus) '(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(hil-heg-invariant (german-step st stimulus)))))
;; Now the more non-trivial cases which involve home picking a request, home
;; sending an invalidate, and home granting an exclusive. Let us look at
;; home-sends-invalidate. Suppose heg is true and no index other than one with
;; hil has ch2. Now home sets the hil of index i to be nil. Why is the
;; invariant ok then? It is ok since we should know at this point that no other
;; index had hil T. But that has not been posited as a predicate yet, so I do
;; so.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk unique-hil (hil heg keys)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(g i hil)
(not (equal i j))
heg)
(not (g j hil))))))
(local
(defun unique-hil-invariant (st) (unique-hil (hil st) (heg st) (keys))))
(local
(defthm |init has unique-hil|
(unique-hil-invariant (init))))
(local
(in-theory (disable unique-hil unique-hil-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now I know that under heg if there is an index in hil then it is a unique
;; index. So I should be able to set this index to anything and set the
;; corresponding channel to anything without violating the hil-heg condition.
;; Now let us come back to hil-heg. We now want to set hil to nil under heg,
;; and know that we do not have any other index with a dangling hil.
(local
(defthm unique-hil-implies-can-set-hil
(implies (and (unique-hil hil heg keys)
(hil-heg keys hil ch2 heg)
heg
(memberp i keys)
(g i hil))
(hil-heg keys (s i v hil) (s i u ch2) heg))
:hints
(("Goal"
:cases
((equal
i
(car (hil-heg-witness keys (s i v hil) (s i u ch2) heg)))))
("Subgoal 2"
:in-theory (enable hil-heg)
:use
((:instance
unique-hil-necc
(j (car (hil-heg-witness keys (s i v hil) (s i u ch2) heg))))))
("Subgoal 1"
:use
((:instance (:definition hil-heg)
(hil (s i v hil))
(ch2 (s i u ch2)))
(:instance
hil-heg-necc
(i (car (hil-heg-witness keys (s i v hil) (s i u ch2) heg)))
(j (mv-nth 1 (hil-heg-witness keys (s i v hil) (s i u ch2) heg))))
(:instance
unique-hil-necc
(i (car (hil-heg-witness keys (s i v hil) (s i u ch2) heg)))
(j (mv-nth 1 (hil-heg-witness keys (s i v hil) (s i u ch2) heg)))))))))
;; All right, now we can prove the hil-heg invariance for
;; home-sends-invalidate.
(local
(defthm |hil-heg when home sends invalidate|
(implies (and (hil-heg-invariant st)
(unique-hil-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hil-heg-invariant (german-step st stimulus)))
:hints (("Goal"
:cases ((heg st))))))
;; What happens when home-grants-exclusive? Here home is setting heg to T so
;; it better damn well know that there is no non-nil value in hil. Now home
;; knows there is no non-nil hil since there is no non-nil hsl and we have
;; hil-hsl as an invariant.
(local
(defthm hil-hsl-and-all-false-to-not-hil
(implies (and (hil-hsl hil hsl keys)
(all-false keys hsl)
(memberp i keys))
(equal (g i hil) nil))))
(local
(defthm hil-hsl-implies-hil-heg
(implies (and (hil-hsl hil hsl keys)
(all-false keys hsl)
(memberp i keys))
(hil-heg keys hil ch2 heg))
:hints (("Goal"
:in-theory (enable hil-heg)))))
(local
(defthm |hil-heg home grants exclusive|
(implies (and (hil-hsl-invariant st)
(hil-heg-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(hil-heg-invariant (german-step st stimulus)))))
;; What happens for home picking a request? We want to say that if someone is
;; in hsl, and if heg is true then that someone must be the only one.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk hsl-heg (hsl heg keys)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(not (equal i j))
heg
(g i hsl))
(not (g j hsl))))))
(local
(defun hsl-heg-invariant (st) (hsl-heg (hsl st) (heg st) (keys))))
(local
(defthm |init has hsl-heg-invariant|
(hsl-heg-invariant (init))))
(local (in-theory (disable hsl-heg hsl-heg-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm hsl-ch2-set-hsl-reduction
(implies (memberp i keys)
(equal (g i (set-hil-hsl keys hil hsl))
(g i hsl)))
:hints (("Subgoal *1/3"
:cases ((equal i (car keys)))))))
(local
(defthm hsl-heg-and-set-hsl-to-hil-heg
(implies (and (hsl-heg hsl heg keys)
(hsl-ch2 hsl keys ch2)
(hil-heg keys hil ch2 heg)
heg)
(hil-heg keys (set-hil-hsl keys hil hsl) ch2 heg))
:hints
(("Goal"
:use
((:instance (:definition hil-heg)
(hil (set-hil-hsl keys hil hsl)))
(:instance
hsl-heg-necc
(i (car (hil-heg-witness keys (set-hil-hsl keys hil hsl)
ch2 heg)))
(j (mv-nth 1 (hil-heg-witness keys (set-hil-hsl keys hil hsl)
ch2 heg))))
(:instance
hil-heg-necc
(i (car (hil-heg-witness keys
(set-hil-hsl keys hil hsl)
ch2 heg)))
(j (mv-nth 1 (hil-heg-witness keys
(set-hil-hsl keys hil hsl)
ch2 heg)))))))))
(local
(defthm |hil-heg after home-picks-request|
(implies (and (hil-heg-invariant st)
(hsl-ch2-invariant st)
(hsl-heg-invariant st)
(equal (action stimulus) :pick-new-request))
(hil-heg-invariant (german-step st stimulus)))
:hints (("Goal"
:cases ((heg st))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hil-heg-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right, so we are done with hil-heg. This took me surprisingly longer
;; than I thought it would require. Partly this is because I had never thought
;; of pick-new-request as anything worth consideration. But well, nothing is
;; trivial in a protocol after all.
;; Now on to invalidate-ack-idle-invariant. This is actually one of the more
;; trivial ones. Let us try it. Best to start with a simple predicate in the
;; morning.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.11: Proof of invalidate-ack-idle ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |invalidate-ack-idle default cases|
(implies (and (invalidate-ack-idle-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive))))
(invalidate-ack-idle-invariant (german-step st stimulus)))))
;; All right now if home makes changes ch3 nothing can happen to this
;; predicate.
(local
(defthm invalidate-ack-idle-if-other-than-invalidate
(implies (and (invalidate-ack-idle clients keys ch3)
(not (equal v :invalidate-ack)))
(invalidate-ack-idle clients keys (s i v ch3)))
:hints
(("Goal"
:cases ((equal i (invalidate-ack-idle-witness clients keys (s i v ch3)))))
("Subgoal 2"
:use
((:instance (:definition invalidate-ack-idle)
(ch3 (s i v ch3)))
(:instance
invalidate-ack-idle-necc
(i (invalidate-ack-idle-witness clients keys (s i v ch3))))))
("Subgoal 1"
:use
((:instance (:definition invalidate-ack-idle)
(ch3 (s i v ch3)))
(:instance
invalidate-ack-idle-necc
(i (invalidate-ack-idle-witness clients keys (s i v ch3)))))))))
(local
(defthm |home-receives invalidate correctly|
(implies (and (invalidate-ack-idle-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(invalidate-ack-idle-invariant (german-step st stimulus)))))
;; Now what happens when an invalidate-ack is introduced? This is rather
;; trivial since it happens only simultaneously with setting the client to
;; idle. So let us prove this case.
(local
(defthm invalidate-ack-idle-set-idle
(implies (invalidate-ack-idle clients keys ch3)
(invalidate-ack-idle (s i :idle clients) keys
(s i :invalidate-ack ch3)))
:hints
(("Goal"
:cases
((equal i (invalidate-ack-idle-witness (s i :idle clients)
keys
(s i :invalidate-ack ch3)))))
("Subgoal 2"
:use
((:instance (:definition invalidate-ack-idle)
(clients (s i :idle clients))
(ch3 (s i :invalidate-ack ch3)))
(:instance
invalidate-ack-idle-necc
(i (invalidate-ack-idle-witness (s i :idle clients)
keys
(s i :invalidate-ack ch3))))))
("Subgoal 1"
:in-theory (enable invalidate-ack-idle)))))
(local
(defthm |invalidate-ack-idle after sharer invalidates|
(implies (and (invalidate-ack-idle-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(invalidate-ack-idle-invariant (german-step st stimulus)))))
;; Now what happens for grant shared and exclusive? We now set something to
;; shared or exclusive so this is relevant. This is saved for us by
;; invalidate-ack-ch2.
(local
(defthm invalidate-ack-ch2-does-it
(implies (and (invalidate-ack-ch2 ch2 ch3 keys)
(g i ch2)
(memberp i keys))
(equal (equal (g i ch3) :invalidate-ack) nil))))
(local
(defthm not-invalidate-ack-implies-set-anything
(implies (and (not (equal (g i ch3) :invalidate-ack))
(invalidate-ack-idle clients keys ch3))
(invalidate-ack-idle (s i v clients) keys ch3))
:hints
(("Goal"
:cases ((equal i (invalidate-ack-idle-witness (s i v clients) keys ch3))))
("Subgoal 1"
:in-theory (enable invalidate-ack-idle))
("Subgoal 2"
:use
((:instance (:definition invalidate-ack-idle)
(clients (s i v clients)))
(:instance
invalidate-ack-idle-necc
(i (invalidate-ack-idle-witness (s i v clients) keys ch3))))))))
;; And putting the above two lemmas together here is the final one.
(local
(defthm invalidate-ack-ch2-reduction
(implies (and (invalidate-ack-ch2 ch2 ch3 keys)
(g i ch2)
(memberp i keys)
(invalidate-ack-idle clients keys ch3))
(invalidate-ack-idle (s i v clients) keys ch3))))
(local
(defthm |invalidate-ack-idle for clients|
(implies (and (invalidate-ack-idle-invariant st)
(invalidate-ack-ch2-invariant st)
(memberp (action stimulus) '(:client-receives-shared
:client-receives-exclusive)))
(invalidate-ack-idle-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of invalidate-ack-idle-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Ha ha ha. Done with one more. On to invalidate-ack-exclusive. Thi states
;; that if one channel has invalidate-ack then no channel has grant-exclusive.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.12: Proof of invalidate-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |invalidate-exclusive default cases|
(implies (and (invalidate-exclusive-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(invalidate-exclusive-invariant (german-step st stimulus)))))
;; Now of course as long as we do not set ch2 to grant-exclusive, I can set ch2
;; to any value and it should not matter.
(local
(defthm invalidate-exclusive-for-not-grant-exclusive
(implies (and (invalidate-exclusive ch3 ch2 keys)
(not (equal v :grant-exclusive)))
(invalidate-exclusive ch3 (s i v ch2) keys))
:hints
(("Goal"
:cases ((equal i (mv-nth 1 (invalidate-exclusive-witness ch3 (s i v ch2)
keys)))))
("Subgoal 1"
:use
((:instance (:definition invalidate-exclusive)
(ch2 (s i v ch2)))))
("Subgoal 2"
:use
((:instance (:definition invalidate-exclusive)
(ch2 (s i v ch2)))
(:instance
invalidate-exclusive-necc
(i (car (invalidate-exclusive-witness ch3 (s i v ch2) keys)))
(j (mv-nth 1 (invalidate-exclusive-witness ch3 (s i v ch2) keys)))))))))
;; And this takes care of a number of cases, in particular all cases other than
;; home-receives-invalidate grant-exclusive and invalidate-cache. At least so
;; I believe. Let us see if I am right.
(local
(defthm |invalidate-exclusive for not ch2 exclusive|
(implies (and (invalidate-exclusive-invariant st)
(memberp (action stimulus)
'(:home-sends-invalidate
:client-receives-shared
:client-receives-exclusive
:home-grants-shared)))
(invalidate-exclusive-invariant (german-step st stimulus)))))
;; Now why does it work when home receives invalidate? This is also trivial. I
;; can set ch3 to anything other than :invalidate-ack and not violate the
;; invariant. This is what home is doing....
(local
(defthm invalidate-exclusive-after-not-exclusive
(implies (and (invalidate-exclusive ch3 ch2 keys)
(not (equal v :invalidate-ack)))
(invalidate-exclusive (s i v ch3) ch2 keys))
:hints
(("Goal"
:cases
((equal i (car (invalidate-exclusive-witness (s i v ch3) ch2 keys)))))
("Subgoal 1"
:use
((:instance (:definition invalidate-exclusive)
(ch3 (s i v ch3)))))
("Subgoal 2"
:use
((:instance (:definition invalidate-exclusive)
(ch3 (s i v ch3)))
(:instance
invalidate-exclusive-necc
(i (car (invalidate-exclusive-witness (s i v ch3) ch2 keys)))
(j (mv-nth 1 (invalidate-exclusive-witness (s i v ch3) ch2 keys)))))))))
(local
(defthm |invalidate-exclusive after home receives invalidate|
(implies (and (invalidate-exclusive-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(invalidate-exclusive-invariant (german-step st stimulus)))))
;; What happens when sharer invalidates the cache? I have to claim that no
;; channel now has grant exclusive. Why is that? Because I know that if
;; somebody does have it, then all channels have to be nil. But all channels
;; are not nil since at least one has :invalidate.
(local
(defthm channel-nil-exclusive-implies-invalidate-exclusive
(implies (and (channel-nil-exclusive ch2 keys)
(memberp i keys)
(not (equal u :grant-exclusive))
(g i ch2))
(invalidate-exclusive (s i v ch3) (s i u ch2) keys))
:hints
(("Goal"
:cases
((equal i (car (invalidate-exclusive-witness (s i v ch3)
(s i u ch2)
keys)))))
("Subgoal 2"
:cases ((equal i (mv-nth 1 (invalidate-exclusive-witness (s i v ch3)
(s i u ch2)
keys)))))
("Subgoal 2.1"
:in-theory (enable invalidate-exclusive))
("Subgoal 2.2"
:in-theory (enable invalidate-exclusive)
:use
((:instance channel-nil-exclusive-necc
(j (car (invalidate-exclusive-witness (s i v ch3)
(s i u ch2)
keys))))))
("Subgoal 1"
:cases
((equal i (mv-nth 1 (invalidate-exclusive-witness (s i v ch3)
(s i u ch2)
keys)))))
("Subgoal 1.1"
:in-theory (enable invalidate-exclusive))
("Subgoal 1.2"
:in-theory (enable invalidate-exclusive)
:use
((:instance
channel-nil-exclusive-necc
(i (car (invalidate-exclusive-witness (s i v ch3)
(s i u ch2)
keys)))
(j (mv-nth 1 (invalidate-exclusive-witness (s i v ch3)
(s i u ch2)
keys)))))))))
(local
(defthm |invalidate-exclusive for sharer invalidate cache|
(implies (and (invalidate-exclusive-invariant st)
(channel-nil-exclusive-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(invalidate-exclusive-invariant (german-step st stimulus)))))
;; Now let us consider the last case which is when somebody is granted
;; exclusive. Why is it ok do do so and know that there was accidentally no
;; invalidate-ack around in channel 3? The reason is that the sharer list is
;; empty. This means that I must have another predicate, which says that if
;; somebody has something in ch3 then hsl has it recorded.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hsl-ch3 (hsl ch3 keys)
(if (endp keys) T
(and (implies (g (first keys) ch3)
(equal (g (first keys) hsl) t))
(hsl-ch3 hsl ch3 (rest keys))))))
(local
(defun hsl-ch3-invariant (st) (hsl-ch3 (hsl st) (ch3 st) (keys))))
(local
(defthm hsl-ch3-for-nil (hsl-ch3 nil nil keys)))
(local
(defthm |init has hsl-ch3-invariant|
(hsl-ch3-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; This argument is just going to go on and it is a simple argument. It says
;; that whenever I have all-false then I am ok. I probably have to have more
;; predicates like that all working with all-false.
(local
(defthm hsl-ch3-all-false-to-not-ch3
(implies (and (hsl-ch3 hsl ch3 keys)
(all-false keys hsl)
(memberp i keys))
(equal (g i ch3) nil))))
(local
(defthm hsl-ch3-all-false-implies-invalidate-exclusive
(implies (and (hsl-ch3 hsl ch3 keys)
(all-false keys hsl))
(invalidate-exclusive ch3 ch2 keys))
:hints (("Goal"
:in-theory (enable invalidate-exclusive)))))
;; So finally we get invalidate-exclusive.
(local
(defthm |invalidate-exclusive for granting exclusive|
(implies (and (hsl-ch3-invariant st)
(invalidate-exclusive-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(invalidate-exclusive-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of invalidate-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right now on to hil-hsl.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.13: Proof of hil-hsl-invariant
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hil-hsl default cases|
(implies (and (hil-hsl-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:home-receives-invalidate
:home-grants-shared
:home-grants-exclusive))))
(hil-hsl-invariant (german-step st stimulus)))))
;; Now consider the situation when set-hil-hsl happens. For this to go thru, I
;; need the fact that everything in hil is a boolean. This is because I just
;; said that the index in hil is not nil, but required that the index in hsl is
;; t. The reason why I chose this is because home checks if (g i hil) but not
;; if (equal (g i hil) T) on certain occasions. Anyhow the predicate is not
;; difficult to define and I do not want to belabor the point.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hsl-boolean (hsl keys)
(if (endp keys) T
(and (booleanp (g (first keys) hsl))
(hsl-boolean hsl (rest keys))))))
(local
(defun hsl-boolean-invariant (st) (hsl-boolean (hsl st) (keys))))
(local
(defthm hsl-boolean-for-nil (hsl-boolean nil keys)))
(local
(defthm |init has hsl-boolean| (hsl-boolean-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; And now some obvious theorems to get the proof to go thru for
;; pick-new-request.
(local
(defthm hil-hsl-memberp
(implies (and (memberp i keys)
(hsl-boolean hsl keys)
(equal v (g i hsl))
(hil-hsl hil hsl keys))
(hil-hsl (s i v hil) hsl keys))
:hints (("Subgoal *1/6"
:cases ((equal i (car keys)))))))
(local
(defthm hil-hsl-not-memberp
(implies (and (not (memberp i keys))
(hil-hsl hil hsl keys))
(hil-hsl (s i v hil) hsl keys))))
(local
(defthm hil-hsl-set-hil-hsl
(implies (and (hil-hsl hil hsl keys)
(hsl-boolean hsl keys))
(hil-hsl (set-hil-hsl keys hil hsl) hsl keys))
:hints (("Subgoal *1/4"
:cases ((memberp (car keys) (cdr keys)))))))
;; Now I can do the pick new request.
(local
(defthm |hil-hsl after picking request|
(implies (and (hil-hsl-invariant st)
(hsl-boolean-invariant st)
(equal (action stimulus) :pick-new-request))
(hil-hsl-invariant (german-step st stimulus)))))
;; Let us do home-sends-invalidate now. This involves showing that if hil is
;; set to nil then hil-hsl does not change.
(local
(defthm hil-hsl-after-hil-nil
(implies (hil-hsl hil hsl keys)
(hil-hsl (s i nil hil) hsl keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-hsl after invalidating|
(implies (and (hil-hsl-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hil-hsl-invariant (german-step st stimulus)))))
;; How about when home receives an invalidate? Here I must know that the index
;; we are talking about is not in hil in the first place and therefore it does
;; not matter that we set hsl to nil. For this we need a new predicate that
;; says that if something has invalidate-ack then its hil is nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hil-invalidate (hil ch3 keys)
(if (endp keys) T
(and (implies (equal (g (first keys) ch3) :invalidate-ack)
(not (g (first keys) hil)))
(hil-invalidate hil ch3 (rest keys))))))
(local
(defun hil-invalidate-invariant (st)
(hil-invalidate (hil st) (ch3 st) (keys))))
(local
(defthm hil-invalidate-for-nil (hil-invalidate nil nil keys)))
(local
(defthm |init has hil invalidate| (hil-invalidate-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now why does it work out for home receiving an invalidate? The reason is
;; rather odd. I know that ch3 is not nil. Thus hsl must be T and hence it
;; does not matter what I set hil to.
(local
(defthm hil-hsl-after-setting-hil
(implies (and (hil-hsl hil hsl keys)
(hil-invalidate hil ch3 keys)
hcm
(equal (g i ch3) :invalidate-ack))
(hil-hsl hil (s i v hsl) keys))
:hints (("Goal"
:do-not '(eliminate-destructors generalize fertilize))
("Subgoal *1/5"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-hsl after home-receives-invalidate|
(implies (and (hil-hsl-invariant st)
(hil-invalidate-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hil-hsl-invariant (german-step st stimulus)))))
;; And finally to the last cases of hil-hsl. These are when hsl is set to T.
;; All I care about is that if I set hsl to T then nothing changes.
(local
(defthm hil-hsl-after-setting-hsl
(implies (hil-hsl hil hsl keys)
(hil-hsl hil (s i T hsl) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-hsl after granting|
(implies (and (hil-hsl-invariant st)
(memberp (action stimulus)
'(:home-grants-shared
:home-grants-exclusive)))
(hil-hsl-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hil-hsl-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right. Now we are done with hil-hsl. Let us move on to
;; invalidate-ack-ch2. This says that when we have an invalidate-ack in a ch3
;; then ch2 is nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.14: Proof of invalidate-ack-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |invalidate-ack-ch2 default cases|
(implies (and (invalidate-ack-ch2-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(invalidate-ack-ch2-invariant (german-step st stimulus)))))
;; Of course if we set ch2 to nil then we have this trivially, unless of course
;; we also set ch3. This will take care of most cases.
(local
(defthm invalidate-ack-ch2-when-ch2-nil
(implies (invalidate-ack-ch2 ch2 ch3 keys)
(invalidate-ack-ch2 (s i nil ch2) ch3 keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm invalidate-ack-ch2-when-ch2-nil-and-ch3-anything
(implies (invalidate-ack-ch2 ch2 ch3 keys)
(invalidate-ack-ch2 (s i nil ch2) (s i v ch3) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |invalidate-ack-ch2 after ch2 nil|
(implies (and (invalidate-ack-ch2-invariant st)
(memberp (action stimulus)
'(:client-receives-shared
:sharer-invalidate-cache
:client-receives-exclusive)))
(invalidate-ack-ch2-invariant (german-step st stimulus)))))
;; Now what happens with the remaining cases? When home-receives-invalidate it
;; is fine since we are setting ch3 to nil.
(local
(defthm invalidate-ack-after-ch3-set
(implies (and (invalidate-ack-ch2 ch2 ch3 keys)
(not (equal v :invalidate-ack)))
(invalidate-ack-ch2 ch2 (s i v ch3) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |invalidate-ack after receiving invalidate|
(implies (and (invalidate-ack-ch2-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(invalidate-ack-ch2-invariant (german-step st stimulus)))))
;; The remaining cases now are home-grants-shared and home-grants-exclusive.
;; Why does this predicate hold after home-grants-shared? The reason is as
;; follows. In this situation I know that hcm is req-shared and (not heg) is
;; true. In this condition no invalidate-ack is there since no invalidate is
;; sent out. I posit that as a new predicate.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk hcm-invalidate-ack (hcm heg ch3 keys)
(forall i
(implies (and (memberp i keys)
(equal (g i ch3) :invalidate-ack))
(or (equal hcm :req-exclusive-access)
(and (equal hcm :req-shared-access)
heg))))))
(local
(defun hcm-invalidate-ack-invariant (st)
(hcm-invalidate-ack (hcm st) (heg st) (ch3 st) (keys))))
(local
(defthm |init has hcm-invalidate-ack|
(hcm-invalidate-ack-invariant (init))))
(local
(in-theory (disable hcm-invalidate-ack hcm-invalidate-ack-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Here we see the use of a witness function to do universal quantification. I
;; define a witness for the negation of the property I care about and then
;; prove that if the witness has the property then everything has the property.
;; When I do this sort of reasoning I feel like I should have defined the
;; predicate using defun-sk directly, but for waht it is worth this is useful
;; for demonstration.
(local
(defun invalidate-ack-ch2-witness (ch2 ch3 keys)
(if (endp keys) nil
(if (and (equal (g (first keys) ch3) :invalidate-ack)
(g (first keys) ch2))
(first keys)
(invalidate-ack-ch2-witness ch2 ch3 (rest keys))))))
(local
(defthm invalidate-ack-from-witness
(implies (or (not (memberp (invalidate-ack-ch2-witness ch2 ch3 keys) keys))
(not (equal (g (invalidate-ack-ch2-witness ch2 ch3 keys) ch3)
:invalidate-ack))
(not (g (invalidate-ack-ch2-witness ch2 ch3 keys) ch2)))
(invalidate-ack-ch2 ch2 ch3 keys))))
(local
(defthm hcm-invalidate-invalidate-ack
(implies (and (hcm-invalidate-ack hcm heg ch3 keys)
(not heg)
(equal hcm :req-shared-access))
(invalidate-ack-ch2 ch2 ch3 keys))
:hints
(("Goal"
:use ((:instance hcm-invalidate-ack-necc
(i (invalidate-ack-ch2-witness ch2 ch3 keys))))))))
(local
(defthm |invalidate-ack-ch2 when home-grants-shared|
(implies (and (invalidate-ack-ch2-invariant st)
(hcm-invalidate-ack-invariant st)
(equal (action stimulus) :home-grants-shared))
(invalidate-ack-ch2-invariant (german-step st stimulus)))))
;; Let us now look at home-grants-exclusive. Why is this predicate ok? I know
;; that if home grants exclusive then all hsl entries are nil. But if all of
;; them are nil then hsl-ch3 tells me that all ch3 are nil. If all ch3 are
;; nil, then of course the predicate holds trivially.
(local
(defthm hsl-ch3-and-all-false-implies-ok
(implies (and (hsl-ch3 hsl ch3 keys)
(all-false keys hsl))
(invalidate-ack-ch2 (s i v ch2) ch3 keys))))
(local
(defthm |invalidate-ack after granting invalidate|
(implies (and (hsl-ch3-invariant st)
(invalidate-ack-ch2-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(invalidate-ack-ch2-invariant (german-step st stimulus)))))
;; And what happens after home-sends-invalidate? This is taken care of by
;; saying that if someone is in hil then it does not contain
;; invalidate-ack. This, together with the guard that the current process
;; is in hil says that the process does not have invalidate-ack in ch3. This
;; means we can set anything to ch2 and get away with it.
(local
(defthm hil-invalidate-invalidate-ack-ch2
(implies (and (hil-invalidate hil ch3 keys)
(memberp i keys)
(g i hil)
(invalidate-ack-ch2 ch2 ch3 keys))
(invalidate-ack-ch2 (s i v ch2) ch3 keys))
:hints (("Subgoal *1/6"
:cases ((equal i (car keys)))))))
(local
(defthm |invalidate-ack-ch2 after home-sends-invalidate|
(implies (and (invalidate-ack-ch2-invariant st)
(hil-invalidate-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(invalidate-ack-ch2-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of invalidate-ack-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right done with one more. Now let us think about what unique-hil. This
;; predicate says that if heg is true then there is at most one index with hil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.15: Proof of unique-hil-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |unique-hil default cases|
(implies (and (unique-hil-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:home-receives-invalidate
:home-grants-exclusive))))
(unique-hil-invariant (german-step st stimulus)))))
;; I will start with home-sends-invalidate. Why is unique-hil an invariant in
;; this case? If a state is unique-nil then setting a particular index to nil
;; does not change the situation.
(local
(defthm unique-hil-implies-so-after-hil-nil
(implies (unique-hil hil heg keys)
(unique-hil (s i nil hil) heg keys))
:hints
(("Goal"
:cases ((equal i (car (unique-hil-witness (s i nil hil) heg keys)))
(equal i (mv-nth 1 (unique-hil-witness (s i nil hil) heg keys)))))
("Subgoal 1"
:in-theory (enable unique-hil))
("Subgoal 2"
:in-theory (enable unique-hil))
("Subgoal 3"
:use
((:instance (:definition unique-hil)
(hil (s i nil hil)))
(:instance
unique-hil-necc
(i (car (unique-hil-witness (s i nil hil) heg keys)))
(j (mv-nth 1 (unique-hil-witness (s i nil hil) heg keys)))))))))
;; Well, that kind of does it for home-sends-invalidate. Here is the proof.
(local
(defthm |unique-hil after home-sends-invalidate|
(implies (and (unique-hil-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(unique-hil-invariant (german-step st stimulus)))))
;; What about home-receives-invalidate? This works because we are now setting
;; heg to hil.
(local
(defthm not-heg-implies-unique-hil
(implies (not heg)
(unique-hil hil heg keys))
:hints (("Goal"
:in-theory (enable unique-hil)))))
(local
(defthm |unique-hil after home-receives-invalidate|
(implies (and (unique-hil-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(unique-hil-invariant (german-step st stimulus)))))
;; This of course does not work for home-grants-exclusive, since here we *are*
;; setting heg. But we know something in this case that will help us out.
;; What do I know? I know all-false holds. This says (together with the
;; predicate hil-hsl that there is no hil at all. So this case does not arise.
(local
(defthm hil-hsl-implies-unique-hil
(implies (and (hil-hsl hil hsl keys)
(all-false keys hsl))
(unique-hil (s i v hil) heg keys))
:hints
(("Goal"
:in-theory (enable unique-hil)
:cases ((equal i (car (unique-hil-witness (s i v hil) heg keys)))))
("Subgoal 1"
:cases
((equal i (mv-nth 1 (unique-hil-witness (s i v hil) heg keys))))))))
;; And of course unique-hil remains if hil is not set at all.
(local
(defthm hil-hsl-implies-unique-hil-not-set
(implies (and (hil-hsl hil hsl keys)
(all-false keys hsl))
(unique-hil hil heg keys))
:hints (("Goal"
:in-theory (enable unique-hil)))))
;; So we can now get this grant-exclusive case thru.
(local
(defthm |unique-hil after home grants exclusive|
(implies (and (unique-hil-invariant st)
(hil-hsl-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(unique-hil-invariant (german-step st stimulus)))))
;; What happens when home picks a new request? The issue here is that we need
;; to claim unique-hil for set-hil-hsl. Now this is true because hsl has the
;; same predicate holding, and after set-hil-hsl therefore hil will have the
;; same predicate.
(local
(defthm hsl-heg-implies-unique-hil
(implies (hsl-heg hsl heg keys)
(unique-hil (set-hil-hsl keys hil hsl)
heg keys))
:hints
(("Goal"
:use
((:instance (:definition unique-hil)
(hil (set-hil-hsl keys hil hsl)))
(:instance
hsl-heg-necc
(i (car (unique-hil-witness (set-hil-hsl keys hil hsl)
heg keys)))
(j (mv-nth 1 (unique-hil-witness (set-hil-hsl keys hil hsl)
heg keys)))))))))
(local
(defthm |unique-hil after picking new request|
(implies (and (unique-hil-invariant st)
(hsl-heg-invariant st)
(equal (action stimulus) :pick-new-request))
(unique-hil-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of unique-hil-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right now to hsl-heg-invariant.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.16: Proof of hsl-heg-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hsl-heg default cases|
(implies (and (hsl-heg-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:home-grants-shared
:home-grants-exclusive))))
(hsl-heg-invariant (german-step st stimulus)))))
;; Now this works for home receiving invalidate since heg is being set to nil.
(local
(defthm hsl-heg-after-heg-nil
(implies (not heg)
(hsl-heg hsl heg keys))
:hints (("Goal"
:in-theory (enable hsl-heg)))))
(local
(defthm |hsl-heg after home receives invalidate|
(implies (and (hsl-heg-invariant st)
(memberp (action stimulus) '(:home-grants-shared
:home-receives-invalidate)))
(hsl-heg-invariant (german-step st stimulus)))))
;; Only left now is when home grants exclusive. Now I know that all other
;; clients are nil. And it is therefore known that we can set anything to hsl.
(local
(defthm all-false-implies-false
(implies (and (all-false keys hsl)
(memberp i keys))
(equal (g i hsl) nil))))
(local
(defthm hsl-can-be-set-when-all-false
(implies (all-false keys hsl)
(hsl-heg (s i v hsl) heg keys))
:hints
(("Goal"
:in-theory (enable hsl-heg)
:cases ((equal i (car (hsl-heg-witness (s i v hsl) heg keys)))
(equal i (mv-nth 1 (hsl-heg-witness (s i v hsl) heg keys))))))))
(local
(defthm |hsl-heg after home-grants-exclusive|
(implies (and (hsl-heg-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(hsl-heg-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hsl-heg-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; hsl-ch3-invariant now.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.17: Proof of hsl-ch3-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hsl-ch3 default cases|
(implies (and (hsl-ch3-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:sharer-invalidate-cache
:home-grants-shared
:home-grants-exclusive))))
(hsl-ch3-invariant (german-step st stimulus)))))
;; Of course it is easy to do the granting of exclusive and shared. All that
;; it is, is that we can set hsl to T as much as we want.
(local
(defthm hsl-T-does-not-change-hsl-ch3
(implies (hsl-ch3 hsl ch3 keys)
(hsl-ch3 (s i T hsl) ch3 keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-ch3 does not change on grant|
(implies (and (hsl-ch3-invariant st)
(memberp (action stimulus) '(:home-grants-shared
:home-grants-exclusive)))
(hsl-ch3-invariant (german-step st stimulus)))))
;; Similarly if ch3 is set to nil then nothing happens.
(local
(defthm hsl-ch3-if-ch3-nil
(implies (hsl-ch3 hsl ch3 keys)
(hsl-ch3 (s i v hsl) (s i nil ch3) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-ch3 after receiving invalidation|
(implies (and (hsl-ch3-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hsl-ch3-invariant (german-step st stimulus)))))
;; The only critical case here is when the client is sending acknowledgement of
;; invalidation to the server. This is because now we must say that the index
;; was already T in hsl. This holds because of hsl-ch2, and the fact that we
;; know that ch2 now containts :invalidate.
(local
(defthm hsl-ch3-for-not-member
(implies (and (hsl-ch3 hsl ch3 keys)
(not (memberp i keys)))
(hsl-ch3 hsl (s i v ch3) keys))))
(local
(defthm hsl-ch2-implies-hsl-ch3-after-set
(implies (and (hsl-ch2 hsl keys ch2)
(hsl-ch3 hsl ch3 keys)
(memberp i keys)
(g i ch2))
(hsl-ch3 hsl (s i v ch3) keys))
:hints (("Goal"
:do-not '(eliminate-destructors generalize fertilize))
("Subgoal *1/6"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-ch3 after sharer invalidates|
(implies (and (hsl-ch3-invariant st)
(hsl-ch2-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(hsl-ch3-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hsl-ch3-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; hsl-boolean-invariant now.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.18: Proof of hsl-boolean-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; This one is particularly trivial, as indeed are most others which have to do
;; with types. In fact it is an inductive invariant in itself.
(local
(defthm |hsl-boolean default cases|
(implies (and (hsl-boolean-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:home-grants-shared
:home-grants-exclusive))))
(hsl-boolean-invariant (german-step st stimulus)))))
(local
(defthm hsl-boolean-if-boolean-val-set
(implies (and (hsl-boolean hsl keys)
(booleanp v))
(hsl-boolean (s i v hsl) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-boolean other cases|
(implies (and (hsl-boolean-invariant st)
(memberp (action stimulus)
'(:home-receives-invalidate
:home-grants-shared
:home-grants-exclusive)))
(hsl-boolean-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hsl-boolean-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.19: Proof of hil-invalidate-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hil-invalidate default cases|
(implies (and (hil-invalidate-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache))))
(hil-invalidate-invariant (german-step st stimulus)))))
;; Now if home sends an invalidate it sets hil to nil and thus it works out.
(local
(defthm hil-invalidate-on-nil
(implies (hil-invalidate hil ch3 keys)
(hil-invalidate (s i nil hil) ch3 keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-invalidate on home-sends-invalidate|
(implies (and (hil-invalidate-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hil-invalidate-invariant (german-step st stimulus)))))
;; Now it must also be ok when home receives it. Now it sets ch3 to something
;; other than invalidate-ack so I dont have to prove anything.
(local
(defthm hil-invalidate-ack-set
(implies (and (hil-invalidate hil ch3 keys)
(not (equal v :invalidate-ack)))
(hil-invalidate hil (s i v ch3) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-invalidate when home receives invalidate|
(implies (and (hil-invalidate-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hil-invalidate-invariant (german-step st stimulus)))))
;; But what happens when the sharer actually inserts an invalidate-ack in ch3?
;; This is the third case we consider. Now what the heck do we know about this
;; situation? Why does this predicate hold? We know that the ch2 is having an
;; :invalidate. So we must know that when ch2 has :invalidate then hil must be
;; nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hil-invalidate-ch2 (hil ch2 keys)
(if (endp keys) T
(and (implies (equal (g (first keys) ch2) :invalidate)
(not (g (first keys) hil)))
(hil-invalidate-ch2 hil ch2 (rest keys))))))
(local
(defun hil-invalidate-ch2-invariant (st)
(hil-invalidate-ch2 (hil st) (ch2 st) (keys))))
(local
(defthm hil-invalidate-ch2-for-nil (hil-invalidate-ch2 nil nil keys)))
(local
(defthm |init has hil-invalidate-ch2| (hil-invalidate-ch2-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm hil-invalidate-ch2-implies-invalidate
(implies (and (hil-invalidate-ch2 hil ch2 keys)
(hil-invalidate hil ch3 keys)
(memberp i keys)
(equal (g i ch2) :invalidate))
(hil-invalidate hil (s i v ch3) keys))
:hints (("Subgoal *1/6"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-invalidate after sharer-invalidate-cache|
(implies (and (hil-invalidate-invariant st)
(hil-invalidate-ch2-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(hil-invalidate-invariant (german-step st stimulus)))))
;; The condition for picking new request is a bit more interesting. I have to
;; claim that at this point there is no invalidate-ack around. But how do we
;; know that? Do I know that anything from hsl does not have invalidate-ack?
;; Clearly not. But what I do know is that if invalidate-ack is true of
;; something then hcm is true. This is from hcm-invalidate-ack.
;; Now I will prove that hcm-invalidate-ack implies hil-invalidate. This is an
;; interesting exercise since I am proving something about a recursive function
;; using a quantified property. To do this I will invoke the so-called
;; "witness function" approach.
(local
(defun hil-invalidate-witness (hil ch3 keys)
(if (endp keys) nil ;; dont care
(if (and (equal (g (first keys) ch3) :invalidate-ack)
(g (first keys) hil))
(first keys)
(hil-invalidate-witness hil ch3 (rest keys))))))
(local
(defthm hil-invalidate-witness-implies-hil-invalidate
(implies (or (not (equal (g (hil-invalidate-witness hil ch3 keys) ch3)
:invalidate-ack))
(not (memberp (hil-invalidate-witness hil ch3 keys)
keys))
(not (g (hil-invalidate-witness hil ch3 keys) hil)))
(hil-invalidate hil ch3 keys))))
(local
(defthm hcm-ch3-implies-hil-invalidate
(implies (and (hcm-invalidate-ack hcm heg ch3 keys)
(not hcm))
(hil-invalidate hil ch3 keys))
:hints (("Goal"
:use ((:instance hcm-invalidate-ack-necc
(i (hil-invalidate-witness hil ch3 keys))))))))
(local
(defthm |hil-invalidate when pick-new-request|
(implies (and (hil-invalidate-invariant st)
(hcm-invalidate-ack-invariant st)
(equal (action stimulus) :pick-new-request))
(hil-invalidate-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hil-invalidate-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now let us get to this predicate hil-invalidate-ch2. I have a premonition
;; that it would involve specifying something about hcm. We will see.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.20: Proof of hil-invalidate-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hil-invalidate-ch2 default cases|
(implies (and (hil-invalidate-ch2-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hil-invalidate-ch2-invariant (german-step st stimulus)))))
;; Of course the standard thing is that if ch2 is set to nil then we are in
;; great shape.
(local
(defthm hil-invalidate-ch2-when-ch2-nil
(implies (hil-invalidate-ch2 hil ch2 keys)
(hil-invalidate-ch2 hil (s i nil ch2) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-invalidate-ch2 when ch2 is reset|
(implies (and (hil-invalidate-ch2-invariant st)
(memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(hil-invalidate-ch2-invariant (german-step st stimulus)))))
;; And as usual setting hil to nil does not matter. So we use that to do the
;; sending of invalidate.
(local
(defthm hil-invalidate-ch2-set-hil-nil
(implies (hil-invalidate-ch2 hil ch2 keys)
(hil-invalidate-ch2 (s i nil hil) (s i v ch2) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-invalidate-ch2 home-sends-invalidate|
(implies (and (hil-invalidate-ch2-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hil-invalidate-ch2-invariant (german-step st stimulus)))))
;; And it does not matter if I set anything other than :invalidate in ch2.
(local
(defthm hil-invalidate-other-than-invalidate
(implies (and (hil-invalidate-ch2 hil ch2 keys)
(not (equal v :invalidate)))
(hil-invalidate-ch2 hil (s i v ch2) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-invalidate-ch2 for grant|
(implies (and (hil-invalidate-ch2-invariant st)
(memberp (action stimulus) '(:home-grants-shared
:home-grants-exclusive)))
(hil-invalidate-ch2-invariant (german-step st stimulus)))))
;; And finally the non-trivial case, namely :pick-new-request. What do we know
;; here? I would have loved to say that if ch2 has invalidate then hsl is nil.
;; But that is not true!!! In fact it is exactly the opposite that is true. I
;; definitely know that if ch2 has an invalidate then hsl *is* true. Why does
;; it work out then? It works out because when hcm is nil ch2 is nil,
;; :grant-exclusive, or :grant-shared. Why? Because home receives some
;; request and works on it and goes on working on it until it can finish
;; processing. During that time the hcm is always holding the command given.
;; It is only after the command has been completely processed that hcm is set
;; to nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk hcm-ch2 (hcm heg ch2 keys)
(forall i (implies (and (memberp i keys)
(equal (g i ch2) :invalidate))
(or (and (equal hcm :req-shared-access)
heg)
(equal hcm :req-exclusive-access))))))
(local
(defun hcm-ch2-invariant (st) (hcm-ch2 (hcm st) (heg st) (ch2 st) (keys))))
(local
(defthm |init has hcm-ch2| (hcm-ch2-invariant (init))))
(local
(in-theory (disable hcm-ch2 hcm-ch2-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm not-hcm-implies-not-invalidate
(implies (and (hcm-ch2 hcm heg ch2 keys)
(not hcm)
(memberp i keys))
(equal (equal (g i ch2) :invalidate) nil))
:hints (("Goal"
:use hcm-ch2-necc))))
;; And here I see how we can mimic quantification with recursion.
(local
(defun hil-invalidate-rwitness (hil ch2 keys)
(if (endp keys) nil ;; dont care
(if (and (equal (g (first keys) ch2) :invalidate)
(g (first keys) hil))
(first keys)
(hil-invalidate-rwitness hil ch2 (rest keys))))))
(local
(defthm hil-invalidate-rwitness-invalidate
(implies (or (not (equal (g (hil-invalidate-rwitness hil ch2 keys) ch2)
:invalidate))
(not (g (hil-invalidate-rwitness hil ch2 keys) hil))
(not (memberp (hil-invalidate-rwitness hil ch2 keys) keys)))
(hil-invalidate-ch2 hil ch2 keys))))
(local
(defthm not-hcm-implies-hil-invalidate
(implies (and (hcm-ch2 hcm heg ch2 keys)
(not hcm))
(hil-invalidate-ch2 hil ch2 keys))
:hints (("Goal"
:in-theory (disable hil-invalidate-rwitness-invalidate)
:use hil-invalidate-rwitness-invalidate))))
(local
(defthm |hil-invalidate on pick-new-request|
(implies (and (hil-invalidate-ch2-invariant st)
(hcm-ch2-invariant st)
(equal (action stimulus) :pick-new-request))
(hil-invalidate-ch2-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hil-invalidate-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; hcm-ch2-invariant
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.21: Proof of hcm-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hcm-ch2 default cases|
(implies (and (hcm-ch2-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hcm-ch2-invariant (german-step st stimulus)))))
;; Now what happens when there is an invalidate-ack? Why is the predicate
;; going to be ok here? There should be no other invalidate-ack. I know this
;; as follows. hsl-heg tells me that if heg is true then there is at most one
;; hsl. hsl-ch3 then tells me that there is at most one ch3. This ch3 is the
;; invalidate-ack I am seeing. Thus if I set this to nil there is no ch3, and
;; hence I am done. And of course if heg was already nil then there is nothing
;; to do.
;; All right, let us do this.
(local
(defthm hsl-ch3-and-ch3-to-hsl
(implies (and (hsl-ch3 hsl ch3 keys)
(memberp i keys)
(g i ch3))
(g i hsl))))
(local
(defthm hsl-heg-hsl-ch3-implies-only-one
(implies (and (hsl-heg hsl heg keys)
(hsl-ch3 hsl ch3 keys)
(hsl-ch2 hsl keys ch2)
(memberp i keys)
(memberp j keys)
heg
(g j ch2)
(g i ch3))
(equal i j))
:rule-classes :forward-chaining
:hints (("Goal"
:use hsl-heg-necc))))
;; Now I will claim that all right I know all this, and I also know from
;; invalidate-ack-ch2 that the guy which has invalidate-ack in ch3 does not
;; have a ch2. This will show that there is no ch2 at all.
(local
(defthm hsl-heg-hsl-ch3-implies-none
(implies (and (hsl-heg hsl heg keys)
(hsl-ch3 hsl ch3 keys)
(invalidate-ack-ch2 ch2 ch3 keys)
(hsl-ch2 hsl keys ch2)
(memberp i keys)
(memberp j keys)
heg
(equal (g i ch3) :invalidate-ack))
(equal (g j ch2) nil))
:hints (("Goal"
:cases ((equal i j))))))
;; And therefore I have it when heg.
(local
(defthm hcm-ch2-when-heg
(implies (and (hsl-heg hsl heg keys)
(hsl-ch3 hsl ch3 keys)
(invalidate-ack-ch2 ch2 ch3 keys)
(memberp i keys)
(equal (g i ch3) :invalidate-ack)
(hsl-ch2 hsl keys ch2)
heg)
(hcm-ch2 hcm v ch2 keys))
:hints (("Goal"
:in-theory (enable hcm-ch2)))))
;; For the final theorem I will case-split on whether heg is true.
(local
(defthm |hcm-ch2 when home-receives-invalidate|
(implies (and (hcm-ch2-invariant st)
(hsl-heg-invariant st)
(hsl-ch3-invariant st)
(invalidate-ack-ch2-invariant st)
(hsl-ch2-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hcm-ch2-invariant (german-step st stimulus)))
:hints (("Goal" :cases ((heg st))))))
;; The argument for picking a request is kind of cute. It says that if hcm is
;; not one of the approved values then there is no invalidate, and since there
;; is no invalidate I am now allowed to make hcm anything! Isn't it cute?
(local
(defthm hcm-ch2-and-not-hcm-implies-hcm-anything
(implies (and (hcm-ch2 hcm heg ch2 keys)
(not (equal hcm :req-exclusive-access))
(or (not (equal hcm :req-shared-access))
(not heg)))
(hcm-ch2 v u ch2 keys))
:hints (("Goal"
:use ((:instance (:definition hcm-ch2)
(hcm v)
(heg u))
(:instance hcm-ch2-necc
(i (hcm-ch2-witness v u ch2 keys))))))))
(local
(defthm |hcm-ch2 for pick-new-request|
(implies (and (hcm-ch2-invariant st)
(equal (action stimulus) :pick-new-request))
(hcm-ch2-invariant (german-step st stimulus)))))
;; For granting shared a similar argument is necessary but now we also set
;; ch2.
(local
(defthm hcm-ch2-and-not-hcm-implies-hcm-anything-with-ch2
(implies (and (hcm-ch2 hcm heg ch2 keys)
(not (equal hcm :req-exclusive-access))
(not (equal w :invalidate))
(or (not (equal hcm :req-shared-access))
(not heg)))
(hcm-ch2 v u (s i w ch2) keys))
:hints (("Goal"
:cases ((equal i (hcm-ch2-witness v u (s i w ch2) keys))))
("Subgoal 1"
:in-theory (enable hcm-ch2))
("Subgoal 2"
:use ((:instance (:definition hcm-ch2)
(hcm v)
(ch2 (s i w ch2))
(heg u))
(:instance hcm-ch2-necc
(i (hcm-ch2-witness v u (s i w ch2) keys))))))))
(local
(defthm |hcm-ch2 after home-grants-shared|
(implies (and (hcm-ch2-invariant st)
(equal (action stimulus) :home-grants-shared))
(hcm-ch2-invariant (german-step st stimulus)))))
;; And home-sends-invalidate is rather trivial since the definition of hcm is
;; done with this predicate in mind.
(local
(defthm hcm-ch2-if-the-right-things-set
(implies (or (and (equal hcm :req-shared-access)
heg)
(equal hcm :req-exclusive-access))
(hcm-ch2 hcm heg ch2 keys))
:hints (("Goal"
:in-theory (enable hcm-ch2)))))
(local
(defthm |hcm-ch2 when home-sends-invalidate|
(implies (and (hcm-ch2-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hcm-ch2-invariant (german-step st stimulus)))))
;; As in fact it does not matter if I set ch2 to something other than
;; :invalidate.
(local
(defthm hcm-ch2-after-setting-ch2
(implies (and (hcm-ch2 hcm heg ch2 keys)
(not (equal v :invalidate)))
(hcm-ch2 hcm heg (s i v ch2) keys))
:hints (("Goal"
:cases ((equal i (hcm-ch2-witness hcm heg (s i v ch2) keys))))
("Subgoal 2"
:use ((:instance (:definition hcm-ch2)
(ch2 (s i v ch2)))
(:instance hcm-ch2-necc
(i (hcm-ch2-witness hcm heg (s i v ch2) keys)))))
("Subgoal 1"
:in-theory (enable hcm-ch2)))))
(local
(defthm |hcm-ch2 after client sets|
(implies (and (hcm-ch2-invariant st)
(memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(hcm-ch2-invariant (german-step st stimulus)))))
;; And the exclusive of course just requires that we have hsl-ch2 which we do.
(local
(defthm hsl-ch2-and-all-false-implies-hcm
(implies (and (hsl-ch2 hsl keys ch2)
(not (equal v :invalidate))
(all-false keys hsl))
(hcm-ch2 hcm heg (s i v ch2) keys))
:hints (("Goal"
:cases ((equal i (hcm-ch2-witness hcm heg (s i v ch2) keys))))
("Subgoal 1"
:in-theory (enable hcm-ch2))
("Subgoal 2"
:in-theory (enable hcm-ch2)))))
(local
(defthm |hsm-ch2 when grants exclusive|
(implies (and (hcm-ch2-invariant st)
(hsl-ch2-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(hcm-ch2-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hcm-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now I handle the hcm-invalidate-ack-invariant. This says that if (not heg)
;; and hcm is equal to :req-shared-access then there is no invalidate-ack.
;; This should be pretty trivial since under these conditions we dont send an
;; invalidate at all.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.22: Proof of hcm-invalidate-ack-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hcm-invalidate-ack default cases|
(implies (and (hcm-invalidate-ack-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-receives-invalidate
:sharer-invalidate-cache
:home-grants-shared
:home-grants-exclusive))))
(hcm-invalidate-ack-invariant (german-step st stimulus)))))
;; Now what happens when we pick a new request? We know hcm is nil. And then
;; there is nothing to prove. This is the same cute trick that we invoked for
;; hcm-ch2.
(local
(defthm hcm-ack-and-not-hcm-implies-hcm-anything
(implies (and (hcm-invalidate-ack hcm heg ch3 keys)
(not (equal hcm :req-exclusive-access))
(or (not (equal hcm :req-shared-access))
(not heg)))
(hcm-invalidate-ack v u ch3 keys))
:hints
(("Goal"
:use ((:instance (:definition hcm-invalidate-ack)
(hcm v)
(heg u))
(:instance hcm-invalidate-ack-necc
(i (hcm-invalidate-ack-witness v u ch3 keys))))))))
(local
(defthm |hcm-invalidate-ack for pick-new-request|
(implies (and (hcm-invalidate-ack-invariant st)
(equal (action stimulus) :pick-new-request))
(hcm-invalidate-ack-invariant (german-step st stimulus)))))
;; And the same trick for grant-shared.
(local
(defthm hcm-ch3-and-not-hcm-implies-hcm-anything-with-ch2
(implies (and (hcm-invalidate-ack hcm heg ch3 keys)
(not (equal hcm :req-exclusive-access))
(not (equal w :invalidate-ack))
(or (not (equal hcm :req-shared-access))
(not heg)))
(hcm-invalidate-ack v u (s i w ch3) keys))
:hints
(("Goal"
:cases ((equal i (hcm-invalidate-ack-witness v u (s i w ch3) keys))))
("Subgoal 1"
:in-theory (enable hcm-invalidate-ack))
("Subgoal 2"
:use
((:instance (:definition hcm-invalidate-ack)
(hcm v)
(ch3 (s i w ch3))
(heg u))
(:instance hcm-invalidate-ack-necc
(i (hcm-invalidate-ack-witness v u (s i w ch3) keys))))))))
(local
(defthm |hcm-invalidate-ack after home-grants-shared|
(implies (and (hcm-invalidate-ack-invariant st)
(equal (action stimulus) :home-grants-shared))
(hcm-invalidate-ack-invariant (german-step st stimulus)))))
;; As I well realize now this predicate is kind of a mirror image of hcm-ch2.
;; So home-receives-invalidate is going to have a problem. And indeed exactly
;; the same problem as hcm-ch2. And the solution is exactly the same too!
(local
(defthm hsl-heg-hsl-ch3-implies-only-one-ch3
(implies (and (hsl-heg hsl heg keys)
(hsl-ch3 hsl ch3 keys)
(memberp i keys)
(memberp j keys)
heg
(g j ch3)
(g i ch3))
(equal i j))
:rule-classes :forward-chaining
:hints (("Goal"
:use hsl-heg-necc))))
;; Now I can prove that if I set ch3 to something else I would be done.
(local
(defthm hcm-ch3-when-heg
(implies (and (hsl-heg hsl heg keys)
(hsl-ch3 hsl ch3 keys)
(memberp i keys)
(not (equal u :invalidate-ack))
(equal (g i ch3) :invalidate-ack)
heg)
(hcm-invalidate-ack hcm v (s i u ch3) keys))
:hints
(("Goal"
:in-theory (enable hcm-invalidate-ack)
:cases ((equal i (hcm-invalidate-ack-witness hcm v (s i u ch3) keys)))))))
;; Well in this case we need to do something for not-heg as well just because I
;; am setting ch3. Now what happens if heg is actually not true. Now in this
;; case the hcm is req-shared-access and since I am not changing hcm it still
;; remains req-shared-access and I have nothing to prove.
(local
(defthm not-heg-invalidate-ack-implies-invalidate-ack
(implies (and (hcm-invalidate-ack hcm heg ch3 keys)
(not heg)
(memberp i keys)
(equal (g i ch3) :invalidate-ack))
(hcm-invalidate-ack hcm v u keys))
:hints (("Goal"
:use ((:instance (:definition hcm-invalidate-ack)
(heg v)
(ch3 u))
(:instance hcm-invalidate-ack-necc))))))
(local
(defthm |hcm-invalidate-ack when home-receives-invalidate|
(implies (and (hsl-heg-invariant st)
(hsl-ch3-invariant st)
(hcm-invalidate-ack-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hcm-invalidate-ack-invariant (german-step st stimulus)))
:hints (("Goal"
:cases ((heg st))))))
;; What happens when the sharer invalidates? I need to claim that under the
;; non-trivial conditions there is no invalidate at all, and hence there is no
;; problem.
(local
(defthm invalidate-not-a-problem
(implies (and (hcm-ch2 hcm heg ch2 keys)
(memberp i keys)
(equal (g i ch2) :invalidate))
(hcm-invalidate-ack hcm heg ch3 keys))
:hints (("Goal"
:in-theory (enable hcm-invalidate-ack)
:use hcm-ch2-necc))))
(local
(defthm |hcm-invalidate-ack after sharer invalidates|
(implies (and (hcm-invalidate-ack-invariant st)
(hcm-ch2-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(hcm-invalidate-ack-invariant (german-step st stimulus)))))
;; Now what happens if either there is a grant-exclusive? Again I will go thru
;; the pain of hsl and all-false. This predicate *is* really like hcm-ch2, the
;; more I think about it.
(local
(defthm hsl-ch3-and-all-false-implies-hcm
(implies (and (hsl-ch3 hsl ch3 keys)
(all-false keys hsl))
(hcm-invalidate-ack hcm heg ch3 keys))
:hints
(("Goal"
:cases ((equal i (hcm-invalidate-ack-witness hcm heg ch3 keys))))
("Subgoal 1"
:in-theory (enable hcm-invalidate-ack))
("Subgoal 2"
:in-theory (enable hcm-invalidate-ack)))))
(local
(defthm |hsm-invalidate-ack when grants exclusive|
(implies (and (hcm-invalidate-ack-invariant st)
(hsl-ch3-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(hcm-invalidate-ack-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hcm-invalidate-ack-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now I handle invalidate-clients-invariant. This should not be too much
;; trouble. If says that if a client has an invalidate it must be shared or
;; exclusive. In other words invalidation is not sent to idle clients. Since
;; this involves a property of two components for the same index, this should
;; be easy.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.22: Proof of hcm-invalidate-ack-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |invalidate-clients default cases|
(implies (and (invalidate-clients-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(invalidate-clients-invariant (german-step st stimulus)))))
;; And as is standard, I will show that if the predicate already holds then
;; setting ch2 to something other than invalidate does not change it.
(local
(defthm invalidate-after-something-else
(implies (and (invalidate-clients ch2 clients keys)
(not (equal v :invalidate)))
(invalidate-clients (s i v ch2) clients keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
;; which takes care of home granting shared or invalidate.
(local
(defthm |invalidate-clients after home-grants|
(implies (and (invalidate-clients-invariant st)
(memberp (action stimulus)
'(:home-grants-shared
:home-grants-exclusive)))
(invalidate-clients-invariant (german-step st stimulus)))))
;; Now when the client receives something it also does not matter as long as it
;; does not receive an invalidate.
(local
(defthm invalidate-after-client-set
(implies (and (invalidate-clients ch2 clients keys)
(not (equal v :invalidate)))
(invalidate-clients (s i v ch2) (s i u clients) keys))
:hints (("Goal"
:do-not '(eliminate-destructors generalize fertilize))
("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |clients are fine with invalidate-clients|
(implies (and (invalidate-clients-invariant st)
(memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(invalidate-clients-invariant (german-step st stimulus)))))
;; The only crucial point is when home sends invalidate. Why is that ok? As I
;; realize now, the reason is kind of subtle and I had not realized this when I
;; posited the predicate. The reason is that if hil has an index that is set
;; then the process is either shared, or exclusive, or grant-shared, or
;; grant-exclusive. The reason actually is that hsl behaves the same way, and
;; therefore hil gets it derived. We thus need to posit this as a predicate.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hil-client-ch2 (hil clients ch2 keys)
(if (endp keys) T
(and (implies (g (first keys) hil)
(or (equal (g (first keys) clients) :shared)
(equal (g (first keys) clients) :exclusive)
(equal (g (first keys) ch2) :grant-shared)
(equal (g (first keys) ch2) :grant-exclusive)))
(hil-client-ch2 hil clients ch2 (rest keys))))))
(local
(defun hil-client-ch2-invariant (st)
(hil-client-ch2 (hil st) (clients st) (ch2 st) (keys))))
(local
(defthm hil-client-for-nil (hil-client-ch2 nil clients ch2 keys)))
(local
(defthm |init has hil-client-ch2| (hil-client-ch2-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now this tells us that everything is ok.
(local
(defthm hil-client-ch2-memberp-reduction
(implies (and (hil-client-ch2 hil clients ch2 keys)
(memberp i keys)
(g i hil))
(or (equal (g i clients) :shared)
(equal (g i clients) :exclusive)
(equal (g i ch2) :grant-shared)
(equal (g i ch2) :grant-exclusive)))
:rule-classes :forward-chaining))
;; Of course now it is fine to do the invalidate since this index is shared of
;; exclusive. (Note that home checks if the ch2 has become empty.)
(local
(defthm invalidate-clients-not-memberp-reduction
(implies (and (invalidate-clients ch2 clients keys)
(not (memberp i keys)))
(invalidate-clients (s i v ch2) clients keys))))
(local
(defthm hil-client-hil-ch2-reduction
(implies (and (hil-client-ch2 hil clients ch2 keys)
(invalidate-clients ch2 clients keys)
(memberp i keys)
(g i hil)
(not (g i ch2)))
(invalidate-clients (s i v ch2) clients keys))
:hints (("Subgoal *1/6"
:cases ((equal i (car keys)))))))
(local
(defthm |invalidate-clients after home-sends-invalidate|
(implies (and (invalidate-clients-invariant st)
(hil-client-ch2-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(invalidate-clients-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of invalidate-clients-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; I am annoyed that the proof is going on and on. I thought when I was
;; proving invalidate-clients that it would be the last predicate I need to
;; reason about, but I got one more predicate. Of course to deal with this I
;; already know one more is necessary, namely about hsl relating it with
;; clients and ch2. But I hope not much more is involved.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.23: Proof of hil-client-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hil-client-ch2 default cases|
(implies (and (hil-client-ch2-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hil-client-ch2-invariant (german-step st stimulus)))))
;; And of course if I set the ch2 to grant-shared or grant-exclusive it does
;; not matter.
(local
(defthm hil-client-ch2-set-ch2
(implies (and (hil-client-ch2 hil clients ch2 keys)
(or (equal v :grant-exclusive)
(equal v :grant-shared)))
(hil-client-ch2 hil clients (s i v ch2) keys))
:hints (("Subgoal *1/3"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-client when home grants|
(implies (and (hil-client-ch2-invariant st)
(memberp (action stimulus)
'(:home-grants-exclusive
:home-grants-shared)))
(hil-client-ch2-invariant (german-step st stimulus)))))
;; And as long as I set the clients to shared or exclusive again it does not
;; matter. In fact it does not matter if we remove things from ch2.
(local
(defthm hil-client-ch2-set-client
(implies (and (hil-client-ch2 hil clients ch2 keys)
(or (equal v :exclusive)
(equal v :shared)))
(hil-client-ch2 hil (s i v clients) (s i u ch2) keys))
:hints (("Subgoal *1/3"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-client when client is set|
(implies (and (hil-client-ch2-invariant st)
(memberp (action stimulus)
'(:client-receives-exclusive
:client-receives-shared)))
(hil-client-ch2-invariant (german-step st stimulus)))))
;; And for sharer-invalidating we only need to say that hil is not existing.
;; And this is known from hil-invalidate-ch2.
(local
(defthm hil-invalidate-implies-can-set-client
(implies (and (hil-client-ch2 hil clients ch2 keys)
(hil-invalidate-ch2 hil ch2 keys)
(equal (g i ch2) :invalidate))
(hil-client-ch2 hil (s i v clients) (s i u ch2) keys))
:hints (("Subgoal *1/5"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-client for sharer invalidating|
(implies (and (hil-client-ch2-invariant st)
(hil-invalidate-ch2-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(hil-client-ch2-invariant (german-step st stimulus)))))
;; Why does hil-client work for home sending the invalidate? I have nothing to
;; prove since hil is being set to nil.
(local
(defthm hil-client-ch2-to-nil
(implies (hil-client-ch2 hil clients ch2 keys)
(hil-client-ch2 (s i nil hil) clients (s i v ch2) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-client-ch2 when home-sends-invalidate|
(implies (and (hil-client-ch2-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hil-client-ch2-invariant (german-step st stimulus)))))
;; All right, now for the non-trivial one. I need to write another predicate
;; which says that hsl has indices that are only shared, exclusive,
;; grant-shared, or grant-exclusive, or in fact the ch3 has invalidate-ack.
;; Otherwise I cannot have hil-client-ch2 when hil is set to hsl.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hsl-client-ch2 (hsl clients ch2 ch3 keys)
(if (endp keys) T
(and (implies (g (first keys) hsl)
(or (equal (g (first keys) clients) :shared)
(equal (g (first keys) clients) :exclusive)
(equal (g (first keys) ch2) :grant-shared)
(equal (g (first keys) ch2) :grant-exclusive)
(equal (g (first keys) ch3) :invalidate-ack)))
(hsl-client-ch2 hsl clients ch2 ch3 (rest keys))))))
(local
(defun hsl-client-ch2-invariant (st)
(hsl-client-ch2 (hsl st) (clients st) (ch2 st) (ch3 st) (keys))))
(local
(defthm hsl-client-for-nil (hsl-client-ch2 nil clients ch2 ch3 keys)))
(local
(defthm |init has hsl-client-ch2| (hsl-client-ch2-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; OK now we can prove that if hsl-client-ch2 holds then set-hil-hsl is fine.
;; I will prove it again using witness functions. I now understand why J said
;; that I really love quantification....!!!
(local
(defun hil-client-witness (hil clients ch2 keys)
(if (endp keys) nil
(if (and (g (first keys) hil)
(not (equal (g (first keys) clients) :shared))
(not (equal (g (first keys) clients) :exclusive))
(not (equal (g (first keys) ch2) :grant-shared))
(not (equal (g (first keys) ch2) :grant-exclusive)))
(first keys)
(hil-client-witness hil clients ch2 (rest keys))))))
(local
(defthm hil-client-witness-to-hil-clients
(implies
(or (not (memberp (hil-client-witness hil clients ch2 keys) keys))
(implies (g (hil-client-witness hil clients ch2 keys) hil)
(or (equal (g (hil-client-witness hil clients ch2 keys)
clients)
:shared)
(equal (g (hil-client-witness hil clients ch2 keys)
clients)
:exclusive)
(equal (g (hil-client-witness hil clients ch2 keys) ch2)
:grant-shared)
(equal (g (hil-client-witness hil clients ch2 keys) ch2)
:grant-exclusive))))
(hil-client-ch2 hil clients ch2 keys))
:rule-classes nil))
;; And now prove that hsl-client-ch2 implies the above conditions.
(local
(defthm hsl-client-member
(implies (and (hsl-client-ch2 hsl clients ch2 ch3 keys)
(memberp i keys)
(not (equal (g i ch3) :invalidate-ack))
(g i hsl))
(or (equal (g i clients) :shared)
(equal (g i clients) :exclusive)
(equal (g i ch2) :grant-shared)
(equal (g i ch2) :grant-exclusive)))
:rule-classes :forward-chaining))
;; Now we are in great shape, since hcm-invalidate-ack guarantees that we have
;; no invalidate-ack.
(local
(defthm hsl-client-hil-client-reduction
(implies (and (hsl-client-ch2 hsl clients ch2 ch3 keys)
(hcm-invalidate-ack hcm heg ch3 keys)
(not hcm))
(hil-client-ch2 (set-hil-hsl keys hil hsl) clients ch2 keys))
:hints
(("Goal"
:use
((:instance hil-client-witness-to-hil-clients
(hil (set-hil-hsl keys hil hsl)))
(:instance
hcm-invalidate-ack-necc
(i (hil-client-witness (set-hil-hsl keys hil hsl)
clients ch2 keys))))))))
(local
(defthm |hil-client-ch2 for picking request|
(implies (and (hsl-client-ch2-invariant st)
(hil-client-ch2-invariant st)
(hcm-invalidate-ack-invariant st)
(equal (action stimulus) :pick-new-request))
(hil-client-ch2-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hil-client-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right! Well done. Now let us trace the hsl and clients and everything
;; and try to finish this proof.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.24: Proof of hsl-client-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hsl-client-ch2 default cases|
(implies (and (hsl-client-ch2-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hsl-client-ch2-invariant (german-step st stimulus)))))
;; Well now if home sends invalidate then I dont have to prove anything. But
;; first let me prove that it is ok.
(local
(defthm hil-hsl-and-hil-and-ch2-implies-hsl
(implies (and (hsl-client-ch2 hsl clients ch2 ch3 keys)
(hil-client-ch2 hil clients ch2 keys)
(g i hil)
(not (g i ch2)))
(hsl-client-ch2 hsl clients (s i v ch2) ch3 keys))
:hints (("Subgoal *1/5"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-client-ch2 on home-sends-invalidate|
(implies (and (hsl-client-ch2-invariant st)
(hil-client-ch2-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hsl-client-ch2-invariant (german-step st stimulus)))))
;; When home-receives invalidate it removes the hsl and therefore I have to
;; prove nothing.
(local
(defthm hsl-client-reset-hsl
(implies (hsl-client-ch2 hsl clients ch2 ch3 keys)
(hsl-client-ch2 (s i nil hsl) clients ch2 (s i v ch3) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-client-ch2 when home-receives-invalidate|
(implies (and (hsl-client-ch2-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hsl-client-ch2-invariant (german-step st stimulus)))))
;; When sharer invalidates cache it sets ch3 to invalidate-ack and hence I dont
;; have to prove anything.
(local
(defthm hsl-client-set-ch3
(implies (hsl-client-ch2 hsl clients ch2 ch3 keys)
(hsl-client-ch2 hsl
(s i u clients)
(s i v ch2)
(s i :invalidate-ack ch3)
keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-client-ch2 when sharer invalidates|
(implies (and (hsl-client-ch2-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(hsl-client-ch2-invariant (german-step st stimulus)))))
;; When the client receives something it sets itself to shared or exclusive so
;; that is fine.
(local
(defthm hsl-client-ch2-on-clients
(implies (and (hsl-client-ch2 hsl clients ch2 ch3 keys)
(or (equal v :exclusive)
(equal v :shared)))
(hsl-client-ch2 hsl
(s i v clients)
(s i u ch2)
ch3 keys))
:hints (("Subgoal *1/3"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-client-ch2 when client sets|
(implies (and (hsl-client-ch2-invariant st)
(memberp (action stimulus)
'(:client-receives-shared
:client-receives-exclusive)))
(hsl-client-ch2-invariant (german-step st stimulus)))))
;; And the last case, when home is granting.
(local
(defthm hsl-client-ch2-on-home-grant
(implies (and (hsl-client-ch2 hsl clients ch2 ch3 keys)
(or (equal v :grant-exclusive)
(equal v :grant-shared)))
(hsl-client-ch2 (s i u hsl)
clients
(s i v ch2)
ch3 keys))
:hints (("Subgoal *1/3"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-client-ch2 when home grants|
(implies (and (hsl-client-ch2-invariant st)
(memberp (action stimulus)
'(:home-grants-shared
:home-grants-exclusive)))
(hsl-client-ch2-invariant (german-step st stimulus)))))
;; All right so finally done. The definition and proof of the inductive
;; invariant took way more time than I anticipated. I missed most of the
;; subtleties of the protocol when I started with the earlier predicates. It
;; would be interesting to see if the predicates can be made much simpler with
;; the insight I possess now, but I am too lazy to get back to them now that
;; the proof is virtually over.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 4: Cleanup and final theorem ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now I have gotten thru the most difficult part of the proof, namely coming
;; up with a set of predicates that together imply that their conjunction holds
;; at the next step. In this proof I have shown all predicates true on a
;; case-by-case basis already, so the final clean-up will not require the
;; definition of the predicates. Further the final cleanup also does not
;; require the definition of german-step. So I disable all definitions here.
;; Note: Since everything was done on a case-by-case basis the replay of the
;; proofs will be rather slow. One way to improve the speed of proof is to
;; just remove all the individual persistence theorems, and do it all together
;; at the end. I normally do that, but I am doing this proof more to show how
;; one comes up with such a proof in ACL2 than to speed up the certification.
;; So I leave things like this. [In practice we define the invariant and every
;; time the persistence of invariance fails we augment the invariant with a new
;; predicate or lemma.]
(local
(in-theory (disable coherent
ch2-client-shared-invariant
ch2-client-exclusive-invariant
not-heg-clients-shared-invariant
channel-nil-exclusive-invariant
hsl-client-invariant
invalidate-ack-clients-invariant
heg-exclusive-invariant
hsl-ch2-invariant
hil-heg-invariant
invalidate-ack-idle-invariant
invalidate-exclusive-invariant
hil-hsl-invariant
invalidate-ack-ch2-invariant
unique-hil-invariant
hsl-heg-invariant
hsl-ch3-invariant
invalidate-clients-invariant
hsl-boolean-invariant
hil-invalidate-invariant
hil-invalidate-ch2-invariant
valid-status-invariant
hcm-ch2-invariant
hcm-invalidate-ack-invariant
hil-client-ch2-invariant
hsl-client-ch2-invariant
init
(init)
german-step)))
(local
(defun inv (st)
(and (coherent st)
(ch2-client-shared-invariant st)
(ch2-client-exclusive-invariant st)
(not-heg-clients-shared-invariant st)
(channel-nil-exclusive-invariant st)
(hsl-client-invariant st)
(invalidate-ack-clients-invariant st)
(heg-exclusive-invariant st)
(hsl-ch2-invariant st)
(hil-heg-invariant st)
(hil-client-ch2-invariant st)
(hsl-client-ch2-invariant st)
(invalidate-ack-idle-invariant st)
(invalidate-exclusive-invariant st)
(invalidate-ack-ch2-invariant st)
(hil-invalidate-ch2-invariant st)
(hsl-heg-invariant st)
(hsl-ch3-invariant st)
(unique-hil-invariant st)
(invalidate-clients-invariant st)
(valid-status-invariant st)
(hsl-boolean-invariant st)
(hcm-ch2-invariant st)
(hcm-invalidate-ack-invariant st)
(hil-invalidate-invariant st)
(hil-hsl-invariant st))))
;; Now the final proofs which should go thru without too much hassle.
(local
(defthm |inv holds in initial state| (inv (init))))
(local
(defthm |inv is inductive| (implies (inv st) (inv (german-step st stimulus)))
:hints (("Goal"
:cases ((equal (action stimulus) :request-shared-access)
(equal (action stimulus) :request-exclusive-access)
(equal (action stimulus) :pick-new-request)
(equal (action stimulus) :home-sends-invalidate)
(equal (action stimulus) :home-receives-invalidate)
(equal (action stimulus) :sharer-invalidate-cache)
(equal (action stimulus) :client-receives-shared)
(equal (action stimulus) :client-receives-exclusive)
(equal (action stimulus) :home-grants-shared)
(equal (action stimulus) :home-grants-exclusive))))))
(local
(defthm |inv implies coherent|
(implies (inv st) (coherent st))))
;; Of course I am done already but just for the heck of it let me prove as a
;; final theorem that inv does imply coherent and hence coherent is true of
;; every execution. First let us define an execution of the german protocol.
(defun german-run (st stimuli)
(if (endp stimuli) st
(let* ((stimulus (first stimuli)))
(german-run (german-step st stimulus) (rest stimuli)))))
(local
(defthm |inv persists along run|
(implies (inv st) (inv (german-run st stimuli)))))
(local
(defthm |inv is true of all runs from init|
(inv (german-run (init) stimuli))))
;; And the final one is a capital DEFTHM.
(DEFTHM |every run is coherent| (coherent (german-run (init) stimuli)))
|
52915
|
(in-package "ACL2")
#|
german.lisp
~~~~~~~~~~~
Author: <NAME>
Date: Wed Oct 5 01:37:01 2005
This book represents my efforts to model the German protocol and reason about
it with ACL2.
Prelude
=======
Background
----------
<NAME> recently was trying to model the German protocol an use ACL2 to
prove it correct. That revived my interest in the protocol. (Thanks, <NAME>.)
I had a version of the Murphy code of the protocol, and <NAME> and I had earlier
modeled it very abstractly earlier to apply predicate abstractions. There we
wanted to see how to automate the proof. But when <NAME>na was doing it I thought
I might as well model the protocol as close to the Murphy code as possible and
see how much effort it is to do it in ACL2.
Note on using Quantification
----------------------------
Many of the predicates necessary for the proof of coherence [including the
property of coherence itself] can be stated easily via quantification. But use
of quantification requires that we be prepared to use hints in the right
places. It is unclear whether it is better to use quantification or recursive
functions in this project. I use quantification in most places since I was
trying to get more practice at using quantifiers, in part as I plan to talk to
<NAME> and <NAME> about how I believe more support should be added to the use of
quantifiers. It should be noted that although the use of quantification
requires hints, the hints were extremely mechanical. [More comments at where I
do quantification proofs.] I have used recursive functions for a couple of
predicates, but I only used them when using it was natural, for example when I
was only quantifying over one process index and so I could write only one
recursive function to capture the property I posit. [I do not like to write a
number of functions defining a property if I can state the property using one
defun-sk.] The one place where I only allow recursive functions is in defining
the functions involved in the state transition of the system. I do so since I
expect that one might want to simulate [execute] the model and hence using
quantification appears to be "wrong" in the context. Either way, I do not want
to advocate anything specific but the proof shows several examples of how to do
either.
Effort
------
I started modeling the protocol on Friday September 30, 2005. I did not have
time to work on the protocol proof on Saturday. I started the proof on Sunday,
and worked about 5 hours. I then spent Monday October 3, and Tuesday October 4
on the proof, working about 8-9 hours each day, doing the proof and the
documentation in real time. I was frustrated on Tuesday evening when I saw
that I had missed one subtlety of the protocol which is listed in Section 3.23.
Then I spent the night of Tuesday, from 11:30p.m. to 1:30a.m. (Wednesday) and
finished the proof.
I wrote the documentation of the prelude (that is, this part) after the proof.
The rest of the documentation was done real time while doing the proof. The
reason I did it that way was that I wanted to document my thoughts, both so
that the script is understandable and so that if I did shelve the proof I could
get back to it easily.
After the proof was done I changed all the defthm events not involving coherent
to local so that at least including the book will work perfectly fast. To
replay the proof do (certify-book "german") at the ACL2 prompt in an empty ACL2
session. To include the book after certification, do (include-book
"german"). The latter should be very fast at least.
|#
; Here is the murphy code for the protocol that I had once gotten from Thomas
; Wahl. I suspect that it is different from the code that Anna showed me,
; since see showed me properties called ctrlpropinv and datapropinv which I
; dont see in this version. But I think possibly the basics of the two codes
; are similar in the description of the protocols.
; Const
; n: 30;
; Type
; Msg: enum { null, req_sh, req_ex, inv, inv_ack, gr_sh, gr_ex };
; State: enum { I, S, E };
; ID: Scalarset(n);
; Var
; ch1: array[ID] of Msg; /* channel 1 */
; ch2: array[ID] of Msg; /* channel 2 */
; ch3: array[ID] of Msg; /* channel 3 */
; hsl: array[ID] of boolean; /* home_shared_list */
; hil: array[ID] of boolean; /* home_invalidate_list */
; heg: boolean; /* home_exclusive_granted */
; hcm: Msg; /* home_current_command */
; hcc: ID; /* home_current_client */
; c: array[ID] of State; /* distributed cache state */
; Ruleset i: ID do
; rule "1" /* client requests shared access */
; c[i] = I & ch1[i] = null ==>
; begin
; ch1[i] := req_sh;
; end;
; rule "2" /* client requests exclusive access */
; c[i] = I & ch1[i] = null ==>
; begin
; ch1[i] := req_ex;
; end;
; rule "3" /* home picks new request */
; hcm = null & ch1[i] != null ==>
; begin
; hcm := ch1[i];
; ch1[i] := null;
; hcc := i;
; for j: ID do
; hil[j] := hsl[j];
; end;
; end;
; rule "4" /* home sends invalidate message */
; hil[i] & ch2[i] = null & ((hcm = req_sh & heg) | hcm = req_ex) ==>
; begin
; ch2[i] := inv;
; hil[i] := false;
; end;
; rule "5" /* home receives invalidate acknowledgement */
; hcm != null & ch3[i] = inv_ack ==>
; begin
; hsl[i] := false;
; heg := false;
; ch3[i] := null;
; end;
; rule "6" /* sharer invalidates cache */
; ch2[i] = inv & ch3[i] = null ==>
; begin
; ch2[i] := null;
; ch3[i] := inv_ack;
; c[i] := I;
; end;
; rule "7" /* client receives shared grant */
; ch2[i] = gr_sh ==>
; begin
; c[i] := S;
; ch2[i] := null;
; end;
; rule "8" /* client receives exclusive grant */
; ch2[i] = gr_ex ==>
; begin
; c[i] := E;
; ch2[i] := null;
; end;
; end; /* ruleset */
; rule "9" /* home grants share */
; hcm = req_sh & !heg & ch2[hcc] = null ==>
; begin
; hsl[hcc] := true;
; hcm := null;
; ch2[hcc] := gr_sh;
; end;
; rule "10" /* home grants exclusive */
; hcm = req_ex & (forall i: ID do hsl[i] = false end) & ch2[hcc] = null ==>
; begin
; hsl[hcc] := true;
; hcm := null;
; heg := true;
; ch2[hcc] := gr_ex;
; end;
; startstate
; begin
; for i: ID do
; ch1[i] := null;
; ch2[i] := null;
; ch3[i] := null;
; c[i] := I;
; hsl[i] := false;
; hil[i] := false;
; end;
; hcm := null;
; hcc := undefined;
; heg := false;
; end;
; Invariant
; forall i: ID do
; c[i] = E ->
; forall j: ID do
; j != i -> c[j] = I
; end
; end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 1: Starting Macros and Other stuff ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now let us begin. I use the records book all over the place as it allows us
;; to conveniently model states and vectors.
(include-book "misc/records" :dir :system)
;; I define the predicate memberp below since I hate the fact that ACL2's
;; member function is not a boolean, that is, does not always return T or
;; NIL. But this might not be important anyways. I am doing it more out of
;; habit than anything else.
(defun memberp (e x)
(cond ((endp x) NIL)
((equal e (first x)) T)
(t (memberp e (rest x)))))
;; I think of the input as a record of two things, namely the index of the
;; process taking the next step, and the action to be taken by the
;; process. That is, it says which process index is being processed and which
;; action is being taken on behalf of that process.
(defmacro pid (stimulus) `(g :pid ,stimulus))
(defmacro action (stimulus) `(g :action ,stimulus))
;; I have several local variables that I need to access. I hate having to write
;; g in my code, so I define some macros to hide g. This also allows me to sort
;; of "declare" variables.
(defmacro clients (st) `(g :clients ,st))
(defmacro ch1 (st) `(g :ch1 ,st))
(defmacro ch2 (st) `(g :ch2 ,st))
(defmacro ch3 (st) `(g :ch3 ,st))
(defmacro hcm (st) `(g :hcm ,st))
(defmacro hil (st) `(g :hil ,st))
(defmacro hsl (st) `(g :hsl ,st))
(defmacro heg (st) `(g :heg ,st))
(defmacro hcc (st) `(g :hcc ,st))
;; I created this macro update for specifically allowing me to write chains to
;; s. I want to be able to write such a chain and still be able to read it!!
(defun update-macro (upds result)
(declare (xargs :guard (keyword-value-listp upds)))
(if (endp upds) result
(update-macro (cddr upds)
(list 's (car upds) (cadr upds) result))))
(defmacro update (old &rest updates)
(declare (xargs :guard (keyword-value-listp updates)))
(update-macro updates old))
(defmacro >st (&rest upds) `(update st ,@upds))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 2: Modeling the German Protocol ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Here are some functions. These are used for updating all indices together
;; when that is appropriate.
(defun set-hil-hsl (keys hil hsl)
(if (endp keys) hil
(s (first keys)
(g (first keys) hsl)
(set-hil-hsl (rest keys) hil hsl))))
(defun all-false (keys hsl)
(if (endp keys) T
(and (not (g (first keys) hsl))
(all-false (rest keys) hsl))))
;; The constant constrained function (keys) below specifies the set of process
;; indices. I have left it as a constrained function so that I can conveniently
;; add hypothesis on keys as necessary (for example we might have to add that
;; keys does not contain nil, or that it is a set of natural numbers, or
;; whatever). But my goal is to prove the protocol imposing as few constraints
;; on keys as possible. To that end, whenever we need to add a constraint I
;; should add an explanatory note saying why the constraint is necessary.
(encapsulate
(((keys) => *))
(local (defun keys () nil)))
;; Here is the state transition function for the protocol. In the original
;; Murphy version (as per my understanding) there were rules which were akin to
;; guarded commands. That is, an action could be taken if the guard for the
;; action was satisfied. In ACL2 we model that as follows. I name each action
;; (the names being based on the comments in the Murphy code and somewhat
;; arbitrary). An input stimulus specifies what action is to be taken. That is,
;; it specifies the name of the action that the system should execute. If the
;; action's guards are satisfied then the action is taken. Otherwise the
;; execution of the action is identity.
(defun german-step (st stimulus)
(let* ((action (action stimulus))
(pid (pid stimulus))
(keys (keys))
(clients (clients st))
(ch1 (ch1 st))
(ch2 (ch2 st))
(ch3 (ch3 st))
(hcm (hcm st))
(hsl (hsl st))
(hil (hil st))
(heg (heg st))
(hcc (hcc st)))
(if (not (memberp pid keys))
;; The reader might be surprised by this condition. I allow the
;; external stimulus to ask *any* process to take a step. In particular
;; that means I allow "garbage" processes. But since we are not
;; modeling processes joining the protocol, I am assuming that this
;; means when I ask a garbage process to make a step then the result is
;; a no-op.
st
(cond (;; Rule 1:
(and (equal action :request-shared-access)
(equal (g pid clients) :idle)
(not ch1))
(>st :ch1
(s pid :req-shared-access ch1)))
(;; Rule 2:
(and (equal action :request-exclusive-access)
(equal (g pid clients) :idle)
(not ch1))
(>st :ch1 (s pid :req-exclusive-access ch1)))
(;; Rule 3:
(and (equal action :pick-new-request)
(not hcm)
(g pid ch1))
(>st :hcm (g pid ch1)
:ch1 (s pid NIL ch1)
:hcc pid
:hil (set-hil-hsl keys hil hsl)))
(;; Rule 4:
(and (equal action :home-sends-invalidate)
(g pid hil)
(not (g pid ch2))
(or (and (equal hcm :req-shared-access)
heg)
(equal hcm :req-exclusive-access)))
(>st :ch2 (s pid :invalidate ch2)
:hil (s pid NIL hil)))
(;; Rule 5:
(and (equal action :home-receives-invalidate)
hcm
(equal (g pid ch3) :invalidate-ack))
(>st :hsl (s pid NIL hsl)
:heg NIL
:ch3 (s pid NIL ch3)))
(;; Rule 6:
(and (equal action :sharer-invalidate-cache)
(equal (g pid ch2) :invalidate)
(not (g pid ch3)))
(>st :ch2 (s pid NIL ch2)
:ch3 (s pid :invalidate-ack ch3)
:clients (s pid :idle clients)))
(;; Rule 7:
(and (equal action :client-receives-shared)
(equal (g pid ch2) :grant-shared))
(>st :clients (s pid :shared clients)
:ch2 (s pid NIL ch2)))
(;; Rule 8:
(and (equal action :client-receives-exclusive)
(equal (g pid ch2) :grant-exclusive))
(>st :clients (s pid :exclusive clients)
:ch2 (s pid NIL ch2)))
(;; Rule 9:
(and (equal action :home-grants-shared)
(equal hcm :req-shared-access)
(not heg)
(not (g hcc ch2)))
(>st :hsl (s hcc T hsl)
:hcm NIL
:ch2 (s hcc :grant-shared ch2)))
(;; Rule 10
(and (equal action :home-grants-exclusive)
(equal hcm :req-exclusive-access)
(all-false keys hsl)
(not (g hcc ch2)))
(>st :hsl (s hcc T hsl)
:hcm nil
:heg T
:ch2 (s hcc :grant-exclusive ch2)))
(t st)))))
;; And finally the initial state (init). All state variables are nil other
;; than the clients which are all :idle. I dont know if this latter
;; restriction is important or not, but I tried to model it as per the Murphy
;; definition.
(defun initial-clients (keys)
(if (endp keys) nil
(let ((clients (initial-clients (rest keys))))
(s (first keys) :idle clients))))
(defthm initial-clients-idle
(implies (memberp i keys)
(equal (g i (initial-clients keys)) :idle)))
(defun init () (s :clients (initial-clients (keys)) nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3: The Coherence predicate and Its proof ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; OK so we have now modeled the german protocol (at least as best as I could
;; based on my interpretation of the Murphy code above). We will now prove
;; that the german protocol has coherence. To do so, I will define a predicate
;; called coherent and show that it is an invariant of the model.
;; How do we define coherent? One way might be to define recursive functions
;; and such. Since the recursive functions do not seem to provide too much
;; additional simplicity, I prefer to define it as a person doing hand-proof
;; would naturally do, namely via quantification. Note that the predicate is
;; exactly a formalization in ACL2 of the Murphy description of the invariant.
(defun-sk coherent-processes (keys clients)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(not (equal i j))
(equal (g i clients) :exclusive))
(equal (g j clients) :idle))))
(defun coherent (st) (coherent-processes (keys) (clients st)))
(local (defthm |initial state is coherent| (coherent (init))))
;; coherent as defined above is an invariant (or so I believe) but is of course
;; not an inductive invariant. For example consider rule 8. The transition
;; following rule 8 does preserve coherence, but assuming coherent for the
;; state from which the transition occurs is not sufficient. We need more.
;; Here is how I will do it. I will start with a set of predicates (initially
;; only the predicate coherent). For each predicate P, in order to prove (P
;; (german-step s i)), we probably might need to assume (and (P s) (Q s)).
;; Then I have added Q to my set of predicates. I continue this process until
;; no other predicate needs to be added to the set. My final inductive
;; invariant then is a conjunction of all the predicates I have created so far.
;; Note: When I define a predicate we immediately prove that the predicate
;; holds for the initial state init. This is a sanity check and also takes
;; care of the base cases of the inductive invariant proof on the fly.
;; For each predicate that I handle I will divide the proof of its invariance
;; in three parts. The first part is what I call "default cases". The
;; predicate holds in these cases merely since the state components which
;; govern the predicate are not modified by german-step. For example, one
;; default case for every predicate we consider is the case where the action is
;; not a legal action. Then according to the protocol above the system state
;; does not change. Thus the predicate holds after the step simply because it
;; used to hold before.
;; The second case involves some property of the predicate we are checking.
;; For example, consider the situation of coherence when the sharer invalidates
;; cache. It sets its the client to idle and hence coherence cannot change.
;; This depends on the property of coherence that setting something to :idle or
;; :shared does not change it. I will prove this property and then handle this
;; case.
;; The third case is when the predicate P holds after a step from s principally
;; because not only P but some other predicate Q holds in s. I will then
;; define Q (and show it holds for the initial state) and then prove this case.
;; This is the toughest part of all in an invariant proof and of course it is
;; possible that the predicates I come up with are not optimal and I realize
;; that later. I will try to minimize the roll-back as much as possible
;; principally because I do not want to spend too much time on this system and
;; I am doing this principally to document how such a proof is done in ACL2, so
;; that the particular predicates are possibly of less importance here.
;; All right back to work. Whenever I define something using quantification I
;; disable the definition and all associated lemmas that were introduced,
;; because I want to have control on how they are used in a proof process. For
;; example I dont want to see a "witness" until I am ready and understand what
;; the witness means in a context. So I deal with quantifiers principally via
;; :use hints.
(local (in-theory (disable coherent-processes coherent-processes-necc)))
;; default cases are pretty simple.
(local
(defthm |coherent default cases|
(implies (and (coherent st)
(not (equal (action stimulus) :sharer-invalidate-cache))
(not (equal (action stimulus) :client-receives-shared))
(not (equal (action stimulus) :client-receives-exclusive)))
(coherent (german-step st stimulus)))))
;; We are now left with 6, 7, and 8. Now 6 is easy. In 6, a client simply
;; sets itself to :idle. If the processes were coherent before then they would
;; still be coherent.
;; Note: This proof is a classic example of how (universal) quantification
;; proofs go. I assume coherence and want to show that it holds after setting
;; i to :idle. How do we do that? To understand this, let us understand
;; clearly how a (universal) quantification works. To prove a universal
;; quantification of a property I must prove that the property holds for an
;; arbitrary object called the witness of the property. Here the witness is a
;; pair of process indices, and what I must show is that if one is :exclusive
;; then the other is :idle. Thus, it is convenient to think of it this way:
;; ACL2 is presenting us with two process indices and daring us to show that
;; the above property holds after I set i to :idle. Now I of course know that
;; before setting this index coherence was holding (since I am proving an
;; implication). Thus *before setting idle* for any two processes p and q if
;; one were exclusive then the other was idle. Now I will basically do the
;; following. I will ask if the index being set, that is, i, is one of the two
;; indices that acl2 is going to present me with. If not then ACL2 is giving
;; us two other indices and thus if one is exclusive the other is shared by
;; virtue of coherence before setting. That leaves us with two cases. First,
;; ACL2 can claim that i is the index of an :exclusive process and dare us to
;; show that every other j is :idle. I can dispatch this case by saying that
;; since I have just set i to :idle, i cannot be :exclusive in the first place.
;; The second is that ACL2 can claim that there is some process which is
;; exclusive and say that show that i is :idle. This case also leaves nothing
;; to be done since I know that i is :idle.
;; The above analysis might appear to be too tedious and difficult to do every
;; time. But it is indeed pretty mechanical. I proved the theorem with the
;; hints below even before I really thought why I gave those hints. The rule
;; of the thumb is as follows. If you know that some property holds before
;; setting a process index to something then do a :cases hint on whether the
;; witness *after* the setting is the index that has been just set. If there
;; are more than one witnesses then do a case hint on each. For each of the
;; cases, just use the definition of the property as a hint and use the -necc
;; lemma for the previous state, setting the quantified variables (i and j in
;; this case) to be the corresponding witnesses for the variables after the
;; update.
(local
(defthm coherent-after-setting-idle
(implies (coherent-processes keys clients)
(coherent-processes keys (s i :idle clients)))
:hints
(("Goal"
:cases
((equal
i
(mv-nth 1
(coherent-processes-witness keys (s i :idle clients))))
(equal i (car (coherent-processes-witness keys (s i :idle clients))))))
("Subgoal 1"
:in-theory (enable coherent-processes)
:use
((:instance
coherent-processes-necc
(i (car (coherent-processes-witness keys (s i :idle clients))))
(j (mv-nth 1 (coherent-processes-witness keys (s i :idle clients)))))))
("Subgoal 2"
:in-theory (enable coherent-processes)
:use
((:instance
coherent-processes-necc
(i (car (coherent-processes-witness keys (s i :idle clients))))
(j (mv-nth 1 (coherent-processes-witness keys (s i :idle clients)))))))
("Subgoal 3"
:use
((:instance (:definition coherent-processes)
(clients (s i :idle clients)))
(:instance
coherent-processes-necc
(i (car (coherent-processes-witness keys (s i :idle clients))))
(j (mv-nth 1 (coherent-processes-witness keys
(s i :idle clients))))))))))
(local
(defthm |coherent after rule 6|
(implies (and (coherent st)
(equal (action stimulus) :sharer-invalidate-cache))
(coherent (german-step st stimulus)))))
;; So we are now left with rules 7 and 8. We need to look carefully at these
;; rules. If the action is :client-receives-shared then why is coherent
;; preserved? The reason is that in the state when a system can execute rule 7,
;; (that is, when the channel 2 has :grant-shared in it for some client), all
;; clients are either :idle or :shared (or at least I hope so). This fact can
;; be codified by the predicate ch2-client-invariant below.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk ch2-client-shared (ch2 keys clients)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(equal (g i ch2) :grant-shared))
(or (equal (g j clients) :shared)
(equal (g j clients) :idle))))))
(local
(defun ch2-client-shared-invariant (st)
(ch2-client-shared (ch2 st) (keys) (clients st))))
(local (defthm |init has ch2-shared| (ch2-client-shared-invariant (init))))
(local (in-theory (disable ch2-client-shared ch2-client-shared-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The following theorem saves us some :use hints since we would often be
;; checking if a client is :exclusive.
(local
(defthm ch2-client-shared-implies-not-exclusive
(implies (and (ch2-client-shared ch2 keys clients)
(memberp i keys)
(memberp j keys)
(equal (g i ch2) :grant-shared))
(equal (equal (g j clients) :exclusive) NIL))
:hints (("Goal"
:use ch2-client-shared-necc))))
(local
(defthm coherent-after-setting-shared
(implies (and (ch2-client-shared ch2 keys clients)
(memberp i keys)
(equal (g i ch2) :grant-shared))
(coherent-processes keys (s j :shared clients)))
:hints (("Goal"
:in-theory (enable coherent-processes)
:cases ((equal j
(car (coherent-processes-witness
keys (s j :shared clients))))))
("Subgoal 2"
:use ((:instance (:definition coherent-processes)
(clients (s j :shared clients))))))))
;; OK so now we can prove that execution of rule 7 gives us a coherent state.
(local
(defthm |coherent after rule 7|
(implies (and (ch2-client-shared-invariant st)
(coherent st)
(equal (action stimulus) :client-receives-shared))
(coherent (german-step st stimulus)))))
;; I define the similar predicate ch2-client-exclusive-invariant that lets us
;; show coherent for rule 8.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk ch2-client-exclusive (ch2 keys clients)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(equal (g i ch2) :grant-exclusive))
(equal (g j clients) :idle)))))
(local
(defun ch2-client-exclusive-invariant (st)
(ch2-client-exclusive (ch2 st) (keys) (clients st))))
(local
(defthm |init has ch2-exclusive| (ch2-client-exclusive-invariant (init))))
(local
(in-theory (disable ch2-client-exclusive ch2-client-exclusive-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm ch2-exclusive-means-idle
(implies (and (ch2-client-exclusive ch2 keys clients)
(memberp i keys)
(memberp j keys)
(equal (g i ch2) :grant-exclusive))
(equal (g j clients) :idle))
:hints (("Goal"
:use ch2-client-exclusive-necc))))
(local
(defthm ch2-exclusive-means-set-idle
(implies (and (ch2-client-exclusive ch2 keys clients)
(memberp i keys)
(memberp m keys)
(memberp n keys)
(equal (g i ch2) :grant-exclusive))
(equal (g m (s n v clients)) (if (equal m n) v :idle)))))
(local
(defthm |ch2-exclusive causes coherence|
(implies (and (ch2-client-exclusive ch2 keys clients)
(memberp i keys)
(equal (g i ch2) :grant-exclusive))
(coherent-processes keys (s j :exclusive clients)))
:hints (("Goal"
:in-theory (enable coherent-processes)
:cases
((equal
j
(car (coherent-processes-witness
keys (s j :exclusive clients)))))))))
;; Now of course rule 8 should just go through.
(local
(defthm |coherent after rule 8|
(implies (and (ch2-client-exclusive-invariant st)
(coherent st)
(equal (action stimulus) :client-receives-exclusive))
(coherent (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of Coherence ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Of course we have now done the coherence, but we now have two other
;; predicates that we need to prove as invariants. They are
;; ch2-client-shared-invariant and ch2-client-exclusive-invariant. I must now
;; prove that these persist too, and in the process add more predicates. I
;; will have a section for each predicate I prove (rather a subsection to
;; Section 3), and each proof will end with a comment "End Proof of ....".
;; This is principally so that I can efficiently search in emacs for the proofs
;; of the predicates I have done.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.1: Proof of ch2-client-shared-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The default cases as usual.
(local
(defthm |ch2 shared default cases|
(implies (and (ch2-client-shared-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(ch2-client-shared-invariant (german-step st stimulus)))))
;; Let us now first take care of sharer-invalidate-cache. This works because
;; if I set something to :idle then nothing changes in terms of what has
;; shared.
(local
(defthm ch2-shared-if-idle
(implies (and (ch2-client-shared ch2 keys clients)
(not (equal val :grant-shared)))
(ch2-client-shared (s i val ch2) keys (s j :idle clients)))
:hints
(("Goal"
:cases
((equal
i
(car (ch2-client-shared-witness
(s i val ch2) keys (s j :idle clients))))
(equal
j
(mv-nth 1 (ch2-client-shared-witness (s i val ch2) keys
(s j :idle clients))))))
("Subgoal 2"
:in-theory (enable ch2-client-shared))
("Subgoal 1"
:in-theory (enable ch2-client-shared))
("Subgoal 3"
:use
((:instance (:definition ch2-client-shared)
(clients (s j :idle clients))
(ch2 (s i val ch2)))
(:instance
ch2-client-shared-necc
(i (car (ch2-client-shared-witness (s i val ch2) keys
(s j :idle clients))))
(j (mv-nth 1 (ch2-client-shared-witness (s i val ch2)
keys
(s j :idle clients))))))))))
(local
(defthm |ch2-shared if sharer-invalidate|
(implies (and (ch2-client-shared-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(ch2-client-shared-invariant (german-step st stimulus)))))
;; Now let us take the other cases in turn. For the case
;; :home-sends-invalidate for example, we know that ch2-client-shared-invariant
;; still holds after the action if it held before. This is because if we
;; change ch2 to something other than :grant-shared the
;; ch2-client-shared-invariant does not change. Let us first prove this fact.
(local
(defthm ch2-client-shared-after-arbitrary
(implies (and (not (equal val :grant-shared))
(ch2-client-shared ch2 keys clients))
(ch2-client-shared (s pid val ch2) keys clients))
:hints (("Goal"
:cases
((equal
(car (ch2-client-shared-witness (s pid val ch2) keys clients))
pid)))
("Subgoal 2"
:use
((:instance (:definition ch2-client-shared)
(ch2 (s pid val ch2)))
(:instance
ch2-client-shared-necc
(i (car (ch2-client-shared-witness (s pid val ch2) keys
clients)))
(j (mv-nth 1 (ch2-client-shared-witness (s pid val ch2) keys
clients))))))
("Subgoal 1"
:use
((:instance (:definition ch2-client-shared)
(ch2 (s pid val ch2)))
(:instance
ch2-client-shared-necc
(i (car (ch2-client-shared-witness (s pid val ch2) keys
clients)))
(j (mv-nth 1 (ch2-client-shared-witness (s pid val ch2) keys
clients)))))))))
;; While we are at it, we might also prove that if a client is set to :shared
;; then the invariant remains.
(local
(defthm |ch2-client-shared after setting shared|
(implies (and (ch2-client-shared ch2 keys clients)
(equal (g i ch2) :grant-shared))
(ch2-client-shared ch2 keys (s j :shared clients)))
:hints (("Goal"
:cases
((equal
j
(mv-nth 1
(ch2-client-shared-witness
ch2 keys (s j :shared clients))))))
("Subgoal 2"
:use
((:instance
(:definition ch2-client-shared)
(clients (s j :shared clients)))
(:instance
ch2-client-shared-necc
(i (car (ch2-client-shared-witness
ch2 keys (s j :shared clients))))
(j (mv-nth
1 (ch2-client-shared-witness
ch2
keys (s j :shared clients)))))))
("Subgoal 1"
:use
((:instance
(:definition ch2-client-shared)
(clients (s j :shared clients)))
(:instance
ch2-client-shared-necc
(i (car (ch2-client-shared-witness
ch2 keys (s j :shared clients))))
(j (mv-nth
1 (ch2-client-shared-witness
ch2
keys (s j :shared clients))))))))))
;; OK this takes care of three of the 5 non-trivial cases of the
;; ch2-client-shared-invariant as shown below.
(local
(defthm |ch2 shared invariant after no grants-shared set|
(implies (and (ch2-client-shared-invariant st)
(memberp (action stimulus) '(:home-grants-exclusive
:client-receives-shared
:home-sends-invalidate)))
(ch2-client-shared-invariant (german-step st stimulus)))))
;; That leaves us with two cases, namely :home-grants-shared and
;; :client-receives-exclusive. Let us look at :home-grants-shared. Why is
;; this going to satisfy ch2-client-shared-invariant? The reason is that when
;; heg is nil every client has status shared or idle.
;; I add this fact as another predicate, since this is a new fact about the
;; system that is not covered by the predicates we have created so far. The
;; predicate is specified below.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk not-heg-clients-shared (heg keys clients)
(forall i
(implies (and (not heg)
(memberp i keys))
(or (equal (g i clients) :shared)
(equal (g i clients) :idle))))))
(local
(defun not-heg-clients-shared-invariant (st)
(not-heg-clients-shared (heg st) (keys) (clients st))))
(local
(defthm |init has not-heg-shared|
(not-heg-clients-shared-invariant (init))))
(local
(in-theory (disable not-heg-clients-shared not-heg-clients-shared-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; And clearly if this predicate holds then ch2-client-shared holds trivially.
(local
(defthm not-heg-clients-shared-implies-ch2-shared
(implies (and (not-heg-clients-shared heg keys clients)
(not heg))
(ch2-client-shared ch2 keys clients))
:hints (("Goal"
:use
((:instance (:definition ch2-client-shared))
(:instance
not-heg-clients-shared-necc
(i (mv-nth 1 (ch2-client-shared-witness ch2 keys clients)))))))))
(local
(defthm |ch2 shared invariant after home grants shared|
(implies (and (ch2-client-shared-invariant st)
(not-heg-clients-shared-invariant st)
(equal (action stimulus) :home-grants-shared))
(ch2-client-shared-invariant (german-step st stimulus)))))
;; The question of grant-exclusive is more interesting. What do we want in
;; this case? We want to say that in case of a :grant-exclusive all other
;; channels have nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk channel-nil-exclusive (ch2 keys)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(not (equal i j))
(equal (g i ch2) :grant-exclusive))
(equal (g j ch2) nil)))))
(local
(defun channel-nil-exclusive-invariant (st)
(channel-nil-exclusive (ch2 st) (keys))))
(local
(defthm |init has channel-nil-exclusive|
(channel-nil-exclusive-invariant (init))))
(local
(in-theory (disable channel-nil-exclusive
channel-nil-exclusive-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Why does channel-nil-invariant allow us to prove
;; ch2-client-shared-invariant? Well, the point is that if ch2-nil-invariant
;; holds then there is no channel that has value :grant-shared. Let us prove
;; this.
(local
(defthm channel-nil-for-exclusiv-implies-not-anything-else
(implies (and (channel-nil-exclusive ch2 keys)
(memberp i keys)
(equal (g i ch2) :grant-exclusive)
(memberp j keys))
(equal (g j ch2)
(if (equal i j) :grant-exclusive nil)))
:hints (("Goal"
:use channel-nil-exclusive-necc))))
(local
(defthm channel-nil-implies-ch2-client-shared
(implies (and (channel-nil-exclusive ch2 keys)
(memberp i keys)
(not (equal a :grant-shared))
(equal (g i ch2) :grant-exclusive))
(ch2-client-shared (s j a ch2)
keys
(s j b clients)))
:hints (("Goal"
:cases ((equal j (car (ch2-client-shared-witness
(s j a ch2)
keys
(s j b clients))))))
("Subgoal 1"
:in-theory (enable ch2-client-shared))
("Subgoal 2"
:in-theory (enable ch2-client-shared)))))
(local
(defthm |ch2-shared after client-receives-exclusive|
(implies (and (ch2-client-shared-invariant st)
(channel-nil-exclusive-invariant st)
(equal (action stimulus) :client-receives-exclusive))
(ch2-client-shared-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of ch2-client-shared-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.2: Proof of ch2-client-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |ch2 exclusive default cases|
(implies (and (ch2-client-exclusive-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:client-receives-shared
:client-receives-exclusive
:sharer-invalidate-cache
:home-grants-shared
:home-grants-exclusive))))
(ch2-client-exclusive-invariant (german-step st stimulus)))))
;; Now here is a property of ch2-client-exclusive. If it holds for a state
;; then I can set ch2 of any process to a value other than :grant-exclusive and
;; set any client to :idle and the predicate is still going to hold. This
;; takes care of sharer-invalidate-cache when I set ch2 to nil and the client
;; to :idle.
(local
(defthm ch2-exclusive-if-idle
(implies (and (ch2-client-exclusive ch2 keys clients)
(not (equal val :grant-exclusive)))
(ch2-client-exclusive (s i val ch2) keys (s j :idle clients)))
:hints
(("Goal"
:cases
((equal
i
(car (ch2-client-exclusive-witness
(s i val ch2) keys (s j :idle clients))))
(equal
j
(mv-nth 1 (ch2-client-exclusive-witness (s i val ch2) keys
(s j :idle clients))))))
("Subgoal 2"
:in-theory (enable ch2-client-exclusive))
("Subgoal 1"
:in-theory (enable ch2-client-exclusive))
("Subgoal 3"
:use
((:instance (:definition ch2-client-exclusive)
(clients (s j :idle clients))
(ch2 (s i val ch2)))
(:instance
ch2-client-exclusive-necc
(i (car (ch2-client-exclusive-witness (s i val ch2) keys
(s j :idle clients))))
(j (mv-nth 1 (ch2-client-exclusive-witness (s i val ch2)
keys
(s j :idle clients))))))))))
(local
(defthm |ch2-exclusive if sharer-invalidate|
(implies (and (ch2-client-exclusive-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(ch2-client-exclusive-invariant (german-step st stimulus)))))
;; Notice however, that the property above does not let us prove things for
;; (say) home-sends-invalidate. This is because in that condition the client
;; is not changed. So we will prove also the lemma that says that we are fine
;; if the client is not changed. This is in fact an easier property than the
;; one we proved before, but we need to prove it anyways. Maybe I could have
;; generalized the property above a little bit and saved myself this lemma.
;; But I dont bother since I am lazy.
(local
(defthm ch2-client-exclusive-after-arbitrary
(implies (and (not (equal val :grant-exclusive))
(ch2-client-exclusive ch2 keys clients))
(ch2-client-exclusive (s pid val ch2) keys clients))
:hints
(("Goal"
:cases
((equal
(car (ch2-client-exclusive-witness (s pid val ch2) keys clients))
pid)))
("Subgoal 2"
:use
((:instance (:definition ch2-client-exclusive)
(ch2 (s pid val ch2)))
(:instance
ch2-client-exclusive-necc
(i (car (ch2-client-exclusive-witness (s pid val ch2) keys clients)))
(j (mv-nth 1 (ch2-client-exclusive-witness
(s pid val ch2) keys clients))))))
("Subgoal 1"
:use
((:instance (:definition ch2-client-exclusive)
(ch2 (s pid val ch2)))
(:instance
ch2-client-shared-necc
(i (car (ch2-client-exclusive-witness (s pid val ch2) keys clients)))
(j (mv-nth 1 (ch2-client-exclusive-witness
(s pid val ch2) keys clients)))))))))
;; This now allows us to prove that ch2-client-exclusive-invariant holds under
;; the actions :home-grants-shared and :home-sends-invalidate.
(local
(defthm |ch2 exclusive for invalidate and shared|
(implies (and (ch2-client-exclusive-invariant st)
(memberp (action stimulus)
'(:home-grants-shared
:home-sends-invalidate)))
(ch2-client-exclusive-invariant (german-step st stimulus)))))
;; Now we are left with three cases, namely client-receives-shared,
;; client-receives-exclusive, and home-grants-exclusive. Why do these cases
;; work? For the first I will use the property that if there is a
;; :grant-exclusive in a channel then all others have nil. In other words I
;; would make use of the channel-nil-exclusive-invariant that I had already
;; defined.
;; Let us first do the case where client is getting shared. Now why does
;; ch2-client-exclusive-invariant hold in this case? Well, there are two cases.
;; Suppose that there was an index having :grant-exclusive in the channel.
;; Then I know that no other channel has :grant-shared (and thus the system
;; does not take a step) so we are done. Otherwise, there is no
;; :grant-exclusive, and thus after taking a step there is still no
;; grant-exclusive and hence we are done.
;; The analysis above suggests that we can define a predicate called
;; no-grant-exclusive to check if there is no grant-exclusive or not, and then
;; use that to prove the persistence of ch2-client-exclusive-invariant. Notice
;; that we are defining this predicate to simplify our reasoning, but this
;; predicate follows in our cases for channel-nil-exclusive. So this is not a
;; new predicate that goes in the definition of the inductive invariant.
;; Indeed, if I am willing to think harder and type more I can get rid of the
;; definition as well.
(local
(defun-sk no-grant-exclusive (keys ch2)
(forall i
(implies (memberp i keys)
(not (equal (g i ch2) :grant-exclusive))))))
(local (in-theory (disable no-grant-exclusive no-grant-exclusive-necc)))
;; Now we first prove that if there is no grant-exclusive then
;; ch2-client-exclusive-invariant holds.
(local
(defthm no-grant-exclusive-implies-ch2-exclusive
(implies (no-grant-exclusive keys ch2)
(ch2-client-exclusive ch2 keys clients))
:hints
(("Goal"
:in-theory (enable ch2-client-exclusive)
:use
((:instance
no-grant-exclusive-necc
(i (car (ch2-client-exclusive-witness ch2 keys clients)))))))))
;; Now we will show that if no-grant-exclusive does not hold that is, if there
;; is some process with :grant-exclusive and there is some other which has some
;; other value then ch2-client-exclusive-invariant does not hold.
(local
(defthm not-grant-exclusive-and-something-implies-not-invariant
(implies (and (not (no-grant-exclusive keys ch2))
(g i ch2)
(memberp i keys)
(not (equal (g i ch2) :grant-exclusive)))
(equal (channel-nil-exclusive ch2 keys) NIL))
:hints (("Goal"
:in-theory (enable no-grant-exclusive)
:use ((:instance channel-nil-exclusive-necc
(i (no-grant-exclusive-witness keys ch2))
(j i)))))))
;; Finally, no-grant-exclusive must mean that after setting a channel to NIL,
;; we still have that property.
(local
(defthm no-grant-after-setting-channel
(implies (no-grant-exclusive keys ch2)
(no-grant-exclusive keys (s i nil ch2)))
:hints
(("Goal"
:use
((:instance (:definition no-grant-exclusive)
(ch2 (s i nil ch2)))
(:instance
no-grant-exclusive-necc
(i (no-grant-exclusive-witness keys (s i nil ch2))))))
("Goal'"
:cases
((equal i (no-grant-exclusive-witness keys (s i nil ch2))))))))
;; Now of course I am done by simply splitting the two cases about whether
;; no-grants-exclusive holds or not.
(local
(defthm |ch2 exclusive for client sharing|
(implies (and (ch2-client-exclusive-invariant st)
(channel-nil-exclusive-invariant st)
(equal (action stimulus) :client-receives-shared))
(ch2-client-exclusive-invariant (german-step st stimulus)))
:hints (("Goal"
:cases ((no-grant-exclusive (keys) (ch2 st)))))))
;; Now we are down to the two cases, which are home-grants-exclusive and
;; client-receives-exclusive. I look at client-receives-exclusive first since
;; that is simpler. Now when client-receives-exclusive, it sets channel to
;; nil, and client to exclusive. We need to ensure that for all channel i if i
;; has the value :grant-exclusive then every client is :idle. But since we are
;; setting every channel to nil, there is no channel with :grant-exclusive, and
;; therefore the invariant is trivial.
(local
(defthm ch2-exclusive-after-ch2-nil
(implies (and (channel-nil-exclusive ch2 keys)
(memberp i keys)
(memberp j keys)
(equal (g i ch2) :grant-exclusive))
(equal (g j (s i nil ch2)) NIL))
:hints (("Goal"
:cases ((equal j i))))))
(local
(defthm ch2-exclusive-after-ch2-nil-2
(implies (and (channel-nil-exclusive ch2 keys)
(equal (g j ch2) :grant-exclusive)
(memberp j keys))
(ch2-client-exclusive (s j nil ch2) keys (s m val clients)))
:hints
(("Goal"
:cases
((equal
j
(car (ch2-client-exclusive-witness
(s i nil ch2) keys (s m val clients))))))
("Subgoal 2"
:in-theory (enable ch2-client-exclusive))
("Subgoal 1"
:in-theory (enable ch2-client-exclusive)))))
(local
(defthm |ch2 exclusive for client exclusive|
(implies (and (ch2-client-exclusive-invariant st)
(channel-nil-exclusive-invariant st)
(equal (action stimulus) :client-receives-exclusive))
(ch2-client-exclusive-invariant (german-step st stimulus)))))
;; The last case, namely home-grants-exclusive. To do this one, what we need
;; to decide how home can manage to send an :invalidate in channel 2. Of
;; course this means that all processes must have channel 2 NIL.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hsl-client (keys clients hsl)
(if (endp keys) T
(and (implies (not (equal (g (first keys) clients) :idle))
(equal (g (first keys) hsl) T))
(hsl-client (rest keys) clients hsl)))))
(local
(defun hsl-client-invariant (st) (hsl-client (keys) (clients st) (hsl st))))
(local
(defthm hsl-client-set
(implies (hsl-client keys clients hsl)
(hsl-client keys (s i :idle clients) hsl))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm hsl-client-initial-client
(hsl-client keys (initial-clients keys) hsl)))
(local
(defthm |init has hsl-client|
(hsl-client-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm hsl-ch2-and-all-false
(implies (and (hsl-client keys clients hsl)
(all-false keys hsl)
(memberp i keys))
(equal (g i clients) :idle))))
(local
(defthm hsl-client-implies-ch2-exclusive
(implies (and (hsl-client keys clients hsl)
(all-false keys hsl))
(ch2-client-exclusive (s i v ch2) keys clients))
:hints (("Goal"
:in-theory (enable ch2-client-exclusive)))))
(local
(defthm |ch2-exclusive for home-grants-exclusive|
(implies (and (hsl-client-invariant st)
(ch2-client-exclusive-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(ch2-client-exclusive-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of ch2-client-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right. One more gone. The next predicate is
;; not-heg-clients-shared-invariant.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.3: Proof of not-heg-clients-shared-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |not heg shared default cases|
(implies (and (not-heg-clients-shared-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-exclusive))))
(not-heg-clients-shared-invariant (german-step st stimulus)))))
;; Now comes the analysis. At home-receives-invalidate, the heg is set to nil.
;; So why is the invariant holding here? The reason is that we can claim that
;; if ch3 has invalidate-ack then all clients are either :idle or :shared.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk invalidate-ack-clients (clients ch3 keys)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(equal (g i ch3) :invalidate-ack))
(or (equal (g j clients) :idle)
(equal (g j clients) :shared))))))
(local
(defun invalidate-ack-clients-invariant (st)
(invalidate-ack-clients (clients st) (ch3 st) (keys))))
(local
(defthm |init has invariant-ack-ch3|
(invalidate-ack-clients-invariant (init))))
(local
(in-theory (disable invalidate-ack-clients invalidate-ack-clients-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now I can claim that if invalidate-ack holds then
;; not-heg-clients-shared-invariant holds.
(local
(defthm invalidate-ack-implies-not-heg
(implies (and (invalidate-ack-clients clients ch3 keys)
(memberp i keys)
(equal (g i ch3) :invalidate-ack))
(not-heg-clients-shared val keys clients))
:hints
(("Goal"
:use
((:instance (:definition not-heg-clients-shared)
(heg val))
(:instance
invalidate-ack-clients-necc
(j (not-heg-clients-shared-witness val keys clients))))))))
(local
(defthm |heg-shared after home-receives-invalidate|
(implies (and (not-heg-clients-shared-invariant st)
(invalidate-ack-clients-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(not-heg-clients-shared-invariant (german-step st stimulus)))))
;; The next case is when client receives shared. This works because client of
;; course can receive as much shared as it wants, and nothing will happen to
;; this predicate.
(local
(defthm not-heg-clients-shared-remains-with-shared
(implies (and (not-heg-clients-shared heg keys clients)
(or (equal val :shared)
(equal val :idle)))
(not-heg-clients-shared heg keys (s i val clients)))
:hints
(("Goal"
:use
((:instance (:definition not-heg-clients-shared)
(clients (s i val clients)))
(:instance
not-heg-clients-shared-necc
(i (not-heg-clients-shared-witness heg keys (s i val clients))))))
("Goal'"
:cases
((equal i
(not-heg-clients-shared-witness heg keys
(s i val clients))))))))
;; So this should give me the case of client-receives-shared.
(local
(defthm |heg-shared after client-receives-shared|
(implies (and (not-heg-clients-shared-invariant st)
(memberp (action stimulus) '(:sharer-invalidate-cache
:client-receives-shared)))
(not-heg-clients-shared-invariant (german-step st stimulus)))))
;; What happens when client-receives-exclusive? What I need here is that when
;; ch2 has grant-exclusive then heg is T
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk heg-exclusive (heg keys ch2)
(forall i
(implies (and (memberp i keys)
(equal (g i ch2) :grant-exclusive))
heg))))
(local
(defun heg-exclusive-invariant (st) (heg-exclusive (heg st) (keys) (ch2 st))))
(local
(defthm |init has heg-exclusive| (heg-exclusive-invariant (init))))
(local (in-theory (disable heg-exclusive heg-exclusive-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm heg-exclusive-and-grant-implies-not-heg
(implies (and (heg-exclusive heg keys ch2)
(memberp i keys)
(equal (g i ch2) :grant-exclusive))
(not-heg-clients-shared heg keys (s j val clients)))
:hints (("Goal"
:use ((:instance (:definition not-heg-clients-shared)
(clients (s j val clients)))
(:instance heg-exclusive-necc))))))
(local
(defthm |heg shared after client-receives-exclusive|
(implies (and (not-heg-clients-shared-invariant st)
(heg-exclusive-invariant st)
(equal (action stimulus) :client-receives-exclusive))
(not-heg-clients-shared-invariant (german-step st stimulus)))))
;; One more to go. This is when home-grants-exclusive. This is the most
;; trivial of the lot. This holds because when home-grants-exclusive it sets
;; heg to T.
(local
(defthm heg-implies-anything-fine
(implies heg
(not-heg-clients-shared heg keys clients))
:hints (("Goal"
:in-theory (enable not-heg-clients-shared)))))
(local
(defthm |heg shared after home-grants-exclusive|
(implies (and (not-heg-clients-shared-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(not-heg-clients-shared-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of ch2-client-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right so I am done with not-heg-clients-shared-invariant. Now I come to
;; channel-nil-exclusive-invariant. This says that if one of the channels has
;; grant-exclusive then all other channels must be nil. To an extent this is a
;; pretty strong statement and almost is the statement of coherence stated in
;; terms of channels. So doing this is going to take some effort.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.4: Proof of channel-nil-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |channel-nil-exclusive default cases|
(implies (and (channel-nil-exclusive-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(channel-nil-exclusive-invariant (german-step st stimulus)))))
;; The next cases to consider are those in which the channel is set to nil.
;; Obviously if a channel is set to nil then nothing can change.
(local
(defthm channel-set-to-nil-implies-channel-nil
(implies (channel-nil-exclusive ch2 keys)
(channel-nil-exclusive (s i nil ch2) keys))
:hints
(("Goal"
:cases
((equal i (car (channel-nil-exclusive-witness (s i nil ch2)
keys)))
(equal i (mv-nth 1 (channel-nil-exclusive-witness (s i nil ch2)
keys)))))
("Subgoal 2"
:in-theory (enable channel-nil-exclusive))
("Subgoal 1"
:in-theory (enable channel-nil-exclusive))
("Subgoal 3"
:use
((:instance
channel-nil-exclusive-necc
(i (car (channel-nil-exclusive-witness (s i nil ch2)
keys)))
(j (mv-nth 1 (channel-nil-exclusive-witness (s i nil ch2)
keys))))
(:instance (:definition channel-nil-exclusive)
(ch2 (s i nil ch2))))))))
(local
(defthm |channels-nil when ch2 set to nil|
(implies (and (channel-nil-exclusive-invariant st)
(memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(channel-nil-exclusive-invariant (german-step st stimulus)))))
;; Now comes the three interesting cases. First is when home-grants-exclusive.
;; I should then know that all channels are nil. This works because I know
;; that all keys are false in hsl. As a result, all channels must be nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hsl-ch2 (hsl keys ch2)
(if (endp keys) T
(and (implies (g (first keys) ch2)
(equal (g (first keys) hsl) T))
(hsl-ch2 hsl (rest keys) ch2)))))
(local
(defun hsl-ch2-invariant (st) (hsl-ch2 (hsl st) (keys) (ch2 st))))
(local
(defthm hsl-ch2-nil (hsl-ch2 nil keys nil)))
(local (defthm |init has hsl-ch2| (hsl-ch2-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm hsl-ch2-and-all-false-implies-nil
(implies (and (hsl-ch2 hsl keys ch2)
(memberp i keys)
(all-false keys hsl))
(equal (g i ch2) nil))))
(local
(defthm hsl-ch2-implies-channel-nil-exclusive
(implies (and (hsl-ch2 hsl keys ch2)
(all-false keys hsl))
(channel-nil-exclusive (s i :grant-exclusive ch2) keys))
:hints (("Goal"
:cases ((equal i (car (channel-nil-exclusive-witness
(s i :grant-exclusive ch2) keys)))))
("Subgoal 2"
:in-theory (enable channel-nil-exclusive))
("Subgoal 1"
:in-theory (enable channel-nil-exclusive)))))
(local
(defthm |channel-nil-exclusive grant-exclusive|
(implies (and (channel-nil-exclusive-invariant st)
(hsl-ch2-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(channel-nil-exclusive-invariant (german-step st stimulus)))))
;; What happens when home-grants-shared? We know (not heg). Thus we
;; automatically know that there is no :grants-exclusive. Hence we have
;; nothing to prove.
(local
(defthm heg-exclusive-and-not-heg-implies-no-exclusive
(implies (and (heg-exclusive heg keys ch2)
(not heg)
(not (equal val :grant-exclusive)))
(channel-nil-exclusive (s i val ch2) keys))
:hints (("Goal"
:cases ((equal i (car (channel-nil-exclusive-witness
(s i val ch2) keys)))))
("Subgoal 2"
:use ((:instance heg-exclusive-necc
(heg nil)
(i (car (channel-nil-exclusive-witness
(s i val ch2) keys)))))
:in-theory (enable channel-nil-exclusive))
("Subgoal 1"
:use ((:instance heg-exclusive-necc
(heg nil)
(i (car (channel-nil-exclusive-witness
(s i val ch2) keys)))))
:in-theory (enable channel-nil-exclusive)))))
(local
(defthm |channel-nil-exclusive grant-shared|
(implies (and (channel-nil-exclusive-invariant st)
(heg-exclusive-invariant st)
(equal (action stimulus) :home-grants-shared))
(channel-nil-exclusive-invariant (german-step st stimulus)))))
;; A more interesting case, and in fact the last case for this predicate, will
;; come up now. This is when home-sends-invalidate. Now I should again know
;; that if (g i hil) holds and heg is T then for all j!=i (g j ch2) = NIL.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk hil-heg (keys hil ch2 heg)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(g i hil)
(not (equal i j))
heg)
(equal (g j ch2) nil)))))
;; BTW I believe this predicate can be generalized and made prettier. But I am
;; trying to write it in the most brain-dead way possible, since I am too tired
;; to think too much about it....:->
(local
(defun hil-heg-invariant (st) (hil-heg (keys) (hil st) (ch2 st) (heg st))))
(local (defthm |init has hil-heg| (hil-heg-invariant (init))))
(local (in-theory (disable hil-heg hil-heg-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm hil-heg-set-reduction
(implies (and (hil-heg keys hil ch2 heg)
heg
(g i hil)
(memberp i keys)
(memberp j keys))
(equal (g j (s i val ch2))
(if (equal i j) val nil)))
:hints (("Goal"
:use hil-heg-necc))))
(local
(defthm hil-heg-channels-nil
(implies (and (hil-heg keys hil ch2 heg)
heg
(g i hil)
(not (equal val :grant-exclusive))
(memberp i keys))
(channel-nil-exclusive (s i val ch2) keys))
:hints (("Goal"
:cases ((equal i (car (channel-nil-exclusive-witness
(s i val ch2) keys)))))
("Subgoal 1"
:in-theory (enable channel-nil-exclusive))
("Subgoal 2"
:in-theory (enable channel-nil-exclusive)))))
;; The above takes care of invalidation when heg is T. But what do we do when
;; heg is nil? In that case we know that there is no grant-exclusive. Thus
;; there is nothing to do.
(local
(defthm |channels-nil for invalidate|
(implies (and (channel-nil-exclusive-invariant st)
(hil-heg-invariant st)
(heg-exclusive-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(channel-nil-exclusive-invariant (german-step st stimulus)))
:hints (("Goal"
:cases ((heg st))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of channel-nil-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Done with this predicate. Now we move on to hsl-client-invariant. This
;; says that for all keys if the client is not idle then hsl has the value T.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.5: Proof of hsl-client-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hsl-client default cases|
(implies (and (hsl-client-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hsl-client-invariant (german-step st stimulus)))))
;; Of course the way hsl-client has been defined it does not matter if given
;; some hsl-client we set hsl to T.
(local
(defthm hsl-set-reduction
(implies (hsl-client keys clients hsl)
(hsl-client keys clients (s i t hsl)))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
;; This takes care of cases where hsl is set to T
(local
(defthm |hsl-clients if hsl set to T|
(implies (and (hsl-client-invariant st)
(memberp (action stimulus)
'(:home-grants-shared
:home-grants-exclusive)))
(hsl-client-invariant (german-step st stimulus)))))
;; Now we come to thhe non-trivial cases. These are the cases in which either
;; hsl is being set to NIL or client is being set. In either case we require
;; more predicates to show that hsl-client-invariant holds.
;; So why does the predicate hold after home-receives-invalidate? It holds
;; because if I set client to :idle I can do anything.
(local
(defthm hsl-idle-reduction
(implies (hsl-client keys clients hsl)
(hsl-client keys (s i :idle clients) hsl))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-clients if clients idle|
(implies (and (hsl-client-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(hsl-client-invariant (german-step st stimulus)))))
;; The second about when home sets hsl to nil. Here I must carry around as
;; invariant that the corresponding client was idle. But first let us prove
;; that if some client is idle then I can set any value to hsl.
(local
(defthm hsl-idle-reduction-2
(implies (and (hsl-client keys clients hsl)
(equal (g i clients) :idle))
(hsl-client keys clients (s i v hsl)))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
;; Now I must posit a predicate that stipulates that the client is idle. Why
;; do we know that? I must know that if some process has :invalidate-ack in
;; channel 3, then that client is idle. Notice that we had previously
;; specified that *all* clients are :shared or :idle in that case.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk invalidate-ack-idle (clients keys ch3)
(forall i
(implies (and (memberp i keys)
(equal (g i ch3) :invalidate-ack))
(equal (g i clients) :idle)))))
(local
(defun invalidate-ack-idle-invariant (st)
(invalidate-ack-idle (clients st) (keys) (ch3 st))))
(local
(defthm |init has invalidate-ack-idle|
(invalidate-ack-idle-invariant (init))))
(local
(in-theory (disable invalidate-ack-idle invalidate-ack-idle-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now why do I know that the client was idle? This is specified by
;; invalidate-ack. One of the things that invalidate-ack-clients was telling
;; us is that the client which has sent invalidate-ack is :idle.
(local
(defthm invalidate-ack-hsl
(implies (and (invalidate-ack-idle clients keys ch3)
(memberp i keys)
(equal (g i ch3) :invalidate-ack)
(hsl-client keys clients hsl))
(hsl-client keys clients (s i v hsl)))
:hints (("Goal"
:use ((:instance invalidate-ack-idle-necc))))))
(local
(defthm |hsl-clients if hsl set|
(implies (and (invalidate-ack-idle-invariant st)
(hsl-client-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hsl-client-invariant (german-step st stimulus)))))
;; All right now down to two more cases for this predicate. These are cases
;; where the client receives a value either shared or exclusive. Now in these
;; cases I know that hsl-ch2 covers me.
(local
(defthm hsl-ch2-set-reduction
(implies (and (hsl-ch2 hsl keys ch2)
(memberp i keys)
(g i ch2))
(equal (g i hsl) t))))
;; I should look into this proof carefully later if time. The proof works but
;; it does double induction, and I dont like double induction. So there might
;; be something I can do about it. Need to look at subgoal *1/2.
(local
(defthm hsl-ch2-set
(implies (and (equal (g i hsl) t)
(memberp i keys)
(hsl-client keys clients hsl))
(hsl-client keys (s i v clients) hsl))
:hints (("Subgoal *1/5"
:cases ((equal i (car keys)))))))
(local
(defthm hsl-hsl-client-packaged
(implies (and (hsl-ch2 hsl keys ch2)
(hsl-client keys clients hsl)
(memberp i keys)
(g i ch2))
(hsl-client keys (s i v clients) hsl))))
(local
(defthm |hsl-client for client-receives|
(implies (and (hsl-client-invariant st)
(hsl-ch2-invariant st)
(memberp (action stimulus) '(:client-receives-shared
:client-receives-exclusive)))
(hsl-client-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hsl-client-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Done with this one. Now we move on to invalidate-ack-clients-invariant. To
;; be honest this is is a little dicey as a predicate. I probably should have
;; broken it up into two. But I give it an old college try anyways.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.6: Proof of invalidate-ack-clients-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |ch3-client default cases|
(implies (and (invalidate-ack-clients-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive))))
(invalidate-ack-clients-invariant (german-step st stimulus)))))
;; All right now back to work. What home does on receiving an invalidate-ack
;; is remove it. This activity does not change the predicate. So the first
;; case is pretty trivial.
(local
(defthm invalidate-ack-does-not-change-if-set
(implies (and (invalidate-ack-clients clients ch3 keys)
(not (equal v :invalidate-ack)))
(invalidate-ack-clients clients (s i v ch3) keys))
:hints
(("Goal"
:cases
((equal i
(car (invalidate-ack-clients-witness clients (s i v ch3) keys)))))
("Subgoal 1"
:in-theory (enable invalidate-ack-clients))
("Subgoal 2"
:use
((:instance (:definition invalidate-ack-clients)
(ch3 (s i v ch3)))
(:instance
invalidate-ack-clients-necc
(i (car (invalidate-ack-clients-witness clients (s i v ch3) keys)))
(j (mv-nth 1 (invalidate-ack-clients-witness clients (s i v ch3)
keys)))))))))
;; This lets us prove the case of home-receives-invalidate
(local
(defthm |invalidate-ack for home-receives-invalidate|
(implies (and (invalidate-ack-clients-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(invalidate-ack-clients-invariant (german-step st stimulus)))))
;; All right, now how about sharer-invalidate-cache? Well, in this case we are
;; simply setting a client to idle and hence nothing can change in terms of
;; clients. But the problem is that we are introducing an :invalidate-ack. We
;; will do this one case at a time. If there were an invalidate-ack around
;; then we would have no problem. But it is now possible that there is no
;; invalidate-ack-around, and thus someone might be exclusive. But then if I
;; do send an invalidate it should be to the exclusive guy, right? So let us
;; say that as a predicate.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun invalidate-clients (ch2 clients keys)
(if (endp keys) T
(and (implies (equal (g (first keys) ch2) :invalidate)
(or (equal (g (first keys) clients) :shared)
(equal (g (first keys) clients) :exclusive)))
(invalidate-clients ch2 clients (rest keys))))))
(local
(defun invalidate-clients-invariant (st)
(invalidate-clients (ch2 st) (clients st) (keys))))
(local
(defthm invalidate-clients-for-nil
(invalidate-clients nil clients keys)))
(local
(defthm |init has invalidate-clients|
(invalidate-clients-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now let us concentrate on what this predicate together with
;; invalidate-ack-clients tells us. It tells us that the guy to which an
;; invalidate is sent must be shared or exclusive. Let us prove this.
(local
(defthm invalidate-clients-implies-shared-or-exclusive
(implies (and (invalidate-clients ch2 clients keys)
(memberp i keys)
(equal (g i ch2) :invalidate))
(or (equal (g i clients) :shared)
(equal (g i clients) :exclusive)))
:rule-classes :forward-chaining))
(local
(defthm invalidate-and-exclusive-implies-invalidate-exclusive
(implies (and (coherent-processes keys clients)
(invalidate-clients ch2 clients keys)
(memberp i keys)
(memberp j keys)
(equal (g i clients) :exclusive)
(equal (g j ch2) :invalidate))
(equal i j))
:rule-classes :forward-chaining
:hints (("Goal"
:use ((:instance coherent-processes-necc))))))
;; Now if the guy to which invalidate is sent was exclusive then coherent will
;; kick in and show that all other processes are shared or idle. Thus when we
;; set this to anything like idle or shared I should be in great shape.
(local
(defthm invalidate-clients-and-coherent-implies-invalidate-ack
(implies (and (coherent-processes keys clients)
(equal (g i clients) :exclusive)
(memberp i keys)
(or (equal v :shared)
(equal v :idle)))
(invalidate-ack-clients (s i v clients)
(s i u ch3)
keys))
:hints
(("Goal"
:cases ((equal i (mv-nth 1 (invalidate-ack-clients-witness (s i v clients)
(s i u ch3)
keys)))))
("Subgoal 1"
:in-theory (enable invalidate-ack-clients))
("Subgoal 2"
:use
((:instance (:definition invalidate-ack-clients)
(clients (s i v clients))
(ch3 (s i u ch3)))
(:instance coherent-processes-necc
(j (mv-nth 1 (invalidate-ack-clients-witness (s i v clients)
(s i u ch3)
keys)))))))))
;; I want to now say that if invalidate-clients holds and coherent-processes
;; holds then invalidate-ack-clients holds irrespective of which client is
;; being set. This is just packaging up the previous theorems.
(local
(defthm invalidate-clients-and-coherent-for-exclusive
(implies (and (invalidate-clients ch2 clients keys)
(coherent-processes keys clients)
(memberp i keys)
(memberp j keys)
(equal (g j ch2) :invalidate)
(equal (g i clients) :exclusive)
(or (equal v :shared)
(equal v :idle)))
(invalidate-ack-clients (s j v clients)
(s j u ch3)
keys))))
;; All right, now if it is exclusive then we are done. But it can be shared.
;; If it is shared then what do I know? Well, I should know that there is no
;; exclusive at all, from coherent-processes. But that is not sufficient.
;; Because I need to say that if there is nothing that is exclusive then all
;; are shared or idle. And that is not a predicate I have defined yet. So I
;; define the predicate valid-status below to take care of that.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun valid-status (clients keys)
(if (endp keys)
T
(and (or (equal (g (first keys) clients) :idle)
(equal (g (first keys) clients) :shared)
(equal (g (first keys) clients) :exclusive))
(valid-status clients (rest keys))))))
(local
(defun valid-status-invariant (st) (valid-status (clients st) (keys))))
(local
(defthm setting-valid-does-not-change-status
(implies (and (valid-status clients keys)
(or (equal v :idle)
(equal v :shared)
(equal v :exclusive)))
(valid-status (s i v clients) keys))
:hints (("Subgoal *1/3"
:cases ((equal i (car keys)))))))
(local
(defthm valid-status-in-initial (valid-status (initial-clients keys) keys)))
(local
(defthm |init has valid status| (valid-status-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now I should know that if valid-status holds and no process has exclusive
;; then all are idle or shared. To simplify the reasoning let us define a
;; function saying that no process is exclusive. Of course this is not an
;; invariant.
(local
(defun no-exclusive (keys clients)
(if (endp keys)
T
(and (not (equal (g (first keys) clients) :exclusive))
(no-exclusive (rest keys) clients)))))
;; So no-exclusive means that all are idle or shared.
(local
(defthm no-exclusive-implies-all-idle-shared
(implies (and (no-exclusive keys clients)
(valid-status clients keys)
(memberp i keys))
(or (equal (g i clients) :shared)
(equal (g i clients) :idle)))
:rule-classes :forward-chaining))
;; And if no-exclusive does not hold then we have some process that is
;; exclusive. Notice now how we need to (and can) define a recursive function
;; that produces the corresponding witness. It is this witness that comes for
;; free if we do quantification. But I have been using quantification and
;; induction in any way whatsoever depending on my mood while quantifying over
;; only one index. So I need to "create" the witness in this case.
(local
(defun exclusive-witness (keys clients)
(if (endp keys) nil
(if (equal (g (first keys) clients) :exclusive)
(first keys)
(exclusive-witness (rest keys) clients)))))
;; This theorem shows one way of using the witness function. This is
;; essentially how we use existential quantifiers. I am saying that if
;; no-exclusive does not hold then there is an index which is exclusive, in
;; particular, exclusive-witness. This is a standard trick of simulating
;; existential quantification using recursive functions. Later we will
;; (hopefully) see a way of using recursive functions to simulate universal
;; quantification. The method is the same, namely define a witness for the
;; property (for a universal quantification we look for a negation of the
;; property). Then we say that if the witness has the property then every
;; object does. The theorem is proved using induction, and then serves to be
;; used exactly as we used the witnesses for defun-sk.
(local
(defthm exclusive-implies-exclusive-witness
(implies (not (no-exclusive keys clients))
(and (memberp (exclusive-witness keys clients) keys)
(equal (g (exclusive-witness keys clients) clients)
:exclusive)))
:rule-classes :forward-chaining))
;; Now we show that if no-exclusive holds then invalidate-ack-clients holds.
(local
(defthm no-exclusive-implies-invalidate-ack-clients
(implies (and (no-exclusive keys clients)
(valid-status clients keys)
(or (equal v :shared)
(equal v :idle)))
(invalidate-ack-clients (s i v clients)
(s i u ch3)
keys))
:hints
(("Goal"
:cases
((equal i (mv-nth 1 (invalidate-ack-clients-witness (s i v clients)
(s i u ch3)
keys)))))
("Subgoal 1"
:in-theory (enable invalidate-ack-clients))
("Subgoal 2"
:in-theory (enable invalidate-ack-clients)))))
;; And this solves it.
(local
(defthm invalidate-coherent-valid-status-invalidate-ack
(implies (and (invalidate-clients ch2 clients keys)
(equal (g j ch2) :invalidate)
(memberp j keys)
(coherent-processes keys clients)
(valid-status clients keys)
(or (equal v :idle)
(equal v :shared)))
(invalidate-ack-clients (s j v clients) (s j u ch3) keys))
:hints (("Goal"
:cases ((no-exclusive keys clients))))))
;; All right, finally done:
(local
(defthm |invalidate-ack-clients for sharer-invalidate-cache|
(implies (and (invalidate-ack-clients-invariant st)
(invalidate-clients-invariant st)
(coherent st)
(valid-status-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(invalidate-ack-clients-invariant (german-step st stimulus)))))
;; Now why does invalidate-ack-clients hold when we have a grant-shared? The
;; reason is ch2-shared-invariant which says that everybody is shared or idle
;; anyways.
(local
(defthm ch2-shared-implies-invalidate-ack-clients
(implies (and (ch2-client-shared ch2 keys clients)
(equal (g i ch2) :grant-shared)
(memberp i keys)
(or (equal v :shared)
(equal v :idle)))
(invalidate-ack-clients (s i v clients) ch3 keys))
:hints
(("Goal"
:cases
((equal i (mv-nth 1 (invalidate-ack-clients-witness (s i v clients)
ch3
keys)))))
("Subgoal 1"
:in-theory (enable invalidate-ack-clients))
("Subgoal 2"
:in-theory (enable invalidate-ack-clients)
:use
((:instance ch2-client-shared-necc
(j (mv-nth 1 (invalidate-ack-clients-witness (s i v clients)
ch3
keys)))))))))
(local
(defthm |invalidate-ack-clients for grant-shared|
(implies (and (invalidate-ack-clients-invariant st)
(ch2-client-shared-invariant st)
(equal (action stimulus) :client-receives-shared))
(invalidate-ack-clients-invariant (german-step st stimulus)))))
;; Now the last case, which is client-receives-exclusive. I dont like to think
;; about this one right now --- I am tired after doing the rest of the cases.
;; But I am pretty sure that if there is an invalidate-ack somewhere then there
;; cannot be a :grant-exclusive. So for now I posit that as a predicate and go
;; on.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk invalidate-exclusive (ch3 ch2 keys)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(equal (g i ch3) :invalidate-ack))
(not (equal (g j ch2) :grant-exclusive))))))
(local
(defun invalidate-exclusive-invariant (st)
(invalidate-exclusive (ch3 st) (ch2 st) (keys))))
(local
(defthm |init has invalidate-exclusive|
(invalidate-exclusive-invariant (init))))
(local
(in-theory (disable invalidate-exclusive invalidate-exclusive-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; And this predicate is going to throw away the remaining case. Admittedly
;; this is not something I recommend. People should analyze things carefully
;; before positing a predicate like the above. But, well, what the heck, I
;; will do it, since I am pretty confident this is an invariant.
(local
(defthm invalidate-exclusive-implies-grant-exclusive
(implies (and (invalidate-exclusive ch3 ch2 keys)
(memberp i keys)
(equal (g i ch2) :grant-exclusive))
(invalidate-ack-clients clients ch3 keys))
:hints
(("Goal"
:in-theory (enable invalidate-ack-clients)
:use
((:instance
invalidate-exclusive-necc
(j i)
(i (car (invalidate-ack-clients-witness clients ch3 keys)))))))))
(local
(defthm |invalidate-ack-clients after client-receives-exclusive|
(implies (and (invalidate-ack-clients-invariant st)
(invalidate-exclusive-invariant st)
(equal (action stimulus) :client-receives-exclusive))
(invalidate-ack-clients-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of invalidate-ack-clients-invariant
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; OK now I am just making a slight change in the order since it is night and I
;; want to do an easy predicate without thinking too much. So I will now prove
;; valid-status-invariant first. I will get back to the normal order of other
;; predicates tomorrow.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.7: Proof of valid-status-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |valid-status default cases|
(implies (and (valid-status-invariant st)
(not (memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive))))
(valid-status-invariant (german-step st stimulus)))))
;; I ought to have proven some lemma about non-default cases here, but I have
;; already proved that lemma while proving that valid-status holds for the
;; initial states. Thus the rest will go thru as well. I might as well have
;; done the whole thing in one theorem. But I am sticking to the habit of
;; splitting proofs into default and non-default cases.
(local
(defthm |valid-status non-default cases|
(implies (and (valid-status-invariant st)
(memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(valid-status-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of valid-status-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; That was really fast!! I will try one more for tonight then. Let us move on
;; now to heg-exclusive-invariant. This says that if there is a
;; :grant-exclusive in a channel then heg holds. This one is particularly
;; easy.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.8: Proof of heg-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |heg-exclusive defaults cases|
(implies (and (heg-exclusive-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(heg-exclusive-invariant (german-step st stimulus)))))
;; What happens for home-grants-exclusive? This is simple. I know that it sets
;; heg to T. Thus nothing has to be done any more.
(local
(defthm heg-exclusive-if-heg-T
(implies heg
(heg-exclusive heg keys ch2))
:hints (("Goal"
:in-theory (enable heg-exclusive)))))
(local
(defthm |heg exclusive home-grants-exclusive|
(implies (and (heg-exclusive-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(heg-exclusive-invariant (german-step st stimulus)))))
;; More interesting is the bunch of cases where ch2 is set. The good thing is
;; that when ch2 is set to anything other than grant-exclusive we can claim
;; that the predicate simply persists.
(local
(defthm heg-exclusive-if-channel-set
(implies (and (heg-exclusive heg keys ch2)
(not (equal v :grant-exclusive)))
(heg-exclusive heg keys (s i v ch2)))
:hints
(("Goal"
:cases ((equal i (heg-exclusive-witness heg keys (s i v ch2)))))
("Subgoal 1"
:in-theory (enable heg-exclusive))
("Subgoal 2"
:use
((:instance (:definition heg-exclusive)
(ch2 (s i v ch2)))
(:instance
heg-exclusive-necc
(i (heg-exclusive-witness heg keys (s i v ch2)))))))))
;; And this will take care of most of the cases for us.
(local
(defthm |heg-exclusive for ch2 set|
(implies (and (heg-exclusive-invariant st)
(memberp (action stimulus)
'(:home-sends-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive)))
(heg-exclusive-invariant (german-step st stimulus)))))
;; The only thorny case is when home actually gets an invalidate. Then it sets
;; heg to nil. Why is this ok? This is ok since we have just by serendipity
;; added the predicate invalidate-exclusive which says that there is no
;; invalidate-ack and grant-exclusive together. Let us prove that it does it.
(local
(defthm invalidate-exclusive-implies-not-heg-is-fine
(implies (and (invalidate-exclusive ch3 ch2 keys)
(memberp i keys)
(equal (g i ch3) :invalidate-ack))
(heg-exclusive heg keys ch2))
:hints (("Goal"
:in-theory (enable heg-exclusive)
:use ((:instance invalidate-exclusive-necc
(j (heg-exclusive-witness heg keys ch2))))))))
(local
(defthm |heg-exclusive for home-receives-invalidate|
(implies (and (heg-exclusive-invariant st)
(invalidate-exclusive-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(heg-exclusive-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of heg-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right, so heg-exclusive out of the way. We get to hsl-ch2.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.9: Proof of hsl-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hsl-ch2 default cases|
(implies (and (hsl-ch2-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hsl-ch2-invariant (german-step st stimulus)))))
;; Here is what one has to do when recursive functions are defined (rather than
;; quantified predicates). I am proving that hsl-ch2 holds after setting i to
;; T in clients and v in ch2. If we defined this predicate using
;; quantification we would have used the cases hint and applied the
;; instantiation of the necc lemma on the first with the witness of the second.
;; But here we prove it using induction. The cases hint we gave can be easily
;; understood by looking at the failed proof. But I dont go into that here.
(local
(defthm hsl-ch2-after-setting-hsl
(implies (hsl-ch2 hsl keys ch2)
(hsl-ch2 (s i T hsl) keys (s i v ch2)))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-ch2 after home sets|
(implies (and (hsl-ch2-invariant st)
(memberp (action stimulus)
'(:home-grants-shared
:home-grants-exclusive)))
(hsl-ch2-invariant (german-step st stimulus)))))
(local
(defthm hsl-ch2-after-ch2-nil
(implies (hsl-ch2 hsl keys ch2)
(hsl-ch2 hsl keys (s i nil ch2)))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-ch2 after client sets|
(implies (and (hsl-ch2-invariant st)
(memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(hsl-ch2-invariant (german-step st stimulus)))))
;; All right now down to the two non-trivial cases for this predicate, namely
;; that home-sends-invalidate and home-receives-invalidate. These two cases
;; involve the following consideration. In home-sends-invalidate I add a
;; :invalidate to ch2. So it must be that hsl is not nil. Why is this true?
;; The reason is that the index is in hil. So we must know that if something
;; is in hil, then it is in hsl. This is true because the hil is set from hsl,
;; and hil is reset *before* hsl.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hil-hsl (hil hsl keys)
(if (endp keys) T
(and (implies (g (first keys) hil)
(equal (g (first keys) hsl) t))
(hil-hsl hil hsl (rest keys))))))
(local
(defun hil-hsl-invariant (st) (hil-hsl (hil st) (hsl st) (keys))))
(local
(defthm hil-hsl-for-nil (hil-hsl nil nil keys)))
(local (defthm |init has hil-hsl| (hil-hsl-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; How does this work? I first know that if hil-hsl holds then every index in
;; hil must have hsl t. When home-sends-invalidate, the hil is t and hence hsl
;; is t. Since hsl is T anyways I dont have to think about what is added to
;; ch2.
(local
(defthm hil-hsl-and-hil-implies-hsl
(implies (and (hil-hsl hil hsl keys)
(g i hil)
(memberp i keys))
(equal (g i hsl) t))))
(local
(defthm hsl-hil-ch2
(implies (and (hil-hsl hil hsl keys)
(hsl-ch2 hsl keys ch2)
(memberp i keys)
(g i hil))
(hsl-ch2 hsl keys (s i v ch2)))
:hints (("Subgoal *1/6"
:cases ((equal i (car keys)))))))
;; Now I can deal with home-sends-invalidate
(local
(defthm |hsl-ch2 after home-sends-invalidate|
(implies (and (hsl-ch2-invariant st)
(hil-hsl-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hsl-ch2-invariant (german-step st stimulus)))))
;; Now I need to deal with home receives invalidate. What this amounts to is
;; the following. If home receives an invalidate-ack in ch3, that means that
;; the ch2 of that process is nil. This lets us prove this.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun invalidate-ack-ch2 (ch2 ch3 keys)
(if (endp keys) T
(and (implies (equal (g (first keys) ch3) :invalidate-ack)
(not (g (first keys) ch2)))
(invalidate-ack-ch2 ch2 ch3 (rest keys))))))
(local
(defun invalidate-ack-ch2-invariant (st)
(invalidate-ack-ch2 (ch2 st) (ch3 st) (keys))))
(local
(defthm invalidate-ack-ch2-nil (invalidate-ack-ch2 nil nil keys)))
(local
(defthm |init has invalidate-ack-ch2|
(invalidate-ack-ch2-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Notice how I am proving these theorems by induction now. I believe
;; induction and quantification really require the same thought and insight,
;; but ACL2 needs a little more support for quantifiers.
(local
(defthm invalidate-ack-ch2-implies-can-set-hsl
(implies (and (invalidate-ack-ch2 ch2 ch3 keys)
(hsl-ch2 hsl keys ch2)
(equal (g i ch3) :invalidate-ack)
(memberp i keys))
(hsl-ch2 (s i v hsl) keys ch2))
:hints (("Subgoal *1/6"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-ch2 after home receives invalidate|
(implies (and (hsl-ch2-invariant st)
(invalidate-ack-ch2-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hsl-ch2-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hsl-ch2-invariant
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now done with hsl-ch2-invariant. On to hil-heg-invariant. This says that
;; if heg holds and somebody is in the invalidate list then every other channel
;; must have nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.10: Proof of hil-heg-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hil-heg default cases|
(implies (and (hil-heg-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hil-heg-invariant (german-step st stimulus)))))
;; Now the first thing we should know is that if heg is set to nil then there
;; is nothing to prove.
(local
(defthm heg-nil-to-hil-heg
(implies (not heg)
(hil-heg keys hil ch2 heg))
:hints (("Goal"
:in-theory (enable hil-heg)))))
;; That takes care of some of the cases.
(local
(defthm |hil-heg for receive invalidate|
(implies (and (hil-heg-invariant st)
(memberp (action stimulus) '(:home-receives-invalidate
:home-grants-shared)))
(hil-heg-invariant (german-step st stimulus)))))
;; The next thing which covers a lot of cases is the statement that if I set
;; ch2 of any process to nil then hil-heg cannot be violated.
(local
(defthm hil-heg-ch2-nil
(implies (hil-heg keys hil ch2 heg)
(hil-heg keys hil (s i nil ch2) heg))
:hints
(("Goal"
:cases
((equal i (mv-nth 1 (hil-heg-witness keys hil (s i nil ch2) heg)))))
("Subgoal 1"
:in-theory (enable hil-heg))
("Subgoal 2"
:use
((:instance (:definition hil-heg)
(ch2 (s i nil ch2)))
(:instance
hil-heg-necc
(i (car (hil-heg-witness keys hil (s i nil ch2) heg)))
(j (mv-nth 1 (hil-heg-witness keys hil (s i nil ch2) heg)))))))))
;; This will let us prove many of the cases, in particular all that involve
;; client.
(local
(defthm |hil-heg for clients|
(implies (and (hil-heg-invariant st)
(memberp (action stimulus) '(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(hil-heg-invariant (german-step st stimulus)))))
;; Now the more non-trivial cases which involve home picking a request, home
;; sending an invalidate, and home granting an exclusive. Let us look at
;; home-sends-invalidate. Suppose heg is true and no index other than one with
;; hil has ch2. Now home sets the hil of index i to be nil. Why is the
;; invariant ok then? It is ok since we should know at this point that no other
;; index had hil T. But that has not been posited as a predicate yet, so I do
;; so.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk unique-hil (hil heg keys)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(g i hil)
(not (equal i j))
heg)
(not (g j hil))))))
(local
(defun unique-hil-invariant (st) (unique-hil (hil st) (heg st) (keys))))
(local
(defthm |init has unique-hil|
(unique-hil-invariant (init))))
(local
(in-theory (disable unique-hil unique-hil-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now I know that under heg if there is an index in hil then it is a unique
;; index. So I should be able to set this index to anything and set the
;; corresponding channel to anything without violating the hil-heg condition.
;; Now let us come back to hil-heg. We now want to set hil to nil under heg,
;; and know that we do not have any other index with a dangling hil.
(local
(defthm unique-hil-implies-can-set-hil
(implies (and (unique-hil hil heg keys)
(hil-heg keys hil ch2 heg)
heg
(memberp i keys)
(g i hil))
(hil-heg keys (s i v hil) (s i u ch2) heg))
:hints
(("Goal"
:cases
((equal
i
(car (hil-heg-witness keys (s i v hil) (s i u ch2) heg)))))
("Subgoal 2"
:in-theory (enable hil-heg)
:use
((:instance
unique-hil-necc
(j (car (hil-heg-witness keys (s i v hil) (s i u ch2) heg))))))
("Subgoal 1"
:use
((:instance (:definition hil-heg)
(hil (s i v hil))
(ch2 (s i u ch2)))
(:instance
hil-heg-necc
(i (car (hil-heg-witness keys (s i v hil) (s i u ch2) heg)))
(j (mv-nth 1 (hil-heg-witness keys (s i v hil) (s i u ch2) heg))))
(:instance
unique-hil-necc
(i (car (hil-heg-witness keys (s i v hil) (s i u ch2) heg)))
(j (mv-nth 1 (hil-heg-witness keys (s i v hil) (s i u ch2) heg)))))))))
;; All right, now we can prove the hil-heg invariance for
;; home-sends-invalidate.
(local
(defthm |hil-heg when home sends invalidate|
(implies (and (hil-heg-invariant st)
(unique-hil-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hil-heg-invariant (german-step st stimulus)))
:hints (("Goal"
:cases ((heg st))))))
;; What happens when home-grants-exclusive? Here home is setting heg to T so
;; it better damn well know that there is no non-nil value in hil. Now home
;; knows there is no non-nil hil since there is no non-nil hsl and we have
;; hil-hsl as an invariant.
(local
(defthm hil-hsl-and-all-false-to-not-hil
(implies (and (hil-hsl hil hsl keys)
(all-false keys hsl)
(memberp i keys))
(equal (g i hil) nil))))
(local
(defthm hil-hsl-implies-hil-heg
(implies (and (hil-hsl hil hsl keys)
(all-false keys hsl)
(memberp i keys))
(hil-heg keys hil ch2 heg))
:hints (("Goal"
:in-theory (enable hil-heg)))))
(local
(defthm |hil-heg home grants exclusive|
(implies (and (hil-hsl-invariant st)
(hil-heg-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(hil-heg-invariant (german-step st stimulus)))))
;; What happens for home picking a request? We want to say that if someone is
;; in hsl, and if heg is true then that someone must be the only one.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk hsl-heg (hsl heg keys)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(not (equal i j))
heg
(g i hsl))
(not (g j hsl))))))
(local
(defun hsl-heg-invariant (st) (hsl-heg (hsl st) (heg st) (keys))))
(local
(defthm |init has hsl-heg-invariant|
(hsl-heg-invariant (init))))
(local (in-theory (disable hsl-heg hsl-heg-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm hsl-ch2-set-hsl-reduction
(implies (memberp i keys)
(equal (g i (set-hil-hsl keys hil hsl))
(g i hsl)))
:hints (("Subgoal *1/3"
:cases ((equal i (car keys)))))))
(local
(defthm hsl-heg-and-set-hsl-to-hil-heg
(implies (and (hsl-heg hsl heg keys)
(hsl-ch2 hsl keys ch2)
(hil-heg keys hil ch2 heg)
heg)
(hil-heg keys (set-hil-hsl keys hil hsl) ch2 heg))
:hints
(("Goal"
:use
((:instance (:definition hil-heg)
(hil (set-hil-hsl keys hil hsl)))
(:instance
hsl-heg-necc
(i (car (hil-heg-witness keys (set-hil-hsl keys hil hsl)
ch2 heg)))
(j (mv-nth 1 (hil-heg-witness keys (set-hil-hsl keys hil hsl)
ch2 heg))))
(:instance
hil-heg-necc
(i (car (hil-heg-witness keys
(set-hil-hsl keys hil hsl)
ch2 heg)))
(j (mv-nth 1 (hil-heg-witness keys
(set-hil-hsl keys hil hsl)
ch2 heg)))))))))
(local
(defthm |hil-heg after home-picks-request|
(implies (and (hil-heg-invariant st)
(hsl-ch2-invariant st)
(hsl-heg-invariant st)
(equal (action stimulus) :pick-new-request))
(hil-heg-invariant (german-step st stimulus)))
:hints (("Goal"
:cases ((heg st))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hil-heg-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right, so we are done with hil-heg. This took me surprisingly longer
;; than I thought it would require. Partly this is because I had never thought
;; of pick-new-request as anything worth consideration. But well, nothing is
;; trivial in a protocol after all.
;; Now on to invalidate-ack-idle-invariant. This is actually one of the more
;; trivial ones. Let us try it. Best to start with a simple predicate in the
;; morning.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.11: Proof of invalidate-ack-idle ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |invalidate-ack-idle default cases|
(implies (and (invalidate-ack-idle-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive))))
(invalidate-ack-idle-invariant (german-step st stimulus)))))
;; All right now if home makes changes ch3 nothing can happen to this
;; predicate.
(local
(defthm invalidate-ack-idle-if-other-than-invalidate
(implies (and (invalidate-ack-idle clients keys ch3)
(not (equal v :invalidate-ack)))
(invalidate-ack-idle clients keys (s i v ch3)))
:hints
(("Goal"
:cases ((equal i (invalidate-ack-idle-witness clients keys (s i v ch3)))))
("Subgoal 2"
:use
((:instance (:definition invalidate-ack-idle)
(ch3 (s i v ch3)))
(:instance
invalidate-ack-idle-necc
(i (invalidate-ack-idle-witness clients keys (s i v ch3))))))
("Subgoal 1"
:use
((:instance (:definition invalidate-ack-idle)
(ch3 (s i v ch3)))
(:instance
invalidate-ack-idle-necc
(i (invalidate-ack-idle-witness clients keys (s i v ch3)))))))))
(local
(defthm |home-receives invalidate correctly|
(implies (and (invalidate-ack-idle-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(invalidate-ack-idle-invariant (german-step st stimulus)))))
;; Now what happens when an invalidate-ack is introduced? This is rather
;; trivial since it happens only simultaneously with setting the client to
;; idle. So let us prove this case.
(local
(defthm invalidate-ack-idle-set-idle
(implies (invalidate-ack-idle clients keys ch3)
(invalidate-ack-idle (s i :idle clients) keys
(s i :invalidate-ack ch3)))
:hints
(("Goal"
:cases
((equal i (invalidate-ack-idle-witness (s i :idle clients)
keys
(s i :invalidate-ack ch3)))))
("Subgoal 2"
:use
((:instance (:definition invalidate-ack-idle)
(clients (s i :idle clients))
(ch3 (s i :invalidate-ack ch3)))
(:instance
invalidate-ack-idle-necc
(i (invalidate-ack-idle-witness (s i :idle clients)
keys
(s i :invalidate-ack ch3))))))
("Subgoal 1"
:in-theory (enable invalidate-ack-idle)))))
(local
(defthm |invalidate-ack-idle after sharer invalidates|
(implies (and (invalidate-ack-idle-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(invalidate-ack-idle-invariant (german-step st stimulus)))))
;; Now what happens for grant shared and exclusive? We now set something to
;; shared or exclusive so this is relevant. This is saved for us by
;; invalidate-ack-ch2.
(local
(defthm invalidate-ack-ch2-does-it
(implies (and (invalidate-ack-ch2 ch2 ch3 keys)
(g i ch2)
(memberp i keys))
(equal (equal (g i ch3) :invalidate-ack) nil))))
(local
(defthm not-invalidate-ack-implies-set-anything
(implies (and (not (equal (g i ch3) :invalidate-ack))
(invalidate-ack-idle clients keys ch3))
(invalidate-ack-idle (s i v clients) keys ch3))
:hints
(("Goal"
:cases ((equal i (invalidate-ack-idle-witness (s i v clients) keys ch3))))
("Subgoal 1"
:in-theory (enable invalidate-ack-idle))
("Subgoal 2"
:use
((:instance (:definition invalidate-ack-idle)
(clients (s i v clients)))
(:instance
invalidate-ack-idle-necc
(i (invalidate-ack-idle-witness (s i v clients) keys ch3))))))))
;; And putting the above two lemmas together here is the final one.
(local
(defthm invalidate-ack-ch2-reduction
(implies (and (invalidate-ack-ch2 ch2 ch3 keys)
(g i ch2)
(memberp i keys)
(invalidate-ack-idle clients keys ch3))
(invalidate-ack-idle (s i v clients) keys ch3))))
(local
(defthm |invalidate-ack-idle for clients|
(implies (and (invalidate-ack-idle-invariant st)
(invalidate-ack-ch2-invariant st)
(memberp (action stimulus) '(:client-receives-shared
:client-receives-exclusive)))
(invalidate-ack-idle-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of invalidate-ack-idle-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Ha ha ha. Done with one more. On to invalidate-ack-exclusive. Thi states
;; that if one channel has invalidate-ack then no channel has grant-exclusive.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.12: Proof of invalidate-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |invalidate-exclusive default cases|
(implies (and (invalidate-exclusive-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(invalidate-exclusive-invariant (german-step st stimulus)))))
;; Now of course as long as we do not set ch2 to grant-exclusive, I can set ch2
;; to any value and it should not matter.
(local
(defthm invalidate-exclusive-for-not-grant-exclusive
(implies (and (invalidate-exclusive ch3 ch2 keys)
(not (equal v :grant-exclusive)))
(invalidate-exclusive ch3 (s i v ch2) keys))
:hints
(("Goal"
:cases ((equal i (mv-nth 1 (invalidate-exclusive-witness ch3 (s i v ch2)
keys)))))
("Subgoal 1"
:use
((:instance (:definition invalidate-exclusive)
(ch2 (s i v ch2)))))
("Subgoal 2"
:use
((:instance (:definition invalidate-exclusive)
(ch2 (s i v ch2)))
(:instance
invalidate-exclusive-necc
(i (car (invalidate-exclusive-witness ch3 (s i v ch2) keys)))
(j (mv-nth 1 (invalidate-exclusive-witness ch3 (s i v ch2) keys)))))))))
;; And this takes care of a number of cases, in particular all cases other than
;; home-receives-invalidate grant-exclusive and invalidate-cache. At least so
;; I believe. Let us see if I am right.
(local
(defthm |invalidate-exclusive for not ch2 exclusive|
(implies (and (invalidate-exclusive-invariant st)
(memberp (action stimulus)
'(:home-sends-invalidate
:client-receives-shared
:client-receives-exclusive
:home-grants-shared)))
(invalidate-exclusive-invariant (german-step st stimulus)))))
;; Now why does it work when home receives invalidate? This is also trivial. I
;; can set ch3 to anything other than :invalidate-ack and not violate the
;; invariant. This is what home is doing....
(local
(defthm invalidate-exclusive-after-not-exclusive
(implies (and (invalidate-exclusive ch3 ch2 keys)
(not (equal v :invalidate-ack)))
(invalidate-exclusive (s i v ch3) ch2 keys))
:hints
(("Goal"
:cases
((equal i (car (invalidate-exclusive-witness (s i v ch3) ch2 keys)))))
("Subgoal 1"
:use
((:instance (:definition invalidate-exclusive)
(ch3 (s i v ch3)))))
("Subgoal 2"
:use
((:instance (:definition invalidate-exclusive)
(ch3 (s i v ch3)))
(:instance
invalidate-exclusive-necc
(i (car (invalidate-exclusive-witness (s i v ch3) ch2 keys)))
(j (mv-nth 1 (invalidate-exclusive-witness (s i v ch3) ch2 keys)))))))))
(local
(defthm |invalidate-exclusive after home receives invalidate|
(implies (and (invalidate-exclusive-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(invalidate-exclusive-invariant (german-step st stimulus)))))
;; What happens when sharer invalidates the cache? I have to claim that no
;; channel now has grant exclusive. Why is that? Because I know that if
;; somebody does have it, then all channels have to be nil. But all channels
;; are not nil since at least one has :invalidate.
(local
(defthm channel-nil-exclusive-implies-invalidate-exclusive
(implies (and (channel-nil-exclusive ch2 keys)
(memberp i keys)
(not (equal u :grant-exclusive))
(g i ch2))
(invalidate-exclusive (s i v ch3) (s i u ch2) keys))
:hints
(("Goal"
:cases
((equal i (car (invalidate-exclusive-witness (s i v ch3)
(s i u ch2)
keys)))))
("Subgoal 2"
:cases ((equal i (mv-nth 1 (invalidate-exclusive-witness (s i v ch3)
(s i u ch2)
keys)))))
("Subgoal 2.1"
:in-theory (enable invalidate-exclusive))
("Subgoal 2.2"
:in-theory (enable invalidate-exclusive)
:use
((:instance channel-nil-exclusive-necc
(j (car (invalidate-exclusive-witness (s i v ch3)
(s i u ch2)
keys))))))
("Subgoal 1"
:cases
((equal i (mv-nth 1 (invalidate-exclusive-witness (s i v ch3)
(s i u ch2)
keys)))))
("Subgoal 1.1"
:in-theory (enable invalidate-exclusive))
("Subgoal 1.2"
:in-theory (enable invalidate-exclusive)
:use
((:instance
channel-nil-exclusive-necc
(i (car (invalidate-exclusive-witness (s i v ch3)
(s i u ch2)
keys)))
(j (mv-nth 1 (invalidate-exclusive-witness (s i v ch3)
(s i u ch2)
keys)))))))))
(local
(defthm |invalidate-exclusive for sharer invalidate cache|
(implies (and (invalidate-exclusive-invariant st)
(channel-nil-exclusive-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(invalidate-exclusive-invariant (german-step st stimulus)))))
;; Now let us consider the last case which is when somebody is granted
;; exclusive. Why is it ok do do so and know that there was accidentally no
;; invalidate-ack around in channel 3? The reason is that the sharer list is
;; empty. This means that I must have another predicate, which says that if
;; somebody has something in ch3 then hsl has it recorded.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hsl-ch3 (hsl ch3 keys)
(if (endp keys) T
(and (implies (g (first keys) ch3)
(equal (g (first keys) hsl) t))
(hsl-ch3 hsl ch3 (rest keys))))))
(local
(defun hsl-ch3-invariant (st) (hsl-ch3 (hsl st) (ch3 st) (keys))))
(local
(defthm hsl-ch3-for-nil (hsl-ch3 nil nil keys)))
(local
(defthm |init has hsl-ch3-invariant|
(hsl-ch3-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; This argument is just going to go on and it is a simple argument. It says
;; that whenever I have all-false then I am ok. I probably have to have more
;; predicates like that all working with all-false.
(local
(defthm hsl-ch3-all-false-to-not-ch3
(implies (and (hsl-ch3 hsl ch3 keys)
(all-false keys hsl)
(memberp i keys))
(equal (g i ch3) nil))))
(local
(defthm hsl-ch3-all-false-implies-invalidate-exclusive
(implies (and (hsl-ch3 hsl ch3 keys)
(all-false keys hsl))
(invalidate-exclusive ch3 ch2 keys))
:hints (("Goal"
:in-theory (enable invalidate-exclusive)))))
;; So finally we get invalidate-exclusive.
(local
(defthm |invalidate-exclusive for granting exclusive|
(implies (and (hsl-ch3-invariant st)
(invalidate-exclusive-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(invalidate-exclusive-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of invalidate-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right now on to hil-hsl.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.13: Proof of hil-hsl-invariant
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hil-hsl default cases|
(implies (and (hil-hsl-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:home-receives-invalidate
:home-grants-shared
:home-grants-exclusive))))
(hil-hsl-invariant (german-step st stimulus)))))
;; Now consider the situation when set-hil-hsl happens. For this to go thru, I
;; need the fact that everything in hil is a boolean. This is because I just
;; said that the index in hil is not nil, but required that the index in hsl is
;; t. The reason why I chose this is because home checks if (g i hil) but not
;; if (equal (g i hil) T) on certain occasions. Anyhow the predicate is not
;; difficult to define and I do not want to belabor the point.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hsl-boolean (hsl keys)
(if (endp keys) T
(and (booleanp (g (first keys) hsl))
(hsl-boolean hsl (rest keys))))))
(local
(defun hsl-boolean-invariant (st) (hsl-boolean (hsl st) (keys))))
(local
(defthm hsl-boolean-for-nil (hsl-boolean nil keys)))
(local
(defthm |init has hsl-boolean| (hsl-boolean-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; And now some obvious theorems to get the proof to go thru for
;; pick-new-request.
(local
(defthm hil-hsl-memberp
(implies (and (memberp i keys)
(hsl-boolean hsl keys)
(equal v (g i hsl))
(hil-hsl hil hsl keys))
(hil-hsl (s i v hil) hsl keys))
:hints (("Subgoal *1/6"
:cases ((equal i (car keys)))))))
(local
(defthm hil-hsl-not-memberp
(implies (and (not (memberp i keys))
(hil-hsl hil hsl keys))
(hil-hsl (s i v hil) hsl keys))))
(local
(defthm hil-hsl-set-hil-hsl
(implies (and (hil-hsl hil hsl keys)
(hsl-boolean hsl keys))
(hil-hsl (set-hil-hsl keys hil hsl) hsl keys))
:hints (("Subgoal *1/4"
:cases ((memberp (car keys) (cdr keys)))))))
;; Now I can do the pick new request.
(local
(defthm |hil-hsl after picking request|
(implies (and (hil-hsl-invariant st)
(hsl-boolean-invariant st)
(equal (action stimulus) :pick-new-request))
(hil-hsl-invariant (german-step st stimulus)))))
;; Let us do home-sends-invalidate now. This involves showing that if hil is
;; set to nil then hil-hsl does not change.
(local
(defthm hil-hsl-after-hil-nil
(implies (hil-hsl hil hsl keys)
(hil-hsl (s i nil hil) hsl keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-hsl after invalidating|
(implies (and (hil-hsl-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hil-hsl-invariant (german-step st stimulus)))))
;; How about when home receives an invalidate? Here I must know that the index
;; we are talking about is not in hil in the first place and therefore it does
;; not matter that we set hsl to nil. For this we need a new predicate that
;; says that if something has invalidate-ack then its hil is nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hil-invalidate (hil ch3 keys)
(if (endp keys) T
(and (implies (equal (g (first keys) ch3) :invalidate-ack)
(not (g (first keys) hil)))
(hil-invalidate hil ch3 (rest keys))))))
(local
(defun hil-invalidate-invariant (st)
(hil-invalidate (hil st) (ch3 st) (keys))))
(local
(defthm hil-invalidate-for-nil (hil-invalidate nil nil keys)))
(local
(defthm |init has hil invalidate| (hil-invalidate-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now why does it work out for home receiving an invalidate? The reason is
;; rather odd. I know that ch3 is not nil. Thus hsl must be T and hence it
;; does not matter what I set hil to.
(local
(defthm hil-hsl-after-setting-hil
(implies (and (hil-hsl hil hsl keys)
(hil-invalidate hil ch3 keys)
hcm
(equal (g i ch3) :invalidate-ack))
(hil-hsl hil (s i v hsl) keys))
:hints (("Goal"
:do-not '(eliminate-destructors generalize fertilize))
("Subgoal *1/5"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-hsl after home-receives-invalidate|
(implies (and (hil-hsl-invariant st)
(hil-invalidate-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hil-hsl-invariant (german-step st stimulus)))))
;; And finally to the last cases of hil-hsl. These are when hsl is set to T.
;; All I care about is that if I set hsl to T then nothing changes.
(local
(defthm hil-hsl-after-setting-hsl
(implies (hil-hsl hil hsl keys)
(hil-hsl hil (s i T hsl) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-hsl after granting|
(implies (and (hil-hsl-invariant st)
(memberp (action stimulus)
'(:home-grants-shared
:home-grants-exclusive)))
(hil-hsl-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hil-hsl-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right. Now we are done with hil-hsl. Let us move on to
;; invalidate-ack-ch2. This says that when we have an invalidate-ack in a ch3
;; then ch2 is nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.14: Proof of invalidate-ack-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |invalidate-ack-ch2 default cases|
(implies (and (invalidate-ack-ch2-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(invalidate-ack-ch2-invariant (german-step st stimulus)))))
;; Of course if we set ch2 to nil then we have this trivially, unless of course
;; we also set ch3. This will take care of most cases.
(local
(defthm invalidate-ack-ch2-when-ch2-nil
(implies (invalidate-ack-ch2 ch2 ch3 keys)
(invalidate-ack-ch2 (s i nil ch2) ch3 keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm invalidate-ack-ch2-when-ch2-nil-and-ch3-anything
(implies (invalidate-ack-ch2 ch2 ch3 keys)
(invalidate-ack-ch2 (s i nil ch2) (s i v ch3) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |invalidate-ack-ch2 after ch2 nil|
(implies (and (invalidate-ack-ch2-invariant st)
(memberp (action stimulus)
'(:client-receives-shared
:sharer-invalidate-cache
:client-receives-exclusive)))
(invalidate-ack-ch2-invariant (german-step st stimulus)))))
;; Now what happens with the remaining cases? When home-receives-invalidate it
;; is fine since we are setting ch3 to nil.
(local
(defthm invalidate-ack-after-ch3-set
(implies (and (invalidate-ack-ch2 ch2 ch3 keys)
(not (equal v :invalidate-ack)))
(invalidate-ack-ch2 ch2 (s i v ch3) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |invalidate-ack after receiving invalidate|
(implies (and (invalidate-ack-ch2-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(invalidate-ack-ch2-invariant (german-step st stimulus)))))
;; The remaining cases now are home-grants-shared and home-grants-exclusive.
;; Why does this predicate hold after home-grants-shared? The reason is as
;; follows. In this situation I know that hcm is req-shared and (not heg) is
;; true. In this condition no invalidate-ack is there since no invalidate is
;; sent out. I posit that as a new predicate.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk hcm-invalidate-ack (hcm heg ch3 keys)
(forall i
(implies (and (memberp i keys)
(equal (g i ch3) :invalidate-ack))
(or (equal hcm :req-exclusive-access)
(and (equal hcm :req-shared-access)
heg))))))
(local
(defun hcm-invalidate-ack-invariant (st)
(hcm-invalidate-ack (hcm st) (heg st) (ch3 st) (keys))))
(local
(defthm |init has hcm-invalidate-ack|
(hcm-invalidate-ack-invariant (init))))
(local
(in-theory (disable hcm-invalidate-ack hcm-invalidate-ack-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Here we see the use of a witness function to do universal quantification. I
;; define a witness for the negation of the property I care about and then
;; prove that if the witness has the property then everything has the property.
;; When I do this sort of reasoning I feel like I should have defined the
;; predicate using defun-sk directly, but for waht it is worth this is useful
;; for demonstration.
(local
(defun invalidate-ack-ch2-witness (ch2 ch3 keys)
(if (endp keys) nil
(if (and (equal (g (first keys) ch3) :invalidate-ack)
(g (first keys) ch2))
(first keys)
(invalidate-ack-ch2-witness ch2 ch3 (rest keys))))))
(local
(defthm invalidate-ack-from-witness
(implies (or (not (memberp (invalidate-ack-ch2-witness ch2 ch3 keys) keys))
(not (equal (g (invalidate-ack-ch2-witness ch2 ch3 keys) ch3)
:invalidate-ack))
(not (g (invalidate-ack-ch2-witness ch2 ch3 keys) ch2)))
(invalidate-ack-ch2 ch2 ch3 keys))))
(local
(defthm hcm-invalidate-invalidate-ack
(implies (and (hcm-invalidate-ack hcm heg ch3 keys)
(not heg)
(equal hcm :req-shared-access))
(invalidate-ack-ch2 ch2 ch3 keys))
:hints
(("Goal"
:use ((:instance hcm-invalidate-ack-necc
(i (invalidate-ack-ch2-witness ch2 ch3 keys))))))))
(local
(defthm |invalidate-ack-ch2 when home-grants-shared|
(implies (and (invalidate-ack-ch2-invariant st)
(hcm-invalidate-ack-invariant st)
(equal (action stimulus) :home-grants-shared))
(invalidate-ack-ch2-invariant (german-step st stimulus)))))
;; Let us now look at home-grants-exclusive. Why is this predicate ok? I know
;; that if home grants exclusive then all hsl entries are nil. But if all of
;; them are nil then hsl-ch3 tells me that all ch3 are nil. If all ch3 are
;; nil, then of course the predicate holds trivially.
(local
(defthm hsl-ch3-and-all-false-implies-ok
(implies (and (hsl-ch3 hsl ch3 keys)
(all-false keys hsl))
(invalidate-ack-ch2 (s i v ch2) ch3 keys))))
(local
(defthm |invalidate-ack after granting invalidate|
(implies (and (hsl-ch3-invariant st)
(invalidate-ack-ch2-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(invalidate-ack-ch2-invariant (german-step st stimulus)))))
;; And what happens after home-sends-invalidate? This is taken care of by
;; saying that if someone is in hil then it does not contain
;; invalidate-ack. This, together with the guard that the current process
;; is in hil says that the process does not have invalidate-ack in ch3. This
;; means we can set anything to ch2 and get away with it.
(local
(defthm hil-invalidate-invalidate-ack-ch2
(implies (and (hil-invalidate hil ch3 keys)
(memberp i keys)
(g i hil)
(invalidate-ack-ch2 ch2 ch3 keys))
(invalidate-ack-ch2 (s i v ch2) ch3 keys))
:hints (("Subgoal *1/6"
:cases ((equal i (car keys)))))))
(local
(defthm |invalidate-ack-ch2 after home-sends-invalidate|
(implies (and (invalidate-ack-ch2-invariant st)
(hil-invalidate-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(invalidate-ack-ch2-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of invalidate-ack-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right done with one more. Now let us think about what unique-hil. This
;; predicate says that if heg is true then there is at most one index with hil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.15: Proof of unique-hil-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |unique-hil default cases|
(implies (and (unique-hil-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:home-receives-invalidate
:home-grants-exclusive))))
(unique-hil-invariant (german-step st stimulus)))))
;; I will start with home-sends-invalidate. Why is unique-hil an invariant in
;; this case? If a state is unique-nil then setting a particular index to nil
;; does not change the situation.
(local
(defthm unique-hil-implies-so-after-hil-nil
(implies (unique-hil hil heg keys)
(unique-hil (s i nil hil) heg keys))
:hints
(("Goal"
:cases ((equal i (car (unique-hil-witness (s i nil hil) heg keys)))
(equal i (mv-nth 1 (unique-hil-witness (s i nil hil) heg keys)))))
("Subgoal 1"
:in-theory (enable unique-hil))
("Subgoal 2"
:in-theory (enable unique-hil))
("Subgoal 3"
:use
((:instance (:definition unique-hil)
(hil (s i nil hil)))
(:instance
unique-hil-necc
(i (car (unique-hil-witness (s i nil hil) heg keys)))
(j (mv-nth 1 (unique-hil-witness (s i nil hil) heg keys)))))))))
;; Well, that kind of does it for home-sends-invalidate. Here is the proof.
(local
(defthm |unique-hil after home-sends-invalidate|
(implies (and (unique-hil-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(unique-hil-invariant (german-step st stimulus)))))
;; What about home-receives-invalidate? This works because we are now setting
;; heg to hil.
(local
(defthm not-heg-implies-unique-hil
(implies (not heg)
(unique-hil hil heg keys))
:hints (("Goal"
:in-theory (enable unique-hil)))))
(local
(defthm |unique-hil after home-receives-invalidate|
(implies (and (unique-hil-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(unique-hil-invariant (german-step st stimulus)))))
;; This of course does not work for home-grants-exclusive, since here we *are*
;; setting heg. But we know something in this case that will help us out.
;; What do I know? I know all-false holds. This says (together with the
;; predicate hil-hsl that there is no hil at all. So this case does not arise.
(local
(defthm hil-hsl-implies-unique-hil
(implies (and (hil-hsl hil hsl keys)
(all-false keys hsl))
(unique-hil (s i v hil) heg keys))
:hints
(("Goal"
:in-theory (enable unique-hil)
:cases ((equal i (car (unique-hil-witness (s i v hil) heg keys)))))
("Subgoal 1"
:cases
((equal i (mv-nth 1 (unique-hil-witness (s i v hil) heg keys))))))))
;; And of course unique-hil remains if hil is not set at all.
(local
(defthm hil-hsl-implies-unique-hil-not-set
(implies (and (hil-hsl hil hsl keys)
(all-false keys hsl))
(unique-hil hil heg keys))
:hints (("Goal"
:in-theory (enable unique-hil)))))
;; So we can now get this grant-exclusive case thru.
(local
(defthm |unique-hil after home grants exclusive|
(implies (and (unique-hil-invariant st)
(hil-hsl-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(unique-hil-invariant (german-step st stimulus)))))
;; What happens when home picks a new request? The issue here is that we need
;; to claim unique-hil for set-hil-hsl. Now this is true because hsl has the
;; same predicate holding, and after set-hil-hsl therefore hil will have the
;; same predicate.
(local
(defthm hsl-heg-implies-unique-hil
(implies (hsl-heg hsl heg keys)
(unique-hil (set-hil-hsl keys hil hsl)
heg keys))
:hints
(("Goal"
:use
((:instance (:definition unique-hil)
(hil (set-hil-hsl keys hil hsl)))
(:instance
hsl-heg-necc
(i (car (unique-hil-witness (set-hil-hsl keys hil hsl)
heg keys)))
(j (mv-nth 1 (unique-hil-witness (set-hil-hsl keys hil hsl)
heg keys)))))))))
(local
(defthm |unique-hil after picking new request|
(implies (and (unique-hil-invariant st)
(hsl-heg-invariant st)
(equal (action stimulus) :pick-new-request))
(unique-hil-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of unique-hil-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right now to hsl-heg-invariant.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.16: Proof of hsl-heg-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hsl-heg default cases|
(implies (and (hsl-heg-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:home-grants-shared
:home-grants-exclusive))))
(hsl-heg-invariant (german-step st stimulus)))))
;; Now this works for home receiving invalidate since heg is being set to nil.
(local
(defthm hsl-heg-after-heg-nil
(implies (not heg)
(hsl-heg hsl heg keys))
:hints (("Goal"
:in-theory (enable hsl-heg)))))
(local
(defthm |hsl-heg after home receives invalidate|
(implies (and (hsl-heg-invariant st)
(memberp (action stimulus) '(:home-grants-shared
:home-receives-invalidate)))
(hsl-heg-invariant (german-step st stimulus)))))
;; Only left now is when home grants exclusive. Now I know that all other
;; clients are nil. And it is therefore known that we can set anything to hsl.
(local
(defthm all-false-implies-false
(implies (and (all-false keys hsl)
(memberp i keys))
(equal (g i hsl) nil))))
(local
(defthm hsl-can-be-set-when-all-false
(implies (all-false keys hsl)
(hsl-heg (s i v hsl) heg keys))
:hints
(("Goal"
:in-theory (enable hsl-heg)
:cases ((equal i (car (hsl-heg-witness (s i v hsl) heg keys)))
(equal i (mv-nth 1 (hsl-heg-witness (s i v hsl) heg keys))))))))
(local
(defthm |hsl-heg after home-grants-exclusive|
(implies (and (hsl-heg-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(hsl-heg-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hsl-heg-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; hsl-ch3-invariant now.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.17: Proof of hsl-ch3-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hsl-ch3 default cases|
(implies (and (hsl-ch3-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:sharer-invalidate-cache
:home-grants-shared
:home-grants-exclusive))))
(hsl-ch3-invariant (german-step st stimulus)))))
;; Of course it is easy to do the granting of exclusive and shared. All that
;; it is, is that we can set hsl to T as much as we want.
(local
(defthm hsl-T-does-not-change-hsl-ch3
(implies (hsl-ch3 hsl ch3 keys)
(hsl-ch3 (s i T hsl) ch3 keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-ch3 does not change on grant|
(implies (and (hsl-ch3-invariant st)
(memberp (action stimulus) '(:home-grants-shared
:home-grants-exclusive)))
(hsl-ch3-invariant (german-step st stimulus)))))
;; Similarly if ch3 is set to nil then nothing happens.
(local
(defthm hsl-ch3-if-ch3-nil
(implies (hsl-ch3 hsl ch3 keys)
(hsl-ch3 (s i v hsl) (s i nil ch3) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-ch3 after receiving invalidation|
(implies (and (hsl-ch3-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hsl-ch3-invariant (german-step st stimulus)))))
;; The only critical case here is when the client is sending acknowledgement of
;; invalidation to the server. This is because now we must say that the index
;; was already T in hsl. This holds because of hsl-ch2, and the fact that we
;; know that ch2 now containts :invalidate.
(local
(defthm hsl-ch3-for-not-member
(implies (and (hsl-ch3 hsl ch3 keys)
(not (memberp i keys)))
(hsl-ch3 hsl (s i v ch3) keys))))
(local
(defthm hsl-ch2-implies-hsl-ch3-after-set
(implies (and (hsl-ch2 hsl keys ch2)
(hsl-ch3 hsl ch3 keys)
(memberp i keys)
(g i ch2))
(hsl-ch3 hsl (s i v ch3) keys))
:hints (("Goal"
:do-not '(eliminate-destructors generalize fertilize))
("Subgoal *1/6"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-ch3 after sharer invalidates|
(implies (and (hsl-ch3-invariant st)
(hsl-ch2-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(hsl-ch3-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hsl-ch3-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; hsl-boolean-invariant now.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.18: Proof of hsl-boolean-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; This one is particularly trivial, as indeed are most others which have to do
;; with types. In fact it is an inductive invariant in itself.
(local
(defthm |hsl-boolean default cases|
(implies (and (hsl-boolean-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:home-grants-shared
:home-grants-exclusive))))
(hsl-boolean-invariant (german-step st stimulus)))))
(local
(defthm hsl-boolean-if-boolean-val-set
(implies (and (hsl-boolean hsl keys)
(booleanp v))
(hsl-boolean (s i v hsl) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-boolean other cases|
(implies (and (hsl-boolean-invariant st)
(memberp (action stimulus)
'(:home-receives-invalidate
:home-grants-shared
:home-grants-exclusive)))
(hsl-boolean-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hsl-boolean-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.19: Proof of hil-invalidate-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hil-invalidate default cases|
(implies (and (hil-invalidate-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache))))
(hil-invalidate-invariant (german-step st stimulus)))))
;; Now if home sends an invalidate it sets hil to nil and thus it works out.
(local
(defthm hil-invalidate-on-nil
(implies (hil-invalidate hil ch3 keys)
(hil-invalidate (s i nil hil) ch3 keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-invalidate on home-sends-invalidate|
(implies (and (hil-invalidate-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hil-invalidate-invariant (german-step st stimulus)))))
;; Now it must also be ok when home receives it. Now it sets ch3 to something
;; other than invalidate-ack so I dont have to prove anything.
(local
(defthm hil-invalidate-ack-set
(implies (and (hil-invalidate hil ch3 keys)
(not (equal v :invalidate-ack)))
(hil-invalidate hil (s i v ch3) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-invalidate when home receives invalidate|
(implies (and (hil-invalidate-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hil-invalidate-invariant (german-step st stimulus)))))
;; But what happens when the sharer actually inserts an invalidate-ack in ch3?
;; This is the third case we consider. Now what the heck do we know about this
;; situation? Why does this predicate hold? We know that the ch2 is having an
;; :invalidate. So we must know that when ch2 has :invalidate then hil must be
;; nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hil-invalidate-ch2 (hil ch2 keys)
(if (endp keys) T
(and (implies (equal (g (first keys) ch2) :invalidate)
(not (g (first keys) hil)))
(hil-invalidate-ch2 hil ch2 (rest keys))))))
(local
(defun hil-invalidate-ch2-invariant (st)
(hil-invalidate-ch2 (hil st) (ch2 st) (keys))))
(local
(defthm hil-invalidate-ch2-for-nil (hil-invalidate-ch2 nil nil keys)))
(local
(defthm |init has hil-invalidate-ch2| (hil-invalidate-ch2-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm hil-invalidate-ch2-implies-invalidate
(implies (and (hil-invalidate-ch2 hil ch2 keys)
(hil-invalidate hil ch3 keys)
(memberp i keys)
(equal (g i ch2) :invalidate))
(hil-invalidate hil (s i v ch3) keys))
:hints (("Subgoal *1/6"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-invalidate after sharer-invalidate-cache|
(implies (and (hil-invalidate-invariant st)
(hil-invalidate-ch2-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(hil-invalidate-invariant (german-step st stimulus)))))
;; The condition for picking new request is a bit more interesting. I have to
;; claim that at this point there is no invalidate-ack around. But how do we
;; know that? Do I know that anything from hsl does not have invalidate-ack?
;; Clearly not. But what I do know is that if invalidate-ack is true of
;; something then hcm is true. This is from hcm-invalidate-ack.
;; Now I will prove that hcm-invalidate-ack implies hil-invalidate. This is an
;; interesting exercise since I am proving something about a recursive function
;; using a quantified property. To do this I will invoke the so-called
;; "witness function" approach.
(local
(defun hil-invalidate-witness (hil ch3 keys)
(if (endp keys) nil ;; dont care
(if (and (equal (g (first keys) ch3) :invalidate-ack)
(g (first keys) hil))
(first keys)
(hil-invalidate-witness hil ch3 (rest keys))))))
(local
(defthm hil-invalidate-witness-implies-hil-invalidate
(implies (or (not (equal (g (hil-invalidate-witness hil ch3 keys) ch3)
:invalidate-ack))
(not (memberp (hil-invalidate-witness hil ch3 keys)
keys))
(not (g (hil-invalidate-witness hil ch3 keys) hil)))
(hil-invalidate hil ch3 keys))))
(local
(defthm hcm-ch3-implies-hil-invalidate
(implies (and (hcm-invalidate-ack hcm heg ch3 keys)
(not hcm))
(hil-invalidate hil ch3 keys))
:hints (("Goal"
:use ((:instance hcm-invalidate-ack-necc
(i (hil-invalidate-witness hil ch3 keys))))))))
(local
(defthm |hil-invalidate when pick-new-request|
(implies (and (hil-invalidate-invariant st)
(hcm-invalidate-ack-invariant st)
(equal (action stimulus) :pick-new-request))
(hil-invalidate-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hil-invalidate-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now let us get to this predicate hil-invalidate-ch2. I have a premonition
;; that it would involve specifying something about hcm. We will see.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.20: Proof of hil-invalidate-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hil-invalidate-ch2 default cases|
(implies (and (hil-invalidate-ch2-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hil-invalidate-ch2-invariant (german-step st stimulus)))))
;; Of course the standard thing is that if ch2 is set to nil then we are in
;; great shape.
(local
(defthm hil-invalidate-ch2-when-ch2-nil
(implies (hil-invalidate-ch2 hil ch2 keys)
(hil-invalidate-ch2 hil (s i nil ch2) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-invalidate-ch2 when ch2 is reset|
(implies (and (hil-invalidate-ch2-invariant st)
(memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(hil-invalidate-ch2-invariant (german-step st stimulus)))))
;; And as usual setting hil to nil does not matter. So we use that to do the
;; sending of invalidate.
(local
(defthm hil-invalidate-ch2-set-hil-nil
(implies (hil-invalidate-ch2 hil ch2 keys)
(hil-invalidate-ch2 (s i nil hil) (s i v ch2) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-invalidate-ch2 home-sends-invalidate|
(implies (and (hil-invalidate-ch2-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hil-invalidate-ch2-invariant (german-step st stimulus)))))
;; And it does not matter if I set anything other than :invalidate in ch2.
(local
(defthm hil-invalidate-other-than-invalidate
(implies (and (hil-invalidate-ch2 hil ch2 keys)
(not (equal v :invalidate)))
(hil-invalidate-ch2 hil (s i v ch2) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-invalidate-ch2 for grant|
(implies (and (hil-invalidate-ch2-invariant st)
(memberp (action stimulus) '(:home-grants-shared
:home-grants-exclusive)))
(hil-invalidate-ch2-invariant (german-step st stimulus)))))
;; And finally the non-trivial case, namely :pick-new-request. What do we know
;; here? I would have loved to say that if ch2 has invalidate then hsl is nil.
;; But that is not true!!! In fact it is exactly the opposite that is true. I
;; definitely know that if ch2 has an invalidate then hsl *is* true. Why does
;; it work out then? It works out because when hcm is nil ch2 is nil,
;; :grant-exclusive, or :grant-shared. Why? Because home receives some
;; request and works on it and goes on working on it until it can finish
;; processing. During that time the hcm is always holding the command given.
;; It is only after the command has been completely processed that hcm is set
;; to nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk hcm-ch2 (hcm heg ch2 keys)
(forall i (implies (and (memberp i keys)
(equal (g i ch2) :invalidate))
(or (and (equal hcm :req-shared-access)
heg)
(equal hcm :req-exclusive-access))))))
(local
(defun hcm-ch2-invariant (st) (hcm-ch2 (hcm st) (heg st) (ch2 st) (keys))))
(local
(defthm |init has hcm-ch2| (hcm-ch2-invariant (init))))
(local
(in-theory (disable hcm-ch2 hcm-ch2-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm not-hcm-implies-not-invalidate
(implies (and (hcm-ch2 hcm heg ch2 keys)
(not hcm)
(memberp i keys))
(equal (equal (g i ch2) :invalidate) nil))
:hints (("Goal"
:use hcm-ch2-necc))))
;; And here I see how we can mimic quantification with recursion.
(local
(defun hil-invalidate-rwitness (hil ch2 keys)
(if (endp keys) nil ;; dont care
(if (and (equal (g (first keys) ch2) :invalidate)
(g (first keys) hil))
(first keys)
(hil-invalidate-rwitness hil ch2 (rest keys))))))
(local
(defthm hil-invalidate-rwitness-invalidate
(implies (or (not (equal (g (hil-invalidate-rwitness hil ch2 keys) ch2)
:invalidate))
(not (g (hil-invalidate-rwitness hil ch2 keys) hil))
(not (memberp (hil-invalidate-rwitness hil ch2 keys) keys)))
(hil-invalidate-ch2 hil ch2 keys))))
(local
(defthm not-hcm-implies-hil-invalidate
(implies (and (hcm-ch2 hcm heg ch2 keys)
(not hcm))
(hil-invalidate-ch2 hil ch2 keys))
:hints (("Goal"
:in-theory (disable hil-invalidate-rwitness-invalidate)
:use hil-invalidate-rwitness-invalidate))))
(local
(defthm |hil-invalidate on pick-new-request|
(implies (and (hil-invalidate-ch2-invariant st)
(hcm-ch2-invariant st)
(equal (action stimulus) :pick-new-request))
(hil-invalidate-ch2-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hil-invalidate-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; hcm-ch2-invariant
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.21: Proof of hcm-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hcm-ch2 default cases|
(implies (and (hcm-ch2-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hcm-ch2-invariant (german-step st stimulus)))))
;; Now what happens when there is an invalidate-ack? Why is the predicate
;; going to be ok here? There should be no other invalidate-ack. I know this
;; as follows. hsl-heg tells me that if heg is true then there is at most one
;; hsl. hsl-ch3 then tells me that there is at most one ch3. This ch3 is the
;; invalidate-ack I am seeing. Thus if I set this to nil there is no ch3, and
;; hence I am done. And of course if heg was already nil then there is nothing
;; to do.
;; All right, let us do this.
(local
(defthm hsl-ch3-and-ch3-to-hsl
(implies (and (hsl-ch3 hsl ch3 keys)
(memberp i keys)
(g i ch3))
(g i hsl))))
(local
(defthm hsl-heg-hsl-ch3-implies-only-one
(implies (and (hsl-heg hsl heg keys)
(hsl-ch3 hsl ch3 keys)
(hsl-ch2 hsl keys ch2)
(memberp i keys)
(memberp j keys)
heg
(g j ch2)
(g i ch3))
(equal i j))
:rule-classes :forward-chaining
:hints (("Goal"
:use hsl-heg-necc))))
;; Now I will claim that all right I know all this, and I also know from
;; invalidate-ack-ch2 that the guy which has invalidate-ack in ch3 does not
;; have a ch2. This will show that there is no ch2 at all.
(local
(defthm hsl-heg-hsl-ch3-implies-none
(implies (and (hsl-heg hsl heg keys)
(hsl-ch3 hsl ch3 keys)
(invalidate-ack-ch2 ch2 ch3 keys)
(hsl-ch2 hsl keys ch2)
(memberp i keys)
(memberp j keys)
heg
(equal (g i ch3) :invalidate-ack))
(equal (g j ch2) nil))
:hints (("Goal"
:cases ((equal i j))))))
;; And therefore I have it when heg.
(local
(defthm hcm-ch2-when-heg
(implies (and (hsl-heg hsl heg keys)
(hsl-ch3 hsl ch3 keys)
(invalidate-ack-ch2 ch2 ch3 keys)
(memberp i keys)
(equal (g i ch3) :invalidate-ack)
(hsl-ch2 hsl keys ch2)
heg)
(hcm-ch2 hcm v ch2 keys))
:hints (("Goal"
:in-theory (enable hcm-ch2)))))
;; For the final theorem I will case-split on whether heg is true.
(local
(defthm |hcm-ch2 when home-receives-invalidate|
(implies (and (hcm-ch2-invariant st)
(hsl-heg-invariant st)
(hsl-ch3-invariant st)
(invalidate-ack-ch2-invariant st)
(hsl-ch2-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hcm-ch2-invariant (german-step st stimulus)))
:hints (("Goal" :cases ((heg st))))))
;; The argument for picking a request is kind of cute. It says that if hcm is
;; not one of the approved values then there is no invalidate, and since there
;; is no invalidate I am now allowed to make hcm anything! Isn't it cute?
(local
(defthm hcm-ch2-and-not-hcm-implies-hcm-anything
(implies (and (hcm-ch2 hcm heg ch2 keys)
(not (equal hcm :req-exclusive-access))
(or (not (equal hcm :req-shared-access))
(not heg)))
(hcm-ch2 v u ch2 keys))
:hints (("Goal"
:use ((:instance (:definition hcm-ch2)
(hcm v)
(heg u))
(:instance hcm-ch2-necc
(i (hcm-ch2-witness v u ch2 keys))))))))
(local
(defthm |hcm-ch2 for pick-new-request|
(implies (and (hcm-ch2-invariant st)
(equal (action stimulus) :pick-new-request))
(hcm-ch2-invariant (german-step st stimulus)))))
;; For granting shared a similar argument is necessary but now we also set
;; ch2.
(local
(defthm hcm-ch2-and-not-hcm-implies-hcm-anything-with-ch2
(implies (and (hcm-ch2 hcm heg ch2 keys)
(not (equal hcm :req-exclusive-access))
(not (equal w :invalidate))
(or (not (equal hcm :req-shared-access))
(not heg)))
(hcm-ch2 v u (s i w ch2) keys))
:hints (("Goal"
:cases ((equal i (hcm-ch2-witness v u (s i w ch2) keys))))
("Subgoal 1"
:in-theory (enable hcm-ch2))
("Subgoal 2"
:use ((:instance (:definition hcm-ch2)
(hcm v)
(ch2 (s i w ch2))
(heg u))
(:instance hcm-ch2-necc
(i (hcm-ch2-witness v u (s i w ch2) keys))))))))
(local
(defthm |hcm-ch2 after home-grants-shared|
(implies (and (hcm-ch2-invariant st)
(equal (action stimulus) :home-grants-shared))
(hcm-ch2-invariant (german-step st stimulus)))))
;; And home-sends-invalidate is rather trivial since the definition of hcm is
;; done with this predicate in mind.
(local
(defthm hcm-ch2-if-the-right-things-set
(implies (or (and (equal hcm :req-shared-access)
heg)
(equal hcm :req-exclusive-access))
(hcm-ch2 hcm heg ch2 keys))
:hints (("Goal"
:in-theory (enable hcm-ch2)))))
(local
(defthm |hcm-ch2 when home-sends-invalidate|
(implies (and (hcm-ch2-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hcm-ch2-invariant (german-step st stimulus)))))
;; As in fact it does not matter if I set ch2 to something other than
;; :invalidate.
(local
(defthm hcm-ch2-after-setting-ch2
(implies (and (hcm-ch2 hcm heg ch2 keys)
(not (equal v :invalidate)))
(hcm-ch2 hcm heg (s i v ch2) keys))
:hints (("Goal"
:cases ((equal i (hcm-ch2-witness hcm heg (s i v ch2) keys))))
("Subgoal 2"
:use ((:instance (:definition hcm-ch2)
(ch2 (s i v ch2)))
(:instance hcm-ch2-necc
(i (hcm-ch2-witness hcm heg (s i v ch2) keys)))))
("Subgoal 1"
:in-theory (enable hcm-ch2)))))
(local
(defthm |hcm-ch2 after client sets|
(implies (and (hcm-ch2-invariant st)
(memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(hcm-ch2-invariant (german-step st stimulus)))))
;; And the exclusive of course just requires that we have hsl-ch2 which we do.
(local
(defthm hsl-ch2-and-all-false-implies-hcm
(implies (and (hsl-ch2 hsl keys ch2)
(not (equal v :invalidate))
(all-false keys hsl))
(hcm-ch2 hcm heg (s i v ch2) keys))
:hints (("Goal"
:cases ((equal i (hcm-ch2-witness hcm heg (s i v ch2) keys))))
("Subgoal 1"
:in-theory (enable hcm-ch2))
("Subgoal 2"
:in-theory (enable hcm-ch2)))))
(local
(defthm |hsm-ch2 when grants exclusive|
(implies (and (hcm-ch2-invariant st)
(hsl-ch2-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(hcm-ch2-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hcm-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now I handle the hcm-invalidate-ack-invariant. This says that if (not heg)
;; and hcm is equal to :req-shared-access then there is no invalidate-ack.
;; This should be pretty trivial since under these conditions we dont send an
;; invalidate at all.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.22: Proof of hcm-invalidate-ack-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hcm-invalidate-ack default cases|
(implies (and (hcm-invalidate-ack-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-receives-invalidate
:sharer-invalidate-cache
:home-grants-shared
:home-grants-exclusive))))
(hcm-invalidate-ack-invariant (german-step st stimulus)))))
;; Now what happens when we pick a new request? We know hcm is nil. And then
;; there is nothing to prove. This is the same cute trick that we invoked for
;; hcm-ch2.
(local
(defthm hcm-ack-and-not-hcm-implies-hcm-anything
(implies (and (hcm-invalidate-ack hcm heg ch3 keys)
(not (equal hcm :req-exclusive-access))
(or (not (equal hcm :req-shared-access))
(not heg)))
(hcm-invalidate-ack v u ch3 keys))
:hints
(("Goal"
:use ((:instance (:definition hcm-invalidate-ack)
(hcm v)
(heg u))
(:instance hcm-invalidate-ack-necc
(i (hcm-invalidate-ack-witness v u ch3 keys))))))))
(local
(defthm |hcm-invalidate-ack for pick-new-request|
(implies (and (hcm-invalidate-ack-invariant st)
(equal (action stimulus) :pick-new-request))
(hcm-invalidate-ack-invariant (german-step st stimulus)))))
;; And the same trick for grant-shared.
(local
(defthm hcm-ch3-and-not-hcm-implies-hcm-anything-with-ch2
(implies (and (hcm-invalidate-ack hcm heg ch3 keys)
(not (equal hcm :req-exclusive-access))
(not (equal w :invalidate-ack))
(or (not (equal hcm :req-shared-access))
(not heg)))
(hcm-invalidate-ack v u (s i w ch3) keys))
:hints
(("Goal"
:cases ((equal i (hcm-invalidate-ack-witness v u (s i w ch3) keys))))
("Subgoal 1"
:in-theory (enable hcm-invalidate-ack))
("Subgoal 2"
:use
((:instance (:definition hcm-invalidate-ack)
(hcm v)
(ch3 (s i w ch3))
(heg u))
(:instance hcm-invalidate-ack-necc
(i (hcm-invalidate-ack-witness v u (s i w ch3) keys))))))))
(local
(defthm |hcm-invalidate-ack after home-grants-shared|
(implies (and (hcm-invalidate-ack-invariant st)
(equal (action stimulus) :home-grants-shared))
(hcm-invalidate-ack-invariant (german-step st stimulus)))))
;; As I well realize now this predicate is kind of a mirror image of hcm-ch2.
;; So home-receives-invalidate is going to have a problem. And indeed exactly
;; the same problem as hcm-ch2. And the solution is exactly the same too!
(local
(defthm hsl-heg-hsl-ch3-implies-only-one-ch3
(implies (and (hsl-heg hsl heg keys)
(hsl-ch3 hsl ch3 keys)
(memberp i keys)
(memberp j keys)
heg
(g j ch3)
(g i ch3))
(equal i j))
:rule-classes :forward-chaining
:hints (("Goal"
:use hsl-heg-necc))))
;; Now I can prove that if I set ch3 to something else I would be done.
(local
(defthm hcm-ch3-when-heg
(implies (and (hsl-heg hsl heg keys)
(hsl-ch3 hsl ch3 keys)
(memberp i keys)
(not (equal u :invalidate-ack))
(equal (g i ch3) :invalidate-ack)
heg)
(hcm-invalidate-ack hcm v (s i u ch3) keys))
:hints
(("Goal"
:in-theory (enable hcm-invalidate-ack)
:cases ((equal i (hcm-invalidate-ack-witness hcm v (s i u ch3) keys)))))))
;; Well in this case we need to do something for not-heg as well just because I
;; am setting ch3. Now what happens if heg is actually not true. Now in this
;; case the hcm is req-shared-access and since I am not changing hcm it still
;; remains req-shared-access and I have nothing to prove.
(local
(defthm not-heg-invalidate-ack-implies-invalidate-ack
(implies (and (hcm-invalidate-ack hcm heg ch3 keys)
(not heg)
(memberp i keys)
(equal (g i ch3) :invalidate-ack))
(hcm-invalidate-ack hcm v u keys))
:hints (("Goal"
:use ((:instance (:definition hcm-invalidate-ack)
(heg v)
(ch3 u))
(:instance hcm-invalidate-ack-necc))))))
(local
(defthm |hcm-invalidate-ack when home-receives-invalidate|
(implies (and (hsl-heg-invariant st)
(hsl-ch3-invariant st)
(hcm-invalidate-ack-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hcm-invalidate-ack-invariant (german-step st stimulus)))
:hints (("Goal"
:cases ((heg st))))))
;; What happens when the sharer invalidates? I need to claim that under the
;; non-trivial conditions there is no invalidate at all, and hence there is no
;; problem.
(local
(defthm invalidate-not-a-problem
(implies (and (hcm-ch2 hcm heg ch2 keys)
(memberp i keys)
(equal (g i ch2) :invalidate))
(hcm-invalidate-ack hcm heg ch3 keys))
:hints (("Goal"
:in-theory (enable hcm-invalidate-ack)
:use hcm-ch2-necc))))
(local
(defthm |hcm-invalidate-ack after sharer invalidates|
(implies (and (hcm-invalidate-ack-invariant st)
(hcm-ch2-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(hcm-invalidate-ack-invariant (german-step st stimulus)))))
;; Now what happens if either there is a grant-exclusive? Again I will go thru
;; the pain of hsl and all-false. This predicate *is* really like hcm-ch2, the
;; more I think about it.
(local
(defthm hsl-ch3-and-all-false-implies-hcm
(implies (and (hsl-ch3 hsl ch3 keys)
(all-false keys hsl))
(hcm-invalidate-ack hcm heg ch3 keys))
:hints
(("Goal"
:cases ((equal i (hcm-invalidate-ack-witness hcm heg ch3 keys))))
("Subgoal 1"
:in-theory (enable hcm-invalidate-ack))
("Subgoal 2"
:in-theory (enable hcm-invalidate-ack)))))
(local
(defthm |hsm-invalidate-ack when grants exclusive|
(implies (and (hcm-invalidate-ack-invariant st)
(hsl-ch3-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(hcm-invalidate-ack-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hcm-invalidate-ack-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now I handle invalidate-clients-invariant. This should not be too much
;; trouble. If says that if a client has an invalidate it must be shared or
;; exclusive. In other words invalidation is not sent to idle clients. Since
;; this involves a property of two components for the same index, this should
;; be easy.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.22: Proof of hcm-invalidate-ack-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |invalidate-clients default cases|
(implies (and (invalidate-clients-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(invalidate-clients-invariant (german-step st stimulus)))))
;; And as is standard, I will show that if the predicate already holds then
;; setting ch2 to something other than invalidate does not change it.
(local
(defthm invalidate-after-something-else
(implies (and (invalidate-clients ch2 clients keys)
(not (equal v :invalidate)))
(invalidate-clients (s i v ch2) clients keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
;; which takes care of home granting shared or invalidate.
(local
(defthm |invalidate-clients after home-grants|
(implies (and (invalidate-clients-invariant st)
(memberp (action stimulus)
'(:home-grants-shared
:home-grants-exclusive)))
(invalidate-clients-invariant (german-step st stimulus)))))
;; Now when the client receives something it also does not matter as long as it
;; does not receive an invalidate.
(local
(defthm invalidate-after-client-set
(implies (and (invalidate-clients ch2 clients keys)
(not (equal v :invalidate)))
(invalidate-clients (s i v ch2) (s i u clients) keys))
:hints (("Goal"
:do-not '(eliminate-destructors generalize fertilize))
("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |clients are fine with invalidate-clients|
(implies (and (invalidate-clients-invariant st)
(memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(invalidate-clients-invariant (german-step st stimulus)))))
;; The only crucial point is when home sends invalidate. Why is that ok? As I
;; realize now, the reason is kind of subtle and I had not realized this when I
;; posited the predicate. The reason is that if hil has an index that is set
;; then the process is either shared, or exclusive, or grant-shared, or
;; grant-exclusive. The reason actually is that hsl behaves the same way, and
;; therefore hil gets it derived. We thus need to posit this as a predicate.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hil-client-ch2 (hil clients ch2 keys)
(if (endp keys) T
(and (implies (g (first keys) hil)
(or (equal (g (first keys) clients) :shared)
(equal (g (first keys) clients) :exclusive)
(equal (g (first keys) ch2) :grant-shared)
(equal (g (first keys) ch2) :grant-exclusive)))
(hil-client-ch2 hil clients ch2 (rest keys))))))
(local
(defun hil-client-ch2-invariant (st)
(hil-client-ch2 (hil st) (clients st) (ch2 st) (keys))))
(local
(defthm hil-client-for-nil (hil-client-ch2 nil clients ch2 keys)))
(local
(defthm |init has hil-client-ch2| (hil-client-ch2-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now this tells us that everything is ok.
(local
(defthm hil-client-ch2-memberp-reduction
(implies (and (hil-client-ch2 hil clients ch2 keys)
(memberp i keys)
(g i hil))
(or (equal (g i clients) :shared)
(equal (g i clients) :exclusive)
(equal (g i ch2) :grant-shared)
(equal (g i ch2) :grant-exclusive)))
:rule-classes :forward-chaining))
;; Of course now it is fine to do the invalidate since this index is shared of
;; exclusive. (Note that home checks if the ch2 has become empty.)
(local
(defthm invalidate-clients-not-memberp-reduction
(implies (and (invalidate-clients ch2 clients keys)
(not (memberp i keys)))
(invalidate-clients (s i v ch2) clients keys))))
(local
(defthm hil-client-hil-ch2-reduction
(implies (and (hil-client-ch2 hil clients ch2 keys)
(invalidate-clients ch2 clients keys)
(memberp i keys)
(g i hil)
(not (g i ch2)))
(invalidate-clients (s i v ch2) clients keys))
:hints (("Subgoal *1/6"
:cases ((equal i (car keys)))))))
(local
(defthm |invalidate-clients after home-sends-invalidate|
(implies (and (invalidate-clients-invariant st)
(hil-client-ch2-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(invalidate-clients-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of invalidate-clients-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; I am annoyed that the proof is going on and on. I thought when I was
;; proving invalidate-clients that it would be the last predicate I need to
;; reason about, but I got one more predicate. Of course to deal with this I
;; already know one more is necessary, namely about hsl relating it with
;; clients and ch2. But I hope not much more is involved.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.23: Proof of hil-client-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hil-client-ch2 default cases|
(implies (and (hil-client-ch2-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hil-client-ch2-invariant (german-step st stimulus)))))
;; And of course if I set the ch2 to grant-shared or grant-exclusive it does
;; not matter.
(local
(defthm hil-client-ch2-set-ch2
(implies (and (hil-client-ch2 hil clients ch2 keys)
(or (equal v :grant-exclusive)
(equal v :grant-shared)))
(hil-client-ch2 hil clients (s i v ch2) keys))
:hints (("Subgoal *1/3"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-client when home grants|
(implies (and (hil-client-ch2-invariant st)
(memberp (action stimulus)
'(:home-grants-exclusive
:home-grants-shared)))
(hil-client-ch2-invariant (german-step st stimulus)))))
;; And as long as I set the clients to shared or exclusive again it does not
;; matter. In fact it does not matter if we remove things from ch2.
(local
(defthm hil-client-ch2-set-client
(implies (and (hil-client-ch2 hil clients ch2 keys)
(or (equal v :exclusive)
(equal v :shared)))
(hil-client-ch2 hil (s i v clients) (s i u ch2) keys))
:hints (("Subgoal *1/3"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-client when client is set|
(implies (and (hil-client-ch2-invariant st)
(memberp (action stimulus)
'(:client-receives-exclusive
:client-receives-shared)))
(hil-client-ch2-invariant (german-step st stimulus)))))
;; And for sharer-invalidating we only need to say that hil is not existing.
;; And this is known from hil-invalidate-ch2.
(local
(defthm hil-invalidate-implies-can-set-client
(implies (and (hil-client-ch2 hil clients ch2 keys)
(hil-invalidate-ch2 hil ch2 keys)
(equal (g i ch2) :invalidate))
(hil-client-ch2 hil (s i v clients) (s i u ch2) keys))
:hints (("Subgoal *1/5"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-client for sharer invalidating|
(implies (and (hil-client-ch2-invariant st)
(hil-invalidate-ch2-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(hil-client-ch2-invariant (german-step st stimulus)))))
;; Why does hil-client work for home sending the invalidate? I have nothing to
;; prove since hil is being set to nil.
(local
(defthm hil-client-ch2-to-nil
(implies (hil-client-ch2 hil clients ch2 keys)
(hil-client-ch2 (s i nil hil) clients (s i v ch2) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-client-ch2 when home-sends-invalidate|
(implies (and (hil-client-ch2-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hil-client-ch2-invariant (german-step st stimulus)))))
;; All right, now for the non-trivial one. I need to write another predicate
;; which says that hsl has indices that are only shared, exclusive,
;; grant-shared, or grant-exclusive, or in fact the ch3 has invalidate-ack.
;; Otherwise I cannot have hil-client-ch2 when hil is set to hsl.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hsl-client-ch2 (hsl clients ch2 ch3 keys)
(if (endp keys) T
(and (implies (g (first keys) hsl)
(or (equal (g (first keys) clients) :shared)
(equal (g (first keys) clients) :exclusive)
(equal (g (first keys) ch2) :grant-shared)
(equal (g (first keys) ch2) :grant-exclusive)
(equal (g (first keys) ch3) :invalidate-ack)))
(hsl-client-ch2 hsl clients ch2 ch3 (rest keys))))))
(local
(defun hsl-client-ch2-invariant (st)
(hsl-client-ch2 (hsl st) (clients st) (ch2 st) (ch3 st) (keys))))
(local
(defthm hsl-client-for-nil (hsl-client-ch2 nil clients ch2 ch3 keys)))
(local
(defthm |init has hsl-client-ch2| (hsl-client-ch2-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; OK now we can prove that if hsl-client-ch2 holds then set-hil-hsl is fine.
;; I will prove it again using witness functions. I now understand why J said
;; that I really love quantification....!!!
(local
(defun hil-client-witness (hil clients ch2 keys)
(if (endp keys) nil
(if (and (g (first keys) hil)
(not (equal (g (first keys) clients) :shared))
(not (equal (g (first keys) clients) :exclusive))
(not (equal (g (first keys) ch2) :grant-shared))
(not (equal (g (first keys) ch2) :grant-exclusive)))
(first keys)
(hil-client-witness hil clients ch2 (rest keys))))))
(local
(defthm hil-client-witness-to-hil-clients
(implies
(or (not (memberp (hil-client-witness hil clients ch2 keys) keys))
(implies (g (hil-client-witness hil clients ch2 keys) hil)
(or (equal (g (hil-client-witness hil clients ch2 keys)
clients)
:shared)
(equal (g (hil-client-witness hil clients ch2 keys)
clients)
:exclusive)
(equal (g (hil-client-witness hil clients ch2 keys) ch2)
:grant-shared)
(equal (g (hil-client-witness hil clients ch2 keys) ch2)
:grant-exclusive))))
(hil-client-ch2 hil clients ch2 keys))
:rule-classes nil))
;; And now prove that hsl-client-ch2 implies the above conditions.
(local
(defthm hsl-client-member
(implies (and (hsl-client-ch2 hsl clients ch2 ch3 keys)
(memberp i keys)
(not (equal (g i ch3) :invalidate-ack))
(g i hsl))
(or (equal (g i clients) :shared)
(equal (g i clients) :exclusive)
(equal (g i ch2) :grant-shared)
(equal (g i ch2) :grant-exclusive)))
:rule-classes :forward-chaining))
;; Now we are in great shape, since hcm-invalidate-ack guarantees that we have
;; no invalidate-ack.
(local
(defthm hsl-client-hil-client-reduction
(implies (and (hsl-client-ch2 hsl clients ch2 ch3 keys)
(hcm-invalidate-ack hcm heg ch3 keys)
(not hcm))
(hil-client-ch2 (set-hil-hsl keys hil hsl) clients ch2 keys))
:hints
(("Goal"
:use
((:instance hil-client-witness-to-hil-clients
(hil (set-hil-hsl keys hil hsl)))
(:instance
hcm-invalidate-ack-necc
(i (hil-client-witness (set-hil-hsl keys hil hsl)
clients ch2 keys))))))))
(local
(defthm |hil-client-ch2 for picking request|
(implies (and (hsl-client-ch2-invariant st)
(hil-client-ch2-invariant st)
(hcm-invalidate-ack-invariant st)
(equal (action stimulus) :pick-new-request))
(hil-client-ch2-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hil-client-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right! Well done. Now let us trace the hsl and clients and everything
;; and try to finish this proof.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.24: Proof of hsl-client-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hsl-client-ch2 default cases|
(implies (and (hsl-client-ch2-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hsl-client-ch2-invariant (german-step st stimulus)))))
;; Well now if home sends invalidate then I dont have to prove anything. But
;; first let me prove that it is ok.
(local
(defthm hil-hsl-and-hil-and-ch2-implies-hsl
(implies (and (hsl-client-ch2 hsl clients ch2 ch3 keys)
(hil-client-ch2 hil clients ch2 keys)
(g i hil)
(not (g i ch2)))
(hsl-client-ch2 hsl clients (s i v ch2) ch3 keys))
:hints (("Subgoal *1/5"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-client-ch2 on home-sends-invalidate|
(implies (and (hsl-client-ch2-invariant st)
(hil-client-ch2-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hsl-client-ch2-invariant (german-step st stimulus)))))
;; When home-receives invalidate it removes the hsl and therefore I have to
;; prove nothing.
(local
(defthm hsl-client-reset-hsl
(implies (hsl-client-ch2 hsl clients ch2 ch3 keys)
(hsl-client-ch2 (s i nil hsl) clients ch2 (s i v ch3) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-client-ch2 when home-receives-invalidate|
(implies (and (hsl-client-ch2-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hsl-client-ch2-invariant (german-step st stimulus)))))
;; When sharer invalidates cache it sets ch3 to invalidate-ack and hence I dont
;; have to prove anything.
(local
(defthm hsl-client-set-ch3
(implies (hsl-client-ch2 hsl clients ch2 ch3 keys)
(hsl-client-ch2 hsl
(s i u clients)
(s i v ch2)
(s i :invalidate-ack ch3)
keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-client-ch2 when sharer invalidates|
(implies (and (hsl-client-ch2-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(hsl-client-ch2-invariant (german-step st stimulus)))))
;; When the client receives something it sets itself to shared or exclusive so
;; that is fine.
(local
(defthm hsl-client-ch2-on-clients
(implies (and (hsl-client-ch2 hsl clients ch2 ch3 keys)
(or (equal v :exclusive)
(equal v :shared)))
(hsl-client-ch2 hsl
(s i v clients)
(s i u ch2)
ch3 keys))
:hints (("Subgoal *1/3"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-client-ch2 when client sets|
(implies (and (hsl-client-ch2-invariant st)
(memberp (action stimulus)
'(:client-receives-shared
:client-receives-exclusive)))
(hsl-client-ch2-invariant (german-step st stimulus)))))
;; And the last case, when home is granting.
(local
(defthm hsl-client-ch2-on-home-grant
(implies (and (hsl-client-ch2 hsl clients ch2 ch3 keys)
(or (equal v :grant-exclusive)
(equal v :grant-shared)))
(hsl-client-ch2 (s i u hsl)
clients
(s i v ch2)
ch3 keys))
:hints (("Subgoal *1/3"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-client-ch2 when home grants|
(implies (and (hsl-client-ch2-invariant st)
(memberp (action stimulus)
'(:home-grants-shared
:home-grants-exclusive)))
(hsl-client-ch2-invariant (german-step st stimulus)))))
;; All right so finally done. The definition and proof of the inductive
;; invariant took way more time than I anticipated. I missed most of the
;; subtleties of the protocol when I started with the earlier predicates. It
;; would be interesting to see if the predicates can be made much simpler with
;; the insight I possess now, but I am too lazy to get back to them now that
;; the proof is virtually over.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 4: Cleanup and final theorem ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now I have gotten thru the most difficult part of the proof, namely coming
;; up with a set of predicates that together imply that their conjunction holds
;; at the next step. In this proof I have shown all predicates true on a
;; case-by-case basis already, so the final clean-up will not require the
;; definition of the predicates. Further the final cleanup also does not
;; require the definition of german-step. So I disable all definitions here.
;; Note: Since everything was done on a case-by-case basis the replay of the
;; proofs will be rather slow. One way to improve the speed of proof is to
;; just remove all the individual persistence theorems, and do it all together
;; at the end. I normally do that, but I am doing this proof more to show how
;; one comes up with such a proof in ACL2 than to speed up the certification.
;; So I leave things like this. [In practice we define the invariant and every
;; time the persistence of invariance fails we augment the invariant with a new
;; predicate or lemma.]
(local
(in-theory (disable coherent
ch2-client-shared-invariant
ch2-client-exclusive-invariant
not-heg-clients-shared-invariant
channel-nil-exclusive-invariant
hsl-client-invariant
invalidate-ack-clients-invariant
heg-exclusive-invariant
hsl-ch2-invariant
hil-heg-invariant
invalidate-ack-idle-invariant
invalidate-exclusive-invariant
hil-hsl-invariant
invalidate-ack-ch2-invariant
unique-hil-invariant
hsl-heg-invariant
hsl-ch3-invariant
invalidate-clients-invariant
hsl-boolean-invariant
hil-invalidate-invariant
hil-invalidate-ch2-invariant
valid-status-invariant
hcm-ch2-invariant
hcm-invalidate-ack-invariant
hil-client-ch2-invariant
hsl-client-ch2-invariant
init
(init)
german-step)))
(local
(defun inv (st)
(and (coherent st)
(ch2-client-shared-invariant st)
(ch2-client-exclusive-invariant st)
(not-heg-clients-shared-invariant st)
(channel-nil-exclusive-invariant st)
(hsl-client-invariant st)
(invalidate-ack-clients-invariant st)
(heg-exclusive-invariant st)
(hsl-ch2-invariant st)
(hil-heg-invariant st)
(hil-client-ch2-invariant st)
(hsl-client-ch2-invariant st)
(invalidate-ack-idle-invariant st)
(invalidate-exclusive-invariant st)
(invalidate-ack-ch2-invariant st)
(hil-invalidate-ch2-invariant st)
(hsl-heg-invariant st)
(hsl-ch3-invariant st)
(unique-hil-invariant st)
(invalidate-clients-invariant st)
(valid-status-invariant st)
(hsl-boolean-invariant st)
(hcm-ch2-invariant st)
(hcm-invalidate-ack-invariant st)
(hil-invalidate-invariant st)
(hil-hsl-invariant st))))
;; Now the final proofs which should go thru without too much hassle.
(local
(defthm |inv holds in initial state| (inv (init))))
(local
(defthm |inv is inductive| (implies (inv st) (inv (german-step st stimulus)))
:hints (("Goal"
:cases ((equal (action stimulus) :request-shared-access)
(equal (action stimulus) :request-exclusive-access)
(equal (action stimulus) :pick-new-request)
(equal (action stimulus) :home-sends-invalidate)
(equal (action stimulus) :home-receives-invalidate)
(equal (action stimulus) :sharer-invalidate-cache)
(equal (action stimulus) :client-receives-shared)
(equal (action stimulus) :client-receives-exclusive)
(equal (action stimulus) :home-grants-shared)
(equal (action stimulus) :home-grants-exclusive))))))
(local
(defthm |inv implies coherent|
(implies (inv st) (coherent st))))
;; Of course I am done already but just for the heck of it let me prove as a
;; final theorem that inv does imply coherent and hence coherent is true of
;; every execution. First let us define an execution of the german protocol.
(defun german-run (st stimuli)
(if (endp stimuli) st
(let* ((stimulus (first stimuli)))
(german-run (german-step st stimulus) (rest stimuli)))))
(local
(defthm |inv persists along run|
(implies (inv st) (inv (german-run st stimuli)))))
(local
(defthm |inv is true of all runs from init|
(inv (german-run (init) stimuli))))
;; And the final one is a capital DEFTHM.
(DEFTHM |every run is coherent| (coherent (german-run (init) stimuli)))
| true |
(in-package "ACL2")
#|
german.lisp
~~~~~~~~~~~
Author: PI:NAME:<NAME>END_PI
Date: Wed Oct 5 01:37:01 2005
This book represents my efforts to model the German protocol and reason about
it with ACL2.
Prelude
=======
Background
----------
PI:NAME:<NAME>END_PI recently was trying to model the German protocol an use ACL2 to
prove it correct. That revived my interest in the protocol. (Thanks, PI:NAME:<NAME>END_PI.)
I had a version of the Murphy code of the protocol, and PI:NAME:<NAME>END_PI and I had earlier
modeled it very abstractly earlier to apply predicate abstractions. There we
wanted to see how to automate the proof. But when PI:NAME:<NAME>END_PIna was doing it I thought
I might as well model the protocol as close to the Murphy code as possible and
see how much effort it is to do it in ACL2.
Note on using Quantification
----------------------------
Many of the predicates necessary for the proof of coherence [including the
property of coherence itself] can be stated easily via quantification. But use
of quantification requires that we be prepared to use hints in the right
places. It is unclear whether it is better to use quantification or recursive
functions in this project. I use quantification in most places since I was
trying to get more practice at using quantifiers, in part as I plan to talk to
PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI about how I believe more support should be added to the use of
quantifiers. It should be noted that although the use of quantification
requires hints, the hints were extremely mechanical. [More comments at where I
do quantification proofs.] I have used recursive functions for a couple of
predicates, but I only used them when using it was natural, for example when I
was only quantifying over one process index and so I could write only one
recursive function to capture the property I posit. [I do not like to write a
number of functions defining a property if I can state the property using one
defun-sk.] The one place where I only allow recursive functions is in defining
the functions involved in the state transition of the system. I do so since I
expect that one might want to simulate [execute] the model and hence using
quantification appears to be "wrong" in the context. Either way, I do not want
to advocate anything specific but the proof shows several examples of how to do
either.
Effort
------
I started modeling the protocol on Friday September 30, 2005. I did not have
time to work on the protocol proof on Saturday. I started the proof on Sunday,
and worked about 5 hours. I then spent Monday October 3, and Tuesday October 4
on the proof, working about 8-9 hours each day, doing the proof and the
documentation in real time. I was frustrated on Tuesday evening when I saw
that I had missed one subtlety of the protocol which is listed in Section 3.23.
Then I spent the night of Tuesday, from 11:30p.m. to 1:30a.m. (Wednesday) and
finished the proof.
I wrote the documentation of the prelude (that is, this part) after the proof.
The rest of the documentation was done real time while doing the proof. The
reason I did it that way was that I wanted to document my thoughts, both so
that the script is understandable and so that if I did shelve the proof I could
get back to it easily.
After the proof was done I changed all the defthm events not involving coherent
to local so that at least including the book will work perfectly fast. To
replay the proof do (certify-book "german") at the ACL2 prompt in an empty ACL2
session. To include the book after certification, do (include-book
"german"). The latter should be very fast at least.
|#
; Here is the murphy code for the protocol that I had once gotten from Thomas
; Wahl. I suspect that it is different from the code that Anna showed me,
; since see showed me properties called ctrlpropinv and datapropinv which I
; dont see in this version. But I think possibly the basics of the two codes
; are similar in the description of the protocols.
; Const
; n: 30;
; Type
; Msg: enum { null, req_sh, req_ex, inv, inv_ack, gr_sh, gr_ex };
; State: enum { I, S, E };
; ID: Scalarset(n);
; Var
; ch1: array[ID] of Msg; /* channel 1 */
; ch2: array[ID] of Msg; /* channel 2 */
; ch3: array[ID] of Msg; /* channel 3 */
; hsl: array[ID] of boolean; /* home_shared_list */
; hil: array[ID] of boolean; /* home_invalidate_list */
; heg: boolean; /* home_exclusive_granted */
; hcm: Msg; /* home_current_command */
; hcc: ID; /* home_current_client */
; c: array[ID] of State; /* distributed cache state */
; Ruleset i: ID do
; rule "1" /* client requests shared access */
; c[i] = I & ch1[i] = null ==>
; begin
; ch1[i] := req_sh;
; end;
; rule "2" /* client requests exclusive access */
; c[i] = I & ch1[i] = null ==>
; begin
; ch1[i] := req_ex;
; end;
; rule "3" /* home picks new request */
; hcm = null & ch1[i] != null ==>
; begin
; hcm := ch1[i];
; ch1[i] := null;
; hcc := i;
; for j: ID do
; hil[j] := hsl[j];
; end;
; end;
; rule "4" /* home sends invalidate message */
; hil[i] & ch2[i] = null & ((hcm = req_sh & heg) | hcm = req_ex) ==>
; begin
; ch2[i] := inv;
; hil[i] := false;
; end;
; rule "5" /* home receives invalidate acknowledgement */
; hcm != null & ch3[i] = inv_ack ==>
; begin
; hsl[i] := false;
; heg := false;
; ch3[i] := null;
; end;
; rule "6" /* sharer invalidates cache */
; ch2[i] = inv & ch3[i] = null ==>
; begin
; ch2[i] := null;
; ch3[i] := inv_ack;
; c[i] := I;
; end;
; rule "7" /* client receives shared grant */
; ch2[i] = gr_sh ==>
; begin
; c[i] := S;
; ch2[i] := null;
; end;
; rule "8" /* client receives exclusive grant */
; ch2[i] = gr_ex ==>
; begin
; c[i] := E;
; ch2[i] := null;
; end;
; end; /* ruleset */
; rule "9" /* home grants share */
; hcm = req_sh & !heg & ch2[hcc] = null ==>
; begin
; hsl[hcc] := true;
; hcm := null;
; ch2[hcc] := gr_sh;
; end;
; rule "10" /* home grants exclusive */
; hcm = req_ex & (forall i: ID do hsl[i] = false end) & ch2[hcc] = null ==>
; begin
; hsl[hcc] := true;
; hcm := null;
; heg := true;
; ch2[hcc] := gr_ex;
; end;
; startstate
; begin
; for i: ID do
; ch1[i] := null;
; ch2[i] := null;
; ch3[i] := null;
; c[i] := I;
; hsl[i] := false;
; hil[i] := false;
; end;
; hcm := null;
; hcc := undefined;
; heg := false;
; end;
; Invariant
; forall i: ID do
; c[i] = E ->
; forall j: ID do
; j != i -> c[j] = I
; end
; end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 1: Starting Macros and Other stuff ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now let us begin. I use the records book all over the place as it allows us
;; to conveniently model states and vectors.
(include-book "misc/records" :dir :system)
;; I define the predicate memberp below since I hate the fact that ACL2's
;; member function is not a boolean, that is, does not always return T or
;; NIL. But this might not be important anyways. I am doing it more out of
;; habit than anything else.
(defun memberp (e x)
(cond ((endp x) NIL)
((equal e (first x)) T)
(t (memberp e (rest x)))))
;; I think of the input as a record of two things, namely the index of the
;; process taking the next step, and the action to be taken by the
;; process. That is, it says which process index is being processed and which
;; action is being taken on behalf of that process.
(defmacro pid (stimulus) `(g :pid ,stimulus))
(defmacro action (stimulus) `(g :action ,stimulus))
;; I have several local variables that I need to access. I hate having to write
;; g in my code, so I define some macros to hide g. This also allows me to sort
;; of "declare" variables.
(defmacro clients (st) `(g :clients ,st))
(defmacro ch1 (st) `(g :ch1 ,st))
(defmacro ch2 (st) `(g :ch2 ,st))
(defmacro ch3 (st) `(g :ch3 ,st))
(defmacro hcm (st) `(g :hcm ,st))
(defmacro hil (st) `(g :hil ,st))
(defmacro hsl (st) `(g :hsl ,st))
(defmacro heg (st) `(g :heg ,st))
(defmacro hcc (st) `(g :hcc ,st))
;; I created this macro update for specifically allowing me to write chains to
;; s. I want to be able to write such a chain and still be able to read it!!
(defun update-macro (upds result)
(declare (xargs :guard (keyword-value-listp upds)))
(if (endp upds) result
(update-macro (cddr upds)
(list 's (car upds) (cadr upds) result))))
(defmacro update (old &rest updates)
(declare (xargs :guard (keyword-value-listp updates)))
(update-macro updates old))
(defmacro >st (&rest upds) `(update st ,@upds))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 2: Modeling the German Protocol ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Here are some functions. These are used for updating all indices together
;; when that is appropriate.
(defun set-hil-hsl (keys hil hsl)
(if (endp keys) hil
(s (first keys)
(g (first keys) hsl)
(set-hil-hsl (rest keys) hil hsl))))
(defun all-false (keys hsl)
(if (endp keys) T
(and (not (g (first keys) hsl))
(all-false (rest keys) hsl))))
;; The constant constrained function (keys) below specifies the set of process
;; indices. I have left it as a constrained function so that I can conveniently
;; add hypothesis on keys as necessary (for example we might have to add that
;; keys does not contain nil, or that it is a set of natural numbers, or
;; whatever). But my goal is to prove the protocol imposing as few constraints
;; on keys as possible. To that end, whenever we need to add a constraint I
;; should add an explanatory note saying why the constraint is necessary.
(encapsulate
(((keys) => *))
(local (defun keys () nil)))
;; Here is the state transition function for the protocol. In the original
;; Murphy version (as per my understanding) there were rules which were akin to
;; guarded commands. That is, an action could be taken if the guard for the
;; action was satisfied. In ACL2 we model that as follows. I name each action
;; (the names being based on the comments in the Murphy code and somewhat
;; arbitrary). An input stimulus specifies what action is to be taken. That is,
;; it specifies the name of the action that the system should execute. If the
;; action's guards are satisfied then the action is taken. Otherwise the
;; execution of the action is identity.
(defun german-step (st stimulus)
(let* ((action (action stimulus))
(pid (pid stimulus))
(keys (keys))
(clients (clients st))
(ch1 (ch1 st))
(ch2 (ch2 st))
(ch3 (ch3 st))
(hcm (hcm st))
(hsl (hsl st))
(hil (hil st))
(heg (heg st))
(hcc (hcc st)))
(if (not (memberp pid keys))
;; The reader might be surprised by this condition. I allow the
;; external stimulus to ask *any* process to take a step. In particular
;; that means I allow "garbage" processes. But since we are not
;; modeling processes joining the protocol, I am assuming that this
;; means when I ask a garbage process to make a step then the result is
;; a no-op.
st
(cond (;; Rule 1:
(and (equal action :request-shared-access)
(equal (g pid clients) :idle)
(not ch1))
(>st :ch1
(s pid :req-shared-access ch1)))
(;; Rule 2:
(and (equal action :request-exclusive-access)
(equal (g pid clients) :idle)
(not ch1))
(>st :ch1 (s pid :req-exclusive-access ch1)))
(;; Rule 3:
(and (equal action :pick-new-request)
(not hcm)
(g pid ch1))
(>st :hcm (g pid ch1)
:ch1 (s pid NIL ch1)
:hcc pid
:hil (set-hil-hsl keys hil hsl)))
(;; Rule 4:
(and (equal action :home-sends-invalidate)
(g pid hil)
(not (g pid ch2))
(or (and (equal hcm :req-shared-access)
heg)
(equal hcm :req-exclusive-access)))
(>st :ch2 (s pid :invalidate ch2)
:hil (s pid NIL hil)))
(;; Rule 5:
(and (equal action :home-receives-invalidate)
hcm
(equal (g pid ch3) :invalidate-ack))
(>st :hsl (s pid NIL hsl)
:heg NIL
:ch3 (s pid NIL ch3)))
(;; Rule 6:
(and (equal action :sharer-invalidate-cache)
(equal (g pid ch2) :invalidate)
(not (g pid ch3)))
(>st :ch2 (s pid NIL ch2)
:ch3 (s pid :invalidate-ack ch3)
:clients (s pid :idle clients)))
(;; Rule 7:
(and (equal action :client-receives-shared)
(equal (g pid ch2) :grant-shared))
(>st :clients (s pid :shared clients)
:ch2 (s pid NIL ch2)))
(;; Rule 8:
(and (equal action :client-receives-exclusive)
(equal (g pid ch2) :grant-exclusive))
(>st :clients (s pid :exclusive clients)
:ch2 (s pid NIL ch2)))
(;; Rule 9:
(and (equal action :home-grants-shared)
(equal hcm :req-shared-access)
(not heg)
(not (g hcc ch2)))
(>st :hsl (s hcc T hsl)
:hcm NIL
:ch2 (s hcc :grant-shared ch2)))
(;; Rule 10
(and (equal action :home-grants-exclusive)
(equal hcm :req-exclusive-access)
(all-false keys hsl)
(not (g hcc ch2)))
(>st :hsl (s hcc T hsl)
:hcm nil
:heg T
:ch2 (s hcc :grant-exclusive ch2)))
(t st)))))
;; And finally the initial state (init). All state variables are nil other
;; than the clients which are all :idle. I dont know if this latter
;; restriction is important or not, but I tried to model it as per the Murphy
;; definition.
(defun initial-clients (keys)
(if (endp keys) nil
(let ((clients (initial-clients (rest keys))))
(s (first keys) :idle clients))))
(defthm initial-clients-idle
(implies (memberp i keys)
(equal (g i (initial-clients keys)) :idle)))
(defun init () (s :clients (initial-clients (keys)) nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3: The Coherence predicate and Its proof ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; OK so we have now modeled the german protocol (at least as best as I could
;; based on my interpretation of the Murphy code above). We will now prove
;; that the german protocol has coherence. To do so, I will define a predicate
;; called coherent and show that it is an invariant of the model.
;; How do we define coherent? One way might be to define recursive functions
;; and such. Since the recursive functions do not seem to provide too much
;; additional simplicity, I prefer to define it as a person doing hand-proof
;; would naturally do, namely via quantification. Note that the predicate is
;; exactly a formalization in ACL2 of the Murphy description of the invariant.
(defun-sk coherent-processes (keys clients)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(not (equal i j))
(equal (g i clients) :exclusive))
(equal (g j clients) :idle))))
(defun coherent (st) (coherent-processes (keys) (clients st)))
(local (defthm |initial state is coherent| (coherent (init))))
;; coherent as defined above is an invariant (or so I believe) but is of course
;; not an inductive invariant. For example consider rule 8. The transition
;; following rule 8 does preserve coherence, but assuming coherent for the
;; state from which the transition occurs is not sufficient. We need more.
;; Here is how I will do it. I will start with a set of predicates (initially
;; only the predicate coherent). For each predicate P, in order to prove (P
;; (german-step s i)), we probably might need to assume (and (P s) (Q s)).
;; Then I have added Q to my set of predicates. I continue this process until
;; no other predicate needs to be added to the set. My final inductive
;; invariant then is a conjunction of all the predicates I have created so far.
;; Note: When I define a predicate we immediately prove that the predicate
;; holds for the initial state init. This is a sanity check and also takes
;; care of the base cases of the inductive invariant proof on the fly.
;; For each predicate that I handle I will divide the proof of its invariance
;; in three parts. The first part is what I call "default cases". The
;; predicate holds in these cases merely since the state components which
;; govern the predicate are not modified by german-step. For example, one
;; default case for every predicate we consider is the case where the action is
;; not a legal action. Then according to the protocol above the system state
;; does not change. Thus the predicate holds after the step simply because it
;; used to hold before.
;; The second case involves some property of the predicate we are checking.
;; For example, consider the situation of coherence when the sharer invalidates
;; cache. It sets its the client to idle and hence coherence cannot change.
;; This depends on the property of coherence that setting something to :idle or
;; :shared does not change it. I will prove this property and then handle this
;; case.
;; The third case is when the predicate P holds after a step from s principally
;; because not only P but some other predicate Q holds in s. I will then
;; define Q (and show it holds for the initial state) and then prove this case.
;; This is the toughest part of all in an invariant proof and of course it is
;; possible that the predicates I come up with are not optimal and I realize
;; that later. I will try to minimize the roll-back as much as possible
;; principally because I do not want to spend too much time on this system and
;; I am doing this principally to document how such a proof is done in ACL2, so
;; that the particular predicates are possibly of less importance here.
;; All right back to work. Whenever I define something using quantification I
;; disable the definition and all associated lemmas that were introduced,
;; because I want to have control on how they are used in a proof process. For
;; example I dont want to see a "witness" until I am ready and understand what
;; the witness means in a context. So I deal with quantifiers principally via
;; :use hints.
(local (in-theory (disable coherent-processes coherent-processes-necc)))
;; default cases are pretty simple.
(local
(defthm |coherent default cases|
(implies (and (coherent st)
(not (equal (action stimulus) :sharer-invalidate-cache))
(not (equal (action stimulus) :client-receives-shared))
(not (equal (action stimulus) :client-receives-exclusive)))
(coherent (german-step st stimulus)))))
;; We are now left with 6, 7, and 8. Now 6 is easy. In 6, a client simply
;; sets itself to :idle. If the processes were coherent before then they would
;; still be coherent.
;; Note: This proof is a classic example of how (universal) quantification
;; proofs go. I assume coherence and want to show that it holds after setting
;; i to :idle. How do we do that? To understand this, let us understand
;; clearly how a (universal) quantification works. To prove a universal
;; quantification of a property I must prove that the property holds for an
;; arbitrary object called the witness of the property. Here the witness is a
;; pair of process indices, and what I must show is that if one is :exclusive
;; then the other is :idle. Thus, it is convenient to think of it this way:
;; ACL2 is presenting us with two process indices and daring us to show that
;; the above property holds after I set i to :idle. Now I of course know that
;; before setting this index coherence was holding (since I am proving an
;; implication). Thus *before setting idle* for any two processes p and q if
;; one were exclusive then the other was idle. Now I will basically do the
;; following. I will ask if the index being set, that is, i, is one of the two
;; indices that acl2 is going to present me with. If not then ACL2 is giving
;; us two other indices and thus if one is exclusive the other is shared by
;; virtue of coherence before setting. That leaves us with two cases. First,
;; ACL2 can claim that i is the index of an :exclusive process and dare us to
;; show that every other j is :idle. I can dispatch this case by saying that
;; since I have just set i to :idle, i cannot be :exclusive in the first place.
;; The second is that ACL2 can claim that there is some process which is
;; exclusive and say that show that i is :idle. This case also leaves nothing
;; to be done since I know that i is :idle.
;; The above analysis might appear to be too tedious and difficult to do every
;; time. But it is indeed pretty mechanical. I proved the theorem with the
;; hints below even before I really thought why I gave those hints. The rule
;; of the thumb is as follows. If you know that some property holds before
;; setting a process index to something then do a :cases hint on whether the
;; witness *after* the setting is the index that has been just set. If there
;; are more than one witnesses then do a case hint on each. For each of the
;; cases, just use the definition of the property as a hint and use the -necc
;; lemma for the previous state, setting the quantified variables (i and j in
;; this case) to be the corresponding witnesses for the variables after the
;; update.
(local
(defthm coherent-after-setting-idle
(implies (coherent-processes keys clients)
(coherent-processes keys (s i :idle clients)))
:hints
(("Goal"
:cases
((equal
i
(mv-nth 1
(coherent-processes-witness keys (s i :idle clients))))
(equal i (car (coherent-processes-witness keys (s i :idle clients))))))
("Subgoal 1"
:in-theory (enable coherent-processes)
:use
((:instance
coherent-processes-necc
(i (car (coherent-processes-witness keys (s i :idle clients))))
(j (mv-nth 1 (coherent-processes-witness keys (s i :idle clients)))))))
("Subgoal 2"
:in-theory (enable coherent-processes)
:use
((:instance
coherent-processes-necc
(i (car (coherent-processes-witness keys (s i :idle clients))))
(j (mv-nth 1 (coherent-processes-witness keys (s i :idle clients)))))))
("Subgoal 3"
:use
((:instance (:definition coherent-processes)
(clients (s i :idle clients)))
(:instance
coherent-processes-necc
(i (car (coherent-processes-witness keys (s i :idle clients))))
(j (mv-nth 1 (coherent-processes-witness keys
(s i :idle clients))))))))))
(local
(defthm |coherent after rule 6|
(implies (and (coherent st)
(equal (action stimulus) :sharer-invalidate-cache))
(coherent (german-step st stimulus)))))
;; So we are now left with rules 7 and 8. We need to look carefully at these
;; rules. If the action is :client-receives-shared then why is coherent
;; preserved? The reason is that in the state when a system can execute rule 7,
;; (that is, when the channel 2 has :grant-shared in it for some client), all
;; clients are either :idle or :shared (or at least I hope so). This fact can
;; be codified by the predicate ch2-client-invariant below.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk ch2-client-shared (ch2 keys clients)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(equal (g i ch2) :grant-shared))
(or (equal (g j clients) :shared)
(equal (g j clients) :idle))))))
(local
(defun ch2-client-shared-invariant (st)
(ch2-client-shared (ch2 st) (keys) (clients st))))
(local (defthm |init has ch2-shared| (ch2-client-shared-invariant (init))))
(local (in-theory (disable ch2-client-shared ch2-client-shared-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The following theorem saves us some :use hints since we would often be
;; checking if a client is :exclusive.
(local
(defthm ch2-client-shared-implies-not-exclusive
(implies (and (ch2-client-shared ch2 keys clients)
(memberp i keys)
(memberp j keys)
(equal (g i ch2) :grant-shared))
(equal (equal (g j clients) :exclusive) NIL))
:hints (("Goal"
:use ch2-client-shared-necc))))
(local
(defthm coherent-after-setting-shared
(implies (and (ch2-client-shared ch2 keys clients)
(memberp i keys)
(equal (g i ch2) :grant-shared))
(coherent-processes keys (s j :shared clients)))
:hints (("Goal"
:in-theory (enable coherent-processes)
:cases ((equal j
(car (coherent-processes-witness
keys (s j :shared clients))))))
("Subgoal 2"
:use ((:instance (:definition coherent-processes)
(clients (s j :shared clients))))))))
;; OK so now we can prove that execution of rule 7 gives us a coherent state.
(local
(defthm |coherent after rule 7|
(implies (and (ch2-client-shared-invariant st)
(coherent st)
(equal (action stimulus) :client-receives-shared))
(coherent (german-step st stimulus)))))
;; I define the similar predicate ch2-client-exclusive-invariant that lets us
;; show coherent for rule 8.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk ch2-client-exclusive (ch2 keys clients)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(equal (g i ch2) :grant-exclusive))
(equal (g j clients) :idle)))))
(local
(defun ch2-client-exclusive-invariant (st)
(ch2-client-exclusive (ch2 st) (keys) (clients st))))
(local
(defthm |init has ch2-exclusive| (ch2-client-exclusive-invariant (init))))
(local
(in-theory (disable ch2-client-exclusive ch2-client-exclusive-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm ch2-exclusive-means-idle
(implies (and (ch2-client-exclusive ch2 keys clients)
(memberp i keys)
(memberp j keys)
(equal (g i ch2) :grant-exclusive))
(equal (g j clients) :idle))
:hints (("Goal"
:use ch2-client-exclusive-necc))))
(local
(defthm ch2-exclusive-means-set-idle
(implies (and (ch2-client-exclusive ch2 keys clients)
(memberp i keys)
(memberp m keys)
(memberp n keys)
(equal (g i ch2) :grant-exclusive))
(equal (g m (s n v clients)) (if (equal m n) v :idle)))))
(local
(defthm |ch2-exclusive causes coherence|
(implies (and (ch2-client-exclusive ch2 keys clients)
(memberp i keys)
(equal (g i ch2) :grant-exclusive))
(coherent-processes keys (s j :exclusive clients)))
:hints (("Goal"
:in-theory (enable coherent-processes)
:cases
((equal
j
(car (coherent-processes-witness
keys (s j :exclusive clients)))))))))
;; Now of course rule 8 should just go through.
(local
(defthm |coherent after rule 8|
(implies (and (ch2-client-exclusive-invariant st)
(coherent st)
(equal (action stimulus) :client-receives-exclusive))
(coherent (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of Coherence ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Of course we have now done the coherence, but we now have two other
;; predicates that we need to prove as invariants. They are
;; ch2-client-shared-invariant and ch2-client-exclusive-invariant. I must now
;; prove that these persist too, and in the process add more predicates. I
;; will have a section for each predicate I prove (rather a subsection to
;; Section 3), and each proof will end with a comment "End Proof of ....".
;; This is principally so that I can efficiently search in emacs for the proofs
;; of the predicates I have done.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.1: Proof of ch2-client-shared-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; The default cases as usual.
(local
(defthm |ch2 shared default cases|
(implies (and (ch2-client-shared-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(ch2-client-shared-invariant (german-step st stimulus)))))
;; Let us now first take care of sharer-invalidate-cache. This works because
;; if I set something to :idle then nothing changes in terms of what has
;; shared.
(local
(defthm ch2-shared-if-idle
(implies (and (ch2-client-shared ch2 keys clients)
(not (equal val :grant-shared)))
(ch2-client-shared (s i val ch2) keys (s j :idle clients)))
:hints
(("Goal"
:cases
((equal
i
(car (ch2-client-shared-witness
(s i val ch2) keys (s j :idle clients))))
(equal
j
(mv-nth 1 (ch2-client-shared-witness (s i val ch2) keys
(s j :idle clients))))))
("Subgoal 2"
:in-theory (enable ch2-client-shared))
("Subgoal 1"
:in-theory (enable ch2-client-shared))
("Subgoal 3"
:use
((:instance (:definition ch2-client-shared)
(clients (s j :idle clients))
(ch2 (s i val ch2)))
(:instance
ch2-client-shared-necc
(i (car (ch2-client-shared-witness (s i val ch2) keys
(s j :idle clients))))
(j (mv-nth 1 (ch2-client-shared-witness (s i val ch2)
keys
(s j :idle clients))))))))))
(local
(defthm |ch2-shared if sharer-invalidate|
(implies (and (ch2-client-shared-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(ch2-client-shared-invariant (german-step st stimulus)))))
;; Now let us take the other cases in turn. For the case
;; :home-sends-invalidate for example, we know that ch2-client-shared-invariant
;; still holds after the action if it held before. This is because if we
;; change ch2 to something other than :grant-shared the
;; ch2-client-shared-invariant does not change. Let us first prove this fact.
(local
(defthm ch2-client-shared-after-arbitrary
(implies (and (not (equal val :grant-shared))
(ch2-client-shared ch2 keys clients))
(ch2-client-shared (s pid val ch2) keys clients))
:hints (("Goal"
:cases
((equal
(car (ch2-client-shared-witness (s pid val ch2) keys clients))
pid)))
("Subgoal 2"
:use
((:instance (:definition ch2-client-shared)
(ch2 (s pid val ch2)))
(:instance
ch2-client-shared-necc
(i (car (ch2-client-shared-witness (s pid val ch2) keys
clients)))
(j (mv-nth 1 (ch2-client-shared-witness (s pid val ch2) keys
clients))))))
("Subgoal 1"
:use
((:instance (:definition ch2-client-shared)
(ch2 (s pid val ch2)))
(:instance
ch2-client-shared-necc
(i (car (ch2-client-shared-witness (s pid val ch2) keys
clients)))
(j (mv-nth 1 (ch2-client-shared-witness (s pid val ch2) keys
clients)))))))))
;; While we are at it, we might also prove that if a client is set to :shared
;; then the invariant remains.
(local
(defthm |ch2-client-shared after setting shared|
(implies (and (ch2-client-shared ch2 keys clients)
(equal (g i ch2) :grant-shared))
(ch2-client-shared ch2 keys (s j :shared clients)))
:hints (("Goal"
:cases
((equal
j
(mv-nth 1
(ch2-client-shared-witness
ch2 keys (s j :shared clients))))))
("Subgoal 2"
:use
((:instance
(:definition ch2-client-shared)
(clients (s j :shared clients)))
(:instance
ch2-client-shared-necc
(i (car (ch2-client-shared-witness
ch2 keys (s j :shared clients))))
(j (mv-nth
1 (ch2-client-shared-witness
ch2
keys (s j :shared clients)))))))
("Subgoal 1"
:use
((:instance
(:definition ch2-client-shared)
(clients (s j :shared clients)))
(:instance
ch2-client-shared-necc
(i (car (ch2-client-shared-witness
ch2 keys (s j :shared clients))))
(j (mv-nth
1 (ch2-client-shared-witness
ch2
keys (s j :shared clients))))))))))
;; OK this takes care of three of the 5 non-trivial cases of the
;; ch2-client-shared-invariant as shown below.
(local
(defthm |ch2 shared invariant after no grants-shared set|
(implies (and (ch2-client-shared-invariant st)
(memberp (action stimulus) '(:home-grants-exclusive
:client-receives-shared
:home-sends-invalidate)))
(ch2-client-shared-invariant (german-step st stimulus)))))
;; That leaves us with two cases, namely :home-grants-shared and
;; :client-receives-exclusive. Let us look at :home-grants-shared. Why is
;; this going to satisfy ch2-client-shared-invariant? The reason is that when
;; heg is nil every client has status shared or idle.
;; I add this fact as another predicate, since this is a new fact about the
;; system that is not covered by the predicates we have created so far. The
;; predicate is specified below.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk not-heg-clients-shared (heg keys clients)
(forall i
(implies (and (not heg)
(memberp i keys))
(or (equal (g i clients) :shared)
(equal (g i clients) :idle))))))
(local
(defun not-heg-clients-shared-invariant (st)
(not-heg-clients-shared (heg st) (keys) (clients st))))
(local
(defthm |init has not-heg-shared|
(not-heg-clients-shared-invariant (init))))
(local
(in-theory (disable not-heg-clients-shared not-heg-clients-shared-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; And clearly if this predicate holds then ch2-client-shared holds trivially.
(local
(defthm not-heg-clients-shared-implies-ch2-shared
(implies (and (not-heg-clients-shared heg keys clients)
(not heg))
(ch2-client-shared ch2 keys clients))
:hints (("Goal"
:use
((:instance (:definition ch2-client-shared))
(:instance
not-heg-clients-shared-necc
(i (mv-nth 1 (ch2-client-shared-witness ch2 keys clients)))))))))
(local
(defthm |ch2 shared invariant after home grants shared|
(implies (and (ch2-client-shared-invariant st)
(not-heg-clients-shared-invariant st)
(equal (action stimulus) :home-grants-shared))
(ch2-client-shared-invariant (german-step st stimulus)))))
;; The question of grant-exclusive is more interesting. What do we want in
;; this case? We want to say that in case of a :grant-exclusive all other
;; channels have nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk channel-nil-exclusive (ch2 keys)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(not (equal i j))
(equal (g i ch2) :grant-exclusive))
(equal (g j ch2) nil)))))
(local
(defun channel-nil-exclusive-invariant (st)
(channel-nil-exclusive (ch2 st) (keys))))
(local
(defthm |init has channel-nil-exclusive|
(channel-nil-exclusive-invariant (init))))
(local
(in-theory (disable channel-nil-exclusive
channel-nil-exclusive-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Why does channel-nil-invariant allow us to prove
;; ch2-client-shared-invariant? Well, the point is that if ch2-nil-invariant
;; holds then there is no channel that has value :grant-shared. Let us prove
;; this.
(local
(defthm channel-nil-for-exclusiv-implies-not-anything-else
(implies (and (channel-nil-exclusive ch2 keys)
(memberp i keys)
(equal (g i ch2) :grant-exclusive)
(memberp j keys))
(equal (g j ch2)
(if (equal i j) :grant-exclusive nil)))
:hints (("Goal"
:use channel-nil-exclusive-necc))))
(local
(defthm channel-nil-implies-ch2-client-shared
(implies (and (channel-nil-exclusive ch2 keys)
(memberp i keys)
(not (equal a :grant-shared))
(equal (g i ch2) :grant-exclusive))
(ch2-client-shared (s j a ch2)
keys
(s j b clients)))
:hints (("Goal"
:cases ((equal j (car (ch2-client-shared-witness
(s j a ch2)
keys
(s j b clients))))))
("Subgoal 1"
:in-theory (enable ch2-client-shared))
("Subgoal 2"
:in-theory (enable ch2-client-shared)))))
(local
(defthm |ch2-shared after client-receives-exclusive|
(implies (and (ch2-client-shared-invariant st)
(channel-nil-exclusive-invariant st)
(equal (action stimulus) :client-receives-exclusive))
(ch2-client-shared-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of ch2-client-shared-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.2: Proof of ch2-client-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |ch2 exclusive default cases|
(implies (and (ch2-client-exclusive-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:client-receives-shared
:client-receives-exclusive
:sharer-invalidate-cache
:home-grants-shared
:home-grants-exclusive))))
(ch2-client-exclusive-invariant (german-step st stimulus)))))
;; Now here is a property of ch2-client-exclusive. If it holds for a state
;; then I can set ch2 of any process to a value other than :grant-exclusive and
;; set any client to :idle and the predicate is still going to hold. This
;; takes care of sharer-invalidate-cache when I set ch2 to nil and the client
;; to :idle.
(local
(defthm ch2-exclusive-if-idle
(implies (and (ch2-client-exclusive ch2 keys clients)
(not (equal val :grant-exclusive)))
(ch2-client-exclusive (s i val ch2) keys (s j :idle clients)))
:hints
(("Goal"
:cases
((equal
i
(car (ch2-client-exclusive-witness
(s i val ch2) keys (s j :idle clients))))
(equal
j
(mv-nth 1 (ch2-client-exclusive-witness (s i val ch2) keys
(s j :idle clients))))))
("Subgoal 2"
:in-theory (enable ch2-client-exclusive))
("Subgoal 1"
:in-theory (enable ch2-client-exclusive))
("Subgoal 3"
:use
((:instance (:definition ch2-client-exclusive)
(clients (s j :idle clients))
(ch2 (s i val ch2)))
(:instance
ch2-client-exclusive-necc
(i (car (ch2-client-exclusive-witness (s i val ch2) keys
(s j :idle clients))))
(j (mv-nth 1 (ch2-client-exclusive-witness (s i val ch2)
keys
(s j :idle clients))))))))))
(local
(defthm |ch2-exclusive if sharer-invalidate|
(implies (and (ch2-client-exclusive-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(ch2-client-exclusive-invariant (german-step st stimulus)))))
;; Notice however, that the property above does not let us prove things for
;; (say) home-sends-invalidate. This is because in that condition the client
;; is not changed. So we will prove also the lemma that says that we are fine
;; if the client is not changed. This is in fact an easier property than the
;; one we proved before, but we need to prove it anyways. Maybe I could have
;; generalized the property above a little bit and saved myself this lemma.
;; But I dont bother since I am lazy.
(local
(defthm ch2-client-exclusive-after-arbitrary
(implies (and (not (equal val :grant-exclusive))
(ch2-client-exclusive ch2 keys clients))
(ch2-client-exclusive (s pid val ch2) keys clients))
:hints
(("Goal"
:cases
((equal
(car (ch2-client-exclusive-witness (s pid val ch2) keys clients))
pid)))
("Subgoal 2"
:use
((:instance (:definition ch2-client-exclusive)
(ch2 (s pid val ch2)))
(:instance
ch2-client-exclusive-necc
(i (car (ch2-client-exclusive-witness (s pid val ch2) keys clients)))
(j (mv-nth 1 (ch2-client-exclusive-witness
(s pid val ch2) keys clients))))))
("Subgoal 1"
:use
((:instance (:definition ch2-client-exclusive)
(ch2 (s pid val ch2)))
(:instance
ch2-client-shared-necc
(i (car (ch2-client-exclusive-witness (s pid val ch2) keys clients)))
(j (mv-nth 1 (ch2-client-exclusive-witness
(s pid val ch2) keys clients)))))))))
;; This now allows us to prove that ch2-client-exclusive-invariant holds under
;; the actions :home-grants-shared and :home-sends-invalidate.
(local
(defthm |ch2 exclusive for invalidate and shared|
(implies (and (ch2-client-exclusive-invariant st)
(memberp (action stimulus)
'(:home-grants-shared
:home-sends-invalidate)))
(ch2-client-exclusive-invariant (german-step st stimulus)))))
;; Now we are left with three cases, namely client-receives-shared,
;; client-receives-exclusive, and home-grants-exclusive. Why do these cases
;; work? For the first I will use the property that if there is a
;; :grant-exclusive in a channel then all others have nil. In other words I
;; would make use of the channel-nil-exclusive-invariant that I had already
;; defined.
;; Let us first do the case where client is getting shared. Now why does
;; ch2-client-exclusive-invariant hold in this case? Well, there are two cases.
;; Suppose that there was an index having :grant-exclusive in the channel.
;; Then I know that no other channel has :grant-shared (and thus the system
;; does not take a step) so we are done. Otherwise, there is no
;; :grant-exclusive, and thus after taking a step there is still no
;; grant-exclusive and hence we are done.
;; The analysis above suggests that we can define a predicate called
;; no-grant-exclusive to check if there is no grant-exclusive or not, and then
;; use that to prove the persistence of ch2-client-exclusive-invariant. Notice
;; that we are defining this predicate to simplify our reasoning, but this
;; predicate follows in our cases for channel-nil-exclusive. So this is not a
;; new predicate that goes in the definition of the inductive invariant.
;; Indeed, if I am willing to think harder and type more I can get rid of the
;; definition as well.
(local
(defun-sk no-grant-exclusive (keys ch2)
(forall i
(implies (memberp i keys)
(not (equal (g i ch2) :grant-exclusive))))))
(local (in-theory (disable no-grant-exclusive no-grant-exclusive-necc)))
;; Now we first prove that if there is no grant-exclusive then
;; ch2-client-exclusive-invariant holds.
(local
(defthm no-grant-exclusive-implies-ch2-exclusive
(implies (no-grant-exclusive keys ch2)
(ch2-client-exclusive ch2 keys clients))
:hints
(("Goal"
:in-theory (enable ch2-client-exclusive)
:use
((:instance
no-grant-exclusive-necc
(i (car (ch2-client-exclusive-witness ch2 keys clients)))))))))
;; Now we will show that if no-grant-exclusive does not hold that is, if there
;; is some process with :grant-exclusive and there is some other which has some
;; other value then ch2-client-exclusive-invariant does not hold.
(local
(defthm not-grant-exclusive-and-something-implies-not-invariant
(implies (and (not (no-grant-exclusive keys ch2))
(g i ch2)
(memberp i keys)
(not (equal (g i ch2) :grant-exclusive)))
(equal (channel-nil-exclusive ch2 keys) NIL))
:hints (("Goal"
:in-theory (enable no-grant-exclusive)
:use ((:instance channel-nil-exclusive-necc
(i (no-grant-exclusive-witness keys ch2))
(j i)))))))
;; Finally, no-grant-exclusive must mean that after setting a channel to NIL,
;; we still have that property.
(local
(defthm no-grant-after-setting-channel
(implies (no-grant-exclusive keys ch2)
(no-grant-exclusive keys (s i nil ch2)))
:hints
(("Goal"
:use
((:instance (:definition no-grant-exclusive)
(ch2 (s i nil ch2)))
(:instance
no-grant-exclusive-necc
(i (no-grant-exclusive-witness keys (s i nil ch2))))))
("Goal'"
:cases
((equal i (no-grant-exclusive-witness keys (s i nil ch2))))))))
;; Now of course I am done by simply splitting the two cases about whether
;; no-grants-exclusive holds or not.
(local
(defthm |ch2 exclusive for client sharing|
(implies (and (ch2-client-exclusive-invariant st)
(channel-nil-exclusive-invariant st)
(equal (action stimulus) :client-receives-shared))
(ch2-client-exclusive-invariant (german-step st stimulus)))
:hints (("Goal"
:cases ((no-grant-exclusive (keys) (ch2 st)))))))
;; Now we are down to the two cases, which are home-grants-exclusive and
;; client-receives-exclusive. I look at client-receives-exclusive first since
;; that is simpler. Now when client-receives-exclusive, it sets channel to
;; nil, and client to exclusive. We need to ensure that for all channel i if i
;; has the value :grant-exclusive then every client is :idle. But since we are
;; setting every channel to nil, there is no channel with :grant-exclusive, and
;; therefore the invariant is trivial.
(local
(defthm ch2-exclusive-after-ch2-nil
(implies (and (channel-nil-exclusive ch2 keys)
(memberp i keys)
(memberp j keys)
(equal (g i ch2) :grant-exclusive))
(equal (g j (s i nil ch2)) NIL))
:hints (("Goal"
:cases ((equal j i))))))
(local
(defthm ch2-exclusive-after-ch2-nil-2
(implies (and (channel-nil-exclusive ch2 keys)
(equal (g j ch2) :grant-exclusive)
(memberp j keys))
(ch2-client-exclusive (s j nil ch2) keys (s m val clients)))
:hints
(("Goal"
:cases
((equal
j
(car (ch2-client-exclusive-witness
(s i nil ch2) keys (s m val clients))))))
("Subgoal 2"
:in-theory (enable ch2-client-exclusive))
("Subgoal 1"
:in-theory (enable ch2-client-exclusive)))))
(local
(defthm |ch2 exclusive for client exclusive|
(implies (and (ch2-client-exclusive-invariant st)
(channel-nil-exclusive-invariant st)
(equal (action stimulus) :client-receives-exclusive))
(ch2-client-exclusive-invariant (german-step st stimulus)))))
;; The last case, namely home-grants-exclusive. To do this one, what we need
;; to decide how home can manage to send an :invalidate in channel 2. Of
;; course this means that all processes must have channel 2 NIL.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hsl-client (keys clients hsl)
(if (endp keys) T
(and (implies (not (equal (g (first keys) clients) :idle))
(equal (g (first keys) hsl) T))
(hsl-client (rest keys) clients hsl)))))
(local
(defun hsl-client-invariant (st) (hsl-client (keys) (clients st) (hsl st))))
(local
(defthm hsl-client-set
(implies (hsl-client keys clients hsl)
(hsl-client keys (s i :idle clients) hsl))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm hsl-client-initial-client
(hsl-client keys (initial-clients keys) hsl)))
(local
(defthm |init has hsl-client|
(hsl-client-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm hsl-ch2-and-all-false
(implies (and (hsl-client keys clients hsl)
(all-false keys hsl)
(memberp i keys))
(equal (g i clients) :idle))))
(local
(defthm hsl-client-implies-ch2-exclusive
(implies (and (hsl-client keys clients hsl)
(all-false keys hsl))
(ch2-client-exclusive (s i v ch2) keys clients))
:hints (("Goal"
:in-theory (enable ch2-client-exclusive)))))
(local
(defthm |ch2-exclusive for home-grants-exclusive|
(implies (and (hsl-client-invariant st)
(ch2-client-exclusive-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(ch2-client-exclusive-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of ch2-client-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right. One more gone. The next predicate is
;; not-heg-clients-shared-invariant.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.3: Proof of not-heg-clients-shared-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |not heg shared default cases|
(implies (and (not-heg-clients-shared-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-exclusive))))
(not-heg-clients-shared-invariant (german-step st stimulus)))))
;; Now comes the analysis. At home-receives-invalidate, the heg is set to nil.
;; So why is the invariant holding here? The reason is that we can claim that
;; if ch3 has invalidate-ack then all clients are either :idle or :shared.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk invalidate-ack-clients (clients ch3 keys)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(equal (g i ch3) :invalidate-ack))
(or (equal (g j clients) :idle)
(equal (g j clients) :shared))))))
(local
(defun invalidate-ack-clients-invariant (st)
(invalidate-ack-clients (clients st) (ch3 st) (keys))))
(local
(defthm |init has invariant-ack-ch3|
(invalidate-ack-clients-invariant (init))))
(local
(in-theory (disable invalidate-ack-clients invalidate-ack-clients-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now I can claim that if invalidate-ack holds then
;; not-heg-clients-shared-invariant holds.
(local
(defthm invalidate-ack-implies-not-heg
(implies (and (invalidate-ack-clients clients ch3 keys)
(memberp i keys)
(equal (g i ch3) :invalidate-ack))
(not-heg-clients-shared val keys clients))
:hints
(("Goal"
:use
((:instance (:definition not-heg-clients-shared)
(heg val))
(:instance
invalidate-ack-clients-necc
(j (not-heg-clients-shared-witness val keys clients))))))))
(local
(defthm |heg-shared after home-receives-invalidate|
(implies (and (not-heg-clients-shared-invariant st)
(invalidate-ack-clients-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(not-heg-clients-shared-invariant (german-step st stimulus)))))
;; The next case is when client receives shared. This works because client of
;; course can receive as much shared as it wants, and nothing will happen to
;; this predicate.
(local
(defthm not-heg-clients-shared-remains-with-shared
(implies (and (not-heg-clients-shared heg keys clients)
(or (equal val :shared)
(equal val :idle)))
(not-heg-clients-shared heg keys (s i val clients)))
:hints
(("Goal"
:use
((:instance (:definition not-heg-clients-shared)
(clients (s i val clients)))
(:instance
not-heg-clients-shared-necc
(i (not-heg-clients-shared-witness heg keys (s i val clients))))))
("Goal'"
:cases
((equal i
(not-heg-clients-shared-witness heg keys
(s i val clients))))))))
;; So this should give me the case of client-receives-shared.
(local
(defthm |heg-shared after client-receives-shared|
(implies (and (not-heg-clients-shared-invariant st)
(memberp (action stimulus) '(:sharer-invalidate-cache
:client-receives-shared)))
(not-heg-clients-shared-invariant (german-step st stimulus)))))
;; What happens when client-receives-exclusive? What I need here is that when
;; ch2 has grant-exclusive then heg is T
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk heg-exclusive (heg keys ch2)
(forall i
(implies (and (memberp i keys)
(equal (g i ch2) :grant-exclusive))
heg))))
(local
(defun heg-exclusive-invariant (st) (heg-exclusive (heg st) (keys) (ch2 st))))
(local
(defthm |init has heg-exclusive| (heg-exclusive-invariant (init))))
(local (in-theory (disable heg-exclusive heg-exclusive-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm heg-exclusive-and-grant-implies-not-heg
(implies (and (heg-exclusive heg keys ch2)
(memberp i keys)
(equal (g i ch2) :grant-exclusive))
(not-heg-clients-shared heg keys (s j val clients)))
:hints (("Goal"
:use ((:instance (:definition not-heg-clients-shared)
(clients (s j val clients)))
(:instance heg-exclusive-necc))))))
(local
(defthm |heg shared after client-receives-exclusive|
(implies (and (not-heg-clients-shared-invariant st)
(heg-exclusive-invariant st)
(equal (action stimulus) :client-receives-exclusive))
(not-heg-clients-shared-invariant (german-step st stimulus)))))
;; One more to go. This is when home-grants-exclusive. This is the most
;; trivial of the lot. This holds because when home-grants-exclusive it sets
;; heg to T.
(local
(defthm heg-implies-anything-fine
(implies heg
(not-heg-clients-shared heg keys clients))
:hints (("Goal"
:in-theory (enable not-heg-clients-shared)))))
(local
(defthm |heg shared after home-grants-exclusive|
(implies (and (not-heg-clients-shared-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(not-heg-clients-shared-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of ch2-client-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right so I am done with not-heg-clients-shared-invariant. Now I come to
;; channel-nil-exclusive-invariant. This says that if one of the channels has
;; grant-exclusive then all other channels must be nil. To an extent this is a
;; pretty strong statement and almost is the statement of coherence stated in
;; terms of channels. So doing this is going to take some effort.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.4: Proof of channel-nil-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |channel-nil-exclusive default cases|
(implies (and (channel-nil-exclusive-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(channel-nil-exclusive-invariant (german-step st stimulus)))))
;; The next cases to consider are those in which the channel is set to nil.
;; Obviously if a channel is set to nil then nothing can change.
(local
(defthm channel-set-to-nil-implies-channel-nil
(implies (channel-nil-exclusive ch2 keys)
(channel-nil-exclusive (s i nil ch2) keys))
:hints
(("Goal"
:cases
((equal i (car (channel-nil-exclusive-witness (s i nil ch2)
keys)))
(equal i (mv-nth 1 (channel-nil-exclusive-witness (s i nil ch2)
keys)))))
("Subgoal 2"
:in-theory (enable channel-nil-exclusive))
("Subgoal 1"
:in-theory (enable channel-nil-exclusive))
("Subgoal 3"
:use
((:instance
channel-nil-exclusive-necc
(i (car (channel-nil-exclusive-witness (s i nil ch2)
keys)))
(j (mv-nth 1 (channel-nil-exclusive-witness (s i nil ch2)
keys))))
(:instance (:definition channel-nil-exclusive)
(ch2 (s i nil ch2))))))))
(local
(defthm |channels-nil when ch2 set to nil|
(implies (and (channel-nil-exclusive-invariant st)
(memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(channel-nil-exclusive-invariant (german-step st stimulus)))))
;; Now comes the three interesting cases. First is when home-grants-exclusive.
;; I should then know that all channels are nil. This works because I know
;; that all keys are false in hsl. As a result, all channels must be nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hsl-ch2 (hsl keys ch2)
(if (endp keys) T
(and (implies (g (first keys) ch2)
(equal (g (first keys) hsl) T))
(hsl-ch2 hsl (rest keys) ch2)))))
(local
(defun hsl-ch2-invariant (st) (hsl-ch2 (hsl st) (keys) (ch2 st))))
(local
(defthm hsl-ch2-nil (hsl-ch2 nil keys nil)))
(local (defthm |init has hsl-ch2| (hsl-ch2-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm hsl-ch2-and-all-false-implies-nil
(implies (and (hsl-ch2 hsl keys ch2)
(memberp i keys)
(all-false keys hsl))
(equal (g i ch2) nil))))
(local
(defthm hsl-ch2-implies-channel-nil-exclusive
(implies (and (hsl-ch2 hsl keys ch2)
(all-false keys hsl))
(channel-nil-exclusive (s i :grant-exclusive ch2) keys))
:hints (("Goal"
:cases ((equal i (car (channel-nil-exclusive-witness
(s i :grant-exclusive ch2) keys)))))
("Subgoal 2"
:in-theory (enable channel-nil-exclusive))
("Subgoal 1"
:in-theory (enable channel-nil-exclusive)))))
(local
(defthm |channel-nil-exclusive grant-exclusive|
(implies (and (channel-nil-exclusive-invariant st)
(hsl-ch2-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(channel-nil-exclusive-invariant (german-step st stimulus)))))
;; What happens when home-grants-shared? We know (not heg). Thus we
;; automatically know that there is no :grants-exclusive. Hence we have
;; nothing to prove.
(local
(defthm heg-exclusive-and-not-heg-implies-no-exclusive
(implies (and (heg-exclusive heg keys ch2)
(not heg)
(not (equal val :grant-exclusive)))
(channel-nil-exclusive (s i val ch2) keys))
:hints (("Goal"
:cases ((equal i (car (channel-nil-exclusive-witness
(s i val ch2) keys)))))
("Subgoal 2"
:use ((:instance heg-exclusive-necc
(heg nil)
(i (car (channel-nil-exclusive-witness
(s i val ch2) keys)))))
:in-theory (enable channel-nil-exclusive))
("Subgoal 1"
:use ((:instance heg-exclusive-necc
(heg nil)
(i (car (channel-nil-exclusive-witness
(s i val ch2) keys)))))
:in-theory (enable channel-nil-exclusive)))))
(local
(defthm |channel-nil-exclusive grant-shared|
(implies (and (channel-nil-exclusive-invariant st)
(heg-exclusive-invariant st)
(equal (action stimulus) :home-grants-shared))
(channel-nil-exclusive-invariant (german-step st stimulus)))))
;; A more interesting case, and in fact the last case for this predicate, will
;; come up now. This is when home-sends-invalidate. Now I should again know
;; that if (g i hil) holds and heg is T then for all j!=i (g j ch2) = NIL.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk hil-heg (keys hil ch2 heg)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(g i hil)
(not (equal i j))
heg)
(equal (g j ch2) nil)))))
;; BTW I believe this predicate can be generalized and made prettier. But I am
;; trying to write it in the most brain-dead way possible, since I am too tired
;; to think too much about it....:->
(local
(defun hil-heg-invariant (st) (hil-heg (keys) (hil st) (ch2 st) (heg st))))
(local (defthm |init has hil-heg| (hil-heg-invariant (init))))
(local (in-theory (disable hil-heg hil-heg-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm hil-heg-set-reduction
(implies (and (hil-heg keys hil ch2 heg)
heg
(g i hil)
(memberp i keys)
(memberp j keys))
(equal (g j (s i val ch2))
(if (equal i j) val nil)))
:hints (("Goal"
:use hil-heg-necc))))
(local
(defthm hil-heg-channels-nil
(implies (and (hil-heg keys hil ch2 heg)
heg
(g i hil)
(not (equal val :grant-exclusive))
(memberp i keys))
(channel-nil-exclusive (s i val ch2) keys))
:hints (("Goal"
:cases ((equal i (car (channel-nil-exclusive-witness
(s i val ch2) keys)))))
("Subgoal 1"
:in-theory (enable channel-nil-exclusive))
("Subgoal 2"
:in-theory (enable channel-nil-exclusive)))))
;; The above takes care of invalidation when heg is T. But what do we do when
;; heg is nil? In that case we know that there is no grant-exclusive. Thus
;; there is nothing to do.
(local
(defthm |channels-nil for invalidate|
(implies (and (channel-nil-exclusive-invariant st)
(hil-heg-invariant st)
(heg-exclusive-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(channel-nil-exclusive-invariant (german-step st stimulus)))
:hints (("Goal"
:cases ((heg st))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of channel-nil-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Done with this predicate. Now we move on to hsl-client-invariant. This
;; says that for all keys if the client is not idle then hsl has the value T.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.5: Proof of hsl-client-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hsl-client default cases|
(implies (and (hsl-client-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hsl-client-invariant (german-step st stimulus)))))
;; Of course the way hsl-client has been defined it does not matter if given
;; some hsl-client we set hsl to T.
(local
(defthm hsl-set-reduction
(implies (hsl-client keys clients hsl)
(hsl-client keys clients (s i t hsl)))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
;; This takes care of cases where hsl is set to T
(local
(defthm |hsl-clients if hsl set to T|
(implies (and (hsl-client-invariant st)
(memberp (action stimulus)
'(:home-grants-shared
:home-grants-exclusive)))
(hsl-client-invariant (german-step st stimulus)))))
;; Now we come to thhe non-trivial cases. These are the cases in which either
;; hsl is being set to NIL or client is being set. In either case we require
;; more predicates to show that hsl-client-invariant holds.
;; So why does the predicate hold after home-receives-invalidate? It holds
;; because if I set client to :idle I can do anything.
(local
(defthm hsl-idle-reduction
(implies (hsl-client keys clients hsl)
(hsl-client keys (s i :idle clients) hsl))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-clients if clients idle|
(implies (and (hsl-client-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(hsl-client-invariant (german-step st stimulus)))))
;; The second about when home sets hsl to nil. Here I must carry around as
;; invariant that the corresponding client was idle. But first let us prove
;; that if some client is idle then I can set any value to hsl.
(local
(defthm hsl-idle-reduction-2
(implies (and (hsl-client keys clients hsl)
(equal (g i clients) :idle))
(hsl-client keys clients (s i v hsl)))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
;; Now I must posit a predicate that stipulates that the client is idle. Why
;; do we know that? I must know that if some process has :invalidate-ack in
;; channel 3, then that client is idle. Notice that we had previously
;; specified that *all* clients are :shared or :idle in that case.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk invalidate-ack-idle (clients keys ch3)
(forall i
(implies (and (memberp i keys)
(equal (g i ch3) :invalidate-ack))
(equal (g i clients) :idle)))))
(local
(defun invalidate-ack-idle-invariant (st)
(invalidate-ack-idle (clients st) (keys) (ch3 st))))
(local
(defthm |init has invalidate-ack-idle|
(invalidate-ack-idle-invariant (init))))
(local
(in-theory (disable invalidate-ack-idle invalidate-ack-idle-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now why do I know that the client was idle? This is specified by
;; invalidate-ack. One of the things that invalidate-ack-clients was telling
;; us is that the client which has sent invalidate-ack is :idle.
(local
(defthm invalidate-ack-hsl
(implies (and (invalidate-ack-idle clients keys ch3)
(memberp i keys)
(equal (g i ch3) :invalidate-ack)
(hsl-client keys clients hsl))
(hsl-client keys clients (s i v hsl)))
:hints (("Goal"
:use ((:instance invalidate-ack-idle-necc))))))
(local
(defthm |hsl-clients if hsl set|
(implies (and (invalidate-ack-idle-invariant st)
(hsl-client-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hsl-client-invariant (german-step st stimulus)))))
;; All right now down to two more cases for this predicate. These are cases
;; where the client receives a value either shared or exclusive. Now in these
;; cases I know that hsl-ch2 covers me.
(local
(defthm hsl-ch2-set-reduction
(implies (and (hsl-ch2 hsl keys ch2)
(memberp i keys)
(g i ch2))
(equal (g i hsl) t))))
;; I should look into this proof carefully later if time. The proof works but
;; it does double induction, and I dont like double induction. So there might
;; be something I can do about it. Need to look at subgoal *1/2.
(local
(defthm hsl-ch2-set
(implies (and (equal (g i hsl) t)
(memberp i keys)
(hsl-client keys clients hsl))
(hsl-client keys (s i v clients) hsl))
:hints (("Subgoal *1/5"
:cases ((equal i (car keys)))))))
(local
(defthm hsl-hsl-client-packaged
(implies (and (hsl-ch2 hsl keys ch2)
(hsl-client keys clients hsl)
(memberp i keys)
(g i ch2))
(hsl-client keys (s i v clients) hsl))))
(local
(defthm |hsl-client for client-receives|
(implies (and (hsl-client-invariant st)
(hsl-ch2-invariant st)
(memberp (action stimulus) '(:client-receives-shared
:client-receives-exclusive)))
(hsl-client-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hsl-client-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Done with this one. Now we move on to invalidate-ack-clients-invariant. To
;; be honest this is is a little dicey as a predicate. I probably should have
;; broken it up into two. But I give it an old college try anyways.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.6: Proof of invalidate-ack-clients-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |ch3-client default cases|
(implies (and (invalidate-ack-clients-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive))))
(invalidate-ack-clients-invariant (german-step st stimulus)))))
;; All right now back to work. What home does on receiving an invalidate-ack
;; is remove it. This activity does not change the predicate. So the first
;; case is pretty trivial.
(local
(defthm invalidate-ack-does-not-change-if-set
(implies (and (invalidate-ack-clients clients ch3 keys)
(not (equal v :invalidate-ack)))
(invalidate-ack-clients clients (s i v ch3) keys))
:hints
(("Goal"
:cases
((equal i
(car (invalidate-ack-clients-witness clients (s i v ch3) keys)))))
("Subgoal 1"
:in-theory (enable invalidate-ack-clients))
("Subgoal 2"
:use
((:instance (:definition invalidate-ack-clients)
(ch3 (s i v ch3)))
(:instance
invalidate-ack-clients-necc
(i (car (invalidate-ack-clients-witness clients (s i v ch3) keys)))
(j (mv-nth 1 (invalidate-ack-clients-witness clients (s i v ch3)
keys)))))))))
;; This lets us prove the case of home-receives-invalidate
(local
(defthm |invalidate-ack for home-receives-invalidate|
(implies (and (invalidate-ack-clients-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(invalidate-ack-clients-invariant (german-step st stimulus)))))
;; All right, now how about sharer-invalidate-cache? Well, in this case we are
;; simply setting a client to idle and hence nothing can change in terms of
;; clients. But the problem is that we are introducing an :invalidate-ack. We
;; will do this one case at a time. If there were an invalidate-ack around
;; then we would have no problem. But it is now possible that there is no
;; invalidate-ack-around, and thus someone might be exclusive. But then if I
;; do send an invalidate it should be to the exclusive guy, right? So let us
;; say that as a predicate.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun invalidate-clients (ch2 clients keys)
(if (endp keys) T
(and (implies (equal (g (first keys) ch2) :invalidate)
(or (equal (g (first keys) clients) :shared)
(equal (g (first keys) clients) :exclusive)))
(invalidate-clients ch2 clients (rest keys))))))
(local
(defun invalidate-clients-invariant (st)
(invalidate-clients (ch2 st) (clients st) (keys))))
(local
(defthm invalidate-clients-for-nil
(invalidate-clients nil clients keys)))
(local
(defthm |init has invalidate-clients|
(invalidate-clients-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now let us concentrate on what this predicate together with
;; invalidate-ack-clients tells us. It tells us that the guy to which an
;; invalidate is sent must be shared or exclusive. Let us prove this.
(local
(defthm invalidate-clients-implies-shared-or-exclusive
(implies (and (invalidate-clients ch2 clients keys)
(memberp i keys)
(equal (g i ch2) :invalidate))
(or (equal (g i clients) :shared)
(equal (g i clients) :exclusive)))
:rule-classes :forward-chaining))
(local
(defthm invalidate-and-exclusive-implies-invalidate-exclusive
(implies (and (coherent-processes keys clients)
(invalidate-clients ch2 clients keys)
(memberp i keys)
(memberp j keys)
(equal (g i clients) :exclusive)
(equal (g j ch2) :invalidate))
(equal i j))
:rule-classes :forward-chaining
:hints (("Goal"
:use ((:instance coherent-processes-necc))))))
;; Now if the guy to which invalidate is sent was exclusive then coherent will
;; kick in and show that all other processes are shared or idle. Thus when we
;; set this to anything like idle or shared I should be in great shape.
(local
(defthm invalidate-clients-and-coherent-implies-invalidate-ack
(implies (and (coherent-processes keys clients)
(equal (g i clients) :exclusive)
(memberp i keys)
(or (equal v :shared)
(equal v :idle)))
(invalidate-ack-clients (s i v clients)
(s i u ch3)
keys))
:hints
(("Goal"
:cases ((equal i (mv-nth 1 (invalidate-ack-clients-witness (s i v clients)
(s i u ch3)
keys)))))
("Subgoal 1"
:in-theory (enable invalidate-ack-clients))
("Subgoal 2"
:use
((:instance (:definition invalidate-ack-clients)
(clients (s i v clients))
(ch3 (s i u ch3)))
(:instance coherent-processes-necc
(j (mv-nth 1 (invalidate-ack-clients-witness (s i v clients)
(s i u ch3)
keys)))))))))
;; I want to now say that if invalidate-clients holds and coherent-processes
;; holds then invalidate-ack-clients holds irrespective of which client is
;; being set. This is just packaging up the previous theorems.
(local
(defthm invalidate-clients-and-coherent-for-exclusive
(implies (and (invalidate-clients ch2 clients keys)
(coherent-processes keys clients)
(memberp i keys)
(memberp j keys)
(equal (g j ch2) :invalidate)
(equal (g i clients) :exclusive)
(or (equal v :shared)
(equal v :idle)))
(invalidate-ack-clients (s j v clients)
(s j u ch3)
keys))))
;; All right, now if it is exclusive then we are done. But it can be shared.
;; If it is shared then what do I know? Well, I should know that there is no
;; exclusive at all, from coherent-processes. But that is not sufficient.
;; Because I need to say that if there is nothing that is exclusive then all
;; are shared or idle. And that is not a predicate I have defined yet. So I
;; define the predicate valid-status below to take care of that.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun valid-status (clients keys)
(if (endp keys)
T
(and (or (equal (g (first keys) clients) :idle)
(equal (g (first keys) clients) :shared)
(equal (g (first keys) clients) :exclusive))
(valid-status clients (rest keys))))))
(local
(defun valid-status-invariant (st) (valid-status (clients st) (keys))))
(local
(defthm setting-valid-does-not-change-status
(implies (and (valid-status clients keys)
(or (equal v :idle)
(equal v :shared)
(equal v :exclusive)))
(valid-status (s i v clients) keys))
:hints (("Subgoal *1/3"
:cases ((equal i (car keys)))))))
(local
(defthm valid-status-in-initial (valid-status (initial-clients keys) keys)))
(local
(defthm |init has valid status| (valid-status-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now I should know that if valid-status holds and no process has exclusive
;; then all are idle or shared. To simplify the reasoning let us define a
;; function saying that no process is exclusive. Of course this is not an
;; invariant.
(local
(defun no-exclusive (keys clients)
(if (endp keys)
T
(and (not (equal (g (first keys) clients) :exclusive))
(no-exclusive (rest keys) clients)))))
;; So no-exclusive means that all are idle or shared.
(local
(defthm no-exclusive-implies-all-idle-shared
(implies (and (no-exclusive keys clients)
(valid-status clients keys)
(memberp i keys))
(or (equal (g i clients) :shared)
(equal (g i clients) :idle)))
:rule-classes :forward-chaining))
;; And if no-exclusive does not hold then we have some process that is
;; exclusive. Notice now how we need to (and can) define a recursive function
;; that produces the corresponding witness. It is this witness that comes for
;; free if we do quantification. But I have been using quantification and
;; induction in any way whatsoever depending on my mood while quantifying over
;; only one index. So I need to "create" the witness in this case.
(local
(defun exclusive-witness (keys clients)
(if (endp keys) nil
(if (equal (g (first keys) clients) :exclusive)
(first keys)
(exclusive-witness (rest keys) clients)))))
;; This theorem shows one way of using the witness function. This is
;; essentially how we use existential quantifiers. I am saying that if
;; no-exclusive does not hold then there is an index which is exclusive, in
;; particular, exclusive-witness. This is a standard trick of simulating
;; existential quantification using recursive functions. Later we will
;; (hopefully) see a way of using recursive functions to simulate universal
;; quantification. The method is the same, namely define a witness for the
;; property (for a universal quantification we look for a negation of the
;; property). Then we say that if the witness has the property then every
;; object does. The theorem is proved using induction, and then serves to be
;; used exactly as we used the witnesses for defun-sk.
(local
(defthm exclusive-implies-exclusive-witness
(implies (not (no-exclusive keys clients))
(and (memberp (exclusive-witness keys clients) keys)
(equal (g (exclusive-witness keys clients) clients)
:exclusive)))
:rule-classes :forward-chaining))
;; Now we show that if no-exclusive holds then invalidate-ack-clients holds.
(local
(defthm no-exclusive-implies-invalidate-ack-clients
(implies (and (no-exclusive keys clients)
(valid-status clients keys)
(or (equal v :shared)
(equal v :idle)))
(invalidate-ack-clients (s i v clients)
(s i u ch3)
keys))
:hints
(("Goal"
:cases
((equal i (mv-nth 1 (invalidate-ack-clients-witness (s i v clients)
(s i u ch3)
keys)))))
("Subgoal 1"
:in-theory (enable invalidate-ack-clients))
("Subgoal 2"
:in-theory (enable invalidate-ack-clients)))))
;; And this solves it.
(local
(defthm invalidate-coherent-valid-status-invalidate-ack
(implies (and (invalidate-clients ch2 clients keys)
(equal (g j ch2) :invalidate)
(memberp j keys)
(coherent-processes keys clients)
(valid-status clients keys)
(or (equal v :idle)
(equal v :shared)))
(invalidate-ack-clients (s j v clients) (s j u ch3) keys))
:hints (("Goal"
:cases ((no-exclusive keys clients))))))
;; All right, finally done:
(local
(defthm |invalidate-ack-clients for sharer-invalidate-cache|
(implies (and (invalidate-ack-clients-invariant st)
(invalidate-clients-invariant st)
(coherent st)
(valid-status-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(invalidate-ack-clients-invariant (german-step st stimulus)))))
;; Now why does invalidate-ack-clients hold when we have a grant-shared? The
;; reason is ch2-shared-invariant which says that everybody is shared or idle
;; anyways.
(local
(defthm ch2-shared-implies-invalidate-ack-clients
(implies (and (ch2-client-shared ch2 keys clients)
(equal (g i ch2) :grant-shared)
(memberp i keys)
(or (equal v :shared)
(equal v :idle)))
(invalidate-ack-clients (s i v clients) ch3 keys))
:hints
(("Goal"
:cases
((equal i (mv-nth 1 (invalidate-ack-clients-witness (s i v clients)
ch3
keys)))))
("Subgoal 1"
:in-theory (enable invalidate-ack-clients))
("Subgoal 2"
:in-theory (enable invalidate-ack-clients)
:use
((:instance ch2-client-shared-necc
(j (mv-nth 1 (invalidate-ack-clients-witness (s i v clients)
ch3
keys)))))))))
(local
(defthm |invalidate-ack-clients for grant-shared|
(implies (and (invalidate-ack-clients-invariant st)
(ch2-client-shared-invariant st)
(equal (action stimulus) :client-receives-shared))
(invalidate-ack-clients-invariant (german-step st stimulus)))))
;; Now the last case, which is client-receives-exclusive. I dont like to think
;; about this one right now --- I am tired after doing the rest of the cases.
;; But I am pretty sure that if there is an invalidate-ack somewhere then there
;; cannot be a :grant-exclusive. So for now I posit that as a predicate and go
;; on.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk invalidate-exclusive (ch3 ch2 keys)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(equal (g i ch3) :invalidate-ack))
(not (equal (g j ch2) :grant-exclusive))))))
(local
(defun invalidate-exclusive-invariant (st)
(invalidate-exclusive (ch3 st) (ch2 st) (keys))))
(local
(defthm |init has invalidate-exclusive|
(invalidate-exclusive-invariant (init))))
(local
(in-theory (disable invalidate-exclusive invalidate-exclusive-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; And this predicate is going to throw away the remaining case. Admittedly
;; this is not something I recommend. People should analyze things carefully
;; before positing a predicate like the above. But, well, what the heck, I
;; will do it, since I am pretty confident this is an invariant.
(local
(defthm invalidate-exclusive-implies-grant-exclusive
(implies (and (invalidate-exclusive ch3 ch2 keys)
(memberp i keys)
(equal (g i ch2) :grant-exclusive))
(invalidate-ack-clients clients ch3 keys))
:hints
(("Goal"
:in-theory (enable invalidate-ack-clients)
:use
((:instance
invalidate-exclusive-necc
(j i)
(i (car (invalidate-ack-clients-witness clients ch3 keys)))))))))
(local
(defthm |invalidate-ack-clients after client-receives-exclusive|
(implies (and (invalidate-ack-clients-invariant st)
(invalidate-exclusive-invariant st)
(equal (action stimulus) :client-receives-exclusive))
(invalidate-ack-clients-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of invalidate-ack-clients-invariant
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; OK now I am just making a slight change in the order since it is night and I
;; want to do an easy predicate without thinking too much. So I will now prove
;; valid-status-invariant first. I will get back to the normal order of other
;; predicates tomorrow.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.7: Proof of valid-status-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |valid-status default cases|
(implies (and (valid-status-invariant st)
(not (memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive))))
(valid-status-invariant (german-step st stimulus)))))
;; I ought to have proven some lemma about non-default cases here, but I have
;; already proved that lemma while proving that valid-status holds for the
;; initial states. Thus the rest will go thru as well. I might as well have
;; done the whole thing in one theorem. But I am sticking to the habit of
;; splitting proofs into default and non-default cases.
(local
(defthm |valid-status non-default cases|
(implies (and (valid-status-invariant st)
(memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(valid-status-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of valid-status-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; That was really fast!! I will try one more for tonight then. Let us move on
;; now to heg-exclusive-invariant. This says that if there is a
;; :grant-exclusive in a channel then heg holds. This one is particularly
;; easy.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.8: Proof of heg-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |heg-exclusive defaults cases|
(implies (and (heg-exclusive-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(heg-exclusive-invariant (german-step st stimulus)))))
;; What happens for home-grants-exclusive? This is simple. I know that it sets
;; heg to T. Thus nothing has to be done any more.
(local
(defthm heg-exclusive-if-heg-T
(implies heg
(heg-exclusive heg keys ch2))
:hints (("Goal"
:in-theory (enable heg-exclusive)))))
(local
(defthm |heg exclusive home-grants-exclusive|
(implies (and (heg-exclusive-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(heg-exclusive-invariant (german-step st stimulus)))))
;; More interesting is the bunch of cases where ch2 is set. The good thing is
;; that when ch2 is set to anything other than grant-exclusive we can claim
;; that the predicate simply persists.
(local
(defthm heg-exclusive-if-channel-set
(implies (and (heg-exclusive heg keys ch2)
(not (equal v :grant-exclusive)))
(heg-exclusive heg keys (s i v ch2)))
:hints
(("Goal"
:cases ((equal i (heg-exclusive-witness heg keys (s i v ch2)))))
("Subgoal 1"
:in-theory (enable heg-exclusive))
("Subgoal 2"
:use
((:instance (:definition heg-exclusive)
(ch2 (s i v ch2)))
(:instance
heg-exclusive-necc
(i (heg-exclusive-witness heg keys (s i v ch2)))))))))
;; And this will take care of most of the cases for us.
(local
(defthm |heg-exclusive for ch2 set|
(implies (and (heg-exclusive-invariant st)
(memberp (action stimulus)
'(:home-sends-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive)))
(heg-exclusive-invariant (german-step st stimulus)))))
;; The only thorny case is when home actually gets an invalidate. Then it sets
;; heg to nil. Why is this ok? This is ok since we have just by serendipity
;; added the predicate invalidate-exclusive which says that there is no
;; invalidate-ack and grant-exclusive together. Let us prove that it does it.
(local
(defthm invalidate-exclusive-implies-not-heg-is-fine
(implies (and (invalidate-exclusive ch3 ch2 keys)
(memberp i keys)
(equal (g i ch3) :invalidate-ack))
(heg-exclusive heg keys ch2))
:hints (("Goal"
:in-theory (enable heg-exclusive)
:use ((:instance invalidate-exclusive-necc
(j (heg-exclusive-witness heg keys ch2))))))))
(local
(defthm |heg-exclusive for home-receives-invalidate|
(implies (and (heg-exclusive-invariant st)
(invalidate-exclusive-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(heg-exclusive-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of heg-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right, so heg-exclusive out of the way. We get to hsl-ch2.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.9: Proof of hsl-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hsl-ch2 default cases|
(implies (and (hsl-ch2-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hsl-ch2-invariant (german-step st stimulus)))))
;; Here is what one has to do when recursive functions are defined (rather than
;; quantified predicates). I am proving that hsl-ch2 holds after setting i to
;; T in clients and v in ch2. If we defined this predicate using
;; quantification we would have used the cases hint and applied the
;; instantiation of the necc lemma on the first with the witness of the second.
;; But here we prove it using induction. The cases hint we gave can be easily
;; understood by looking at the failed proof. But I dont go into that here.
(local
(defthm hsl-ch2-after-setting-hsl
(implies (hsl-ch2 hsl keys ch2)
(hsl-ch2 (s i T hsl) keys (s i v ch2)))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-ch2 after home sets|
(implies (and (hsl-ch2-invariant st)
(memberp (action stimulus)
'(:home-grants-shared
:home-grants-exclusive)))
(hsl-ch2-invariant (german-step st stimulus)))))
(local
(defthm hsl-ch2-after-ch2-nil
(implies (hsl-ch2 hsl keys ch2)
(hsl-ch2 hsl keys (s i nil ch2)))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-ch2 after client sets|
(implies (and (hsl-ch2-invariant st)
(memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(hsl-ch2-invariant (german-step st stimulus)))))
;; All right now down to the two non-trivial cases for this predicate, namely
;; that home-sends-invalidate and home-receives-invalidate. These two cases
;; involve the following consideration. In home-sends-invalidate I add a
;; :invalidate to ch2. So it must be that hsl is not nil. Why is this true?
;; The reason is that the index is in hil. So we must know that if something
;; is in hil, then it is in hsl. This is true because the hil is set from hsl,
;; and hil is reset *before* hsl.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hil-hsl (hil hsl keys)
(if (endp keys) T
(and (implies (g (first keys) hil)
(equal (g (first keys) hsl) t))
(hil-hsl hil hsl (rest keys))))))
(local
(defun hil-hsl-invariant (st) (hil-hsl (hil st) (hsl st) (keys))))
(local
(defthm hil-hsl-for-nil (hil-hsl nil nil keys)))
(local (defthm |init has hil-hsl| (hil-hsl-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; How does this work? I first know that if hil-hsl holds then every index in
;; hil must have hsl t. When home-sends-invalidate, the hil is t and hence hsl
;; is t. Since hsl is T anyways I dont have to think about what is added to
;; ch2.
(local
(defthm hil-hsl-and-hil-implies-hsl
(implies (and (hil-hsl hil hsl keys)
(g i hil)
(memberp i keys))
(equal (g i hsl) t))))
(local
(defthm hsl-hil-ch2
(implies (and (hil-hsl hil hsl keys)
(hsl-ch2 hsl keys ch2)
(memberp i keys)
(g i hil))
(hsl-ch2 hsl keys (s i v ch2)))
:hints (("Subgoal *1/6"
:cases ((equal i (car keys)))))))
;; Now I can deal with home-sends-invalidate
(local
(defthm |hsl-ch2 after home-sends-invalidate|
(implies (and (hsl-ch2-invariant st)
(hil-hsl-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hsl-ch2-invariant (german-step st stimulus)))))
;; Now I need to deal with home receives invalidate. What this amounts to is
;; the following. If home receives an invalidate-ack in ch3, that means that
;; the ch2 of that process is nil. This lets us prove this.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun invalidate-ack-ch2 (ch2 ch3 keys)
(if (endp keys) T
(and (implies (equal (g (first keys) ch3) :invalidate-ack)
(not (g (first keys) ch2)))
(invalidate-ack-ch2 ch2 ch3 (rest keys))))))
(local
(defun invalidate-ack-ch2-invariant (st)
(invalidate-ack-ch2 (ch2 st) (ch3 st) (keys))))
(local
(defthm invalidate-ack-ch2-nil (invalidate-ack-ch2 nil nil keys)))
(local
(defthm |init has invalidate-ack-ch2|
(invalidate-ack-ch2-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Notice how I am proving these theorems by induction now. I believe
;; induction and quantification really require the same thought and insight,
;; but ACL2 needs a little more support for quantifiers.
(local
(defthm invalidate-ack-ch2-implies-can-set-hsl
(implies (and (invalidate-ack-ch2 ch2 ch3 keys)
(hsl-ch2 hsl keys ch2)
(equal (g i ch3) :invalidate-ack)
(memberp i keys))
(hsl-ch2 (s i v hsl) keys ch2))
:hints (("Subgoal *1/6"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-ch2 after home receives invalidate|
(implies (and (hsl-ch2-invariant st)
(invalidate-ack-ch2-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hsl-ch2-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hsl-ch2-invariant
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now done with hsl-ch2-invariant. On to hil-heg-invariant. This says that
;; if heg holds and somebody is in the invalidate list then every other channel
;; must have nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.10: Proof of hil-heg-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hil-heg default cases|
(implies (and (hil-heg-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hil-heg-invariant (german-step st stimulus)))))
;; Now the first thing we should know is that if heg is set to nil then there
;; is nothing to prove.
(local
(defthm heg-nil-to-hil-heg
(implies (not heg)
(hil-heg keys hil ch2 heg))
:hints (("Goal"
:in-theory (enable hil-heg)))))
;; That takes care of some of the cases.
(local
(defthm |hil-heg for receive invalidate|
(implies (and (hil-heg-invariant st)
(memberp (action stimulus) '(:home-receives-invalidate
:home-grants-shared)))
(hil-heg-invariant (german-step st stimulus)))))
;; The next thing which covers a lot of cases is the statement that if I set
;; ch2 of any process to nil then hil-heg cannot be violated.
(local
(defthm hil-heg-ch2-nil
(implies (hil-heg keys hil ch2 heg)
(hil-heg keys hil (s i nil ch2) heg))
:hints
(("Goal"
:cases
((equal i (mv-nth 1 (hil-heg-witness keys hil (s i nil ch2) heg)))))
("Subgoal 1"
:in-theory (enable hil-heg))
("Subgoal 2"
:use
((:instance (:definition hil-heg)
(ch2 (s i nil ch2)))
(:instance
hil-heg-necc
(i (car (hil-heg-witness keys hil (s i nil ch2) heg)))
(j (mv-nth 1 (hil-heg-witness keys hil (s i nil ch2) heg)))))))))
;; This will let us prove many of the cases, in particular all that involve
;; client.
(local
(defthm |hil-heg for clients|
(implies (and (hil-heg-invariant st)
(memberp (action stimulus) '(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(hil-heg-invariant (german-step st stimulus)))))
;; Now the more non-trivial cases which involve home picking a request, home
;; sending an invalidate, and home granting an exclusive. Let us look at
;; home-sends-invalidate. Suppose heg is true and no index other than one with
;; hil has ch2. Now home sets the hil of index i to be nil. Why is the
;; invariant ok then? It is ok since we should know at this point that no other
;; index had hil T. But that has not been posited as a predicate yet, so I do
;; so.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk unique-hil (hil heg keys)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(g i hil)
(not (equal i j))
heg)
(not (g j hil))))))
(local
(defun unique-hil-invariant (st) (unique-hil (hil st) (heg st) (keys))))
(local
(defthm |init has unique-hil|
(unique-hil-invariant (init))))
(local
(in-theory (disable unique-hil unique-hil-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now I know that under heg if there is an index in hil then it is a unique
;; index. So I should be able to set this index to anything and set the
;; corresponding channel to anything without violating the hil-heg condition.
;; Now let us come back to hil-heg. We now want to set hil to nil under heg,
;; and know that we do not have any other index with a dangling hil.
(local
(defthm unique-hil-implies-can-set-hil
(implies (and (unique-hil hil heg keys)
(hil-heg keys hil ch2 heg)
heg
(memberp i keys)
(g i hil))
(hil-heg keys (s i v hil) (s i u ch2) heg))
:hints
(("Goal"
:cases
((equal
i
(car (hil-heg-witness keys (s i v hil) (s i u ch2) heg)))))
("Subgoal 2"
:in-theory (enable hil-heg)
:use
((:instance
unique-hil-necc
(j (car (hil-heg-witness keys (s i v hil) (s i u ch2) heg))))))
("Subgoal 1"
:use
((:instance (:definition hil-heg)
(hil (s i v hil))
(ch2 (s i u ch2)))
(:instance
hil-heg-necc
(i (car (hil-heg-witness keys (s i v hil) (s i u ch2) heg)))
(j (mv-nth 1 (hil-heg-witness keys (s i v hil) (s i u ch2) heg))))
(:instance
unique-hil-necc
(i (car (hil-heg-witness keys (s i v hil) (s i u ch2) heg)))
(j (mv-nth 1 (hil-heg-witness keys (s i v hil) (s i u ch2) heg)))))))))
;; All right, now we can prove the hil-heg invariance for
;; home-sends-invalidate.
(local
(defthm |hil-heg when home sends invalidate|
(implies (and (hil-heg-invariant st)
(unique-hil-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hil-heg-invariant (german-step st stimulus)))
:hints (("Goal"
:cases ((heg st))))))
;; What happens when home-grants-exclusive? Here home is setting heg to T so
;; it better damn well know that there is no non-nil value in hil. Now home
;; knows there is no non-nil hil since there is no non-nil hsl and we have
;; hil-hsl as an invariant.
(local
(defthm hil-hsl-and-all-false-to-not-hil
(implies (and (hil-hsl hil hsl keys)
(all-false keys hsl)
(memberp i keys))
(equal (g i hil) nil))))
(local
(defthm hil-hsl-implies-hil-heg
(implies (and (hil-hsl hil hsl keys)
(all-false keys hsl)
(memberp i keys))
(hil-heg keys hil ch2 heg))
:hints (("Goal"
:in-theory (enable hil-heg)))))
(local
(defthm |hil-heg home grants exclusive|
(implies (and (hil-hsl-invariant st)
(hil-heg-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(hil-heg-invariant (german-step st stimulus)))))
;; What happens for home picking a request? We want to say that if someone is
;; in hsl, and if heg is true then that someone must be the only one.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk hsl-heg (hsl heg keys)
(forall (i j)
(implies (and (memberp i keys)
(memberp j keys)
(not (equal i j))
heg
(g i hsl))
(not (g j hsl))))))
(local
(defun hsl-heg-invariant (st) (hsl-heg (hsl st) (heg st) (keys))))
(local
(defthm |init has hsl-heg-invariant|
(hsl-heg-invariant (init))))
(local (in-theory (disable hsl-heg hsl-heg-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm hsl-ch2-set-hsl-reduction
(implies (memberp i keys)
(equal (g i (set-hil-hsl keys hil hsl))
(g i hsl)))
:hints (("Subgoal *1/3"
:cases ((equal i (car keys)))))))
(local
(defthm hsl-heg-and-set-hsl-to-hil-heg
(implies (and (hsl-heg hsl heg keys)
(hsl-ch2 hsl keys ch2)
(hil-heg keys hil ch2 heg)
heg)
(hil-heg keys (set-hil-hsl keys hil hsl) ch2 heg))
:hints
(("Goal"
:use
((:instance (:definition hil-heg)
(hil (set-hil-hsl keys hil hsl)))
(:instance
hsl-heg-necc
(i (car (hil-heg-witness keys (set-hil-hsl keys hil hsl)
ch2 heg)))
(j (mv-nth 1 (hil-heg-witness keys (set-hil-hsl keys hil hsl)
ch2 heg))))
(:instance
hil-heg-necc
(i (car (hil-heg-witness keys
(set-hil-hsl keys hil hsl)
ch2 heg)))
(j (mv-nth 1 (hil-heg-witness keys
(set-hil-hsl keys hil hsl)
ch2 heg)))))))))
(local
(defthm |hil-heg after home-picks-request|
(implies (and (hil-heg-invariant st)
(hsl-ch2-invariant st)
(hsl-heg-invariant st)
(equal (action stimulus) :pick-new-request))
(hil-heg-invariant (german-step st stimulus)))
:hints (("Goal"
:cases ((heg st))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hil-heg-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right, so we are done with hil-heg. This took me surprisingly longer
;; than I thought it would require. Partly this is because I had never thought
;; of pick-new-request as anything worth consideration. But well, nothing is
;; trivial in a protocol after all.
;; Now on to invalidate-ack-idle-invariant. This is actually one of the more
;; trivial ones. Let us try it. Best to start with a simple predicate in the
;; morning.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.11: Proof of invalidate-ack-idle ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |invalidate-ack-idle default cases|
(implies (and (invalidate-ack-idle-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive))))
(invalidate-ack-idle-invariant (german-step st stimulus)))))
;; All right now if home makes changes ch3 nothing can happen to this
;; predicate.
(local
(defthm invalidate-ack-idle-if-other-than-invalidate
(implies (and (invalidate-ack-idle clients keys ch3)
(not (equal v :invalidate-ack)))
(invalidate-ack-idle clients keys (s i v ch3)))
:hints
(("Goal"
:cases ((equal i (invalidate-ack-idle-witness clients keys (s i v ch3)))))
("Subgoal 2"
:use
((:instance (:definition invalidate-ack-idle)
(ch3 (s i v ch3)))
(:instance
invalidate-ack-idle-necc
(i (invalidate-ack-idle-witness clients keys (s i v ch3))))))
("Subgoal 1"
:use
((:instance (:definition invalidate-ack-idle)
(ch3 (s i v ch3)))
(:instance
invalidate-ack-idle-necc
(i (invalidate-ack-idle-witness clients keys (s i v ch3)))))))))
(local
(defthm |home-receives invalidate correctly|
(implies (and (invalidate-ack-idle-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(invalidate-ack-idle-invariant (german-step st stimulus)))))
;; Now what happens when an invalidate-ack is introduced? This is rather
;; trivial since it happens only simultaneously with setting the client to
;; idle. So let us prove this case.
(local
(defthm invalidate-ack-idle-set-idle
(implies (invalidate-ack-idle clients keys ch3)
(invalidate-ack-idle (s i :idle clients) keys
(s i :invalidate-ack ch3)))
:hints
(("Goal"
:cases
((equal i (invalidate-ack-idle-witness (s i :idle clients)
keys
(s i :invalidate-ack ch3)))))
("Subgoal 2"
:use
((:instance (:definition invalidate-ack-idle)
(clients (s i :idle clients))
(ch3 (s i :invalidate-ack ch3)))
(:instance
invalidate-ack-idle-necc
(i (invalidate-ack-idle-witness (s i :idle clients)
keys
(s i :invalidate-ack ch3))))))
("Subgoal 1"
:in-theory (enable invalidate-ack-idle)))))
(local
(defthm |invalidate-ack-idle after sharer invalidates|
(implies (and (invalidate-ack-idle-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(invalidate-ack-idle-invariant (german-step st stimulus)))))
;; Now what happens for grant shared and exclusive? We now set something to
;; shared or exclusive so this is relevant. This is saved for us by
;; invalidate-ack-ch2.
(local
(defthm invalidate-ack-ch2-does-it
(implies (and (invalidate-ack-ch2 ch2 ch3 keys)
(g i ch2)
(memberp i keys))
(equal (equal (g i ch3) :invalidate-ack) nil))))
(local
(defthm not-invalidate-ack-implies-set-anything
(implies (and (not (equal (g i ch3) :invalidate-ack))
(invalidate-ack-idle clients keys ch3))
(invalidate-ack-idle (s i v clients) keys ch3))
:hints
(("Goal"
:cases ((equal i (invalidate-ack-idle-witness (s i v clients) keys ch3))))
("Subgoal 1"
:in-theory (enable invalidate-ack-idle))
("Subgoal 2"
:use
((:instance (:definition invalidate-ack-idle)
(clients (s i v clients)))
(:instance
invalidate-ack-idle-necc
(i (invalidate-ack-idle-witness (s i v clients) keys ch3))))))))
;; And putting the above two lemmas together here is the final one.
(local
(defthm invalidate-ack-ch2-reduction
(implies (and (invalidate-ack-ch2 ch2 ch3 keys)
(g i ch2)
(memberp i keys)
(invalidate-ack-idle clients keys ch3))
(invalidate-ack-idle (s i v clients) keys ch3))))
(local
(defthm |invalidate-ack-idle for clients|
(implies (and (invalidate-ack-idle-invariant st)
(invalidate-ack-ch2-invariant st)
(memberp (action stimulus) '(:client-receives-shared
:client-receives-exclusive)))
(invalidate-ack-idle-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of invalidate-ack-idle-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Ha ha ha. Done with one more. On to invalidate-ack-exclusive. Thi states
;; that if one channel has invalidate-ack then no channel has grant-exclusive.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.12: Proof of invalidate-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |invalidate-exclusive default cases|
(implies (and (invalidate-exclusive-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(invalidate-exclusive-invariant (german-step st stimulus)))))
;; Now of course as long as we do not set ch2 to grant-exclusive, I can set ch2
;; to any value and it should not matter.
(local
(defthm invalidate-exclusive-for-not-grant-exclusive
(implies (and (invalidate-exclusive ch3 ch2 keys)
(not (equal v :grant-exclusive)))
(invalidate-exclusive ch3 (s i v ch2) keys))
:hints
(("Goal"
:cases ((equal i (mv-nth 1 (invalidate-exclusive-witness ch3 (s i v ch2)
keys)))))
("Subgoal 1"
:use
((:instance (:definition invalidate-exclusive)
(ch2 (s i v ch2)))))
("Subgoal 2"
:use
((:instance (:definition invalidate-exclusive)
(ch2 (s i v ch2)))
(:instance
invalidate-exclusive-necc
(i (car (invalidate-exclusive-witness ch3 (s i v ch2) keys)))
(j (mv-nth 1 (invalidate-exclusive-witness ch3 (s i v ch2) keys)))))))))
;; And this takes care of a number of cases, in particular all cases other than
;; home-receives-invalidate grant-exclusive and invalidate-cache. At least so
;; I believe. Let us see if I am right.
(local
(defthm |invalidate-exclusive for not ch2 exclusive|
(implies (and (invalidate-exclusive-invariant st)
(memberp (action stimulus)
'(:home-sends-invalidate
:client-receives-shared
:client-receives-exclusive
:home-grants-shared)))
(invalidate-exclusive-invariant (german-step st stimulus)))))
;; Now why does it work when home receives invalidate? This is also trivial. I
;; can set ch3 to anything other than :invalidate-ack and not violate the
;; invariant. This is what home is doing....
(local
(defthm invalidate-exclusive-after-not-exclusive
(implies (and (invalidate-exclusive ch3 ch2 keys)
(not (equal v :invalidate-ack)))
(invalidate-exclusive (s i v ch3) ch2 keys))
:hints
(("Goal"
:cases
((equal i (car (invalidate-exclusive-witness (s i v ch3) ch2 keys)))))
("Subgoal 1"
:use
((:instance (:definition invalidate-exclusive)
(ch3 (s i v ch3)))))
("Subgoal 2"
:use
((:instance (:definition invalidate-exclusive)
(ch3 (s i v ch3)))
(:instance
invalidate-exclusive-necc
(i (car (invalidate-exclusive-witness (s i v ch3) ch2 keys)))
(j (mv-nth 1 (invalidate-exclusive-witness (s i v ch3) ch2 keys)))))))))
(local
(defthm |invalidate-exclusive after home receives invalidate|
(implies (and (invalidate-exclusive-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(invalidate-exclusive-invariant (german-step st stimulus)))))
;; What happens when sharer invalidates the cache? I have to claim that no
;; channel now has grant exclusive. Why is that? Because I know that if
;; somebody does have it, then all channels have to be nil. But all channels
;; are not nil since at least one has :invalidate.
(local
(defthm channel-nil-exclusive-implies-invalidate-exclusive
(implies (and (channel-nil-exclusive ch2 keys)
(memberp i keys)
(not (equal u :grant-exclusive))
(g i ch2))
(invalidate-exclusive (s i v ch3) (s i u ch2) keys))
:hints
(("Goal"
:cases
((equal i (car (invalidate-exclusive-witness (s i v ch3)
(s i u ch2)
keys)))))
("Subgoal 2"
:cases ((equal i (mv-nth 1 (invalidate-exclusive-witness (s i v ch3)
(s i u ch2)
keys)))))
("Subgoal 2.1"
:in-theory (enable invalidate-exclusive))
("Subgoal 2.2"
:in-theory (enable invalidate-exclusive)
:use
((:instance channel-nil-exclusive-necc
(j (car (invalidate-exclusive-witness (s i v ch3)
(s i u ch2)
keys))))))
("Subgoal 1"
:cases
((equal i (mv-nth 1 (invalidate-exclusive-witness (s i v ch3)
(s i u ch2)
keys)))))
("Subgoal 1.1"
:in-theory (enable invalidate-exclusive))
("Subgoal 1.2"
:in-theory (enable invalidate-exclusive)
:use
((:instance
channel-nil-exclusive-necc
(i (car (invalidate-exclusive-witness (s i v ch3)
(s i u ch2)
keys)))
(j (mv-nth 1 (invalidate-exclusive-witness (s i v ch3)
(s i u ch2)
keys)))))))))
(local
(defthm |invalidate-exclusive for sharer invalidate cache|
(implies (and (invalidate-exclusive-invariant st)
(channel-nil-exclusive-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(invalidate-exclusive-invariant (german-step st stimulus)))))
;; Now let us consider the last case which is when somebody is granted
;; exclusive. Why is it ok do do so and know that there was accidentally no
;; invalidate-ack around in channel 3? The reason is that the sharer list is
;; empty. This means that I must have another predicate, which says that if
;; somebody has something in ch3 then hsl has it recorded.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hsl-ch3 (hsl ch3 keys)
(if (endp keys) T
(and (implies (g (first keys) ch3)
(equal (g (first keys) hsl) t))
(hsl-ch3 hsl ch3 (rest keys))))))
(local
(defun hsl-ch3-invariant (st) (hsl-ch3 (hsl st) (ch3 st) (keys))))
(local
(defthm hsl-ch3-for-nil (hsl-ch3 nil nil keys)))
(local
(defthm |init has hsl-ch3-invariant|
(hsl-ch3-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; This argument is just going to go on and it is a simple argument. It says
;; that whenever I have all-false then I am ok. I probably have to have more
;; predicates like that all working with all-false.
(local
(defthm hsl-ch3-all-false-to-not-ch3
(implies (and (hsl-ch3 hsl ch3 keys)
(all-false keys hsl)
(memberp i keys))
(equal (g i ch3) nil))))
(local
(defthm hsl-ch3-all-false-implies-invalidate-exclusive
(implies (and (hsl-ch3 hsl ch3 keys)
(all-false keys hsl))
(invalidate-exclusive ch3 ch2 keys))
:hints (("Goal"
:in-theory (enable invalidate-exclusive)))))
;; So finally we get invalidate-exclusive.
(local
(defthm |invalidate-exclusive for granting exclusive|
(implies (and (hsl-ch3-invariant st)
(invalidate-exclusive-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(invalidate-exclusive-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of invalidate-exclusive-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right now on to hil-hsl.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.13: Proof of hil-hsl-invariant
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hil-hsl default cases|
(implies (and (hil-hsl-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:home-receives-invalidate
:home-grants-shared
:home-grants-exclusive))))
(hil-hsl-invariant (german-step st stimulus)))))
;; Now consider the situation when set-hil-hsl happens. For this to go thru, I
;; need the fact that everything in hil is a boolean. This is because I just
;; said that the index in hil is not nil, but required that the index in hsl is
;; t. The reason why I chose this is because home checks if (g i hil) but not
;; if (equal (g i hil) T) on certain occasions. Anyhow the predicate is not
;; difficult to define and I do not want to belabor the point.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hsl-boolean (hsl keys)
(if (endp keys) T
(and (booleanp (g (first keys) hsl))
(hsl-boolean hsl (rest keys))))))
(local
(defun hsl-boolean-invariant (st) (hsl-boolean (hsl st) (keys))))
(local
(defthm hsl-boolean-for-nil (hsl-boolean nil keys)))
(local
(defthm |init has hsl-boolean| (hsl-boolean-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; And now some obvious theorems to get the proof to go thru for
;; pick-new-request.
(local
(defthm hil-hsl-memberp
(implies (and (memberp i keys)
(hsl-boolean hsl keys)
(equal v (g i hsl))
(hil-hsl hil hsl keys))
(hil-hsl (s i v hil) hsl keys))
:hints (("Subgoal *1/6"
:cases ((equal i (car keys)))))))
(local
(defthm hil-hsl-not-memberp
(implies (and (not (memberp i keys))
(hil-hsl hil hsl keys))
(hil-hsl (s i v hil) hsl keys))))
(local
(defthm hil-hsl-set-hil-hsl
(implies (and (hil-hsl hil hsl keys)
(hsl-boolean hsl keys))
(hil-hsl (set-hil-hsl keys hil hsl) hsl keys))
:hints (("Subgoal *1/4"
:cases ((memberp (car keys) (cdr keys)))))))
;; Now I can do the pick new request.
(local
(defthm |hil-hsl after picking request|
(implies (and (hil-hsl-invariant st)
(hsl-boolean-invariant st)
(equal (action stimulus) :pick-new-request))
(hil-hsl-invariant (german-step st stimulus)))))
;; Let us do home-sends-invalidate now. This involves showing that if hil is
;; set to nil then hil-hsl does not change.
(local
(defthm hil-hsl-after-hil-nil
(implies (hil-hsl hil hsl keys)
(hil-hsl (s i nil hil) hsl keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-hsl after invalidating|
(implies (and (hil-hsl-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hil-hsl-invariant (german-step st stimulus)))))
;; How about when home receives an invalidate? Here I must know that the index
;; we are talking about is not in hil in the first place and therefore it does
;; not matter that we set hsl to nil. For this we need a new predicate that
;; says that if something has invalidate-ack then its hil is nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hil-invalidate (hil ch3 keys)
(if (endp keys) T
(and (implies (equal (g (first keys) ch3) :invalidate-ack)
(not (g (first keys) hil)))
(hil-invalidate hil ch3 (rest keys))))))
(local
(defun hil-invalidate-invariant (st)
(hil-invalidate (hil st) (ch3 st) (keys))))
(local
(defthm hil-invalidate-for-nil (hil-invalidate nil nil keys)))
(local
(defthm |init has hil invalidate| (hil-invalidate-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now why does it work out for home receiving an invalidate? The reason is
;; rather odd. I know that ch3 is not nil. Thus hsl must be T and hence it
;; does not matter what I set hil to.
(local
(defthm hil-hsl-after-setting-hil
(implies (and (hil-hsl hil hsl keys)
(hil-invalidate hil ch3 keys)
hcm
(equal (g i ch3) :invalidate-ack))
(hil-hsl hil (s i v hsl) keys))
:hints (("Goal"
:do-not '(eliminate-destructors generalize fertilize))
("Subgoal *1/5"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-hsl after home-receives-invalidate|
(implies (and (hil-hsl-invariant st)
(hil-invalidate-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hil-hsl-invariant (german-step st stimulus)))))
;; And finally to the last cases of hil-hsl. These are when hsl is set to T.
;; All I care about is that if I set hsl to T then nothing changes.
(local
(defthm hil-hsl-after-setting-hsl
(implies (hil-hsl hil hsl keys)
(hil-hsl hil (s i T hsl) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-hsl after granting|
(implies (and (hil-hsl-invariant st)
(memberp (action stimulus)
'(:home-grants-shared
:home-grants-exclusive)))
(hil-hsl-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hil-hsl-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right. Now we are done with hil-hsl. Let us move on to
;; invalidate-ack-ch2. This says that when we have an invalidate-ack in a ch3
;; then ch2 is nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.14: Proof of invalidate-ack-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |invalidate-ack-ch2 default cases|
(implies (and (invalidate-ack-ch2-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(invalidate-ack-ch2-invariant (german-step st stimulus)))))
;; Of course if we set ch2 to nil then we have this trivially, unless of course
;; we also set ch3. This will take care of most cases.
(local
(defthm invalidate-ack-ch2-when-ch2-nil
(implies (invalidate-ack-ch2 ch2 ch3 keys)
(invalidate-ack-ch2 (s i nil ch2) ch3 keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm invalidate-ack-ch2-when-ch2-nil-and-ch3-anything
(implies (invalidate-ack-ch2 ch2 ch3 keys)
(invalidate-ack-ch2 (s i nil ch2) (s i v ch3) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |invalidate-ack-ch2 after ch2 nil|
(implies (and (invalidate-ack-ch2-invariant st)
(memberp (action stimulus)
'(:client-receives-shared
:sharer-invalidate-cache
:client-receives-exclusive)))
(invalidate-ack-ch2-invariant (german-step st stimulus)))))
;; Now what happens with the remaining cases? When home-receives-invalidate it
;; is fine since we are setting ch3 to nil.
(local
(defthm invalidate-ack-after-ch3-set
(implies (and (invalidate-ack-ch2 ch2 ch3 keys)
(not (equal v :invalidate-ack)))
(invalidate-ack-ch2 ch2 (s i v ch3) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |invalidate-ack after receiving invalidate|
(implies (and (invalidate-ack-ch2-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(invalidate-ack-ch2-invariant (german-step st stimulus)))))
;; The remaining cases now are home-grants-shared and home-grants-exclusive.
;; Why does this predicate hold after home-grants-shared? The reason is as
;; follows. In this situation I know that hcm is req-shared and (not heg) is
;; true. In this condition no invalidate-ack is there since no invalidate is
;; sent out. I posit that as a new predicate.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk hcm-invalidate-ack (hcm heg ch3 keys)
(forall i
(implies (and (memberp i keys)
(equal (g i ch3) :invalidate-ack))
(or (equal hcm :req-exclusive-access)
(and (equal hcm :req-shared-access)
heg))))))
(local
(defun hcm-invalidate-ack-invariant (st)
(hcm-invalidate-ack (hcm st) (heg st) (ch3 st) (keys))))
(local
(defthm |init has hcm-invalidate-ack|
(hcm-invalidate-ack-invariant (init))))
(local
(in-theory (disable hcm-invalidate-ack hcm-invalidate-ack-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Here we see the use of a witness function to do universal quantification. I
;; define a witness for the negation of the property I care about and then
;; prove that if the witness has the property then everything has the property.
;; When I do this sort of reasoning I feel like I should have defined the
;; predicate using defun-sk directly, but for waht it is worth this is useful
;; for demonstration.
(local
(defun invalidate-ack-ch2-witness (ch2 ch3 keys)
(if (endp keys) nil
(if (and (equal (g (first keys) ch3) :invalidate-ack)
(g (first keys) ch2))
(first keys)
(invalidate-ack-ch2-witness ch2 ch3 (rest keys))))))
(local
(defthm invalidate-ack-from-witness
(implies (or (not (memberp (invalidate-ack-ch2-witness ch2 ch3 keys) keys))
(not (equal (g (invalidate-ack-ch2-witness ch2 ch3 keys) ch3)
:invalidate-ack))
(not (g (invalidate-ack-ch2-witness ch2 ch3 keys) ch2)))
(invalidate-ack-ch2 ch2 ch3 keys))))
(local
(defthm hcm-invalidate-invalidate-ack
(implies (and (hcm-invalidate-ack hcm heg ch3 keys)
(not heg)
(equal hcm :req-shared-access))
(invalidate-ack-ch2 ch2 ch3 keys))
:hints
(("Goal"
:use ((:instance hcm-invalidate-ack-necc
(i (invalidate-ack-ch2-witness ch2 ch3 keys))))))))
(local
(defthm |invalidate-ack-ch2 when home-grants-shared|
(implies (and (invalidate-ack-ch2-invariant st)
(hcm-invalidate-ack-invariant st)
(equal (action stimulus) :home-grants-shared))
(invalidate-ack-ch2-invariant (german-step st stimulus)))))
;; Let us now look at home-grants-exclusive. Why is this predicate ok? I know
;; that if home grants exclusive then all hsl entries are nil. But if all of
;; them are nil then hsl-ch3 tells me that all ch3 are nil. If all ch3 are
;; nil, then of course the predicate holds trivially.
(local
(defthm hsl-ch3-and-all-false-implies-ok
(implies (and (hsl-ch3 hsl ch3 keys)
(all-false keys hsl))
(invalidate-ack-ch2 (s i v ch2) ch3 keys))))
(local
(defthm |invalidate-ack after granting invalidate|
(implies (and (hsl-ch3-invariant st)
(invalidate-ack-ch2-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(invalidate-ack-ch2-invariant (german-step st stimulus)))))
;; And what happens after home-sends-invalidate? This is taken care of by
;; saying that if someone is in hil then it does not contain
;; invalidate-ack. This, together with the guard that the current process
;; is in hil says that the process does not have invalidate-ack in ch3. This
;; means we can set anything to ch2 and get away with it.
(local
(defthm hil-invalidate-invalidate-ack-ch2
(implies (and (hil-invalidate hil ch3 keys)
(memberp i keys)
(g i hil)
(invalidate-ack-ch2 ch2 ch3 keys))
(invalidate-ack-ch2 (s i v ch2) ch3 keys))
:hints (("Subgoal *1/6"
:cases ((equal i (car keys)))))))
(local
(defthm |invalidate-ack-ch2 after home-sends-invalidate|
(implies (and (invalidate-ack-ch2-invariant st)
(hil-invalidate-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(invalidate-ack-ch2-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of invalidate-ack-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right done with one more. Now let us think about what unique-hil. This
;; predicate says that if heg is true then there is at most one index with hil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.15: Proof of unique-hil-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |unique-hil default cases|
(implies (and (unique-hil-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:home-receives-invalidate
:home-grants-exclusive))))
(unique-hil-invariant (german-step st stimulus)))))
;; I will start with home-sends-invalidate. Why is unique-hil an invariant in
;; this case? If a state is unique-nil then setting a particular index to nil
;; does not change the situation.
(local
(defthm unique-hil-implies-so-after-hil-nil
(implies (unique-hil hil heg keys)
(unique-hil (s i nil hil) heg keys))
:hints
(("Goal"
:cases ((equal i (car (unique-hil-witness (s i nil hil) heg keys)))
(equal i (mv-nth 1 (unique-hil-witness (s i nil hil) heg keys)))))
("Subgoal 1"
:in-theory (enable unique-hil))
("Subgoal 2"
:in-theory (enable unique-hil))
("Subgoal 3"
:use
((:instance (:definition unique-hil)
(hil (s i nil hil)))
(:instance
unique-hil-necc
(i (car (unique-hil-witness (s i nil hil) heg keys)))
(j (mv-nth 1 (unique-hil-witness (s i nil hil) heg keys)))))))))
;; Well, that kind of does it for home-sends-invalidate. Here is the proof.
(local
(defthm |unique-hil after home-sends-invalidate|
(implies (and (unique-hil-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(unique-hil-invariant (german-step st stimulus)))))
;; What about home-receives-invalidate? This works because we are now setting
;; heg to hil.
(local
(defthm not-heg-implies-unique-hil
(implies (not heg)
(unique-hil hil heg keys))
:hints (("Goal"
:in-theory (enable unique-hil)))))
(local
(defthm |unique-hil after home-receives-invalidate|
(implies (and (unique-hil-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(unique-hil-invariant (german-step st stimulus)))))
;; This of course does not work for home-grants-exclusive, since here we *are*
;; setting heg. But we know something in this case that will help us out.
;; What do I know? I know all-false holds. This says (together with the
;; predicate hil-hsl that there is no hil at all. So this case does not arise.
(local
(defthm hil-hsl-implies-unique-hil
(implies (and (hil-hsl hil hsl keys)
(all-false keys hsl))
(unique-hil (s i v hil) heg keys))
:hints
(("Goal"
:in-theory (enable unique-hil)
:cases ((equal i (car (unique-hil-witness (s i v hil) heg keys)))))
("Subgoal 1"
:cases
((equal i (mv-nth 1 (unique-hil-witness (s i v hil) heg keys))))))))
;; And of course unique-hil remains if hil is not set at all.
(local
(defthm hil-hsl-implies-unique-hil-not-set
(implies (and (hil-hsl hil hsl keys)
(all-false keys hsl))
(unique-hil hil heg keys))
:hints (("Goal"
:in-theory (enable unique-hil)))))
;; So we can now get this grant-exclusive case thru.
(local
(defthm |unique-hil after home grants exclusive|
(implies (and (unique-hil-invariant st)
(hil-hsl-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(unique-hil-invariant (german-step st stimulus)))))
;; What happens when home picks a new request? The issue here is that we need
;; to claim unique-hil for set-hil-hsl. Now this is true because hsl has the
;; same predicate holding, and after set-hil-hsl therefore hil will have the
;; same predicate.
(local
(defthm hsl-heg-implies-unique-hil
(implies (hsl-heg hsl heg keys)
(unique-hil (set-hil-hsl keys hil hsl)
heg keys))
:hints
(("Goal"
:use
((:instance (:definition unique-hil)
(hil (set-hil-hsl keys hil hsl)))
(:instance
hsl-heg-necc
(i (car (unique-hil-witness (set-hil-hsl keys hil hsl)
heg keys)))
(j (mv-nth 1 (unique-hil-witness (set-hil-hsl keys hil hsl)
heg keys)))))))))
(local
(defthm |unique-hil after picking new request|
(implies (and (unique-hil-invariant st)
(hsl-heg-invariant st)
(equal (action stimulus) :pick-new-request))
(unique-hil-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of unique-hil-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right now to hsl-heg-invariant.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.16: Proof of hsl-heg-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hsl-heg default cases|
(implies (and (hsl-heg-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:home-grants-shared
:home-grants-exclusive))))
(hsl-heg-invariant (german-step st stimulus)))))
;; Now this works for home receiving invalidate since heg is being set to nil.
(local
(defthm hsl-heg-after-heg-nil
(implies (not heg)
(hsl-heg hsl heg keys))
:hints (("Goal"
:in-theory (enable hsl-heg)))))
(local
(defthm |hsl-heg after home receives invalidate|
(implies (and (hsl-heg-invariant st)
(memberp (action stimulus) '(:home-grants-shared
:home-receives-invalidate)))
(hsl-heg-invariant (german-step st stimulus)))))
;; Only left now is when home grants exclusive. Now I know that all other
;; clients are nil. And it is therefore known that we can set anything to hsl.
(local
(defthm all-false-implies-false
(implies (and (all-false keys hsl)
(memberp i keys))
(equal (g i hsl) nil))))
(local
(defthm hsl-can-be-set-when-all-false
(implies (all-false keys hsl)
(hsl-heg (s i v hsl) heg keys))
:hints
(("Goal"
:in-theory (enable hsl-heg)
:cases ((equal i (car (hsl-heg-witness (s i v hsl) heg keys)))
(equal i (mv-nth 1 (hsl-heg-witness (s i v hsl) heg keys))))))))
(local
(defthm |hsl-heg after home-grants-exclusive|
(implies (and (hsl-heg-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(hsl-heg-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hsl-heg-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; hsl-ch3-invariant now.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.17: Proof of hsl-ch3-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hsl-ch3 default cases|
(implies (and (hsl-ch3-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:sharer-invalidate-cache
:home-grants-shared
:home-grants-exclusive))))
(hsl-ch3-invariant (german-step st stimulus)))))
;; Of course it is easy to do the granting of exclusive and shared. All that
;; it is, is that we can set hsl to T as much as we want.
(local
(defthm hsl-T-does-not-change-hsl-ch3
(implies (hsl-ch3 hsl ch3 keys)
(hsl-ch3 (s i T hsl) ch3 keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-ch3 does not change on grant|
(implies (and (hsl-ch3-invariant st)
(memberp (action stimulus) '(:home-grants-shared
:home-grants-exclusive)))
(hsl-ch3-invariant (german-step st stimulus)))))
;; Similarly if ch3 is set to nil then nothing happens.
(local
(defthm hsl-ch3-if-ch3-nil
(implies (hsl-ch3 hsl ch3 keys)
(hsl-ch3 (s i v hsl) (s i nil ch3) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-ch3 after receiving invalidation|
(implies (and (hsl-ch3-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hsl-ch3-invariant (german-step st stimulus)))))
;; The only critical case here is when the client is sending acknowledgement of
;; invalidation to the server. This is because now we must say that the index
;; was already T in hsl. This holds because of hsl-ch2, and the fact that we
;; know that ch2 now containts :invalidate.
(local
(defthm hsl-ch3-for-not-member
(implies (and (hsl-ch3 hsl ch3 keys)
(not (memberp i keys)))
(hsl-ch3 hsl (s i v ch3) keys))))
(local
(defthm hsl-ch2-implies-hsl-ch3-after-set
(implies (and (hsl-ch2 hsl keys ch2)
(hsl-ch3 hsl ch3 keys)
(memberp i keys)
(g i ch2))
(hsl-ch3 hsl (s i v ch3) keys))
:hints (("Goal"
:do-not '(eliminate-destructors generalize fertilize))
("Subgoal *1/6"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-ch3 after sharer invalidates|
(implies (and (hsl-ch3-invariant st)
(hsl-ch2-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(hsl-ch3-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hsl-ch3-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; hsl-boolean-invariant now.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.18: Proof of hsl-boolean-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; This one is particularly trivial, as indeed are most others which have to do
;; with types. In fact it is an inductive invariant in itself.
(local
(defthm |hsl-boolean default cases|
(implies (and (hsl-boolean-invariant st)
(not (memberp (action stimulus)
'(:home-receives-invalidate
:home-grants-shared
:home-grants-exclusive))))
(hsl-boolean-invariant (german-step st stimulus)))))
(local
(defthm hsl-boolean-if-boolean-val-set
(implies (and (hsl-boolean hsl keys)
(booleanp v))
(hsl-boolean (s i v hsl) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-boolean other cases|
(implies (and (hsl-boolean-invariant st)
(memberp (action stimulus)
'(:home-receives-invalidate
:home-grants-shared
:home-grants-exclusive)))
(hsl-boolean-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hsl-boolean-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.19: Proof of hil-invalidate-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hil-invalidate default cases|
(implies (and (hil-invalidate-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache))))
(hil-invalidate-invariant (german-step st stimulus)))))
;; Now if home sends an invalidate it sets hil to nil and thus it works out.
(local
(defthm hil-invalidate-on-nil
(implies (hil-invalidate hil ch3 keys)
(hil-invalidate (s i nil hil) ch3 keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-invalidate on home-sends-invalidate|
(implies (and (hil-invalidate-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hil-invalidate-invariant (german-step st stimulus)))))
;; Now it must also be ok when home receives it. Now it sets ch3 to something
;; other than invalidate-ack so I dont have to prove anything.
(local
(defthm hil-invalidate-ack-set
(implies (and (hil-invalidate hil ch3 keys)
(not (equal v :invalidate-ack)))
(hil-invalidate hil (s i v ch3) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-invalidate when home receives invalidate|
(implies (and (hil-invalidate-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hil-invalidate-invariant (german-step st stimulus)))))
;; But what happens when the sharer actually inserts an invalidate-ack in ch3?
;; This is the third case we consider. Now what the heck do we know about this
;; situation? Why does this predicate hold? We know that the ch2 is having an
;; :invalidate. So we must know that when ch2 has :invalidate then hil must be
;; nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hil-invalidate-ch2 (hil ch2 keys)
(if (endp keys) T
(and (implies (equal (g (first keys) ch2) :invalidate)
(not (g (first keys) hil)))
(hil-invalidate-ch2 hil ch2 (rest keys))))))
(local
(defun hil-invalidate-ch2-invariant (st)
(hil-invalidate-ch2 (hil st) (ch2 st) (keys))))
(local
(defthm hil-invalidate-ch2-for-nil (hil-invalidate-ch2 nil nil keys)))
(local
(defthm |init has hil-invalidate-ch2| (hil-invalidate-ch2-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm hil-invalidate-ch2-implies-invalidate
(implies (and (hil-invalidate-ch2 hil ch2 keys)
(hil-invalidate hil ch3 keys)
(memberp i keys)
(equal (g i ch2) :invalidate))
(hil-invalidate hil (s i v ch3) keys))
:hints (("Subgoal *1/6"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-invalidate after sharer-invalidate-cache|
(implies (and (hil-invalidate-invariant st)
(hil-invalidate-ch2-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(hil-invalidate-invariant (german-step st stimulus)))))
;; The condition for picking new request is a bit more interesting. I have to
;; claim that at this point there is no invalidate-ack around. But how do we
;; know that? Do I know that anything from hsl does not have invalidate-ack?
;; Clearly not. But what I do know is that if invalidate-ack is true of
;; something then hcm is true. This is from hcm-invalidate-ack.
;; Now I will prove that hcm-invalidate-ack implies hil-invalidate. This is an
;; interesting exercise since I am proving something about a recursive function
;; using a quantified property. To do this I will invoke the so-called
;; "witness function" approach.
(local
(defun hil-invalidate-witness (hil ch3 keys)
(if (endp keys) nil ;; dont care
(if (and (equal (g (first keys) ch3) :invalidate-ack)
(g (first keys) hil))
(first keys)
(hil-invalidate-witness hil ch3 (rest keys))))))
(local
(defthm hil-invalidate-witness-implies-hil-invalidate
(implies (or (not (equal (g (hil-invalidate-witness hil ch3 keys) ch3)
:invalidate-ack))
(not (memberp (hil-invalidate-witness hil ch3 keys)
keys))
(not (g (hil-invalidate-witness hil ch3 keys) hil)))
(hil-invalidate hil ch3 keys))))
(local
(defthm hcm-ch3-implies-hil-invalidate
(implies (and (hcm-invalidate-ack hcm heg ch3 keys)
(not hcm))
(hil-invalidate hil ch3 keys))
:hints (("Goal"
:use ((:instance hcm-invalidate-ack-necc
(i (hil-invalidate-witness hil ch3 keys))))))))
(local
(defthm |hil-invalidate when pick-new-request|
(implies (and (hil-invalidate-invariant st)
(hcm-invalidate-ack-invariant st)
(equal (action stimulus) :pick-new-request))
(hil-invalidate-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hil-invalidate-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now let us get to this predicate hil-invalidate-ch2. I have a premonition
;; that it would involve specifying something about hcm. We will see.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.20: Proof of hil-invalidate-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hil-invalidate-ch2 default cases|
(implies (and (hil-invalidate-ch2-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hil-invalidate-ch2-invariant (german-step st stimulus)))))
;; Of course the standard thing is that if ch2 is set to nil then we are in
;; great shape.
(local
(defthm hil-invalidate-ch2-when-ch2-nil
(implies (hil-invalidate-ch2 hil ch2 keys)
(hil-invalidate-ch2 hil (s i nil ch2) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-invalidate-ch2 when ch2 is reset|
(implies (and (hil-invalidate-ch2-invariant st)
(memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(hil-invalidate-ch2-invariant (german-step st stimulus)))))
;; And as usual setting hil to nil does not matter. So we use that to do the
;; sending of invalidate.
(local
(defthm hil-invalidate-ch2-set-hil-nil
(implies (hil-invalidate-ch2 hil ch2 keys)
(hil-invalidate-ch2 (s i nil hil) (s i v ch2) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-invalidate-ch2 home-sends-invalidate|
(implies (and (hil-invalidate-ch2-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hil-invalidate-ch2-invariant (german-step st stimulus)))))
;; And it does not matter if I set anything other than :invalidate in ch2.
(local
(defthm hil-invalidate-other-than-invalidate
(implies (and (hil-invalidate-ch2 hil ch2 keys)
(not (equal v :invalidate)))
(hil-invalidate-ch2 hil (s i v ch2) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-invalidate-ch2 for grant|
(implies (and (hil-invalidate-ch2-invariant st)
(memberp (action stimulus) '(:home-grants-shared
:home-grants-exclusive)))
(hil-invalidate-ch2-invariant (german-step st stimulus)))))
;; And finally the non-trivial case, namely :pick-new-request. What do we know
;; here? I would have loved to say that if ch2 has invalidate then hsl is nil.
;; But that is not true!!! In fact it is exactly the opposite that is true. I
;; definitely know that if ch2 has an invalidate then hsl *is* true. Why does
;; it work out then? It works out because when hcm is nil ch2 is nil,
;; :grant-exclusive, or :grant-shared. Why? Because home receives some
;; request and works on it and goes on working on it until it can finish
;; processing. During that time the hcm is always holding the command given.
;; It is only after the command has been completely processed that hcm is set
;; to nil.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun-sk hcm-ch2 (hcm heg ch2 keys)
(forall i (implies (and (memberp i keys)
(equal (g i ch2) :invalidate))
(or (and (equal hcm :req-shared-access)
heg)
(equal hcm :req-exclusive-access))))))
(local
(defun hcm-ch2-invariant (st) (hcm-ch2 (hcm st) (heg st) (ch2 st) (keys))))
(local
(defthm |init has hcm-ch2| (hcm-ch2-invariant (init))))
(local
(in-theory (disable hcm-ch2 hcm-ch2-necc)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm not-hcm-implies-not-invalidate
(implies (and (hcm-ch2 hcm heg ch2 keys)
(not hcm)
(memberp i keys))
(equal (equal (g i ch2) :invalidate) nil))
:hints (("Goal"
:use hcm-ch2-necc))))
;; And here I see how we can mimic quantification with recursion.
(local
(defun hil-invalidate-rwitness (hil ch2 keys)
(if (endp keys) nil ;; dont care
(if (and (equal (g (first keys) ch2) :invalidate)
(g (first keys) hil))
(first keys)
(hil-invalidate-rwitness hil ch2 (rest keys))))))
(local
(defthm hil-invalidate-rwitness-invalidate
(implies (or (not (equal (g (hil-invalidate-rwitness hil ch2 keys) ch2)
:invalidate))
(not (g (hil-invalidate-rwitness hil ch2 keys) hil))
(not (memberp (hil-invalidate-rwitness hil ch2 keys) keys)))
(hil-invalidate-ch2 hil ch2 keys))))
(local
(defthm not-hcm-implies-hil-invalidate
(implies (and (hcm-ch2 hcm heg ch2 keys)
(not hcm))
(hil-invalidate-ch2 hil ch2 keys))
:hints (("Goal"
:in-theory (disable hil-invalidate-rwitness-invalidate)
:use hil-invalidate-rwitness-invalidate))))
(local
(defthm |hil-invalidate on pick-new-request|
(implies (and (hil-invalidate-ch2-invariant st)
(hcm-ch2-invariant st)
(equal (action stimulus) :pick-new-request))
(hil-invalidate-ch2-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hil-invalidate-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; hcm-ch2-invariant
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.21: Proof of hcm-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hcm-ch2 default cases|
(implies (and (hcm-ch2-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hcm-ch2-invariant (german-step st stimulus)))))
;; Now what happens when there is an invalidate-ack? Why is the predicate
;; going to be ok here? There should be no other invalidate-ack. I know this
;; as follows. hsl-heg tells me that if heg is true then there is at most one
;; hsl. hsl-ch3 then tells me that there is at most one ch3. This ch3 is the
;; invalidate-ack I am seeing. Thus if I set this to nil there is no ch3, and
;; hence I am done. And of course if heg was already nil then there is nothing
;; to do.
;; All right, let us do this.
(local
(defthm hsl-ch3-and-ch3-to-hsl
(implies (and (hsl-ch3 hsl ch3 keys)
(memberp i keys)
(g i ch3))
(g i hsl))))
(local
(defthm hsl-heg-hsl-ch3-implies-only-one
(implies (and (hsl-heg hsl heg keys)
(hsl-ch3 hsl ch3 keys)
(hsl-ch2 hsl keys ch2)
(memberp i keys)
(memberp j keys)
heg
(g j ch2)
(g i ch3))
(equal i j))
:rule-classes :forward-chaining
:hints (("Goal"
:use hsl-heg-necc))))
;; Now I will claim that all right I know all this, and I also know from
;; invalidate-ack-ch2 that the guy which has invalidate-ack in ch3 does not
;; have a ch2. This will show that there is no ch2 at all.
(local
(defthm hsl-heg-hsl-ch3-implies-none
(implies (and (hsl-heg hsl heg keys)
(hsl-ch3 hsl ch3 keys)
(invalidate-ack-ch2 ch2 ch3 keys)
(hsl-ch2 hsl keys ch2)
(memberp i keys)
(memberp j keys)
heg
(equal (g i ch3) :invalidate-ack))
(equal (g j ch2) nil))
:hints (("Goal"
:cases ((equal i j))))))
;; And therefore I have it when heg.
(local
(defthm hcm-ch2-when-heg
(implies (and (hsl-heg hsl heg keys)
(hsl-ch3 hsl ch3 keys)
(invalidate-ack-ch2 ch2 ch3 keys)
(memberp i keys)
(equal (g i ch3) :invalidate-ack)
(hsl-ch2 hsl keys ch2)
heg)
(hcm-ch2 hcm v ch2 keys))
:hints (("Goal"
:in-theory (enable hcm-ch2)))))
;; For the final theorem I will case-split on whether heg is true.
(local
(defthm |hcm-ch2 when home-receives-invalidate|
(implies (and (hcm-ch2-invariant st)
(hsl-heg-invariant st)
(hsl-ch3-invariant st)
(invalidate-ack-ch2-invariant st)
(hsl-ch2-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hcm-ch2-invariant (german-step st stimulus)))
:hints (("Goal" :cases ((heg st))))))
;; The argument for picking a request is kind of cute. It says that if hcm is
;; not one of the approved values then there is no invalidate, and since there
;; is no invalidate I am now allowed to make hcm anything! Isn't it cute?
(local
(defthm hcm-ch2-and-not-hcm-implies-hcm-anything
(implies (and (hcm-ch2 hcm heg ch2 keys)
(not (equal hcm :req-exclusive-access))
(or (not (equal hcm :req-shared-access))
(not heg)))
(hcm-ch2 v u ch2 keys))
:hints (("Goal"
:use ((:instance (:definition hcm-ch2)
(hcm v)
(heg u))
(:instance hcm-ch2-necc
(i (hcm-ch2-witness v u ch2 keys))))))))
(local
(defthm |hcm-ch2 for pick-new-request|
(implies (and (hcm-ch2-invariant st)
(equal (action stimulus) :pick-new-request))
(hcm-ch2-invariant (german-step st stimulus)))))
;; For granting shared a similar argument is necessary but now we also set
;; ch2.
(local
(defthm hcm-ch2-and-not-hcm-implies-hcm-anything-with-ch2
(implies (and (hcm-ch2 hcm heg ch2 keys)
(not (equal hcm :req-exclusive-access))
(not (equal w :invalidate))
(or (not (equal hcm :req-shared-access))
(not heg)))
(hcm-ch2 v u (s i w ch2) keys))
:hints (("Goal"
:cases ((equal i (hcm-ch2-witness v u (s i w ch2) keys))))
("Subgoal 1"
:in-theory (enable hcm-ch2))
("Subgoal 2"
:use ((:instance (:definition hcm-ch2)
(hcm v)
(ch2 (s i w ch2))
(heg u))
(:instance hcm-ch2-necc
(i (hcm-ch2-witness v u (s i w ch2) keys))))))))
(local
(defthm |hcm-ch2 after home-grants-shared|
(implies (and (hcm-ch2-invariant st)
(equal (action stimulus) :home-grants-shared))
(hcm-ch2-invariant (german-step st stimulus)))))
;; And home-sends-invalidate is rather trivial since the definition of hcm is
;; done with this predicate in mind.
(local
(defthm hcm-ch2-if-the-right-things-set
(implies (or (and (equal hcm :req-shared-access)
heg)
(equal hcm :req-exclusive-access))
(hcm-ch2 hcm heg ch2 keys))
:hints (("Goal"
:in-theory (enable hcm-ch2)))))
(local
(defthm |hcm-ch2 when home-sends-invalidate|
(implies (and (hcm-ch2-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hcm-ch2-invariant (german-step st stimulus)))))
;; As in fact it does not matter if I set ch2 to something other than
;; :invalidate.
(local
(defthm hcm-ch2-after-setting-ch2
(implies (and (hcm-ch2 hcm heg ch2 keys)
(not (equal v :invalidate)))
(hcm-ch2 hcm heg (s i v ch2) keys))
:hints (("Goal"
:cases ((equal i (hcm-ch2-witness hcm heg (s i v ch2) keys))))
("Subgoal 2"
:use ((:instance (:definition hcm-ch2)
(ch2 (s i v ch2)))
(:instance hcm-ch2-necc
(i (hcm-ch2-witness hcm heg (s i v ch2) keys)))))
("Subgoal 1"
:in-theory (enable hcm-ch2)))))
(local
(defthm |hcm-ch2 after client sets|
(implies (and (hcm-ch2-invariant st)
(memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(hcm-ch2-invariant (german-step st stimulus)))))
;; And the exclusive of course just requires that we have hsl-ch2 which we do.
(local
(defthm hsl-ch2-and-all-false-implies-hcm
(implies (and (hsl-ch2 hsl keys ch2)
(not (equal v :invalidate))
(all-false keys hsl))
(hcm-ch2 hcm heg (s i v ch2) keys))
:hints (("Goal"
:cases ((equal i (hcm-ch2-witness hcm heg (s i v ch2) keys))))
("Subgoal 1"
:in-theory (enable hcm-ch2))
("Subgoal 2"
:in-theory (enable hcm-ch2)))))
(local
(defthm |hsm-ch2 when grants exclusive|
(implies (and (hcm-ch2-invariant st)
(hsl-ch2-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(hcm-ch2-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hcm-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now I handle the hcm-invalidate-ack-invariant. This says that if (not heg)
;; and hcm is equal to :req-shared-access then there is no invalidate-ack.
;; This should be pretty trivial since under these conditions we dont send an
;; invalidate at all.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.22: Proof of hcm-invalidate-ack-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hcm-invalidate-ack default cases|
(implies (and (hcm-invalidate-ack-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-receives-invalidate
:sharer-invalidate-cache
:home-grants-shared
:home-grants-exclusive))))
(hcm-invalidate-ack-invariant (german-step st stimulus)))))
;; Now what happens when we pick a new request? We know hcm is nil. And then
;; there is nothing to prove. This is the same cute trick that we invoked for
;; hcm-ch2.
(local
(defthm hcm-ack-and-not-hcm-implies-hcm-anything
(implies (and (hcm-invalidate-ack hcm heg ch3 keys)
(not (equal hcm :req-exclusive-access))
(or (not (equal hcm :req-shared-access))
(not heg)))
(hcm-invalidate-ack v u ch3 keys))
:hints
(("Goal"
:use ((:instance (:definition hcm-invalidate-ack)
(hcm v)
(heg u))
(:instance hcm-invalidate-ack-necc
(i (hcm-invalidate-ack-witness v u ch3 keys))))))))
(local
(defthm |hcm-invalidate-ack for pick-new-request|
(implies (and (hcm-invalidate-ack-invariant st)
(equal (action stimulus) :pick-new-request))
(hcm-invalidate-ack-invariant (german-step st stimulus)))))
;; And the same trick for grant-shared.
(local
(defthm hcm-ch3-and-not-hcm-implies-hcm-anything-with-ch2
(implies (and (hcm-invalidate-ack hcm heg ch3 keys)
(not (equal hcm :req-exclusive-access))
(not (equal w :invalidate-ack))
(or (not (equal hcm :req-shared-access))
(not heg)))
(hcm-invalidate-ack v u (s i w ch3) keys))
:hints
(("Goal"
:cases ((equal i (hcm-invalidate-ack-witness v u (s i w ch3) keys))))
("Subgoal 1"
:in-theory (enable hcm-invalidate-ack))
("Subgoal 2"
:use
((:instance (:definition hcm-invalidate-ack)
(hcm v)
(ch3 (s i w ch3))
(heg u))
(:instance hcm-invalidate-ack-necc
(i (hcm-invalidate-ack-witness v u (s i w ch3) keys))))))))
(local
(defthm |hcm-invalidate-ack after home-grants-shared|
(implies (and (hcm-invalidate-ack-invariant st)
(equal (action stimulus) :home-grants-shared))
(hcm-invalidate-ack-invariant (german-step st stimulus)))))
;; As I well realize now this predicate is kind of a mirror image of hcm-ch2.
;; So home-receives-invalidate is going to have a problem. And indeed exactly
;; the same problem as hcm-ch2. And the solution is exactly the same too!
(local
(defthm hsl-heg-hsl-ch3-implies-only-one-ch3
(implies (and (hsl-heg hsl heg keys)
(hsl-ch3 hsl ch3 keys)
(memberp i keys)
(memberp j keys)
heg
(g j ch3)
(g i ch3))
(equal i j))
:rule-classes :forward-chaining
:hints (("Goal"
:use hsl-heg-necc))))
;; Now I can prove that if I set ch3 to something else I would be done.
(local
(defthm hcm-ch3-when-heg
(implies (and (hsl-heg hsl heg keys)
(hsl-ch3 hsl ch3 keys)
(memberp i keys)
(not (equal u :invalidate-ack))
(equal (g i ch3) :invalidate-ack)
heg)
(hcm-invalidate-ack hcm v (s i u ch3) keys))
:hints
(("Goal"
:in-theory (enable hcm-invalidate-ack)
:cases ((equal i (hcm-invalidate-ack-witness hcm v (s i u ch3) keys)))))))
;; Well in this case we need to do something for not-heg as well just because I
;; am setting ch3. Now what happens if heg is actually not true. Now in this
;; case the hcm is req-shared-access and since I am not changing hcm it still
;; remains req-shared-access and I have nothing to prove.
(local
(defthm not-heg-invalidate-ack-implies-invalidate-ack
(implies (and (hcm-invalidate-ack hcm heg ch3 keys)
(not heg)
(memberp i keys)
(equal (g i ch3) :invalidate-ack))
(hcm-invalidate-ack hcm v u keys))
:hints (("Goal"
:use ((:instance (:definition hcm-invalidate-ack)
(heg v)
(ch3 u))
(:instance hcm-invalidate-ack-necc))))))
(local
(defthm |hcm-invalidate-ack when home-receives-invalidate|
(implies (and (hsl-heg-invariant st)
(hsl-ch3-invariant st)
(hcm-invalidate-ack-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hcm-invalidate-ack-invariant (german-step st stimulus)))
:hints (("Goal"
:cases ((heg st))))))
;; What happens when the sharer invalidates? I need to claim that under the
;; non-trivial conditions there is no invalidate at all, and hence there is no
;; problem.
(local
(defthm invalidate-not-a-problem
(implies (and (hcm-ch2 hcm heg ch2 keys)
(memberp i keys)
(equal (g i ch2) :invalidate))
(hcm-invalidate-ack hcm heg ch3 keys))
:hints (("Goal"
:in-theory (enable hcm-invalidate-ack)
:use hcm-ch2-necc))))
(local
(defthm |hcm-invalidate-ack after sharer invalidates|
(implies (and (hcm-invalidate-ack-invariant st)
(hcm-ch2-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(hcm-invalidate-ack-invariant (german-step st stimulus)))))
;; Now what happens if either there is a grant-exclusive? Again I will go thru
;; the pain of hsl and all-false. This predicate *is* really like hcm-ch2, the
;; more I think about it.
(local
(defthm hsl-ch3-and-all-false-implies-hcm
(implies (and (hsl-ch3 hsl ch3 keys)
(all-false keys hsl))
(hcm-invalidate-ack hcm heg ch3 keys))
:hints
(("Goal"
:cases ((equal i (hcm-invalidate-ack-witness hcm heg ch3 keys))))
("Subgoal 1"
:in-theory (enable hcm-invalidate-ack))
("Subgoal 2"
:in-theory (enable hcm-invalidate-ack)))))
(local
(defthm |hsm-invalidate-ack when grants exclusive|
(implies (and (hcm-invalidate-ack-invariant st)
(hsl-ch3-invariant st)
(equal (action stimulus) :home-grants-exclusive))
(hcm-invalidate-ack-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hcm-invalidate-ack-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now I handle invalidate-clients-invariant. This should not be too much
;; trouble. If says that if a client has an invalidate it must be shared or
;; exclusive. In other words invalidation is not sent to idle clients. Since
;; this involves a property of two components for the same index, this should
;; be easy.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.22: Proof of hcm-invalidate-ack-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |invalidate-clients default cases|
(implies (and (invalidate-clients-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(invalidate-clients-invariant (german-step st stimulus)))))
;; And as is standard, I will show that if the predicate already holds then
;; setting ch2 to something other than invalidate does not change it.
(local
(defthm invalidate-after-something-else
(implies (and (invalidate-clients ch2 clients keys)
(not (equal v :invalidate)))
(invalidate-clients (s i v ch2) clients keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
;; which takes care of home granting shared or invalidate.
(local
(defthm |invalidate-clients after home-grants|
(implies (and (invalidate-clients-invariant st)
(memberp (action stimulus)
'(:home-grants-shared
:home-grants-exclusive)))
(invalidate-clients-invariant (german-step st stimulus)))))
;; Now when the client receives something it also does not matter as long as it
;; does not receive an invalidate.
(local
(defthm invalidate-after-client-set
(implies (and (invalidate-clients ch2 clients keys)
(not (equal v :invalidate)))
(invalidate-clients (s i v ch2) (s i u clients) keys))
:hints (("Goal"
:do-not '(eliminate-destructors generalize fertilize))
("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |clients are fine with invalidate-clients|
(implies (and (invalidate-clients-invariant st)
(memberp (action stimulus)
'(:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive)))
(invalidate-clients-invariant (german-step st stimulus)))))
;; The only crucial point is when home sends invalidate. Why is that ok? As I
;; realize now, the reason is kind of subtle and I had not realized this when I
;; posited the predicate. The reason is that if hil has an index that is set
;; then the process is either shared, or exclusive, or grant-shared, or
;; grant-exclusive. The reason actually is that hsl behaves the same way, and
;; therefore hil gets it derived. We thus need to posit this as a predicate.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hil-client-ch2 (hil clients ch2 keys)
(if (endp keys) T
(and (implies (g (first keys) hil)
(or (equal (g (first keys) clients) :shared)
(equal (g (first keys) clients) :exclusive)
(equal (g (first keys) ch2) :grant-shared)
(equal (g (first keys) ch2) :grant-exclusive)))
(hil-client-ch2 hil clients ch2 (rest keys))))))
(local
(defun hil-client-ch2-invariant (st)
(hil-client-ch2 (hil st) (clients st) (ch2 st) (keys))))
(local
(defthm hil-client-for-nil (hil-client-ch2 nil clients ch2 keys)))
(local
(defthm |init has hil-client-ch2| (hil-client-ch2-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now this tells us that everything is ok.
(local
(defthm hil-client-ch2-memberp-reduction
(implies (and (hil-client-ch2 hil clients ch2 keys)
(memberp i keys)
(g i hil))
(or (equal (g i clients) :shared)
(equal (g i clients) :exclusive)
(equal (g i ch2) :grant-shared)
(equal (g i ch2) :grant-exclusive)))
:rule-classes :forward-chaining))
;; Of course now it is fine to do the invalidate since this index is shared of
;; exclusive. (Note that home checks if the ch2 has become empty.)
(local
(defthm invalidate-clients-not-memberp-reduction
(implies (and (invalidate-clients ch2 clients keys)
(not (memberp i keys)))
(invalidate-clients (s i v ch2) clients keys))))
(local
(defthm hil-client-hil-ch2-reduction
(implies (and (hil-client-ch2 hil clients ch2 keys)
(invalidate-clients ch2 clients keys)
(memberp i keys)
(g i hil)
(not (g i ch2)))
(invalidate-clients (s i v ch2) clients keys))
:hints (("Subgoal *1/6"
:cases ((equal i (car keys)))))))
(local
(defthm |invalidate-clients after home-sends-invalidate|
(implies (and (invalidate-clients-invariant st)
(hil-client-ch2-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(invalidate-clients-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of invalidate-clients-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; I am annoyed that the proof is going on and on. I thought when I was
;; proving invalidate-clients that it would be the last predicate I need to
;; reason about, but I got one more predicate. Of course to deal with this I
;; already know one more is necessary, namely about hsl relating it with
;; clients and ch2. But I hope not much more is involved.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.23: Proof of hil-client-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hil-client-ch2 default cases|
(implies (and (hil-client-ch2-invariant st)
(not (memberp (action stimulus)
'(:pick-new-request
:home-sends-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hil-client-ch2-invariant (german-step st stimulus)))))
;; And of course if I set the ch2 to grant-shared or grant-exclusive it does
;; not matter.
(local
(defthm hil-client-ch2-set-ch2
(implies (and (hil-client-ch2 hil clients ch2 keys)
(or (equal v :grant-exclusive)
(equal v :grant-shared)))
(hil-client-ch2 hil clients (s i v ch2) keys))
:hints (("Subgoal *1/3"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-client when home grants|
(implies (and (hil-client-ch2-invariant st)
(memberp (action stimulus)
'(:home-grants-exclusive
:home-grants-shared)))
(hil-client-ch2-invariant (german-step st stimulus)))))
;; And as long as I set the clients to shared or exclusive again it does not
;; matter. In fact it does not matter if we remove things from ch2.
(local
(defthm hil-client-ch2-set-client
(implies (and (hil-client-ch2 hil clients ch2 keys)
(or (equal v :exclusive)
(equal v :shared)))
(hil-client-ch2 hil (s i v clients) (s i u ch2) keys))
:hints (("Subgoal *1/3"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-client when client is set|
(implies (and (hil-client-ch2-invariant st)
(memberp (action stimulus)
'(:client-receives-exclusive
:client-receives-shared)))
(hil-client-ch2-invariant (german-step st stimulus)))))
;; And for sharer-invalidating we only need to say that hil is not existing.
;; And this is known from hil-invalidate-ch2.
(local
(defthm hil-invalidate-implies-can-set-client
(implies (and (hil-client-ch2 hil clients ch2 keys)
(hil-invalidate-ch2 hil ch2 keys)
(equal (g i ch2) :invalidate))
(hil-client-ch2 hil (s i v clients) (s i u ch2) keys))
:hints (("Subgoal *1/5"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-client for sharer invalidating|
(implies (and (hil-client-ch2-invariant st)
(hil-invalidate-ch2-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(hil-client-ch2-invariant (german-step st stimulus)))))
;; Why does hil-client work for home sending the invalidate? I have nothing to
;; prove since hil is being set to nil.
(local
(defthm hil-client-ch2-to-nil
(implies (hil-client-ch2 hil clients ch2 keys)
(hil-client-ch2 (s i nil hil) clients (s i v ch2) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hil-client-ch2 when home-sends-invalidate|
(implies (and (hil-client-ch2-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hil-client-ch2-invariant (german-step st stimulus)))))
;; All right, now for the non-trivial one. I need to write another predicate
;; which says that hsl has indices that are only shared, exclusive,
;; grant-shared, or grant-exclusive, or in fact the ch3 has invalidate-ack.
;; Otherwise I cannot have hil-client-ch2 when hil is set to hsl.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Begin Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defun hsl-client-ch2 (hsl clients ch2 ch3 keys)
(if (endp keys) T
(and (implies (g (first keys) hsl)
(or (equal (g (first keys) clients) :shared)
(equal (g (first keys) clients) :exclusive)
(equal (g (first keys) ch2) :grant-shared)
(equal (g (first keys) ch2) :grant-exclusive)
(equal (g (first keys) ch3) :invalidate-ack)))
(hsl-client-ch2 hsl clients ch2 ch3 (rest keys))))))
(local
(defun hsl-client-ch2-invariant (st)
(hsl-client-ch2 (hsl st) (clients st) (ch2 st) (ch3 st) (keys))))
(local
(defthm hsl-client-for-nil (hsl-client-ch2 nil clients ch2 ch3 keys)))
(local
(defthm |init has hsl-client-ch2| (hsl-client-ch2-invariant (init))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Definition of new predicate ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; OK now we can prove that if hsl-client-ch2 holds then set-hil-hsl is fine.
;; I will prove it again using witness functions. I now understand why J said
;; that I really love quantification....!!!
(local
(defun hil-client-witness (hil clients ch2 keys)
(if (endp keys) nil
(if (and (g (first keys) hil)
(not (equal (g (first keys) clients) :shared))
(not (equal (g (first keys) clients) :exclusive))
(not (equal (g (first keys) ch2) :grant-shared))
(not (equal (g (first keys) ch2) :grant-exclusive)))
(first keys)
(hil-client-witness hil clients ch2 (rest keys))))))
(local
(defthm hil-client-witness-to-hil-clients
(implies
(or (not (memberp (hil-client-witness hil clients ch2 keys) keys))
(implies (g (hil-client-witness hil clients ch2 keys) hil)
(or (equal (g (hil-client-witness hil clients ch2 keys)
clients)
:shared)
(equal (g (hil-client-witness hil clients ch2 keys)
clients)
:exclusive)
(equal (g (hil-client-witness hil clients ch2 keys) ch2)
:grant-shared)
(equal (g (hil-client-witness hil clients ch2 keys) ch2)
:grant-exclusive))))
(hil-client-ch2 hil clients ch2 keys))
:rule-classes nil))
;; And now prove that hsl-client-ch2 implies the above conditions.
(local
(defthm hsl-client-member
(implies (and (hsl-client-ch2 hsl clients ch2 ch3 keys)
(memberp i keys)
(not (equal (g i ch3) :invalidate-ack))
(g i hsl))
(or (equal (g i clients) :shared)
(equal (g i clients) :exclusive)
(equal (g i ch2) :grant-shared)
(equal (g i ch2) :grant-exclusive)))
:rule-classes :forward-chaining))
;; Now we are in great shape, since hcm-invalidate-ack guarantees that we have
;; no invalidate-ack.
(local
(defthm hsl-client-hil-client-reduction
(implies (and (hsl-client-ch2 hsl clients ch2 ch3 keys)
(hcm-invalidate-ack hcm heg ch3 keys)
(not hcm))
(hil-client-ch2 (set-hil-hsl keys hil hsl) clients ch2 keys))
:hints
(("Goal"
:use
((:instance hil-client-witness-to-hil-clients
(hil (set-hil-hsl keys hil hsl)))
(:instance
hcm-invalidate-ack-necc
(i (hil-client-witness (set-hil-hsl keys hil hsl)
clients ch2 keys))))))))
(local
(defthm |hil-client-ch2 for picking request|
(implies (and (hsl-client-ch2-invariant st)
(hil-client-ch2-invariant st)
(hcm-invalidate-ack-invariant st)
(equal (action stimulus) :pick-new-request))
(hil-client-ch2-invariant (german-step st stimulus)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End Proof of hil-client-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; All right! Well done. Now let us trace the hsl and clients and everything
;; and try to finish this proof.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 3.24: Proof of hsl-client-ch2-invariant ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(local
(defthm |hsl-client-ch2 default cases|
(implies (and (hsl-client-ch2-invariant st)
(not (memberp (action stimulus)
'(:home-sends-invalidate
:home-receives-invalidate
:sharer-invalidate-cache
:client-receives-shared
:client-receives-exclusive
:home-grants-shared
:home-grants-exclusive))))
(hsl-client-ch2-invariant (german-step st stimulus)))))
;; Well now if home sends invalidate then I dont have to prove anything. But
;; first let me prove that it is ok.
(local
(defthm hil-hsl-and-hil-and-ch2-implies-hsl
(implies (and (hsl-client-ch2 hsl clients ch2 ch3 keys)
(hil-client-ch2 hil clients ch2 keys)
(g i hil)
(not (g i ch2)))
(hsl-client-ch2 hsl clients (s i v ch2) ch3 keys))
:hints (("Subgoal *1/5"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-client-ch2 on home-sends-invalidate|
(implies (and (hsl-client-ch2-invariant st)
(hil-client-ch2-invariant st)
(equal (action stimulus) :home-sends-invalidate))
(hsl-client-ch2-invariant (german-step st stimulus)))))
;; When home-receives invalidate it removes the hsl and therefore I have to
;; prove nothing.
(local
(defthm hsl-client-reset-hsl
(implies (hsl-client-ch2 hsl clients ch2 ch3 keys)
(hsl-client-ch2 (s i nil hsl) clients ch2 (s i v ch3) keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-client-ch2 when home-receives-invalidate|
(implies (and (hsl-client-ch2-invariant st)
(equal (action stimulus) :home-receives-invalidate))
(hsl-client-ch2-invariant (german-step st stimulus)))))
;; When sharer invalidates cache it sets ch3 to invalidate-ack and hence I dont
;; have to prove anything.
(local
(defthm hsl-client-set-ch3
(implies (hsl-client-ch2 hsl clients ch2 ch3 keys)
(hsl-client-ch2 hsl
(s i u clients)
(s i v ch2)
(s i :invalidate-ack ch3)
keys))
:hints (("Subgoal *1/4"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-client-ch2 when sharer invalidates|
(implies (and (hsl-client-ch2-invariant st)
(equal (action stimulus) :sharer-invalidate-cache))
(hsl-client-ch2-invariant (german-step st stimulus)))))
;; When the client receives something it sets itself to shared or exclusive so
;; that is fine.
(local
(defthm hsl-client-ch2-on-clients
(implies (and (hsl-client-ch2 hsl clients ch2 ch3 keys)
(or (equal v :exclusive)
(equal v :shared)))
(hsl-client-ch2 hsl
(s i v clients)
(s i u ch2)
ch3 keys))
:hints (("Subgoal *1/3"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-client-ch2 when client sets|
(implies (and (hsl-client-ch2-invariant st)
(memberp (action stimulus)
'(:client-receives-shared
:client-receives-exclusive)))
(hsl-client-ch2-invariant (german-step st stimulus)))))
;; And the last case, when home is granting.
(local
(defthm hsl-client-ch2-on-home-grant
(implies (and (hsl-client-ch2 hsl clients ch2 ch3 keys)
(or (equal v :grant-exclusive)
(equal v :grant-shared)))
(hsl-client-ch2 (s i u hsl)
clients
(s i v ch2)
ch3 keys))
:hints (("Subgoal *1/3"
:cases ((equal i (car keys)))))))
(local
(defthm |hsl-client-ch2 when home grants|
(implies (and (hsl-client-ch2-invariant st)
(memberp (action stimulus)
'(:home-grants-shared
:home-grants-exclusive)))
(hsl-client-ch2-invariant (german-step st stimulus)))))
;; All right so finally done. The definition and proof of the inductive
;; invariant took way more time than I anticipated. I missed most of the
;; subtleties of the protocol when I started with the earlier predicates. It
;; would be interesting to see if the predicates can be made much simpler with
;; the insight I possess now, but I am too lazy to get back to them now that
;; the proof is virtually over.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Section 4: Cleanup and final theorem ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Now I have gotten thru the most difficult part of the proof, namely coming
;; up with a set of predicates that together imply that their conjunction holds
;; at the next step. In this proof I have shown all predicates true on a
;; case-by-case basis already, so the final clean-up will not require the
;; definition of the predicates. Further the final cleanup also does not
;; require the definition of german-step. So I disable all definitions here.
;; Note: Since everything was done on a case-by-case basis the replay of the
;; proofs will be rather slow. One way to improve the speed of proof is to
;; just remove all the individual persistence theorems, and do it all together
;; at the end. I normally do that, but I am doing this proof more to show how
;; one comes up with such a proof in ACL2 than to speed up the certification.
;; So I leave things like this. [In practice we define the invariant and every
;; time the persistence of invariance fails we augment the invariant with a new
;; predicate or lemma.]
(local
(in-theory (disable coherent
ch2-client-shared-invariant
ch2-client-exclusive-invariant
not-heg-clients-shared-invariant
channel-nil-exclusive-invariant
hsl-client-invariant
invalidate-ack-clients-invariant
heg-exclusive-invariant
hsl-ch2-invariant
hil-heg-invariant
invalidate-ack-idle-invariant
invalidate-exclusive-invariant
hil-hsl-invariant
invalidate-ack-ch2-invariant
unique-hil-invariant
hsl-heg-invariant
hsl-ch3-invariant
invalidate-clients-invariant
hsl-boolean-invariant
hil-invalidate-invariant
hil-invalidate-ch2-invariant
valid-status-invariant
hcm-ch2-invariant
hcm-invalidate-ack-invariant
hil-client-ch2-invariant
hsl-client-ch2-invariant
init
(init)
german-step)))
(local
(defun inv (st)
(and (coherent st)
(ch2-client-shared-invariant st)
(ch2-client-exclusive-invariant st)
(not-heg-clients-shared-invariant st)
(channel-nil-exclusive-invariant st)
(hsl-client-invariant st)
(invalidate-ack-clients-invariant st)
(heg-exclusive-invariant st)
(hsl-ch2-invariant st)
(hil-heg-invariant st)
(hil-client-ch2-invariant st)
(hsl-client-ch2-invariant st)
(invalidate-ack-idle-invariant st)
(invalidate-exclusive-invariant st)
(invalidate-ack-ch2-invariant st)
(hil-invalidate-ch2-invariant st)
(hsl-heg-invariant st)
(hsl-ch3-invariant st)
(unique-hil-invariant st)
(invalidate-clients-invariant st)
(valid-status-invariant st)
(hsl-boolean-invariant st)
(hcm-ch2-invariant st)
(hcm-invalidate-ack-invariant st)
(hil-invalidate-invariant st)
(hil-hsl-invariant st))))
;; Now the final proofs which should go thru without too much hassle.
(local
(defthm |inv holds in initial state| (inv (init))))
(local
(defthm |inv is inductive| (implies (inv st) (inv (german-step st stimulus)))
:hints (("Goal"
:cases ((equal (action stimulus) :request-shared-access)
(equal (action stimulus) :request-exclusive-access)
(equal (action stimulus) :pick-new-request)
(equal (action stimulus) :home-sends-invalidate)
(equal (action stimulus) :home-receives-invalidate)
(equal (action stimulus) :sharer-invalidate-cache)
(equal (action stimulus) :client-receives-shared)
(equal (action stimulus) :client-receives-exclusive)
(equal (action stimulus) :home-grants-shared)
(equal (action stimulus) :home-grants-exclusive))))))
(local
(defthm |inv implies coherent|
(implies (inv st) (coherent st))))
;; Of course I am done already but just for the heck of it let me prove as a
;; final theorem that inv does imply coherent and hence coherent is true of
;; every execution. First let us define an execution of the german protocol.
(defun german-run (st stimuli)
(if (endp stimuli) st
(let* ((stimulus (first stimuli)))
(german-run (german-step st stimulus) (rest stimuli)))))
(local
(defthm |inv persists along run|
(implies (inv st) (inv (german-run st stimuli)))))
(local
(defthm |inv is true of all runs from init|
(inv (german-run (init) stimuli))))
;; And the final one is a capital DEFTHM.
(DEFTHM |every run is coherent| (coherent (german-run (init) stimuli)))
|
[
{
"context": "il address to:\n;;; CommonLoops Coordinator\n;;; Xerox PARC\n;;; 3333 Coyote Hill Rd.\n;;; Palo Alto, CA 94",
"end": 859,
"score": 0.9524916410446167,
"start": 849,
"tag": "NAME",
"value": "Xerox PARC"
},
{
"context": " Palo Alto, CA 94304\n;;; (or send Arpanet mail to [email protected])\n;;;\n;;; Suggestions, comments and requests for i",
"end": 979,
"score": 0.9991103410720825,
"start": 942,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
pcl/cache.lisp
|
binghe/portable-clos
| 57 |
;;;-*-Mode:LISP; Package:(PCL LISP 1000); Base:10; Syntax:Common-lisp -*-
;;;
;;; *************************************************************************
;;; Copyright (c) 1985, 1986, 1987, 1988, 1989, 1990 Xerox Corporation.
;;; All rights reserved.
;;;
;;; Use and copying of this software and preparation of derivative works
;;; based upon this software are permitted. Any distribution of this
;;; software or derivative works must comply with all applicable United
;;; States export control laws.
;;;
;;; This software is made available AS IS, and Xerox Corporation makes no
;;; warranty about the software, its performance or its conformity to any
;;; specification.
;;;
;;; Any person obtaining a copy of this software is requested to send their
;;; name and post office or electronic mail address to:
;;; CommonLoops Coordinator
;;; Xerox PARC
;;; 3333 Coyote Hill Rd.
;;; Palo Alto, CA 94304
;;; (or send Arpanet mail to [email protected])
;;;
;;; Suggestions, comments and requests for improvements are also welcome.
;;; *************************************************************************
;;;
;;; The basics of the PCL wrapper cache mechanism.
;;;
(in-package :pcl)
;;;
;;; The caching algorithm implemented:
;;;
;;; << put a paper here >>
;;;
;;; For now, understand that as far as most of this code goes, a cache has
;;; two important properties. The first is the number of wrappers used as
;;; keys in each cache line. Throughout this code, this value is always
;;; called NKEYS. The second is whether or not the cache lines of a cache
;;; store a value. Throughout this code, this always called VALUEP.
;;;
;;; Depending on these values, there are three kinds of caches.
;;;
;;; NKEYS = 1, VALUEP = NIL
;;;
;;; In this kind of cache, each line is 1 word long. No cache locking is
;;; needed since all read's in the cache are a single value. Nevertheless
;;; line 0 (location 0) is reserved, to ensure that invalid wrappers will
;;; not get a first probe hit.
;;;
;;; To keep the code simpler, a cache lock count does appear in location 0
;;; of these caches, that count is incremented whenever data is written to
;;; the cache. But, the actual lookup code (see make-dlap) doesn't need to
;;; do locking when reading the cache.
;;;
;;;
;;; NKEYS = 1, VALUEP = T
;;;
;;; In this kind of cache, each line is 2 words long. Cache locking must
;;; be done to ensure the synchronization of cache reads. Line 0 of the
;;; cache (location 0) is reserved for the cache lock count. Location 1
;;; of the cache is unused (in effect wasted).
;;;
;;; NKEYS > 1
;;;
;;; In this kind of cache, the 0 word of the cache holds the lock count.
;;; The 1 word of the cache is line 0. Line 0 of these caches is not
;;; reserved.
;;;
;;; This is done because in this sort of cache, the overhead of doing the
;;; cache probe is high enough that the 1+ required to offset the location
;;; is not a significant cost. In addition, because of the larger line
;;; sizes, the space that would be wasted by reserving line 0 to hold the
;;; lock count is more significant.
;;;
;;;
;;; Caches
;;;
;;; A cache is essentially just a vector. The use of the individual `words'
;;; in the vector depends on particular properties of the cache as described
;;; above.
;;;
;;; This defines an abstraction for caches in terms of their most obvious
;;; implementation as simple vectors. But, please notice that part of the
;;; implementation of this abstraction, is the function lap-out-cache-ref.
;;; This means that most port-specific modifications to the implementation
;;; of caches will require corresponding port-specific modifications to the
;;; lap code assembler.
;;;
(defmacro cache-vector-ref (cache-vector location)
`(svref (the simple-vector ,cache-vector)
(#-cmu the #+cmu ext:truly-the fixnum ,location)))
(defmacro cache-vector-size (cache-vector)
`(array-dimension (the simple-vector ,cache-vector) 0))
(defun allocate-cache-vector (size)
(make-array size :adjustable nil))
(defmacro cache-vector-lock-count (cache-vector)
`(cache-vector-ref ,cache-vector 0))
(defun flush-cache-vector-internal (cache-vector)
(without-interrupts
(fill (the simple-vector cache-vector) nil)
(setf (cache-vector-lock-count cache-vector) 0))
cache-vector)
(defmacro modify-cache (cache-vector &body body)
`(without-interrupts
(multiple-value-prog1
(progn ,@body)
(let ((old-count (cache-vector-lock-count ,cache-vector)))
(declare (fixnum old-count))
(setf (cache-vector-lock-count ,cache-vector)
(if (= old-count most-positive-fixnum)
1 (the fixnum (1+ old-count))))))))
(deftype field-type ()
'(integer 0 ;#.(position 'number wrapper-layout)
7)) ;#.(position 'number wrapper-layout :from-end t)
(eval-when (compile load eval)
(defun power-of-two-ceiling (x)
(declare (fixnum x))
;;(expt 2 (ceiling (log x 2)))
(the fixnum (ash 1 (integer-length (1- x)))))
(defconstant *nkeys-limit* 256)
)
(defstruct (cache
(:print-function print-cache)
(:constructor make-cache ())
(:copier copy-cache-internal))
(owner nil)
(nkeys 1 :type (integer 1 #.*nkeys-limit*))
(valuep nil :type (member nil t))
(nlines 0 :type fixnum)
(field 0 :type field-type)
(limit-fn #'default-limit-fn :type function)
(mask 0 :type fixnum)
(size 0 :type fixnum)
(line-size 1 :type (integer 1 #.(power-of-two-ceiling (1+ *nkeys-limit*))))
(max-location 0 :type fixnum)
(vector #() :type simple-vector)
(overflow nil :type list))
(defun print-cache (cache stream depth)
(declare (ignore depth))
(printing-random-thing (cache stream)
(format stream "cache ~D ~S ~D"
(cache-nkeys cache) (cache-valuep cache) (cache-nlines cache))))
#+akcl
(si::freeze-defstruct 'cache)
(defmacro cache-lock-count (cache)
`(cache-vector-lock-count (cache-vector ,cache)))
;;;
;;; Some facilities for allocation and freeing caches as they are needed.
;;; This is done on the assumption that a better port of PCL will arrange
;;; to cons these all the same static area. Given that, the fact that
;;; PCL tries to reuse them should be a win.
;;;
(defvar *free-cache-vectors* (make-hash-table :size 16 :test 'eql))
;;;
;;; Return a cache that has had flush-cache-vector-internal called on it. This
;;; returns a cache of exactly the size requested, it won't ever return a
;;; larger cache.
;;;
(defun get-cache-vector (size)
(let ((entry (gethash size *free-cache-vectors*)))
(without-interrupts
(cond ((null entry)
(setf (gethash size *free-cache-vectors*) (cons 0 nil))
(get-cache-vector size))
((null (cdr entry))
(incf (car entry))
(flush-cache-vector-internal (allocate-cache-vector size)))
(t
(let ((cache (cdr entry)))
(setf (cdr entry) (cache-vector-ref cache 0))
(flush-cache-vector-internal cache)))))))
(defun free-cache-vector (cache-vector)
(let ((entry (gethash (cache-vector-size cache-vector) *free-cache-vectors*)))
(without-interrupts
(if (null entry)
(error "Attempt to free a cache-vector not allocated by GET-CACHE-VECTOR.")
(let ((thread (cdr entry)))
(loop (unless thread (return))
(when (eq thread cache-vector) (error "Freeing a cache twice."))
(setq thread (cache-vector-ref thread 0)))
(flush-cache-vector-internal cache-vector) ;Help the GC
(setf (cache-vector-ref cache-vector 0) (cdr entry))
(setf (cdr entry) cache-vector)
nil)))))
;;;
;;; This is just for debugging and analysis. It shows the state of the free
;;; cache resource.
;;;
(defun show-free-cache-vectors ()
(let ((elements ()))
(maphash #'(lambda (s e) (push (list s e) elements)) *free-cache-vectors*)
(setq elements (sort elements #'< :key #'car))
(dolist (e elements)
(let* ((size (car e))
(entry (cadr e))
(allocated (car entry))
(head (cdr entry))
(free 0))
(loop (when (null head) (return t))
(setq head (cache-vector-ref head 0))
(incf free))
(format t
"~&There ~4D are caches of size ~4D. (~D free ~3D%)"
allocated
size
free
(floor (* 100 (/ free (float allocated)))))))))
;;;
;;; Wrapper cache numbers
;;;
;;;
;;; The constant WRAPPER-CACHE-NUMBER-ADDS-OK controls the number of non-zero
;;; bits wrapper cache numbers will have.
;;;
;;; The value of this constant is the number of wrapper cache numbers which
;;; can be added and still be certain the result will be a fixnum. This is
;;; used by all the code that computes primary cache locations from multiple
;;; wrappers.
;;;
;;; The value of this constant is used to derive the next two which are the
;;; forms of this constant which it is more convenient for the runtime code
;;; to use.
;;;
(eval-when (compile load eval)
(defconstant wrapper-cache-number-adds-ok 4)
(defconstant wrapper-cache-number-length
(- (integer-length most-positive-fixnum)
wrapper-cache-number-adds-ok))
(defconstant wrapper-cache-number-mask
(1- (expt 2 wrapper-cache-number-length)))
(defvar *get-wrapper-cache-number* (make-random-state))
(defun get-wrapper-cache-number ()
(let ((n 0))
(declare (fixnum n))
(loop
(setq n
(logand wrapper-cache-number-mask
(random most-positive-fixnum *get-wrapper-cache-number*)))
(unless (zerop n) (return n)))))
(unless (> wrapper-cache-number-length 8)
(error "In this implementation of Common Lisp, fixnums are so small that~@
wrapper cache numbers end up being only ~D bits long. This does~@
not actually keep PCL from running, but it may degrade cache~@
performance.~@
You may want to consider changing the value of the constant~@
WRAPPER-CACHE-NUMBER-ADDS-OK.")))
;;;
;;; wrappers themselves
;;;
;;; This caching algorithm requires that wrappers have more than one wrapper
;;; cache number. You should think of these multiple numbers as being in
;;; columns. That is, for a given cache, the same column of wrapper cache
;;; numbers will be used.
;;;
;;; If at some point the cache distribution of a cache gets bad, the cache
;;; can be rehashed by switching to a different column.
;;;
;;; The columns are referred to by field number which is that number which,
;;; when used as a second argument to wrapper-ref, will return that column
;;; of wrapper cache number.
;;;
;;; This code is written to allow flexibility as to how many wrapper cache
;;; numbers will be in each wrapper, and where they will be located. It is
;;; also set up to allow port specific modifications to `pack' the wrapper
;;; cache numbers on machines where the addressing modes make that a good
;;; idea.
;;;
#-structure-wrapper
(progn
(eval-when (compile load eval)
(defconstant wrapper-layout
'(number
number
number
number
number
number
number
number
state
instance-slots-layout
class-slots
class
no-of-instance-slots))
)
(eval-when (compile load eval)
(defun wrapper-field (type)
(posq type wrapper-layout))
(defun next-wrapper-field (field-number)
(position (nth field-number wrapper-layout)
wrapper-layout
:start (1+ field-number)))
(defmacro first-wrapper-cache-number-index ()
`(wrapper-field 'number))
(defmacro next-wrapper-cache-number-index (field-number)
`(next-wrapper-field ,field-number))
);eval-when
(defmacro wrapper-cache-number-vector (wrapper)
wrapper)
(defmacro cache-number-vector-ref (cnv n)
`(svref ,cnv ,n))
(defmacro wrapper-ref (wrapper n)
`(svref ,wrapper ,n))
(defmacro wrapper-state (wrapper)
`(wrapper-ref ,wrapper ,(wrapper-field 'state)))
(defmacro wrapper-instance-slots-layout (wrapper)
`(wrapper-ref ,wrapper ,(wrapper-field 'instance-slots-layout)))
(defmacro wrapper-class-slots (wrapper)
`(wrapper-ref ,wrapper ,(wrapper-field 'class-slots)))
(defmacro wrapper-class (wrapper)
`(wrapper-ref ,wrapper ,(wrapper-field 'class)))
(defmacro wrapper-no-of-instance-slots (wrapper)
`(wrapper-ref ,wrapper ,(wrapper-field 'no-of-instance-slots)))
(defmacro make-wrapper-internal ()
`(let ((wrapper (make-array ,(length wrapper-layout) :adjustable nil)))
,@(gathering1 (collecting)
(iterate ((i (interval :from 0))
(desc (list-elements wrapper-layout)))
(ecase desc
(number
(gather1 `(setf (wrapper-ref wrapper ,i)
(get-wrapper-cache-number))))
((state instance-slots-layout class-slots class no-of-instance-slots)))))
(setf (wrapper-state wrapper) 't)
wrapper))
(defun make-wrapper (no-of-instance-slots &optional class)
(let ((wrapper (make-wrapper-internal)))
(setf (wrapper-no-of-instance-slots wrapper) no-of-instance-slots)
(setf (wrapper-class wrapper) class)
wrapper))
)
; In CMUCL we want to do type checking as early as possible; structures help this.
#+structure-wrapper
(eval-when (compile load eval)
(defconstant wrapper-cache-number-vector-length 8)
(deftype cache-number-vector ()
`(simple-array fixnum (8)))
(defconstant wrapper-layout (make-list wrapper-cache-number-vector-length
:initial-element 'number))
)
#+structure-wrapper
(progn
#-new-kcl-wrapper
(defun make-wrapper-cache-number-vector ()
(let ((cnv (make-array #.wrapper-cache-number-vector-length
:element-type 'fixnum)))
(dotimes (i #.wrapper-cache-number-vector-length)
(setf (aref cnv i) (get-wrapper-cache-number)))
cnv))
(defstruct (wrapper
#+new-kcl-wrapper (:include si::basic-wrapper)
(:print-function print-wrapper)
#-new-kcl-wrapper
(:constructor make-wrapper (no-of-instance-slots &optional class))
#+new-kcl-wrapper
(:constructor make-wrapper-internal))
#-new-kcl-wrapper
(cache-number-vector (make-wrapper-cache-number-vector)
:type cache-number-vector)
#-new-kcl-wrapper
(state t :type (or (member t) cons))
;; either t or a list (state-sym new-wrapper)
;; where state-sym is either :flush or :obsolete
(instance-slots-layout nil :type list)
(class-slots nil :type list)
#-new-kcl-wrapper
(no-of-instance-slots 0 :type fixnum)
#-new-kcl-wrapper
(class *the-class-t* :type class))
(unless (boundp '*the-class-t*) (setq *the-class-t* nil))
#+new-kcl-wrapper
(defmacro wrapper-no-of-instance-slots (wrapper)
`(si::s-data-length ,wrapper))
#+new-kcl-wrapper
(defun make-wrapper (size &optional class)
(multiple-value-bind (raw slot-positions)
(if (< size 50)
(values si::*all-t-s-type* si::*standard-slot-positions*)
(values (make-array size :element-type 'unsigned-char)
(let ((array (make-array size :element-type 'unsigned-short)))
(dotimes (i size)
(declare (fixnum i))
(setf (aref array i) (* #.(si::size-of t) i))))))
(make-wrapper-internal :length size
:raw raw
:print-function 'print-std-instance
:slot-position slot-positions
:size (* size #.(si::size-of t))
:class class)))
(defun print-wrapper (wrapper stream depth)
(declare (ignore depth))
(printing-random-thing (wrapper stream)
(format stream "Wrapper ~S" (wrapper-class wrapper))))
(defmacro first-wrapper-cache-number-index ()
0)
(defmacro next-wrapper-cache-number-index (field-number)
`(and (< ,field-number #.(1- wrapper-cache-number-vector-length))
(1+ ,field-number)))
(defmacro cache-number-vector-ref (cnv n)
`(#-kcl svref #+kcl aref ,cnv ,n))
)
(defmacro wrapper-cache-number-vector-ref (wrapper n)
`(the fixnum
(#-structure-wrapper svref #+structure-wrapper aref
(wrapper-cache-number-vector ,wrapper) ,n)))
(defmacro class-no-of-instance-slots (class)
`(wrapper-no-of-instance-slots (class-wrapper ,class)))
(defmacro wrapper-class* (wrapper)
#-new-kcl-wrapper
`(wrapper-class ,wrapper)
#+new-kcl-wrapper
`(let ((wrapper ,wrapper))
(or (wrapper-class wrapper)
(find-structure-class (si::s-data-name wrapper)))))
;;;
;;; The wrapper cache machinery provides general mechanism for trapping on
;;; the next access to any instance of a given class. This mechanism is
;;; used to implement the updating of instances when the class is redefined
;;; (make-instances-obsolete). The same mechanism is also used to update
;;; generic function caches when there is a change to the supers of a class.
;;;
;;; Basically, a given wrapper can be valid or invalid. If it is invalid,
;;; it means that any attempt to do a wrapper cache lookup using the wrapper
;;; should trap. Also, methods on slot-value-using-class check the wrapper
;;; validity as well. This is done by calling check-wrapper-validity.
;;;
(defmacro invalid-wrapper-p (wrapper)
`(neq (wrapper-state ,wrapper) 't))
(defvar *previous-nwrappers* (make-hash-table))
(defun invalidate-wrapper (owrapper state nwrapper)
(ecase state
((:flush :obsolete)
(let ((new-previous ()))
;;
;; First off, a previous call to invalidate-wrapper may have recorded
;; owrapper as an nwrapper to update to. Since owrapper is about to
;; be invalid, it no longer makes sense to update to it.
;;
;; We go back and change the previously invalidated wrappers so that
;; they will now update directly to nwrapper. This corresponds to a
;; kind of transitivity of wrapper updates.
;;
(dolist (previous (gethash owrapper *previous-nwrappers*))
(when (eq state ':obsolete)
(setf (car previous) ':obsolete))
(setf (cadr previous) nwrapper)
(push previous new-previous))
(let ((ocnv (wrapper-cache-number-vector owrapper)))
(iterate ((type (list-elements wrapper-layout))
(i (interval :from 0)))
(when (eq type 'number) (setf (cache-number-vector-ref ocnv i) 0))))
(push (setf (wrapper-state owrapper) (list state nwrapper))
new-previous)
(setf (gethash owrapper *previous-nwrappers*) ()
(gethash nwrapper *previous-nwrappers*) new-previous)))))
(defun check-wrapper-validity (instance)
(let* ((owrapper (wrapper-of instance))
(state (wrapper-state owrapper)))
(if (eq state 't)
owrapper
(let ((nwrapper
(ecase (car state)
(:flush
(flush-cache-trap owrapper (cadr state) instance))
(:obsolete
(obsolete-instance-trap owrapper (cadr state) instance)))))
;;
;; This little bit of error checking is superfluous. It only
;; checks to see whether the person who implemented the trap
;; handling screwed up. Since that person is hacking internal
;; PCL code, and is not a user, this should be needless. Also,
;; since this directly slows down instance update and generic
;; function cache refilling, feel free to take it out sometime
;; soon.
;;
(cond ((neq nwrapper (wrapper-of instance))
(error "Wrapper returned from trap not wrapper of instance."))
((invalid-wrapper-p nwrapper)
(error "Wrapper returned from trap invalid.")))
nwrapper))))
(defmacro check-wrapper-validity1 (object)
(let ((owrapper (gensym)))
`(let ((,owrapper (cond ((std-instance-p ,object)
(std-instance-wrapper ,object))
((fsc-instance-p ,object)
(fsc-instance-wrapper ,object))
#+new-kcl-wrapper
(t (built-in-wrapper-of ,object))
#-new-kcl-wrapper
(t (wrapper-of ,object)))))
(if (eq 't (wrapper-state ,owrapper))
,owrapper
(check-wrapper-validity ,object)))))
(defvar *free-caches* nil)
(defun get-cache (nkeys valuep limit-fn nlines)
(let ((cache (or (without-interrupts (pop *free-caches*)) (make-cache))))
(declare (type cache cache))
(multiple-value-bind (cache-mask actual-size line-size nlines)
(compute-cache-parameters nkeys valuep nlines)
(setf (cache-nkeys cache) nkeys
(cache-valuep cache) valuep
(cache-nlines cache) nlines
(cache-field cache) (first-wrapper-cache-number-index)
(cache-limit-fn cache) limit-fn
(cache-mask cache) cache-mask
(cache-size cache) actual-size
(cache-line-size cache) line-size
(cache-max-location cache) (let ((line (1- nlines)))
(if (= nkeys 1)
(* line line-size)
(1+ (* line line-size))))
(cache-vector cache) (get-cache-vector actual-size)
(cache-overflow cache) nil)
cache)))
(defun get-cache-from-cache (old-cache new-nlines
&optional (new-field (first-wrapper-cache-number-index)))
(let ((nkeys (cache-nkeys old-cache))
(valuep (cache-valuep old-cache))
(cache (or (without-interrupts (pop *free-caches*)) (make-cache))))
(declare (type cache cache))
(multiple-value-bind (cache-mask actual-size line-size nlines)
(if (= new-nlines (cache-nlines old-cache))
(values (cache-mask old-cache) (cache-size old-cache)
(cache-line-size old-cache) (cache-nlines old-cache))
(compute-cache-parameters nkeys valuep new-nlines))
(setf (cache-owner cache) (cache-owner old-cache)
(cache-nkeys cache) nkeys
(cache-valuep cache) valuep
(cache-nlines cache) nlines
(cache-field cache) new-field
(cache-limit-fn cache) (cache-limit-fn old-cache)
(cache-mask cache) cache-mask
(cache-size cache) actual-size
(cache-line-size cache) line-size
(cache-max-location cache) (let ((line (1- nlines)))
(if (= nkeys 1)
(* line line-size)
(1+ (* line line-size))))
(cache-vector cache) (get-cache-vector actual-size)
(cache-overflow cache) nil)
cache)))
(defun copy-cache (old-cache)
(let* ((new-cache (copy-cache-internal old-cache))
(size (cache-size old-cache))
(old-vector (cache-vector old-cache))
(new-vector (get-cache-vector size)))
(declare (simple-vector old-vector new-vector))
(dotimes (i size)
(setf (svref new-vector i) (svref old-vector i)))
(setf (cache-vector new-cache) new-vector)
new-cache))
(defun free-cache (cache)
(free-cache-vector (cache-vector cache))
(setf (cache-vector cache) #())
(setf (cache-owner cache) nil)
(push cache *free-caches*)
nil)
(defun compute-line-size (x)
(power-of-two-ceiling x))
(defun compute-cache-parameters (nkeys valuep nlines-or-cache-vector)
;;(declare (values cache-mask actual-size line-size nlines))
(declare (fixnum nkeys))
(if (= nkeys 1)
(let* ((line-size (if valuep 2 1))
(cache-size (if (typep nlines-or-cache-vector 'fixnum)
(the fixnum
(* line-size
(the fixnum
(power-of-two-ceiling
nlines-or-cache-vector))))
(cache-vector-size nlines-or-cache-vector))))
(declare (fixnum line-size cache-size))
(values (logxor (the fixnum (1- cache-size)) (the fixnum (1- line-size)))
cache-size
line-size
(the fixnum (floor cache-size line-size))))
(let* ((line-size (power-of-two-ceiling (if valuep (1+ nkeys) nkeys)))
(cache-size (if (typep nlines-or-cache-vector 'fixnum)
(the fixnum
(* line-size
(the fixnum
(power-of-two-ceiling
nlines-or-cache-vector))))
(1- (cache-vector-size nlines-or-cache-vector)))))
(declare (fixnum line-size cache-size))
(values (logxor (the fixnum (1- cache-size)) (the fixnum (1- line-size)))
(the fixnum (1+ cache-size))
line-size
(the fixnum (floor cache-size line-size))))))
;;;
;;; The various implementations of computing a primary cache location from
;;; wrappers. Because some implementations of this must run fast there are
;;; several implementations of the same algorithm.
;;;
;;; The algorithm is:
;;;
;;; SUM over the wrapper cache numbers,
;;; ENSURING that the result is a fixnum
;;; MASK the result against the mask argument.
;;;
;;;
;;;
;;; COMPUTE-PRIMARY-CACHE-LOCATION
;;;
;;; The basic functional version. This is used by the cache miss code to
;;; compute the primary location of an entry.
;;;
(defun compute-primary-cache-location (field mask wrappers)
(declare (type field-type field) (fixnum mask))
(if (not (listp wrappers))
(logand mask (the fixnum (wrapper-cache-number-vector-ref wrappers field)))
(let ((location 0) (i 0))
(declare (fixnum location i))
(dolist (wrapper wrappers)
;;
;; First add the cache number of this wrapper to location.
;;
(let ((wrapper-cache-number (wrapper-cache-number-vector-ref wrapper field)))
(declare (fixnum wrapper-cache-number))
(if (zerop wrapper-cache-number)
(return-from compute-primary-cache-location 0)
(setq location (the fixnum (+ location wrapper-cache-number)))))
;;
;; Then, if we are working with lots of wrappers, deal with
;; the wrapper-cache-number-mask stuff.
;;
(when (and (not (zerop i))
(zerop (mod i wrapper-cache-number-adds-ok)))
(setq location
(logand location wrapper-cache-number-mask)))
(incf i))
(the fixnum (1+ (logand mask location))))))
;;;
;;; COMPUTE-PRIMARY-CACHE-LOCATION-FROM-LOCATION
;;;
;;; This version is called on a cache line. It fetches the wrappers from
;;; the cache line and determines the primary location. Various parts of
;;; the cache filling code call this to determine whether it is appropriate
;;; to displace a given cache entry.
;;;
;;; If this comes across a wrapper whose cache-no is 0, it returns the symbol
;;; invalid to suggest to its caller that it would be provident to blow away
;;; the cache line in question.
;;;
(defun compute-primary-cache-location-from-location (to-cache from-location
&optional (from-cache to-cache))
(declare (type cache to-cache from-cache) (fixnum from-location))
(let ((result 0)
(cache-vector (cache-vector from-cache))
(field (cache-field to-cache))
(mask (cache-mask to-cache))
(nkeys (cache-nkeys to-cache)))
(declare (type field-type field) (fixnum result mask nkeys)
(simple-vector cache-vector))
(dotimes (i nkeys)
(let* ((wrapper (cache-vector-ref cache-vector (+ i from-location)))
(wcn (wrapper-cache-number-vector-ref wrapper field)))
(declare (fixnum wcn))
(setq result (+ result wcn)))
(when (and (not (zerop i))
(zerop (mod i wrapper-cache-number-adds-ok)))
(setq result (logand result wrapper-cache-number-mask))))
(if (= nkeys 1)
(logand mask result)
(the fixnum (1+ (logand mask result))))))
;;;
;;; NIL means nothing so far, no actual arg info has NILs
;;; in the metatype
;;; CLASS seen all sorts of metaclasses
;;; (specifically, more than one of the next 4 values)
;;; T means everything so far is the class T
;;; STANDARD-CLASS seen only standard classes
;;; BUILT-IN-CLASS seen only built in classes
;;; STRUCTURE-CLASS seen only structure classes
;;;
(defun raise-metatype (metatype new-specializer)
(let ((slot (find-class 'slot-class))
(standard (find-class 'standard-class))
(fsc (find-class 'funcallable-standard-class))
(structure (find-class 'structure-class))
(built-in (find-class 'built-in-class)))
(flet ((specializer->metatype (x)
(let ((meta-specializer
(if (eq *boot-state* 'complete)
(class-of (specializer-class x))
(class-of x))))
(cond ((eq x *the-class-t*) t)
((*subtypep meta-specializer standard) 'standard-instance)
((*subtypep meta-specializer fsc) 'standard-instance)
((*subtypep meta-specializer structure) 'structure-instance)
((*subtypep meta-specializer built-in) 'built-in-instance)
((*subtypep meta-specializer slot) 'slot-instance)
(t (error "PCL can not handle the specializer ~S (meta-specializer ~S)."
new-specializer meta-specializer))))))
;;
;; We implement the following table. The notation is
;; that X and Y are distinct meta specializer names.
;;
;; NIL <anything> ===> <anything>
;; X X ===> X
;; X Y ===> CLASS
;;
(let ((new-metatype (specializer->metatype new-specializer)))
(cond ((eq new-metatype 'slot-instance) 'class)
((null metatype) new-metatype)
((eq metatype new-metatype) new-metatype)
(t 'class))))))
(defmacro with-dfun-wrappers ((args metatypes)
(dfun-wrappers invalid-wrapper-p
&optional wrappers classes types)
invalid-arguments-form
&body body)
`(let* ((args-tail ,args) (,invalid-wrapper-p nil) (invalid-arguments-p nil)
(,dfun-wrappers nil) (dfun-wrappers-tail nil)
,@(when wrappers
`((wrappers-rev nil) (types-rev nil) (classes-rev nil))))
(dolist (mt ,metatypes)
(unless args-tail
(setq invalid-arguments-p t)
(return nil))
(let* ((arg (pop args-tail))
(wrapper nil)
,@(when wrappers
`((class *the-class-t*)
(type 't))))
(unless (eq mt 't)
(setq wrapper (wrapper-of arg))
(when (invalid-wrapper-p wrapper)
(setq ,invalid-wrapper-p t)
(setq wrapper (check-wrapper-validity arg)))
(cond ((null ,dfun-wrappers)
(setq ,dfun-wrappers wrapper))
((not (consp ,dfun-wrappers))
(setq dfun-wrappers-tail (list wrapper))
(setq ,dfun-wrappers (cons ,dfun-wrappers dfun-wrappers-tail)))
(t
(let ((new-dfun-wrappers-tail (list wrapper)))
(setf (cdr dfun-wrappers-tail) new-dfun-wrappers-tail)
(setf dfun-wrappers-tail new-dfun-wrappers-tail))))
,@(when wrappers
`((setq class (wrapper-class* wrapper))
(setq type `(class-eq ,class)))))
,@(when wrappers
`((push wrapper wrappers-rev)
(push class classes-rev)
(push type types-rev)))))
(if invalid-arguments-p
,invalid-arguments-form
(let* (,@(when wrappers
`((,wrappers (nreverse wrappers-rev))
(,classes (nreverse classes-rev))
(,types (mapcar #'(lambda (class)
`(class-eq ,class))
,classes)))))
,@body))))
;;;
;;; Some support stuff for getting a hold of symbols that we need when
;;; building the discriminator codes. Its ok for these to be interned
;;; symbols because we don't capture any user code in the scope in which
;;; these symbols are bound.
;;;
(defvar *dfun-arg-symbols* '(.ARG0. .ARG1. .ARG2. .ARG3.))
(defun dfun-arg-symbol (arg-number)
(or (nth arg-number (the list *dfun-arg-symbols*))
(intern (format nil ".ARG~A." arg-number) *the-pcl-package*)))
(defvar *slot-vector-symbols* '(.SLOTS0. .SLOTS1. .SLOTS2. .SLOTS3.))
(defun slot-vector-symbol (arg-number)
(or (nth arg-number (the list *slot-vector-symbols*))
(intern (format nil ".SLOTS~A." arg-number) *the-pcl-package*)))
(defun make-dfun-lambda-list (metatypes applyp)
(gathering1 (collecting)
(iterate ((i (interval :from 0))
(s (list-elements metatypes)))
(progn s)
(gather1 (dfun-arg-symbol i)))
(when applyp
(gather1 '&rest)
(gather1 '.dfun-rest-arg.))))
(defun make-dlap-lambda-list (metatypes applyp)
(gathering1 (collecting)
(iterate ((i (interval :from 0))
(s (list-elements metatypes)))
(progn s)
(gather1 (dfun-arg-symbol i)))
(when applyp
(gather1 '&rest))))
(defun make-emf-call (metatypes applyp fn-variable &optional emf-type)
(let ((required
(gathering1 (collecting)
(iterate ((i (interval :from 0))
(s (list-elements metatypes)))
(progn s)
(gather1 (dfun-arg-symbol i))))))
`(,(if (eq emf-type 'fast-method-call)
'invoke-effective-method-function-fast
'invoke-effective-method-function)
,fn-variable ,applyp ,@required ,@(when applyp `(.dfun-rest-arg.)))))
(defun make-dfun-call (metatypes applyp fn-variable)
(let ((required
(gathering1 (collecting)
(iterate ((i (interval :from 0))
(s (list-elements metatypes)))
(progn s)
(gather1 (dfun-arg-symbol i))))))
(if applyp
`(function-apply ,fn-variable ,@required .dfun-rest-arg.)
`(function-funcall ,fn-variable ,@required))))
(defun make-dfun-arg-list (metatypes applyp)
(let ((required
(gathering1 (collecting)
(iterate ((i (interval :from 0))
(s (list-elements metatypes)))
(progn s)
(gather1 (dfun-arg-symbol i))))))
(if applyp
`(list* ,@required .dfun-rest-arg.)
`(list ,@required))))
(defun make-fast-method-call-lambda-list (metatypes applyp)
(gathering1 (collecting)
(gather1 '.pv-cell.)
(gather1 '.next-method-call.)
(iterate ((i (interval :from 0))
(s (list-elements metatypes)))
(progn s)
(gather1 (dfun-arg-symbol i)))
(when applyp
(gather1 '.dfun-rest-arg.))))
;;;
;;; Its too bad Common Lisp compilers freak out when you have a defun with
;;; a lot of LABELS in it. If I could do that I could make this code much
;;; easier to read and work with.
;;;
;;; Ahh Scheme...
;;;
;;; In the absence of that, the following little macro makes the code that
;;; follows a little bit more reasonable. I would like to add that having
;;; to practically write my own compiler in order to get just this simple
;;; thing is something of a drag.
;;;
(eval-when (compile load eval)
(defvar *cache* nil)
(defconstant *local-cache-functions*
'((cache () .cache.)
(nkeys () (cache-nkeys .cache.))
(line-size () (cache-line-size .cache.))
(vector () (cache-vector .cache.))
(valuep () (cache-valuep .cache.))
(nlines () (cache-nlines .cache.))
(max-location () (cache-max-location .cache.))
(limit-fn () (cache-limit-fn .cache.))
(size () (cache-size .cache.))
(mask () (cache-mask .cache.))
(field () (cache-field .cache.))
(overflow () (cache-overflow .cache.))
;;
;; Return T IFF this cache location is reserved. The only time
;; this is true is for line number 0 of an nkeys=1 cache.
;;
(line-reserved-p (line)
(declare (fixnum line))
(and (= (nkeys) 1)
(= line 0)))
;;
(location-reserved-p (location)
(declare (fixnum location))
(and (= (nkeys) 1)
(= location 0)))
;;
;; Given a line number, return the cache location. This is the
;; value that is the second argument to cache-vector-ref. Basically,
;; this deals with the offset of nkeys>1 caches and multiplies
;; by line size.
;;
(line-location (line)
(declare (fixnum line))
(when (line-reserved-p line)
(error "line is reserved"))
(if (= (nkeys) 1)
(the fixnum (* line (line-size)))
(the fixnum (1+ (the fixnum (* line (line-size)))))))
;;
;; Given a cache location, return the line. This is the inverse
;; of LINE-LOCATION.
;;
(location-line (location)
(declare (fixnum location))
(if (= (nkeys) 1)
(floor location (line-size))
(floor (the fixnum (1- location)) (line-size))))
;;
;; Given a line number, return the wrappers stored at that line.
;; As usual, if nkeys=1, this returns a single value. Only when
;; nkeys>1 does it return a list. An error is signalled if the
;; line is reserved.
;;
(line-wrappers (line)
(declare (fixnum line))
(when (line-reserved-p line) (error "Line is reserved."))
(location-wrappers (line-location line)))
;;
(location-wrappers (location) ; avoid multiplies caused by line-location
(declare (fixnum location))
(if (= (nkeys) 1)
(cache-vector-ref (vector) location)
(let ((list (make-list (nkeys)))
(vector (vector)))
(declare (simple-vector vector))
(dotimes (i (nkeys) list)
(setf (nth i list) (cache-vector-ref vector (+ location i)))))))
;;
;; Given a line number, return true IFF the line's
;; wrappers are the same as wrappers.
;;
(line-matches-wrappers-p (line wrappers)
(declare (fixnum line))
(and (not (line-reserved-p line))
(location-matches-wrappers-p (line-location line) wrappers)))
;;
(location-matches-wrappers-p (loc wrappers) ; must not be reserved
(declare (fixnum loc))
(let ((cache-vector (vector)))
(declare (simple-vector cache-vector))
(if (= (nkeys) 1)
(eq wrappers (cache-vector-ref cache-vector loc))
(dotimes (i (nkeys) t)
(unless (eq (pop wrappers) (cache-vector-ref cache-vector (+ loc i)))
(return nil))))))
;;
;; Given a line number, return the value stored at that line.
;; If valuep is NIL, this returns NIL. As with line-wrappers,
;; an error is signalled if the line is reserved.
;;
(line-value (line)
(declare (fixnum line))
(when (line-reserved-p line) (error "Line is reserved."))
(location-value (line-location line)))
;;
(location-value (loc)
(declare (fixnum loc))
(and (valuep)
(cache-vector-ref (vector) (+ loc (nkeys)))))
;;
;; Given a line number, return true IFF that line has data in
;; it. The state of the wrappers stored in the line is not
;; checked. An error is signalled if line is reserved.
(line-full-p (line)
(when (line-reserved-p line) (error "Line is reserved."))
(not (null (cache-vector-ref (vector) (line-location line)))))
;;
;; Given a line number, return true IFF the line is full and
;; there are no invalid wrappers in the line, and the line's
;; wrappers are different from wrappers.
;; An error is signalled if the line is reserved.
;;
(line-valid-p (line wrappers)
(declare (fixnum line))
(when (line-reserved-p line) (error "Line is reserved."))
(location-valid-p (line-location line) wrappers))
;;
(location-valid-p (loc wrappers)
(declare (fixnum loc))
(let ((cache-vector (vector))
(wrappers-mismatch-p (null wrappers)))
(declare (simple-vector cache-vector))
(dotimes (i (nkeys) wrappers-mismatch-p)
(let ((wrapper (cache-vector-ref cache-vector (+ loc i))))
(when (or (null wrapper)
(invalid-wrapper-p wrapper))
(return nil))
(unless (and wrappers
(eq wrapper
(if (consp wrappers) (pop wrappers) wrappers)))
(setq wrappers-mismatch-p t))))))
;;
;; How many unreserved lines separate line-1 and line-2.
;;
(line-separation (line-1 line-2)
(declare (fixnum line-1 line-2))
(let ((diff (the fixnum (- line-2 line-1))))
(declare (fixnum diff))
(when (minusp diff)
(setq diff (+ diff (nlines)))
(when (line-reserved-p 0)
(setq diff (1- diff))))
diff))
;;
;; Given a cache line, get the next cache line. This will not
;; return a reserved line.
;;
(next-line (line)
(declare (fixnum line))
(if (= line (the fixnum (1- (nlines))))
(if (line-reserved-p 0) 1 0)
(the fixnum (1+ line))))
;;
(next-location (loc)
(declare (fixnum loc))
(if (= loc (max-location))
(if (= (nkeys) 1)
(line-size)
1)
(the fixnum (+ loc (line-size)))))
;;
;; Given a line which has a valid entry in it, this will return
;; the primary cache line of the wrappers in that line. We just
;; call COMPUTE-PRIMARY-CACHE-LOCATION-FROM-LOCATION, this is an
;; easier packaging up of the call to it.
;;
(line-primary (line)
(declare (fixnum line))
(location-line (line-primary-location line)))
;;
(line-primary-location (line)
(declare (fixnum line))
(compute-primary-cache-location-from-location
(cache) (line-location line)))
))
(defmacro with-local-cache-functions ((cache) &body body)
`(let ((.cache. ,cache))
(declare (type cache .cache.))
(macrolet ,(mapcar #'(lambda (fn)
`(,(car fn) ,(cadr fn)
`(let (,,@(mapcar #'(lambda (var)
``(,',var ,,var))
(cadr fn)))
,@',(cddr fn))))
*local-cache-functions*)
,@body)))
)
;;;
;;; Here is where we actually fill, recache and expand caches.
;;;
;;; The functions FILL-CACHE and PROBE-CACHE are the ONLY external
;;; entrypoints into this code.
;;;
;;; FILL-CACHE returns 1 value: a new cache
;;;
;;; a wrapper field number
;;; a cache
;;; a mask
;;; an absolute cache size (the size of the actual vector)
;;; It tries to re-adjust the cache every time it makes a new fill. The
;;; intuition here is that we want uniformity in the number of probes needed to
;;; find an entry. Furthermore, adjusting has the nice property of throwing out
;;; any entries that are invalid.
;;;
(defvar *cache-expand-threshold* 1.25)
(defun fill-cache (cache wrappers value &optional free-cache-p)
;;(declare (values cache))
(unless wrappers ; fill-cache won't return if wrappers is nil, might as well check.
(error "fill-cache: wrappers arg is NIL!"))
(or (fill-cache-p nil cache wrappers value)
(and (< (ceiling (* (cache-count cache) 1.25))
(if (= (cache-nkeys cache) 1)
(1- (cache-nlines cache))
(cache-nlines cache)))
(adjust-cache cache wrappers value free-cache-p))
(expand-cache cache wrappers value free-cache-p)))
(defvar *check-cache-p* nil)
(defmacro maybe-check-cache (cache)
`(progn
(when *check-cache-p*
(check-cache ,cache))
,cache))
(defun check-cache (cache)
(with-local-cache-functions (cache)
(let ((location (if (= (nkeys) 1) 0 1))
(limit (funcall (limit-fn) (nlines))))
(dotimes (i (nlines) cache)
(when (and (not (location-reserved-p location))
(line-full-p i))
(let* ((home-loc (compute-primary-cache-location-from-location
cache location))
(home (location-line (if (location-reserved-p home-loc)
(next-location home-loc)
home-loc)))
(sep (when home (line-separation home i))))
(when (and sep (> sep limit))
(error "bad cache ~S ~@
value at location ~D is ~D lines from its home. limit is ~D."
cache location sep limit))))
(setq location (next-location location))))))
(defun probe-cache (cache wrappers &optional default limit-fn)
;;(declare (values value))
(unless wrappers (error "probe-cache: wrappers arg is NIL!"))
(with-local-cache-functions (cache)
(let* ((location (compute-primary-cache-location (field) (mask) wrappers))
(limit (funcall (or limit-fn (limit-fn)) (nlines))))
(declare (fixnum location limit))
(when (location-reserved-p location)
(setq location (next-location location)))
(dotimes (i (1+ limit))
(when (location-matches-wrappers-p location wrappers)
(return-from probe-cache (or (not (valuep))
(location-value location))))
(setq location (next-location location)))
(dolist (entry (overflow))
(when (equal (car entry) wrappers)
(return-from probe-cache (or (not (valuep))
(cdr entry)))))
default)))
(defun map-cache (function cache &optional set-p)
(with-local-cache-functions (cache)
(let ((set-p (and set-p (valuep))))
(dotimes (i (nlines) cache)
(unless (or (line-reserved-p i) (not (line-valid-p i nil)))
(let ((value (funcall function (line-wrappers i) (line-value i))))
(when set-p
(setf (cache-vector-ref (vector) (+ (line-location i) (nkeys)))
value)))))
(dolist (entry (overflow))
(let ((value (funcall function (car entry) (cdr entry))))
(when set-p
(setf (cdr entry) value))))))
cache)
(defun cache-count (cache)
(with-local-cache-functions (cache)
(let ((count 0))
(declare (fixnum count))
(dotimes (i (nlines) count)
(unless (line-reserved-p i)
(when (line-full-p i)
(incf count)))))))
(defun entry-in-cache-p (cache wrappers value)
(declare (ignore value))
(with-local-cache-functions (cache)
(dotimes (i (nlines))
(unless (line-reserved-p i)
(when (equal (line-wrappers i) wrappers)
(return t))))))
;;;
;;; returns T or NIL
;;;
(defun fill-cache-p (forcep cache wrappers value)
(with-local-cache-functions (cache)
(let* ((location (compute-primary-cache-location (field) (mask) wrappers))
(primary (location-line location)))
(declare (fixnum location primary))
(multiple-value-bind (free emptyp)
(find-free-cache-line primary cache wrappers)
(when (or forcep emptyp)
(when (not emptyp)
(push (cons (line-wrappers free) (line-value free))
(cache-overflow cache)))
;;(fill-line free wrappers value)
(let ((line free))
(declare (fixnum line))
(when (line-reserved-p line)
(error "Attempt to fill a reserved line."))
(let ((loc (line-location line))
(cache-vector (vector)))
(declare (fixnum loc) (simple-vector cache-vector))
(cond ((= (nkeys) 1)
(setf (cache-vector-ref cache-vector loc) wrappers)
(when (valuep)
(setf (cache-vector-ref cache-vector (1+ loc)) value)))
(t
(let ((i 0))
(declare (fixnum i))
(dolist (w wrappers)
(setf (cache-vector-ref cache-vector (+ loc i)) w)
(setq i (the fixnum (1+ i)))))
(when (valuep)
(setf (cache-vector-ref cache-vector (+ loc (nkeys)))
value))))
(maybe-check-cache cache))))))))
(defun fill-cache-from-cache-p (forcep cache from-cache from-line)
(declare (fixnum from-line))
(with-local-cache-functions (cache)
(let ((primary (location-line (compute-primary-cache-location-from-location
cache (line-location from-line) from-cache))))
(declare (fixnum primary))
(multiple-value-bind (free emptyp)
(find-free-cache-line primary cache)
(when (or forcep emptyp)
(when (not emptyp)
(push (cons (line-wrappers free) (line-value free))
(cache-overflow cache)))
;;(transfer-line from-cache-vector from-line cache-vector free)
(let ((from-cache-vector (cache-vector from-cache))
(to-cache-vector (vector))
(to-line free))
(declare (fixnum to-line))
(if (line-reserved-p to-line)
(error "transfering something into a reserved cache line.")
(let ((from-loc (line-location from-line))
(to-loc (line-location to-line)))
(declare (fixnum from-loc to-loc))
(modify-cache to-cache-vector
(dotimes (i (line-size))
(setf (cache-vector-ref to-cache-vector
(+ to-loc i))
(cache-vector-ref from-cache-vector
(+ from-loc i)))))))
(maybe-check-cache cache)))))))
;;;
;;; Returns NIL or (values <field> <cache-vector>)
;;;
;;; This is only called when it isn't possible to put the entry in the cache
;;; the easy way. That is, this function assumes that FILL-CACHE-P has been
;;; called as returned NIL.
;;;
;;; If this returns NIL, it means that it wasn't possible to find a wrapper
;;; field for which all of the entries could be put in the cache (within the
;;; limit).
;;;
(defun adjust-cache (cache wrappers value free-old-cache-p)
(with-local-cache-functions (cache)
(let ((ncache (get-cache-from-cache cache (nlines) (field))))
(do ((nfield (cache-field ncache) (next-wrapper-cache-number-index nfield)))
((null nfield) (free-cache ncache) nil)
(setf (cache-field ncache) nfield)
(labels ((try-one-fill-from-line (line)
(fill-cache-from-cache-p nil ncache cache line))
(try-one-fill (wrappers value)
(fill-cache-p nil ncache wrappers value)))
(if (and (dotimes (i (nlines) t)
(when (and (null (line-reserved-p i))
(line-valid-p i wrappers))
(unless (try-one-fill-from-line i) (return nil))))
(dolist (wrappers+value (cache-overflow cache) t)
(unless (try-one-fill (car wrappers+value) (cdr wrappers+value))
(return nil)))
(try-one-fill wrappers value))
(progn (when free-old-cache-p (free-cache cache))
(return (maybe-check-cache ncache)))
(flush-cache-vector-internal (cache-vector ncache))))))))
;;;
;;; returns: (values <cache>)
;;;
(defun expand-cache (cache wrappers value free-old-cache-p)
;;(declare (values cache))
(with-local-cache-functions (cache)
(let ((ncache (get-cache-from-cache cache (* (nlines) 2))))
(labels ((do-one-fill-from-line (line)
(unless (fill-cache-from-cache-p nil ncache cache line)
(do-one-fill (line-wrappers line) (line-value line))))
(do-one-fill (wrappers value)
(setq ncache (or (adjust-cache ncache wrappers value t)
(fill-cache-p t ncache wrappers value))))
(try-one-fill (wrappers value)
(fill-cache-p nil ncache wrappers value)))
(dotimes (i (nlines))
(when (and (null (line-reserved-p i))
(line-valid-p i wrappers))
(do-one-fill-from-line i)))
(dolist (wrappers+value (cache-overflow cache))
(unless (try-one-fill (car wrappers+value) (cdr wrappers+value))
(do-one-fill (car wrappers+value) (cdr wrappers+value))))
(unless (try-one-fill wrappers value)
(do-one-fill wrappers value))
(when free-old-cache-p (free-cache cache))
(maybe-check-cache ncache)))))
;;;
;;; This is the heart of the cache filling mechanism. It implements the decisions
;;; about where entries are placed.
;;;
;;; Find a line in the cache at which a new entry can be inserted.
;;;
;;; <line>
;;; <empty?> is <line> in fact empty?
;;;
(defun find-free-cache-line (primary cache &optional wrappers)
;;(declare (values line empty?))
(declare (fixnum primary))
(with-local-cache-functions (cache)
(when (line-reserved-p primary) (setq primary (next-line primary)))
(let ((limit (funcall (limit-fn) (nlines)))
(wrappedp nil)
(lines nil)
(p primary) (s primary))
(declare (fixnum p s limit))
(block find-free
(loop
;; Try to find a free line starting at <s>. <p> is the
;; primary line of the entry we are finding a free
;; line for, it is used to compute the seperations.
(do* ((line s (next-line line))
(nsep (line-separation p s) (1+ nsep)))
(())
(declare (fixnum line nsep))
(when (null (line-valid-p line wrappers)) ;If this line is empty or
(push line lines) ;invalid, just use it.
(return-from find-free))
(when (and wrappedp (>= line primary))
;; have gone all the way around the cache, time to quit
(return-from find-free-cache-line (values primary nil)))
(let ((osep (line-separation (line-primary line) line)))
(when (>= osep limit)
(return-from find-free-cache-line (values primary nil)))
(when (cond ((= nsep limit) t)
((= nsep osep) (zerop (random 2)))
((> nsep osep) t)
(t nil))
;; See if we can displace what is in this line so that we
;; can use the line.
(when (= line (the fixnum (1- (nlines)))) (setq wrappedp t))
(setq p (line-primary line))
(setq s (next-line line))
(push line lines)
(return nil)))
(when (= line (the fixnum (1- (nlines)))) (setq wrappedp t)))))
;; Do all the displacing.
(loop
(when (null (cdr lines)) (return nil))
(let ((dline (pop lines))
(line (car lines)))
(declare (fixnum dline line))
;;Copy from line to dline (dline is known to be free).
(let ((from-loc (line-location line))
(to-loc (line-location dline))
(cache-vector (vector)))
(declare (fixnum from-loc to-loc) (simple-vector cache-vector))
(modify-cache cache-vector
(dotimes (i (line-size))
(setf (cache-vector-ref cache-vector (+ to-loc i))
(cache-vector-ref cache-vector (+ from-loc i)))
(setf (cache-vector-ref cache-vector (+ from-loc i))
nil))))))
(values (car lines) t))))
(defun default-limit-fn (nlines)
(case nlines
((1 2 4) 1)
((8 16) 4)
(otherwise 6)))
(defvar *empty-cache* (make-cache)) ; for defstruct slot initial value forms
;;;
;;; pre-allocate generic function caches. The hope is that this will put
;;; them nicely together in memory, and that that may be a win. Of course
;;; the first gc copy will probably blow that out, this really wants to be
;;; wrapped in something that declares the area static.
;;;
;;; This preallocation only creates about 25% more caches than PCL itself
;;; uses. Some ports may want to preallocate some more of these.
;;;
(eval-when (load)
(dolist (n-size '((1 513)(3 257)(3 129)(14 128)(6 65)(2 64)(7 33)(16 32)
(16 17)(32 16)(64 9)(64 8)(6 5)(128 4)(35 2)))
(let ((n (car n-size))
(size (cadr n-size)))
(mapcar #'free-cache-vector
(mapcar #'get-cache-vector
(make-list n :initial-element size))))))
(defun caches-to-allocate ()
(sort (let ((l nil))
(maphash #'(lambda (size entry)
(push (list (car entry) size) l))
pcl::*free-caches*)
l)
#'> :key #'cadr))
|
50409
|
;;;-*-Mode:LISP; Package:(PCL LISP 1000); Base:10; Syntax:Common-lisp -*-
;;;
;;; *************************************************************************
;;; Copyright (c) 1985, 1986, 1987, 1988, 1989, 1990 Xerox Corporation.
;;; All rights reserved.
;;;
;;; Use and copying of this software and preparation of derivative works
;;; based upon this software are permitted. Any distribution of this
;;; software or derivative works must comply with all applicable United
;;; States export control laws.
;;;
;;; This software is made available AS IS, and Xerox Corporation makes no
;;; warranty about the software, its performance or its conformity to any
;;; specification.
;;;
;;; Any person obtaining a copy of this software is requested to send their
;;; name and post office or electronic mail address to:
;;; CommonLoops Coordinator
;;; <NAME>
;;; 3333 Coyote Hill Rd.
;;; Palo Alto, CA 94304
;;; (or send Arpanet mail to <EMAIL>)
;;;
;;; Suggestions, comments and requests for improvements are also welcome.
;;; *************************************************************************
;;;
;;; The basics of the PCL wrapper cache mechanism.
;;;
(in-package :pcl)
;;;
;;; The caching algorithm implemented:
;;;
;;; << put a paper here >>
;;;
;;; For now, understand that as far as most of this code goes, a cache has
;;; two important properties. The first is the number of wrappers used as
;;; keys in each cache line. Throughout this code, this value is always
;;; called NKEYS. The second is whether or not the cache lines of a cache
;;; store a value. Throughout this code, this always called VALUEP.
;;;
;;; Depending on these values, there are three kinds of caches.
;;;
;;; NKEYS = 1, VALUEP = NIL
;;;
;;; In this kind of cache, each line is 1 word long. No cache locking is
;;; needed since all read's in the cache are a single value. Nevertheless
;;; line 0 (location 0) is reserved, to ensure that invalid wrappers will
;;; not get a first probe hit.
;;;
;;; To keep the code simpler, a cache lock count does appear in location 0
;;; of these caches, that count is incremented whenever data is written to
;;; the cache. But, the actual lookup code (see make-dlap) doesn't need to
;;; do locking when reading the cache.
;;;
;;;
;;; NKEYS = 1, VALUEP = T
;;;
;;; In this kind of cache, each line is 2 words long. Cache locking must
;;; be done to ensure the synchronization of cache reads. Line 0 of the
;;; cache (location 0) is reserved for the cache lock count. Location 1
;;; of the cache is unused (in effect wasted).
;;;
;;; NKEYS > 1
;;;
;;; In this kind of cache, the 0 word of the cache holds the lock count.
;;; The 1 word of the cache is line 0. Line 0 of these caches is not
;;; reserved.
;;;
;;; This is done because in this sort of cache, the overhead of doing the
;;; cache probe is high enough that the 1+ required to offset the location
;;; is not a significant cost. In addition, because of the larger line
;;; sizes, the space that would be wasted by reserving line 0 to hold the
;;; lock count is more significant.
;;;
;;;
;;; Caches
;;;
;;; A cache is essentially just a vector. The use of the individual `words'
;;; in the vector depends on particular properties of the cache as described
;;; above.
;;;
;;; This defines an abstraction for caches in terms of their most obvious
;;; implementation as simple vectors. But, please notice that part of the
;;; implementation of this abstraction, is the function lap-out-cache-ref.
;;; This means that most port-specific modifications to the implementation
;;; of caches will require corresponding port-specific modifications to the
;;; lap code assembler.
;;;
(defmacro cache-vector-ref (cache-vector location)
`(svref (the simple-vector ,cache-vector)
(#-cmu the #+cmu ext:truly-the fixnum ,location)))
(defmacro cache-vector-size (cache-vector)
`(array-dimension (the simple-vector ,cache-vector) 0))
(defun allocate-cache-vector (size)
(make-array size :adjustable nil))
(defmacro cache-vector-lock-count (cache-vector)
`(cache-vector-ref ,cache-vector 0))
(defun flush-cache-vector-internal (cache-vector)
(without-interrupts
(fill (the simple-vector cache-vector) nil)
(setf (cache-vector-lock-count cache-vector) 0))
cache-vector)
(defmacro modify-cache (cache-vector &body body)
`(without-interrupts
(multiple-value-prog1
(progn ,@body)
(let ((old-count (cache-vector-lock-count ,cache-vector)))
(declare (fixnum old-count))
(setf (cache-vector-lock-count ,cache-vector)
(if (= old-count most-positive-fixnum)
1 (the fixnum (1+ old-count))))))))
(deftype field-type ()
'(integer 0 ;#.(position 'number wrapper-layout)
7)) ;#.(position 'number wrapper-layout :from-end t)
(eval-when (compile load eval)
(defun power-of-two-ceiling (x)
(declare (fixnum x))
;;(expt 2 (ceiling (log x 2)))
(the fixnum (ash 1 (integer-length (1- x)))))
(defconstant *nkeys-limit* 256)
)
(defstruct (cache
(:print-function print-cache)
(:constructor make-cache ())
(:copier copy-cache-internal))
(owner nil)
(nkeys 1 :type (integer 1 #.*nkeys-limit*))
(valuep nil :type (member nil t))
(nlines 0 :type fixnum)
(field 0 :type field-type)
(limit-fn #'default-limit-fn :type function)
(mask 0 :type fixnum)
(size 0 :type fixnum)
(line-size 1 :type (integer 1 #.(power-of-two-ceiling (1+ *nkeys-limit*))))
(max-location 0 :type fixnum)
(vector #() :type simple-vector)
(overflow nil :type list))
(defun print-cache (cache stream depth)
(declare (ignore depth))
(printing-random-thing (cache stream)
(format stream "cache ~D ~S ~D"
(cache-nkeys cache) (cache-valuep cache) (cache-nlines cache))))
#+akcl
(si::freeze-defstruct 'cache)
(defmacro cache-lock-count (cache)
`(cache-vector-lock-count (cache-vector ,cache)))
;;;
;;; Some facilities for allocation and freeing caches as they are needed.
;;; This is done on the assumption that a better port of PCL will arrange
;;; to cons these all the same static area. Given that, the fact that
;;; PCL tries to reuse them should be a win.
;;;
(defvar *free-cache-vectors* (make-hash-table :size 16 :test 'eql))
;;;
;;; Return a cache that has had flush-cache-vector-internal called on it. This
;;; returns a cache of exactly the size requested, it won't ever return a
;;; larger cache.
;;;
(defun get-cache-vector (size)
(let ((entry (gethash size *free-cache-vectors*)))
(without-interrupts
(cond ((null entry)
(setf (gethash size *free-cache-vectors*) (cons 0 nil))
(get-cache-vector size))
((null (cdr entry))
(incf (car entry))
(flush-cache-vector-internal (allocate-cache-vector size)))
(t
(let ((cache (cdr entry)))
(setf (cdr entry) (cache-vector-ref cache 0))
(flush-cache-vector-internal cache)))))))
(defun free-cache-vector (cache-vector)
(let ((entry (gethash (cache-vector-size cache-vector) *free-cache-vectors*)))
(without-interrupts
(if (null entry)
(error "Attempt to free a cache-vector not allocated by GET-CACHE-VECTOR.")
(let ((thread (cdr entry)))
(loop (unless thread (return))
(when (eq thread cache-vector) (error "Freeing a cache twice."))
(setq thread (cache-vector-ref thread 0)))
(flush-cache-vector-internal cache-vector) ;Help the GC
(setf (cache-vector-ref cache-vector 0) (cdr entry))
(setf (cdr entry) cache-vector)
nil)))))
;;;
;;; This is just for debugging and analysis. It shows the state of the free
;;; cache resource.
;;;
(defun show-free-cache-vectors ()
(let ((elements ()))
(maphash #'(lambda (s e) (push (list s e) elements)) *free-cache-vectors*)
(setq elements (sort elements #'< :key #'car))
(dolist (e elements)
(let* ((size (car e))
(entry (cadr e))
(allocated (car entry))
(head (cdr entry))
(free 0))
(loop (when (null head) (return t))
(setq head (cache-vector-ref head 0))
(incf free))
(format t
"~&There ~4D are caches of size ~4D. (~D free ~3D%)"
allocated
size
free
(floor (* 100 (/ free (float allocated)))))))))
;;;
;;; Wrapper cache numbers
;;;
;;;
;;; The constant WRAPPER-CACHE-NUMBER-ADDS-OK controls the number of non-zero
;;; bits wrapper cache numbers will have.
;;;
;;; The value of this constant is the number of wrapper cache numbers which
;;; can be added and still be certain the result will be a fixnum. This is
;;; used by all the code that computes primary cache locations from multiple
;;; wrappers.
;;;
;;; The value of this constant is used to derive the next two which are the
;;; forms of this constant which it is more convenient for the runtime code
;;; to use.
;;;
(eval-when (compile load eval)
(defconstant wrapper-cache-number-adds-ok 4)
(defconstant wrapper-cache-number-length
(- (integer-length most-positive-fixnum)
wrapper-cache-number-adds-ok))
(defconstant wrapper-cache-number-mask
(1- (expt 2 wrapper-cache-number-length)))
(defvar *get-wrapper-cache-number* (make-random-state))
(defun get-wrapper-cache-number ()
(let ((n 0))
(declare (fixnum n))
(loop
(setq n
(logand wrapper-cache-number-mask
(random most-positive-fixnum *get-wrapper-cache-number*)))
(unless (zerop n) (return n)))))
(unless (> wrapper-cache-number-length 8)
(error "In this implementation of Common Lisp, fixnums are so small that~@
wrapper cache numbers end up being only ~D bits long. This does~@
not actually keep PCL from running, but it may degrade cache~@
performance.~@
You may want to consider changing the value of the constant~@
WRAPPER-CACHE-NUMBER-ADDS-OK.")))
;;;
;;; wrappers themselves
;;;
;;; This caching algorithm requires that wrappers have more than one wrapper
;;; cache number. You should think of these multiple numbers as being in
;;; columns. That is, for a given cache, the same column of wrapper cache
;;; numbers will be used.
;;;
;;; If at some point the cache distribution of a cache gets bad, the cache
;;; can be rehashed by switching to a different column.
;;;
;;; The columns are referred to by field number which is that number which,
;;; when used as a second argument to wrapper-ref, will return that column
;;; of wrapper cache number.
;;;
;;; This code is written to allow flexibility as to how many wrapper cache
;;; numbers will be in each wrapper, and where they will be located. It is
;;; also set up to allow port specific modifications to `pack' the wrapper
;;; cache numbers on machines where the addressing modes make that a good
;;; idea.
;;;
#-structure-wrapper
(progn
(eval-when (compile load eval)
(defconstant wrapper-layout
'(number
number
number
number
number
number
number
number
state
instance-slots-layout
class-slots
class
no-of-instance-slots))
)
(eval-when (compile load eval)
(defun wrapper-field (type)
(posq type wrapper-layout))
(defun next-wrapper-field (field-number)
(position (nth field-number wrapper-layout)
wrapper-layout
:start (1+ field-number)))
(defmacro first-wrapper-cache-number-index ()
`(wrapper-field 'number))
(defmacro next-wrapper-cache-number-index (field-number)
`(next-wrapper-field ,field-number))
);eval-when
(defmacro wrapper-cache-number-vector (wrapper)
wrapper)
(defmacro cache-number-vector-ref (cnv n)
`(svref ,cnv ,n))
(defmacro wrapper-ref (wrapper n)
`(svref ,wrapper ,n))
(defmacro wrapper-state (wrapper)
`(wrapper-ref ,wrapper ,(wrapper-field 'state)))
(defmacro wrapper-instance-slots-layout (wrapper)
`(wrapper-ref ,wrapper ,(wrapper-field 'instance-slots-layout)))
(defmacro wrapper-class-slots (wrapper)
`(wrapper-ref ,wrapper ,(wrapper-field 'class-slots)))
(defmacro wrapper-class (wrapper)
`(wrapper-ref ,wrapper ,(wrapper-field 'class)))
(defmacro wrapper-no-of-instance-slots (wrapper)
`(wrapper-ref ,wrapper ,(wrapper-field 'no-of-instance-slots)))
(defmacro make-wrapper-internal ()
`(let ((wrapper (make-array ,(length wrapper-layout) :adjustable nil)))
,@(gathering1 (collecting)
(iterate ((i (interval :from 0))
(desc (list-elements wrapper-layout)))
(ecase desc
(number
(gather1 `(setf (wrapper-ref wrapper ,i)
(get-wrapper-cache-number))))
((state instance-slots-layout class-slots class no-of-instance-slots)))))
(setf (wrapper-state wrapper) 't)
wrapper))
(defun make-wrapper (no-of-instance-slots &optional class)
(let ((wrapper (make-wrapper-internal)))
(setf (wrapper-no-of-instance-slots wrapper) no-of-instance-slots)
(setf (wrapper-class wrapper) class)
wrapper))
)
; In CMUCL we want to do type checking as early as possible; structures help this.
#+structure-wrapper
(eval-when (compile load eval)
(defconstant wrapper-cache-number-vector-length 8)
(deftype cache-number-vector ()
`(simple-array fixnum (8)))
(defconstant wrapper-layout (make-list wrapper-cache-number-vector-length
:initial-element 'number))
)
#+structure-wrapper
(progn
#-new-kcl-wrapper
(defun make-wrapper-cache-number-vector ()
(let ((cnv (make-array #.wrapper-cache-number-vector-length
:element-type 'fixnum)))
(dotimes (i #.wrapper-cache-number-vector-length)
(setf (aref cnv i) (get-wrapper-cache-number)))
cnv))
(defstruct (wrapper
#+new-kcl-wrapper (:include si::basic-wrapper)
(:print-function print-wrapper)
#-new-kcl-wrapper
(:constructor make-wrapper (no-of-instance-slots &optional class))
#+new-kcl-wrapper
(:constructor make-wrapper-internal))
#-new-kcl-wrapper
(cache-number-vector (make-wrapper-cache-number-vector)
:type cache-number-vector)
#-new-kcl-wrapper
(state t :type (or (member t) cons))
;; either t or a list (state-sym new-wrapper)
;; where state-sym is either :flush or :obsolete
(instance-slots-layout nil :type list)
(class-slots nil :type list)
#-new-kcl-wrapper
(no-of-instance-slots 0 :type fixnum)
#-new-kcl-wrapper
(class *the-class-t* :type class))
(unless (boundp '*the-class-t*) (setq *the-class-t* nil))
#+new-kcl-wrapper
(defmacro wrapper-no-of-instance-slots (wrapper)
`(si::s-data-length ,wrapper))
#+new-kcl-wrapper
(defun make-wrapper (size &optional class)
(multiple-value-bind (raw slot-positions)
(if (< size 50)
(values si::*all-t-s-type* si::*standard-slot-positions*)
(values (make-array size :element-type 'unsigned-char)
(let ((array (make-array size :element-type 'unsigned-short)))
(dotimes (i size)
(declare (fixnum i))
(setf (aref array i) (* #.(si::size-of t) i))))))
(make-wrapper-internal :length size
:raw raw
:print-function 'print-std-instance
:slot-position slot-positions
:size (* size #.(si::size-of t))
:class class)))
(defun print-wrapper (wrapper stream depth)
(declare (ignore depth))
(printing-random-thing (wrapper stream)
(format stream "Wrapper ~S" (wrapper-class wrapper))))
(defmacro first-wrapper-cache-number-index ()
0)
(defmacro next-wrapper-cache-number-index (field-number)
`(and (< ,field-number #.(1- wrapper-cache-number-vector-length))
(1+ ,field-number)))
(defmacro cache-number-vector-ref (cnv n)
`(#-kcl svref #+kcl aref ,cnv ,n))
)
(defmacro wrapper-cache-number-vector-ref (wrapper n)
`(the fixnum
(#-structure-wrapper svref #+structure-wrapper aref
(wrapper-cache-number-vector ,wrapper) ,n)))
(defmacro class-no-of-instance-slots (class)
`(wrapper-no-of-instance-slots (class-wrapper ,class)))
(defmacro wrapper-class* (wrapper)
#-new-kcl-wrapper
`(wrapper-class ,wrapper)
#+new-kcl-wrapper
`(let ((wrapper ,wrapper))
(or (wrapper-class wrapper)
(find-structure-class (si::s-data-name wrapper)))))
;;;
;;; The wrapper cache machinery provides general mechanism for trapping on
;;; the next access to any instance of a given class. This mechanism is
;;; used to implement the updating of instances when the class is redefined
;;; (make-instances-obsolete). The same mechanism is also used to update
;;; generic function caches when there is a change to the supers of a class.
;;;
;;; Basically, a given wrapper can be valid or invalid. If it is invalid,
;;; it means that any attempt to do a wrapper cache lookup using the wrapper
;;; should trap. Also, methods on slot-value-using-class check the wrapper
;;; validity as well. This is done by calling check-wrapper-validity.
;;;
(defmacro invalid-wrapper-p (wrapper)
`(neq (wrapper-state ,wrapper) 't))
(defvar *previous-nwrappers* (make-hash-table))
(defun invalidate-wrapper (owrapper state nwrapper)
(ecase state
((:flush :obsolete)
(let ((new-previous ()))
;;
;; First off, a previous call to invalidate-wrapper may have recorded
;; owrapper as an nwrapper to update to. Since owrapper is about to
;; be invalid, it no longer makes sense to update to it.
;;
;; We go back and change the previously invalidated wrappers so that
;; they will now update directly to nwrapper. This corresponds to a
;; kind of transitivity of wrapper updates.
;;
(dolist (previous (gethash owrapper *previous-nwrappers*))
(when (eq state ':obsolete)
(setf (car previous) ':obsolete))
(setf (cadr previous) nwrapper)
(push previous new-previous))
(let ((ocnv (wrapper-cache-number-vector owrapper)))
(iterate ((type (list-elements wrapper-layout))
(i (interval :from 0)))
(when (eq type 'number) (setf (cache-number-vector-ref ocnv i) 0))))
(push (setf (wrapper-state owrapper) (list state nwrapper))
new-previous)
(setf (gethash owrapper *previous-nwrappers*) ()
(gethash nwrapper *previous-nwrappers*) new-previous)))))
(defun check-wrapper-validity (instance)
(let* ((owrapper (wrapper-of instance))
(state (wrapper-state owrapper)))
(if (eq state 't)
owrapper
(let ((nwrapper
(ecase (car state)
(:flush
(flush-cache-trap owrapper (cadr state) instance))
(:obsolete
(obsolete-instance-trap owrapper (cadr state) instance)))))
;;
;; This little bit of error checking is superfluous. It only
;; checks to see whether the person who implemented the trap
;; handling screwed up. Since that person is hacking internal
;; PCL code, and is not a user, this should be needless. Also,
;; since this directly slows down instance update and generic
;; function cache refilling, feel free to take it out sometime
;; soon.
;;
(cond ((neq nwrapper (wrapper-of instance))
(error "Wrapper returned from trap not wrapper of instance."))
((invalid-wrapper-p nwrapper)
(error "Wrapper returned from trap invalid.")))
nwrapper))))
(defmacro check-wrapper-validity1 (object)
(let ((owrapper (gensym)))
`(let ((,owrapper (cond ((std-instance-p ,object)
(std-instance-wrapper ,object))
((fsc-instance-p ,object)
(fsc-instance-wrapper ,object))
#+new-kcl-wrapper
(t (built-in-wrapper-of ,object))
#-new-kcl-wrapper
(t (wrapper-of ,object)))))
(if (eq 't (wrapper-state ,owrapper))
,owrapper
(check-wrapper-validity ,object)))))
(defvar *free-caches* nil)
(defun get-cache (nkeys valuep limit-fn nlines)
(let ((cache (or (without-interrupts (pop *free-caches*)) (make-cache))))
(declare (type cache cache))
(multiple-value-bind (cache-mask actual-size line-size nlines)
(compute-cache-parameters nkeys valuep nlines)
(setf (cache-nkeys cache) nkeys
(cache-valuep cache) valuep
(cache-nlines cache) nlines
(cache-field cache) (first-wrapper-cache-number-index)
(cache-limit-fn cache) limit-fn
(cache-mask cache) cache-mask
(cache-size cache) actual-size
(cache-line-size cache) line-size
(cache-max-location cache) (let ((line (1- nlines)))
(if (= nkeys 1)
(* line line-size)
(1+ (* line line-size))))
(cache-vector cache) (get-cache-vector actual-size)
(cache-overflow cache) nil)
cache)))
(defun get-cache-from-cache (old-cache new-nlines
&optional (new-field (first-wrapper-cache-number-index)))
(let ((nkeys (cache-nkeys old-cache))
(valuep (cache-valuep old-cache))
(cache (or (without-interrupts (pop *free-caches*)) (make-cache))))
(declare (type cache cache))
(multiple-value-bind (cache-mask actual-size line-size nlines)
(if (= new-nlines (cache-nlines old-cache))
(values (cache-mask old-cache) (cache-size old-cache)
(cache-line-size old-cache) (cache-nlines old-cache))
(compute-cache-parameters nkeys valuep new-nlines))
(setf (cache-owner cache) (cache-owner old-cache)
(cache-nkeys cache) nkeys
(cache-valuep cache) valuep
(cache-nlines cache) nlines
(cache-field cache) new-field
(cache-limit-fn cache) (cache-limit-fn old-cache)
(cache-mask cache) cache-mask
(cache-size cache) actual-size
(cache-line-size cache) line-size
(cache-max-location cache) (let ((line (1- nlines)))
(if (= nkeys 1)
(* line line-size)
(1+ (* line line-size))))
(cache-vector cache) (get-cache-vector actual-size)
(cache-overflow cache) nil)
cache)))
(defun copy-cache (old-cache)
(let* ((new-cache (copy-cache-internal old-cache))
(size (cache-size old-cache))
(old-vector (cache-vector old-cache))
(new-vector (get-cache-vector size)))
(declare (simple-vector old-vector new-vector))
(dotimes (i size)
(setf (svref new-vector i) (svref old-vector i)))
(setf (cache-vector new-cache) new-vector)
new-cache))
(defun free-cache (cache)
(free-cache-vector (cache-vector cache))
(setf (cache-vector cache) #())
(setf (cache-owner cache) nil)
(push cache *free-caches*)
nil)
(defun compute-line-size (x)
(power-of-two-ceiling x))
(defun compute-cache-parameters (nkeys valuep nlines-or-cache-vector)
;;(declare (values cache-mask actual-size line-size nlines))
(declare (fixnum nkeys))
(if (= nkeys 1)
(let* ((line-size (if valuep 2 1))
(cache-size (if (typep nlines-or-cache-vector 'fixnum)
(the fixnum
(* line-size
(the fixnum
(power-of-two-ceiling
nlines-or-cache-vector))))
(cache-vector-size nlines-or-cache-vector))))
(declare (fixnum line-size cache-size))
(values (logxor (the fixnum (1- cache-size)) (the fixnum (1- line-size)))
cache-size
line-size
(the fixnum (floor cache-size line-size))))
(let* ((line-size (power-of-two-ceiling (if valuep (1+ nkeys) nkeys)))
(cache-size (if (typep nlines-or-cache-vector 'fixnum)
(the fixnum
(* line-size
(the fixnum
(power-of-two-ceiling
nlines-or-cache-vector))))
(1- (cache-vector-size nlines-or-cache-vector)))))
(declare (fixnum line-size cache-size))
(values (logxor (the fixnum (1- cache-size)) (the fixnum (1- line-size)))
(the fixnum (1+ cache-size))
line-size
(the fixnum (floor cache-size line-size))))))
;;;
;;; The various implementations of computing a primary cache location from
;;; wrappers. Because some implementations of this must run fast there are
;;; several implementations of the same algorithm.
;;;
;;; The algorithm is:
;;;
;;; SUM over the wrapper cache numbers,
;;; ENSURING that the result is a fixnum
;;; MASK the result against the mask argument.
;;;
;;;
;;;
;;; COMPUTE-PRIMARY-CACHE-LOCATION
;;;
;;; The basic functional version. This is used by the cache miss code to
;;; compute the primary location of an entry.
;;;
(defun compute-primary-cache-location (field mask wrappers)
(declare (type field-type field) (fixnum mask))
(if (not (listp wrappers))
(logand mask (the fixnum (wrapper-cache-number-vector-ref wrappers field)))
(let ((location 0) (i 0))
(declare (fixnum location i))
(dolist (wrapper wrappers)
;;
;; First add the cache number of this wrapper to location.
;;
(let ((wrapper-cache-number (wrapper-cache-number-vector-ref wrapper field)))
(declare (fixnum wrapper-cache-number))
(if (zerop wrapper-cache-number)
(return-from compute-primary-cache-location 0)
(setq location (the fixnum (+ location wrapper-cache-number)))))
;;
;; Then, if we are working with lots of wrappers, deal with
;; the wrapper-cache-number-mask stuff.
;;
(when (and (not (zerop i))
(zerop (mod i wrapper-cache-number-adds-ok)))
(setq location
(logand location wrapper-cache-number-mask)))
(incf i))
(the fixnum (1+ (logand mask location))))))
;;;
;;; COMPUTE-PRIMARY-CACHE-LOCATION-FROM-LOCATION
;;;
;;; This version is called on a cache line. It fetches the wrappers from
;;; the cache line and determines the primary location. Various parts of
;;; the cache filling code call this to determine whether it is appropriate
;;; to displace a given cache entry.
;;;
;;; If this comes across a wrapper whose cache-no is 0, it returns the symbol
;;; invalid to suggest to its caller that it would be provident to blow away
;;; the cache line in question.
;;;
(defun compute-primary-cache-location-from-location (to-cache from-location
&optional (from-cache to-cache))
(declare (type cache to-cache from-cache) (fixnum from-location))
(let ((result 0)
(cache-vector (cache-vector from-cache))
(field (cache-field to-cache))
(mask (cache-mask to-cache))
(nkeys (cache-nkeys to-cache)))
(declare (type field-type field) (fixnum result mask nkeys)
(simple-vector cache-vector))
(dotimes (i nkeys)
(let* ((wrapper (cache-vector-ref cache-vector (+ i from-location)))
(wcn (wrapper-cache-number-vector-ref wrapper field)))
(declare (fixnum wcn))
(setq result (+ result wcn)))
(when (and (not (zerop i))
(zerop (mod i wrapper-cache-number-adds-ok)))
(setq result (logand result wrapper-cache-number-mask))))
(if (= nkeys 1)
(logand mask result)
(the fixnum (1+ (logand mask result))))))
;;;
;;; NIL means nothing so far, no actual arg info has NILs
;;; in the metatype
;;; CLASS seen all sorts of metaclasses
;;; (specifically, more than one of the next 4 values)
;;; T means everything so far is the class T
;;; STANDARD-CLASS seen only standard classes
;;; BUILT-IN-CLASS seen only built in classes
;;; STRUCTURE-CLASS seen only structure classes
;;;
(defun raise-metatype (metatype new-specializer)
(let ((slot (find-class 'slot-class))
(standard (find-class 'standard-class))
(fsc (find-class 'funcallable-standard-class))
(structure (find-class 'structure-class))
(built-in (find-class 'built-in-class)))
(flet ((specializer->metatype (x)
(let ((meta-specializer
(if (eq *boot-state* 'complete)
(class-of (specializer-class x))
(class-of x))))
(cond ((eq x *the-class-t*) t)
((*subtypep meta-specializer standard) 'standard-instance)
((*subtypep meta-specializer fsc) 'standard-instance)
((*subtypep meta-specializer structure) 'structure-instance)
((*subtypep meta-specializer built-in) 'built-in-instance)
((*subtypep meta-specializer slot) 'slot-instance)
(t (error "PCL can not handle the specializer ~S (meta-specializer ~S)."
new-specializer meta-specializer))))))
;;
;; We implement the following table. The notation is
;; that X and Y are distinct meta specializer names.
;;
;; NIL <anything> ===> <anything>
;; X X ===> X
;; X Y ===> CLASS
;;
(let ((new-metatype (specializer->metatype new-specializer)))
(cond ((eq new-metatype 'slot-instance) 'class)
((null metatype) new-metatype)
((eq metatype new-metatype) new-metatype)
(t 'class))))))
(defmacro with-dfun-wrappers ((args metatypes)
(dfun-wrappers invalid-wrapper-p
&optional wrappers classes types)
invalid-arguments-form
&body body)
`(let* ((args-tail ,args) (,invalid-wrapper-p nil) (invalid-arguments-p nil)
(,dfun-wrappers nil) (dfun-wrappers-tail nil)
,@(when wrappers
`((wrappers-rev nil) (types-rev nil) (classes-rev nil))))
(dolist (mt ,metatypes)
(unless args-tail
(setq invalid-arguments-p t)
(return nil))
(let* ((arg (pop args-tail))
(wrapper nil)
,@(when wrappers
`((class *the-class-t*)
(type 't))))
(unless (eq mt 't)
(setq wrapper (wrapper-of arg))
(when (invalid-wrapper-p wrapper)
(setq ,invalid-wrapper-p t)
(setq wrapper (check-wrapper-validity arg)))
(cond ((null ,dfun-wrappers)
(setq ,dfun-wrappers wrapper))
((not (consp ,dfun-wrappers))
(setq dfun-wrappers-tail (list wrapper))
(setq ,dfun-wrappers (cons ,dfun-wrappers dfun-wrappers-tail)))
(t
(let ((new-dfun-wrappers-tail (list wrapper)))
(setf (cdr dfun-wrappers-tail) new-dfun-wrappers-tail)
(setf dfun-wrappers-tail new-dfun-wrappers-tail))))
,@(when wrappers
`((setq class (wrapper-class* wrapper))
(setq type `(class-eq ,class)))))
,@(when wrappers
`((push wrapper wrappers-rev)
(push class classes-rev)
(push type types-rev)))))
(if invalid-arguments-p
,invalid-arguments-form
(let* (,@(when wrappers
`((,wrappers (nreverse wrappers-rev))
(,classes (nreverse classes-rev))
(,types (mapcar #'(lambda (class)
`(class-eq ,class))
,classes)))))
,@body))))
;;;
;;; Some support stuff for getting a hold of symbols that we need when
;;; building the discriminator codes. Its ok for these to be interned
;;; symbols because we don't capture any user code in the scope in which
;;; these symbols are bound.
;;;
(defvar *dfun-arg-symbols* '(.ARG0. .ARG1. .ARG2. .ARG3.))
(defun dfun-arg-symbol (arg-number)
(or (nth arg-number (the list *dfun-arg-symbols*))
(intern (format nil ".ARG~A." arg-number) *the-pcl-package*)))
(defvar *slot-vector-symbols* '(.SLOTS0. .SLOTS1. .SLOTS2. .SLOTS3.))
(defun slot-vector-symbol (arg-number)
(or (nth arg-number (the list *slot-vector-symbols*))
(intern (format nil ".SLOTS~A." arg-number) *the-pcl-package*)))
(defun make-dfun-lambda-list (metatypes applyp)
(gathering1 (collecting)
(iterate ((i (interval :from 0))
(s (list-elements metatypes)))
(progn s)
(gather1 (dfun-arg-symbol i)))
(when applyp
(gather1 '&rest)
(gather1 '.dfun-rest-arg.))))
(defun make-dlap-lambda-list (metatypes applyp)
(gathering1 (collecting)
(iterate ((i (interval :from 0))
(s (list-elements metatypes)))
(progn s)
(gather1 (dfun-arg-symbol i)))
(when applyp
(gather1 '&rest))))
(defun make-emf-call (metatypes applyp fn-variable &optional emf-type)
(let ((required
(gathering1 (collecting)
(iterate ((i (interval :from 0))
(s (list-elements metatypes)))
(progn s)
(gather1 (dfun-arg-symbol i))))))
`(,(if (eq emf-type 'fast-method-call)
'invoke-effective-method-function-fast
'invoke-effective-method-function)
,fn-variable ,applyp ,@required ,@(when applyp `(.dfun-rest-arg.)))))
(defun make-dfun-call (metatypes applyp fn-variable)
(let ((required
(gathering1 (collecting)
(iterate ((i (interval :from 0))
(s (list-elements metatypes)))
(progn s)
(gather1 (dfun-arg-symbol i))))))
(if applyp
`(function-apply ,fn-variable ,@required .dfun-rest-arg.)
`(function-funcall ,fn-variable ,@required))))
(defun make-dfun-arg-list (metatypes applyp)
(let ((required
(gathering1 (collecting)
(iterate ((i (interval :from 0))
(s (list-elements metatypes)))
(progn s)
(gather1 (dfun-arg-symbol i))))))
(if applyp
`(list* ,@required .dfun-rest-arg.)
`(list ,@required))))
(defun make-fast-method-call-lambda-list (metatypes applyp)
(gathering1 (collecting)
(gather1 '.pv-cell.)
(gather1 '.next-method-call.)
(iterate ((i (interval :from 0))
(s (list-elements metatypes)))
(progn s)
(gather1 (dfun-arg-symbol i)))
(when applyp
(gather1 '.dfun-rest-arg.))))
;;;
;;; Its too bad Common Lisp compilers freak out when you have a defun with
;;; a lot of LABELS in it. If I could do that I could make this code much
;;; easier to read and work with.
;;;
;;; Ahh Scheme...
;;;
;;; In the absence of that, the following little macro makes the code that
;;; follows a little bit more reasonable. I would like to add that having
;;; to practically write my own compiler in order to get just this simple
;;; thing is something of a drag.
;;;
(eval-when (compile load eval)
(defvar *cache* nil)
(defconstant *local-cache-functions*
'((cache () .cache.)
(nkeys () (cache-nkeys .cache.))
(line-size () (cache-line-size .cache.))
(vector () (cache-vector .cache.))
(valuep () (cache-valuep .cache.))
(nlines () (cache-nlines .cache.))
(max-location () (cache-max-location .cache.))
(limit-fn () (cache-limit-fn .cache.))
(size () (cache-size .cache.))
(mask () (cache-mask .cache.))
(field () (cache-field .cache.))
(overflow () (cache-overflow .cache.))
;;
;; Return T IFF this cache location is reserved. The only time
;; this is true is for line number 0 of an nkeys=1 cache.
;;
(line-reserved-p (line)
(declare (fixnum line))
(and (= (nkeys) 1)
(= line 0)))
;;
(location-reserved-p (location)
(declare (fixnum location))
(and (= (nkeys) 1)
(= location 0)))
;;
;; Given a line number, return the cache location. This is the
;; value that is the second argument to cache-vector-ref. Basically,
;; this deals with the offset of nkeys>1 caches and multiplies
;; by line size.
;;
(line-location (line)
(declare (fixnum line))
(when (line-reserved-p line)
(error "line is reserved"))
(if (= (nkeys) 1)
(the fixnum (* line (line-size)))
(the fixnum (1+ (the fixnum (* line (line-size)))))))
;;
;; Given a cache location, return the line. This is the inverse
;; of LINE-LOCATION.
;;
(location-line (location)
(declare (fixnum location))
(if (= (nkeys) 1)
(floor location (line-size))
(floor (the fixnum (1- location)) (line-size))))
;;
;; Given a line number, return the wrappers stored at that line.
;; As usual, if nkeys=1, this returns a single value. Only when
;; nkeys>1 does it return a list. An error is signalled if the
;; line is reserved.
;;
(line-wrappers (line)
(declare (fixnum line))
(when (line-reserved-p line) (error "Line is reserved."))
(location-wrappers (line-location line)))
;;
(location-wrappers (location) ; avoid multiplies caused by line-location
(declare (fixnum location))
(if (= (nkeys) 1)
(cache-vector-ref (vector) location)
(let ((list (make-list (nkeys)))
(vector (vector)))
(declare (simple-vector vector))
(dotimes (i (nkeys) list)
(setf (nth i list) (cache-vector-ref vector (+ location i)))))))
;;
;; Given a line number, return true IFF the line's
;; wrappers are the same as wrappers.
;;
(line-matches-wrappers-p (line wrappers)
(declare (fixnum line))
(and (not (line-reserved-p line))
(location-matches-wrappers-p (line-location line) wrappers)))
;;
(location-matches-wrappers-p (loc wrappers) ; must not be reserved
(declare (fixnum loc))
(let ((cache-vector (vector)))
(declare (simple-vector cache-vector))
(if (= (nkeys) 1)
(eq wrappers (cache-vector-ref cache-vector loc))
(dotimes (i (nkeys) t)
(unless (eq (pop wrappers) (cache-vector-ref cache-vector (+ loc i)))
(return nil))))))
;;
;; Given a line number, return the value stored at that line.
;; If valuep is NIL, this returns NIL. As with line-wrappers,
;; an error is signalled if the line is reserved.
;;
(line-value (line)
(declare (fixnum line))
(when (line-reserved-p line) (error "Line is reserved."))
(location-value (line-location line)))
;;
(location-value (loc)
(declare (fixnum loc))
(and (valuep)
(cache-vector-ref (vector) (+ loc (nkeys)))))
;;
;; Given a line number, return true IFF that line has data in
;; it. The state of the wrappers stored in the line is not
;; checked. An error is signalled if line is reserved.
(line-full-p (line)
(when (line-reserved-p line) (error "Line is reserved."))
(not (null (cache-vector-ref (vector) (line-location line)))))
;;
;; Given a line number, return true IFF the line is full and
;; there are no invalid wrappers in the line, and the line's
;; wrappers are different from wrappers.
;; An error is signalled if the line is reserved.
;;
(line-valid-p (line wrappers)
(declare (fixnum line))
(when (line-reserved-p line) (error "Line is reserved."))
(location-valid-p (line-location line) wrappers))
;;
(location-valid-p (loc wrappers)
(declare (fixnum loc))
(let ((cache-vector (vector))
(wrappers-mismatch-p (null wrappers)))
(declare (simple-vector cache-vector))
(dotimes (i (nkeys) wrappers-mismatch-p)
(let ((wrapper (cache-vector-ref cache-vector (+ loc i))))
(when (or (null wrapper)
(invalid-wrapper-p wrapper))
(return nil))
(unless (and wrappers
(eq wrapper
(if (consp wrappers) (pop wrappers) wrappers)))
(setq wrappers-mismatch-p t))))))
;;
;; How many unreserved lines separate line-1 and line-2.
;;
(line-separation (line-1 line-2)
(declare (fixnum line-1 line-2))
(let ((diff (the fixnum (- line-2 line-1))))
(declare (fixnum diff))
(when (minusp diff)
(setq diff (+ diff (nlines)))
(when (line-reserved-p 0)
(setq diff (1- diff))))
diff))
;;
;; Given a cache line, get the next cache line. This will not
;; return a reserved line.
;;
(next-line (line)
(declare (fixnum line))
(if (= line (the fixnum (1- (nlines))))
(if (line-reserved-p 0) 1 0)
(the fixnum (1+ line))))
;;
(next-location (loc)
(declare (fixnum loc))
(if (= loc (max-location))
(if (= (nkeys) 1)
(line-size)
1)
(the fixnum (+ loc (line-size)))))
;;
;; Given a line which has a valid entry in it, this will return
;; the primary cache line of the wrappers in that line. We just
;; call COMPUTE-PRIMARY-CACHE-LOCATION-FROM-LOCATION, this is an
;; easier packaging up of the call to it.
;;
(line-primary (line)
(declare (fixnum line))
(location-line (line-primary-location line)))
;;
(line-primary-location (line)
(declare (fixnum line))
(compute-primary-cache-location-from-location
(cache) (line-location line)))
))
(defmacro with-local-cache-functions ((cache) &body body)
`(let ((.cache. ,cache))
(declare (type cache .cache.))
(macrolet ,(mapcar #'(lambda (fn)
`(,(car fn) ,(cadr fn)
`(let (,,@(mapcar #'(lambda (var)
``(,',var ,,var))
(cadr fn)))
,@',(cddr fn))))
*local-cache-functions*)
,@body)))
)
;;;
;;; Here is where we actually fill, recache and expand caches.
;;;
;;; The functions FILL-CACHE and PROBE-CACHE are the ONLY external
;;; entrypoints into this code.
;;;
;;; FILL-CACHE returns 1 value: a new cache
;;;
;;; a wrapper field number
;;; a cache
;;; a mask
;;; an absolute cache size (the size of the actual vector)
;;; It tries to re-adjust the cache every time it makes a new fill. The
;;; intuition here is that we want uniformity in the number of probes needed to
;;; find an entry. Furthermore, adjusting has the nice property of throwing out
;;; any entries that are invalid.
;;;
(defvar *cache-expand-threshold* 1.25)
(defun fill-cache (cache wrappers value &optional free-cache-p)
;;(declare (values cache))
(unless wrappers ; fill-cache won't return if wrappers is nil, might as well check.
(error "fill-cache: wrappers arg is NIL!"))
(or (fill-cache-p nil cache wrappers value)
(and (< (ceiling (* (cache-count cache) 1.25))
(if (= (cache-nkeys cache) 1)
(1- (cache-nlines cache))
(cache-nlines cache)))
(adjust-cache cache wrappers value free-cache-p))
(expand-cache cache wrappers value free-cache-p)))
(defvar *check-cache-p* nil)
(defmacro maybe-check-cache (cache)
`(progn
(when *check-cache-p*
(check-cache ,cache))
,cache))
(defun check-cache (cache)
(with-local-cache-functions (cache)
(let ((location (if (= (nkeys) 1) 0 1))
(limit (funcall (limit-fn) (nlines))))
(dotimes (i (nlines) cache)
(when (and (not (location-reserved-p location))
(line-full-p i))
(let* ((home-loc (compute-primary-cache-location-from-location
cache location))
(home (location-line (if (location-reserved-p home-loc)
(next-location home-loc)
home-loc)))
(sep (when home (line-separation home i))))
(when (and sep (> sep limit))
(error "bad cache ~S ~@
value at location ~D is ~D lines from its home. limit is ~D."
cache location sep limit))))
(setq location (next-location location))))))
(defun probe-cache (cache wrappers &optional default limit-fn)
;;(declare (values value))
(unless wrappers (error "probe-cache: wrappers arg is NIL!"))
(with-local-cache-functions (cache)
(let* ((location (compute-primary-cache-location (field) (mask) wrappers))
(limit (funcall (or limit-fn (limit-fn)) (nlines))))
(declare (fixnum location limit))
(when (location-reserved-p location)
(setq location (next-location location)))
(dotimes (i (1+ limit))
(when (location-matches-wrappers-p location wrappers)
(return-from probe-cache (or (not (valuep))
(location-value location))))
(setq location (next-location location)))
(dolist (entry (overflow))
(when (equal (car entry) wrappers)
(return-from probe-cache (or (not (valuep))
(cdr entry)))))
default)))
(defun map-cache (function cache &optional set-p)
(with-local-cache-functions (cache)
(let ((set-p (and set-p (valuep))))
(dotimes (i (nlines) cache)
(unless (or (line-reserved-p i) (not (line-valid-p i nil)))
(let ((value (funcall function (line-wrappers i) (line-value i))))
(when set-p
(setf (cache-vector-ref (vector) (+ (line-location i) (nkeys)))
value)))))
(dolist (entry (overflow))
(let ((value (funcall function (car entry) (cdr entry))))
(when set-p
(setf (cdr entry) value))))))
cache)
(defun cache-count (cache)
(with-local-cache-functions (cache)
(let ((count 0))
(declare (fixnum count))
(dotimes (i (nlines) count)
(unless (line-reserved-p i)
(when (line-full-p i)
(incf count)))))))
(defun entry-in-cache-p (cache wrappers value)
(declare (ignore value))
(with-local-cache-functions (cache)
(dotimes (i (nlines))
(unless (line-reserved-p i)
(when (equal (line-wrappers i) wrappers)
(return t))))))
;;;
;;; returns T or NIL
;;;
(defun fill-cache-p (forcep cache wrappers value)
(with-local-cache-functions (cache)
(let* ((location (compute-primary-cache-location (field) (mask) wrappers))
(primary (location-line location)))
(declare (fixnum location primary))
(multiple-value-bind (free emptyp)
(find-free-cache-line primary cache wrappers)
(when (or forcep emptyp)
(when (not emptyp)
(push (cons (line-wrappers free) (line-value free))
(cache-overflow cache)))
;;(fill-line free wrappers value)
(let ((line free))
(declare (fixnum line))
(when (line-reserved-p line)
(error "Attempt to fill a reserved line."))
(let ((loc (line-location line))
(cache-vector (vector)))
(declare (fixnum loc) (simple-vector cache-vector))
(cond ((= (nkeys) 1)
(setf (cache-vector-ref cache-vector loc) wrappers)
(when (valuep)
(setf (cache-vector-ref cache-vector (1+ loc)) value)))
(t
(let ((i 0))
(declare (fixnum i))
(dolist (w wrappers)
(setf (cache-vector-ref cache-vector (+ loc i)) w)
(setq i (the fixnum (1+ i)))))
(when (valuep)
(setf (cache-vector-ref cache-vector (+ loc (nkeys)))
value))))
(maybe-check-cache cache))))))))
(defun fill-cache-from-cache-p (forcep cache from-cache from-line)
(declare (fixnum from-line))
(with-local-cache-functions (cache)
(let ((primary (location-line (compute-primary-cache-location-from-location
cache (line-location from-line) from-cache))))
(declare (fixnum primary))
(multiple-value-bind (free emptyp)
(find-free-cache-line primary cache)
(when (or forcep emptyp)
(when (not emptyp)
(push (cons (line-wrappers free) (line-value free))
(cache-overflow cache)))
;;(transfer-line from-cache-vector from-line cache-vector free)
(let ((from-cache-vector (cache-vector from-cache))
(to-cache-vector (vector))
(to-line free))
(declare (fixnum to-line))
(if (line-reserved-p to-line)
(error "transfering something into a reserved cache line.")
(let ((from-loc (line-location from-line))
(to-loc (line-location to-line)))
(declare (fixnum from-loc to-loc))
(modify-cache to-cache-vector
(dotimes (i (line-size))
(setf (cache-vector-ref to-cache-vector
(+ to-loc i))
(cache-vector-ref from-cache-vector
(+ from-loc i)))))))
(maybe-check-cache cache)))))))
;;;
;;; Returns NIL or (values <field> <cache-vector>)
;;;
;;; This is only called when it isn't possible to put the entry in the cache
;;; the easy way. That is, this function assumes that FILL-CACHE-P has been
;;; called as returned NIL.
;;;
;;; If this returns NIL, it means that it wasn't possible to find a wrapper
;;; field for which all of the entries could be put in the cache (within the
;;; limit).
;;;
(defun adjust-cache (cache wrappers value free-old-cache-p)
(with-local-cache-functions (cache)
(let ((ncache (get-cache-from-cache cache (nlines) (field))))
(do ((nfield (cache-field ncache) (next-wrapper-cache-number-index nfield)))
((null nfield) (free-cache ncache) nil)
(setf (cache-field ncache) nfield)
(labels ((try-one-fill-from-line (line)
(fill-cache-from-cache-p nil ncache cache line))
(try-one-fill (wrappers value)
(fill-cache-p nil ncache wrappers value)))
(if (and (dotimes (i (nlines) t)
(when (and (null (line-reserved-p i))
(line-valid-p i wrappers))
(unless (try-one-fill-from-line i) (return nil))))
(dolist (wrappers+value (cache-overflow cache) t)
(unless (try-one-fill (car wrappers+value) (cdr wrappers+value))
(return nil)))
(try-one-fill wrappers value))
(progn (when free-old-cache-p (free-cache cache))
(return (maybe-check-cache ncache)))
(flush-cache-vector-internal (cache-vector ncache))))))))
;;;
;;; returns: (values <cache>)
;;;
(defun expand-cache (cache wrappers value free-old-cache-p)
;;(declare (values cache))
(with-local-cache-functions (cache)
(let ((ncache (get-cache-from-cache cache (* (nlines) 2))))
(labels ((do-one-fill-from-line (line)
(unless (fill-cache-from-cache-p nil ncache cache line)
(do-one-fill (line-wrappers line) (line-value line))))
(do-one-fill (wrappers value)
(setq ncache (or (adjust-cache ncache wrappers value t)
(fill-cache-p t ncache wrappers value))))
(try-one-fill (wrappers value)
(fill-cache-p nil ncache wrappers value)))
(dotimes (i (nlines))
(when (and (null (line-reserved-p i))
(line-valid-p i wrappers))
(do-one-fill-from-line i)))
(dolist (wrappers+value (cache-overflow cache))
(unless (try-one-fill (car wrappers+value) (cdr wrappers+value))
(do-one-fill (car wrappers+value) (cdr wrappers+value))))
(unless (try-one-fill wrappers value)
(do-one-fill wrappers value))
(when free-old-cache-p (free-cache cache))
(maybe-check-cache ncache)))))
;;;
;;; This is the heart of the cache filling mechanism. It implements the decisions
;;; about where entries are placed.
;;;
;;; Find a line in the cache at which a new entry can be inserted.
;;;
;;; <line>
;;; <empty?> is <line> in fact empty?
;;;
(defun find-free-cache-line (primary cache &optional wrappers)
;;(declare (values line empty?))
(declare (fixnum primary))
(with-local-cache-functions (cache)
(when (line-reserved-p primary) (setq primary (next-line primary)))
(let ((limit (funcall (limit-fn) (nlines)))
(wrappedp nil)
(lines nil)
(p primary) (s primary))
(declare (fixnum p s limit))
(block find-free
(loop
;; Try to find a free line starting at <s>. <p> is the
;; primary line of the entry we are finding a free
;; line for, it is used to compute the seperations.
(do* ((line s (next-line line))
(nsep (line-separation p s) (1+ nsep)))
(())
(declare (fixnum line nsep))
(when (null (line-valid-p line wrappers)) ;If this line is empty or
(push line lines) ;invalid, just use it.
(return-from find-free))
(when (and wrappedp (>= line primary))
;; have gone all the way around the cache, time to quit
(return-from find-free-cache-line (values primary nil)))
(let ((osep (line-separation (line-primary line) line)))
(when (>= osep limit)
(return-from find-free-cache-line (values primary nil)))
(when (cond ((= nsep limit) t)
((= nsep osep) (zerop (random 2)))
((> nsep osep) t)
(t nil))
;; See if we can displace what is in this line so that we
;; can use the line.
(when (= line (the fixnum (1- (nlines)))) (setq wrappedp t))
(setq p (line-primary line))
(setq s (next-line line))
(push line lines)
(return nil)))
(when (= line (the fixnum (1- (nlines)))) (setq wrappedp t)))))
;; Do all the displacing.
(loop
(when (null (cdr lines)) (return nil))
(let ((dline (pop lines))
(line (car lines)))
(declare (fixnum dline line))
;;Copy from line to dline (dline is known to be free).
(let ((from-loc (line-location line))
(to-loc (line-location dline))
(cache-vector (vector)))
(declare (fixnum from-loc to-loc) (simple-vector cache-vector))
(modify-cache cache-vector
(dotimes (i (line-size))
(setf (cache-vector-ref cache-vector (+ to-loc i))
(cache-vector-ref cache-vector (+ from-loc i)))
(setf (cache-vector-ref cache-vector (+ from-loc i))
nil))))))
(values (car lines) t))))
(defun default-limit-fn (nlines)
(case nlines
((1 2 4) 1)
((8 16) 4)
(otherwise 6)))
(defvar *empty-cache* (make-cache)) ; for defstruct slot initial value forms
;;;
;;; pre-allocate generic function caches. The hope is that this will put
;;; them nicely together in memory, and that that may be a win. Of course
;;; the first gc copy will probably blow that out, this really wants to be
;;; wrapped in something that declares the area static.
;;;
;;; This preallocation only creates about 25% more caches than PCL itself
;;; uses. Some ports may want to preallocate some more of these.
;;;
(eval-when (load)
(dolist (n-size '((1 513)(3 257)(3 129)(14 128)(6 65)(2 64)(7 33)(16 32)
(16 17)(32 16)(64 9)(64 8)(6 5)(128 4)(35 2)))
(let ((n (car n-size))
(size (cadr n-size)))
(mapcar #'free-cache-vector
(mapcar #'get-cache-vector
(make-list n :initial-element size))))))
(defun caches-to-allocate ()
(sort (let ((l nil))
(maphash #'(lambda (size entry)
(push (list (car entry) size) l))
pcl::*free-caches*)
l)
#'> :key #'cadr))
| true |
;;;-*-Mode:LISP; Package:(PCL LISP 1000); Base:10; Syntax:Common-lisp -*-
;;;
;;; *************************************************************************
;;; Copyright (c) 1985, 1986, 1987, 1988, 1989, 1990 Xerox Corporation.
;;; All rights reserved.
;;;
;;; Use and copying of this software and preparation of derivative works
;;; based upon this software are permitted. Any distribution of this
;;; software or derivative works must comply with all applicable United
;;; States export control laws.
;;;
;;; This software is made available AS IS, and Xerox Corporation makes no
;;; warranty about the software, its performance or its conformity to any
;;; specification.
;;;
;;; Any person obtaining a copy of this software is requested to send their
;;; name and post office or electronic mail address to:
;;; CommonLoops Coordinator
;;; PI:NAME:<NAME>END_PI
;;; 3333 Coyote Hill Rd.
;;; Palo Alto, CA 94304
;;; (or send Arpanet mail to PI:EMAIL:<EMAIL>END_PI)
;;;
;;; Suggestions, comments and requests for improvements are also welcome.
;;; *************************************************************************
;;;
;;; The basics of the PCL wrapper cache mechanism.
;;;
(in-package :pcl)
;;;
;;; The caching algorithm implemented:
;;;
;;; << put a paper here >>
;;;
;;; For now, understand that as far as most of this code goes, a cache has
;;; two important properties. The first is the number of wrappers used as
;;; keys in each cache line. Throughout this code, this value is always
;;; called NKEYS. The second is whether or not the cache lines of a cache
;;; store a value. Throughout this code, this always called VALUEP.
;;;
;;; Depending on these values, there are three kinds of caches.
;;;
;;; NKEYS = 1, VALUEP = NIL
;;;
;;; In this kind of cache, each line is 1 word long. No cache locking is
;;; needed since all read's in the cache are a single value. Nevertheless
;;; line 0 (location 0) is reserved, to ensure that invalid wrappers will
;;; not get a first probe hit.
;;;
;;; To keep the code simpler, a cache lock count does appear in location 0
;;; of these caches, that count is incremented whenever data is written to
;;; the cache. But, the actual lookup code (see make-dlap) doesn't need to
;;; do locking when reading the cache.
;;;
;;;
;;; NKEYS = 1, VALUEP = T
;;;
;;; In this kind of cache, each line is 2 words long. Cache locking must
;;; be done to ensure the synchronization of cache reads. Line 0 of the
;;; cache (location 0) is reserved for the cache lock count. Location 1
;;; of the cache is unused (in effect wasted).
;;;
;;; NKEYS > 1
;;;
;;; In this kind of cache, the 0 word of the cache holds the lock count.
;;; The 1 word of the cache is line 0. Line 0 of these caches is not
;;; reserved.
;;;
;;; This is done because in this sort of cache, the overhead of doing the
;;; cache probe is high enough that the 1+ required to offset the location
;;; is not a significant cost. In addition, because of the larger line
;;; sizes, the space that would be wasted by reserving line 0 to hold the
;;; lock count is more significant.
;;;
;;;
;;; Caches
;;;
;;; A cache is essentially just a vector. The use of the individual `words'
;;; in the vector depends on particular properties of the cache as described
;;; above.
;;;
;;; This defines an abstraction for caches in terms of their most obvious
;;; implementation as simple vectors. But, please notice that part of the
;;; implementation of this abstraction, is the function lap-out-cache-ref.
;;; This means that most port-specific modifications to the implementation
;;; of caches will require corresponding port-specific modifications to the
;;; lap code assembler.
;;;
(defmacro cache-vector-ref (cache-vector location)
`(svref (the simple-vector ,cache-vector)
(#-cmu the #+cmu ext:truly-the fixnum ,location)))
(defmacro cache-vector-size (cache-vector)
`(array-dimension (the simple-vector ,cache-vector) 0))
(defun allocate-cache-vector (size)
(make-array size :adjustable nil))
(defmacro cache-vector-lock-count (cache-vector)
`(cache-vector-ref ,cache-vector 0))
(defun flush-cache-vector-internal (cache-vector)
(without-interrupts
(fill (the simple-vector cache-vector) nil)
(setf (cache-vector-lock-count cache-vector) 0))
cache-vector)
(defmacro modify-cache (cache-vector &body body)
`(without-interrupts
(multiple-value-prog1
(progn ,@body)
(let ((old-count (cache-vector-lock-count ,cache-vector)))
(declare (fixnum old-count))
(setf (cache-vector-lock-count ,cache-vector)
(if (= old-count most-positive-fixnum)
1 (the fixnum (1+ old-count))))))))
(deftype field-type ()
'(integer 0 ;#.(position 'number wrapper-layout)
7)) ;#.(position 'number wrapper-layout :from-end t)
(eval-when (compile load eval)
(defun power-of-two-ceiling (x)
(declare (fixnum x))
;;(expt 2 (ceiling (log x 2)))
(the fixnum (ash 1 (integer-length (1- x)))))
(defconstant *nkeys-limit* 256)
)
(defstruct (cache
(:print-function print-cache)
(:constructor make-cache ())
(:copier copy-cache-internal))
(owner nil)
(nkeys 1 :type (integer 1 #.*nkeys-limit*))
(valuep nil :type (member nil t))
(nlines 0 :type fixnum)
(field 0 :type field-type)
(limit-fn #'default-limit-fn :type function)
(mask 0 :type fixnum)
(size 0 :type fixnum)
(line-size 1 :type (integer 1 #.(power-of-two-ceiling (1+ *nkeys-limit*))))
(max-location 0 :type fixnum)
(vector #() :type simple-vector)
(overflow nil :type list))
(defun print-cache (cache stream depth)
(declare (ignore depth))
(printing-random-thing (cache stream)
(format stream "cache ~D ~S ~D"
(cache-nkeys cache) (cache-valuep cache) (cache-nlines cache))))
#+akcl
(si::freeze-defstruct 'cache)
(defmacro cache-lock-count (cache)
`(cache-vector-lock-count (cache-vector ,cache)))
;;;
;;; Some facilities for allocation and freeing caches as they are needed.
;;; This is done on the assumption that a better port of PCL will arrange
;;; to cons these all the same static area. Given that, the fact that
;;; PCL tries to reuse them should be a win.
;;;
(defvar *free-cache-vectors* (make-hash-table :size 16 :test 'eql))
;;;
;;; Return a cache that has had flush-cache-vector-internal called on it. This
;;; returns a cache of exactly the size requested, it won't ever return a
;;; larger cache.
;;;
(defun get-cache-vector (size)
(let ((entry (gethash size *free-cache-vectors*)))
(without-interrupts
(cond ((null entry)
(setf (gethash size *free-cache-vectors*) (cons 0 nil))
(get-cache-vector size))
((null (cdr entry))
(incf (car entry))
(flush-cache-vector-internal (allocate-cache-vector size)))
(t
(let ((cache (cdr entry)))
(setf (cdr entry) (cache-vector-ref cache 0))
(flush-cache-vector-internal cache)))))))
(defun free-cache-vector (cache-vector)
(let ((entry (gethash (cache-vector-size cache-vector) *free-cache-vectors*)))
(without-interrupts
(if (null entry)
(error "Attempt to free a cache-vector not allocated by GET-CACHE-VECTOR.")
(let ((thread (cdr entry)))
(loop (unless thread (return))
(when (eq thread cache-vector) (error "Freeing a cache twice."))
(setq thread (cache-vector-ref thread 0)))
(flush-cache-vector-internal cache-vector) ;Help the GC
(setf (cache-vector-ref cache-vector 0) (cdr entry))
(setf (cdr entry) cache-vector)
nil)))))
;;;
;;; This is just for debugging and analysis. It shows the state of the free
;;; cache resource.
;;;
(defun show-free-cache-vectors ()
(let ((elements ()))
(maphash #'(lambda (s e) (push (list s e) elements)) *free-cache-vectors*)
(setq elements (sort elements #'< :key #'car))
(dolist (e elements)
(let* ((size (car e))
(entry (cadr e))
(allocated (car entry))
(head (cdr entry))
(free 0))
(loop (when (null head) (return t))
(setq head (cache-vector-ref head 0))
(incf free))
(format t
"~&There ~4D are caches of size ~4D. (~D free ~3D%)"
allocated
size
free
(floor (* 100 (/ free (float allocated)))))))))
;;;
;;; Wrapper cache numbers
;;;
;;;
;;; The constant WRAPPER-CACHE-NUMBER-ADDS-OK controls the number of non-zero
;;; bits wrapper cache numbers will have.
;;;
;;; The value of this constant is the number of wrapper cache numbers which
;;; can be added and still be certain the result will be a fixnum. This is
;;; used by all the code that computes primary cache locations from multiple
;;; wrappers.
;;;
;;; The value of this constant is used to derive the next two which are the
;;; forms of this constant which it is more convenient for the runtime code
;;; to use.
;;;
(eval-when (compile load eval)
(defconstant wrapper-cache-number-adds-ok 4)
(defconstant wrapper-cache-number-length
(- (integer-length most-positive-fixnum)
wrapper-cache-number-adds-ok))
(defconstant wrapper-cache-number-mask
(1- (expt 2 wrapper-cache-number-length)))
(defvar *get-wrapper-cache-number* (make-random-state))
(defun get-wrapper-cache-number ()
(let ((n 0))
(declare (fixnum n))
(loop
(setq n
(logand wrapper-cache-number-mask
(random most-positive-fixnum *get-wrapper-cache-number*)))
(unless (zerop n) (return n)))))
(unless (> wrapper-cache-number-length 8)
(error "In this implementation of Common Lisp, fixnums are so small that~@
wrapper cache numbers end up being only ~D bits long. This does~@
not actually keep PCL from running, but it may degrade cache~@
performance.~@
You may want to consider changing the value of the constant~@
WRAPPER-CACHE-NUMBER-ADDS-OK.")))
;;;
;;; wrappers themselves
;;;
;;; This caching algorithm requires that wrappers have more than one wrapper
;;; cache number. You should think of these multiple numbers as being in
;;; columns. That is, for a given cache, the same column of wrapper cache
;;; numbers will be used.
;;;
;;; If at some point the cache distribution of a cache gets bad, the cache
;;; can be rehashed by switching to a different column.
;;;
;;; The columns are referred to by field number which is that number which,
;;; when used as a second argument to wrapper-ref, will return that column
;;; of wrapper cache number.
;;;
;;; This code is written to allow flexibility as to how many wrapper cache
;;; numbers will be in each wrapper, and where they will be located. It is
;;; also set up to allow port specific modifications to `pack' the wrapper
;;; cache numbers on machines where the addressing modes make that a good
;;; idea.
;;;
#-structure-wrapper
(progn
(eval-when (compile load eval)
(defconstant wrapper-layout
'(number
number
number
number
number
number
number
number
state
instance-slots-layout
class-slots
class
no-of-instance-slots))
)
(eval-when (compile load eval)
(defun wrapper-field (type)
(posq type wrapper-layout))
(defun next-wrapper-field (field-number)
(position (nth field-number wrapper-layout)
wrapper-layout
:start (1+ field-number)))
(defmacro first-wrapper-cache-number-index ()
`(wrapper-field 'number))
(defmacro next-wrapper-cache-number-index (field-number)
`(next-wrapper-field ,field-number))
);eval-when
(defmacro wrapper-cache-number-vector (wrapper)
wrapper)
(defmacro cache-number-vector-ref (cnv n)
`(svref ,cnv ,n))
(defmacro wrapper-ref (wrapper n)
`(svref ,wrapper ,n))
(defmacro wrapper-state (wrapper)
`(wrapper-ref ,wrapper ,(wrapper-field 'state)))
(defmacro wrapper-instance-slots-layout (wrapper)
`(wrapper-ref ,wrapper ,(wrapper-field 'instance-slots-layout)))
(defmacro wrapper-class-slots (wrapper)
`(wrapper-ref ,wrapper ,(wrapper-field 'class-slots)))
(defmacro wrapper-class (wrapper)
`(wrapper-ref ,wrapper ,(wrapper-field 'class)))
(defmacro wrapper-no-of-instance-slots (wrapper)
`(wrapper-ref ,wrapper ,(wrapper-field 'no-of-instance-slots)))
(defmacro make-wrapper-internal ()
`(let ((wrapper (make-array ,(length wrapper-layout) :adjustable nil)))
,@(gathering1 (collecting)
(iterate ((i (interval :from 0))
(desc (list-elements wrapper-layout)))
(ecase desc
(number
(gather1 `(setf (wrapper-ref wrapper ,i)
(get-wrapper-cache-number))))
((state instance-slots-layout class-slots class no-of-instance-slots)))))
(setf (wrapper-state wrapper) 't)
wrapper))
(defun make-wrapper (no-of-instance-slots &optional class)
(let ((wrapper (make-wrapper-internal)))
(setf (wrapper-no-of-instance-slots wrapper) no-of-instance-slots)
(setf (wrapper-class wrapper) class)
wrapper))
)
; In CMUCL we want to do type checking as early as possible; structures help this.
#+structure-wrapper
(eval-when (compile load eval)
(defconstant wrapper-cache-number-vector-length 8)
(deftype cache-number-vector ()
`(simple-array fixnum (8)))
(defconstant wrapper-layout (make-list wrapper-cache-number-vector-length
:initial-element 'number))
)
#+structure-wrapper
(progn
#-new-kcl-wrapper
(defun make-wrapper-cache-number-vector ()
(let ((cnv (make-array #.wrapper-cache-number-vector-length
:element-type 'fixnum)))
(dotimes (i #.wrapper-cache-number-vector-length)
(setf (aref cnv i) (get-wrapper-cache-number)))
cnv))
(defstruct (wrapper
#+new-kcl-wrapper (:include si::basic-wrapper)
(:print-function print-wrapper)
#-new-kcl-wrapper
(:constructor make-wrapper (no-of-instance-slots &optional class))
#+new-kcl-wrapper
(:constructor make-wrapper-internal))
#-new-kcl-wrapper
(cache-number-vector (make-wrapper-cache-number-vector)
:type cache-number-vector)
#-new-kcl-wrapper
(state t :type (or (member t) cons))
;; either t or a list (state-sym new-wrapper)
;; where state-sym is either :flush or :obsolete
(instance-slots-layout nil :type list)
(class-slots nil :type list)
#-new-kcl-wrapper
(no-of-instance-slots 0 :type fixnum)
#-new-kcl-wrapper
(class *the-class-t* :type class))
(unless (boundp '*the-class-t*) (setq *the-class-t* nil))
#+new-kcl-wrapper
(defmacro wrapper-no-of-instance-slots (wrapper)
`(si::s-data-length ,wrapper))
#+new-kcl-wrapper
(defun make-wrapper (size &optional class)
(multiple-value-bind (raw slot-positions)
(if (< size 50)
(values si::*all-t-s-type* si::*standard-slot-positions*)
(values (make-array size :element-type 'unsigned-char)
(let ((array (make-array size :element-type 'unsigned-short)))
(dotimes (i size)
(declare (fixnum i))
(setf (aref array i) (* #.(si::size-of t) i))))))
(make-wrapper-internal :length size
:raw raw
:print-function 'print-std-instance
:slot-position slot-positions
:size (* size #.(si::size-of t))
:class class)))
(defun print-wrapper (wrapper stream depth)
(declare (ignore depth))
(printing-random-thing (wrapper stream)
(format stream "Wrapper ~S" (wrapper-class wrapper))))
(defmacro first-wrapper-cache-number-index ()
0)
(defmacro next-wrapper-cache-number-index (field-number)
`(and (< ,field-number #.(1- wrapper-cache-number-vector-length))
(1+ ,field-number)))
(defmacro cache-number-vector-ref (cnv n)
`(#-kcl svref #+kcl aref ,cnv ,n))
)
(defmacro wrapper-cache-number-vector-ref (wrapper n)
`(the fixnum
(#-structure-wrapper svref #+structure-wrapper aref
(wrapper-cache-number-vector ,wrapper) ,n)))
(defmacro class-no-of-instance-slots (class)
`(wrapper-no-of-instance-slots (class-wrapper ,class)))
(defmacro wrapper-class* (wrapper)
#-new-kcl-wrapper
`(wrapper-class ,wrapper)
#+new-kcl-wrapper
`(let ((wrapper ,wrapper))
(or (wrapper-class wrapper)
(find-structure-class (si::s-data-name wrapper)))))
;;;
;;; The wrapper cache machinery provides general mechanism for trapping on
;;; the next access to any instance of a given class. This mechanism is
;;; used to implement the updating of instances when the class is redefined
;;; (make-instances-obsolete). The same mechanism is also used to update
;;; generic function caches when there is a change to the supers of a class.
;;;
;;; Basically, a given wrapper can be valid or invalid. If it is invalid,
;;; it means that any attempt to do a wrapper cache lookup using the wrapper
;;; should trap. Also, methods on slot-value-using-class check the wrapper
;;; validity as well. This is done by calling check-wrapper-validity.
;;;
(defmacro invalid-wrapper-p (wrapper)
`(neq (wrapper-state ,wrapper) 't))
(defvar *previous-nwrappers* (make-hash-table))
(defun invalidate-wrapper (owrapper state nwrapper)
(ecase state
((:flush :obsolete)
(let ((new-previous ()))
;;
;; First off, a previous call to invalidate-wrapper may have recorded
;; owrapper as an nwrapper to update to. Since owrapper is about to
;; be invalid, it no longer makes sense to update to it.
;;
;; We go back and change the previously invalidated wrappers so that
;; they will now update directly to nwrapper. This corresponds to a
;; kind of transitivity of wrapper updates.
;;
(dolist (previous (gethash owrapper *previous-nwrappers*))
(when (eq state ':obsolete)
(setf (car previous) ':obsolete))
(setf (cadr previous) nwrapper)
(push previous new-previous))
(let ((ocnv (wrapper-cache-number-vector owrapper)))
(iterate ((type (list-elements wrapper-layout))
(i (interval :from 0)))
(when (eq type 'number) (setf (cache-number-vector-ref ocnv i) 0))))
(push (setf (wrapper-state owrapper) (list state nwrapper))
new-previous)
(setf (gethash owrapper *previous-nwrappers*) ()
(gethash nwrapper *previous-nwrappers*) new-previous)))))
(defun check-wrapper-validity (instance)
(let* ((owrapper (wrapper-of instance))
(state (wrapper-state owrapper)))
(if (eq state 't)
owrapper
(let ((nwrapper
(ecase (car state)
(:flush
(flush-cache-trap owrapper (cadr state) instance))
(:obsolete
(obsolete-instance-trap owrapper (cadr state) instance)))))
;;
;; This little bit of error checking is superfluous. It only
;; checks to see whether the person who implemented the trap
;; handling screwed up. Since that person is hacking internal
;; PCL code, and is not a user, this should be needless. Also,
;; since this directly slows down instance update and generic
;; function cache refilling, feel free to take it out sometime
;; soon.
;;
(cond ((neq nwrapper (wrapper-of instance))
(error "Wrapper returned from trap not wrapper of instance."))
((invalid-wrapper-p nwrapper)
(error "Wrapper returned from trap invalid.")))
nwrapper))))
(defmacro check-wrapper-validity1 (object)
(let ((owrapper (gensym)))
`(let ((,owrapper (cond ((std-instance-p ,object)
(std-instance-wrapper ,object))
((fsc-instance-p ,object)
(fsc-instance-wrapper ,object))
#+new-kcl-wrapper
(t (built-in-wrapper-of ,object))
#-new-kcl-wrapper
(t (wrapper-of ,object)))))
(if (eq 't (wrapper-state ,owrapper))
,owrapper
(check-wrapper-validity ,object)))))
(defvar *free-caches* nil)
(defun get-cache (nkeys valuep limit-fn nlines)
(let ((cache (or (without-interrupts (pop *free-caches*)) (make-cache))))
(declare (type cache cache))
(multiple-value-bind (cache-mask actual-size line-size nlines)
(compute-cache-parameters nkeys valuep nlines)
(setf (cache-nkeys cache) nkeys
(cache-valuep cache) valuep
(cache-nlines cache) nlines
(cache-field cache) (first-wrapper-cache-number-index)
(cache-limit-fn cache) limit-fn
(cache-mask cache) cache-mask
(cache-size cache) actual-size
(cache-line-size cache) line-size
(cache-max-location cache) (let ((line (1- nlines)))
(if (= nkeys 1)
(* line line-size)
(1+ (* line line-size))))
(cache-vector cache) (get-cache-vector actual-size)
(cache-overflow cache) nil)
cache)))
(defun get-cache-from-cache (old-cache new-nlines
&optional (new-field (first-wrapper-cache-number-index)))
(let ((nkeys (cache-nkeys old-cache))
(valuep (cache-valuep old-cache))
(cache (or (without-interrupts (pop *free-caches*)) (make-cache))))
(declare (type cache cache))
(multiple-value-bind (cache-mask actual-size line-size nlines)
(if (= new-nlines (cache-nlines old-cache))
(values (cache-mask old-cache) (cache-size old-cache)
(cache-line-size old-cache) (cache-nlines old-cache))
(compute-cache-parameters nkeys valuep new-nlines))
(setf (cache-owner cache) (cache-owner old-cache)
(cache-nkeys cache) nkeys
(cache-valuep cache) valuep
(cache-nlines cache) nlines
(cache-field cache) new-field
(cache-limit-fn cache) (cache-limit-fn old-cache)
(cache-mask cache) cache-mask
(cache-size cache) actual-size
(cache-line-size cache) line-size
(cache-max-location cache) (let ((line (1- nlines)))
(if (= nkeys 1)
(* line line-size)
(1+ (* line line-size))))
(cache-vector cache) (get-cache-vector actual-size)
(cache-overflow cache) nil)
cache)))
(defun copy-cache (old-cache)
(let* ((new-cache (copy-cache-internal old-cache))
(size (cache-size old-cache))
(old-vector (cache-vector old-cache))
(new-vector (get-cache-vector size)))
(declare (simple-vector old-vector new-vector))
(dotimes (i size)
(setf (svref new-vector i) (svref old-vector i)))
(setf (cache-vector new-cache) new-vector)
new-cache))
(defun free-cache (cache)
(free-cache-vector (cache-vector cache))
(setf (cache-vector cache) #())
(setf (cache-owner cache) nil)
(push cache *free-caches*)
nil)
(defun compute-line-size (x)
(power-of-two-ceiling x))
(defun compute-cache-parameters (nkeys valuep nlines-or-cache-vector)
;;(declare (values cache-mask actual-size line-size nlines))
(declare (fixnum nkeys))
(if (= nkeys 1)
(let* ((line-size (if valuep 2 1))
(cache-size (if (typep nlines-or-cache-vector 'fixnum)
(the fixnum
(* line-size
(the fixnum
(power-of-two-ceiling
nlines-or-cache-vector))))
(cache-vector-size nlines-or-cache-vector))))
(declare (fixnum line-size cache-size))
(values (logxor (the fixnum (1- cache-size)) (the fixnum (1- line-size)))
cache-size
line-size
(the fixnum (floor cache-size line-size))))
(let* ((line-size (power-of-two-ceiling (if valuep (1+ nkeys) nkeys)))
(cache-size (if (typep nlines-or-cache-vector 'fixnum)
(the fixnum
(* line-size
(the fixnum
(power-of-two-ceiling
nlines-or-cache-vector))))
(1- (cache-vector-size nlines-or-cache-vector)))))
(declare (fixnum line-size cache-size))
(values (logxor (the fixnum (1- cache-size)) (the fixnum (1- line-size)))
(the fixnum (1+ cache-size))
line-size
(the fixnum (floor cache-size line-size))))))
;;;
;;; The various implementations of computing a primary cache location from
;;; wrappers. Because some implementations of this must run fast there are
;;; several implementations of the same algorithm.
;;;
;;; The algorithm is:
;;;
;;; SUM over the wrapper cache numbers,
;;; ENSURING that the result is a fixnum
;;; MASK the result against the mask argument.
;;;
;;;
;;;
;;; COMPUTE-PRIMARY-CACHE-LOCATION
;;;
;;; The basic functional version. This is used by the cache miss code to
;;; compute the primary location of an entry.
;;;
(defun compute-primary-cache-location (field mask wrappers)
(declare (type field-type field) (fixnum mask))
(if (not (listp wrappers))
(logand mask (the fixnum (wrapper-cache-number-vector-ref wrappers field)))
(let ((location 0) (i 0))
(declare (fixnum location i))
(dolist (wrapper wrappers)
;;
;; First add the cache number of this wrapper to location.
;;
(let ((wrapper-cache-number (wrapper-cache-number-vector-ref wrapper field)))
(declare (fixnum wrapper-cache-number))
(if (zerop wrapper-cache-number)
(return-from compute-primary-cache-location 0)
(setq location (the fixnum (+ location wrapper-cache-number)))))
;;
;; Then, if we are working with lots of wrappers, deal with
;; the wrapper-cache-number-mask stuff.
;;
(when (and (not (zerop i))
(zerop (mod i wrapper-cache-number-adds-ok)))
(setq location
(logand location wrapper-cache-number-mask)))
(incf i))
(the fixnum (1+ (logand mask location))))))
;;;
;;; COMPUTE-PRIMARY-CACHE-LOCATION-FROM-LOCATION
;;;
;;; This version is called on a cache line. It fetches the wrappers from
;;; the cache line and determines the primary location. Various parts of
;;; the cache filling code call this to determine whether it is appropriate
;;; to displace a given cache entry.
;;;
;;; If this comes across a wrapper whose cache-no is 0, it returns the symbol
;;; invalid to suggest to its caller that it would be provident to blow away
;;; the cache line in question.
;;;
(defun compute-primary-cache-location-from-location (to-cache from-location
&optional (from-cache to-cache))
(declare (type cache to-cache from-cache) (fixnum from-location))
(let ((result 0)
(cache-vector (cache-vector from-cache))
(field (cache-field to-cache))
(mask (cache-mask to-cache))
(nkeys (cache-nkeys to-cache)))
(declare (type field-type field) (fixnum result mask nkeys)
(simple-vector cache-vector))
(dotimes (i nkeys)
(let* ((wrapper (cache-vector-ref cache-vector (+ i from-location)))
(wcn (wrapper-cache-number-vector-ref wrapper field)))
(declare (fixnum wcn))
(setq result (+ result wcn)))
(when (and (not (zerop i))
(zerop (mod i wrapper-cache-number-adds-ok)))
(setq result (logand result wrapper-cache-number-mask))))
(if (= nkeys 1)
(logand mask result)
(the fixnum (1+ (logand mask result))))))
;;;
;;; NIL means nothing so far, no actual arg info has NILs
;;; in the metatype
;;; CLASS seen all sorts of metaclasses
;;; (specifically, more than one of the next 4 values)
;;; T means everything so far is the class T
;;; STANDARD-CLASS seen only standard classes
;;; BUILT-IN-CLASS seen only built in classes
;;; STRUCTURE-CLASS seen only structure classes
;;;
(defun raise-metatype (metatype new-specializer)
(let ((slot (find-class 'slot-class))
(standard (find-class 'standard-class))
(fsc (find-class 'funcallable-standard-class))
(structure (find-class 'structure-class))
(built-in (find-class 'built-in-class)))
(flet ((specializer->metatype (x)
(let ((meta-specializer
(if (eq *boot-state* 'complete)
(class-of (specializer-class x))
(class-of x))))
(cond ((eq x *the-class-t*) t)
((*subtypep meta-specializer standard) 'standard-instance)
((*subtypep meta-specializer fsc) 'standard-instance)
((*subtypep meta-specializer structure) 'structure-instance)
((*subtypep meta-specializer built-in) 'built-in-instance)
((*subtypep meta-specializer slot) 'slot-instance)
(t (error "PCL can not handle the specializer ~S (meta-specializer ~S)."
new-specializer meta-specializer))))))
;;
;; We implement the following table. The notation is
;; that X and Y are distinct meta specializer names.
;;
;; NIL <anything> ===> <anything>
;; X X ===> X
;; X Y ===> CLASS
;;
(let ((new-metatype (specializer->metatype new-specializer)))
(cond ((eq new-metatype 'slot-instance) 'class)
((null metatype) new-metatype)
((eq metatype new-metatype) new-metatype)
(t 'class))))))
(defmacro with-dfun-wrappers ((args metatypes)
(dfun-wrappers invalid-wrapper-p
&optional wrappers classes types)
invalid-arguments-form
&body body)
`(let* ((args-tail ,args) (,invalid-wrapper-p nil) (invalid-arguments-p nil)
(,dfun-wrappers nil) (dfun-wrappers-tail nil)
,@(when wrappers
`((wrappers-rev nil) (types-rev nil) (classes-rev nil))))
(dolist (mt ,metatypes)
(unless args-tail
(setq invalid-arguments-p t)
(return nil))
(let* ((arg (pop args-tail))
(wrapper nil)
,@(when wrappers
`((class *the-class-t*)
(type 't))))
(unless (eq mt 't)
(setq wrapper (wrapper-of arg))
(when (invalid-wrapper-p wrapper)
(setq ,invalid-wrapper-p t)
(setq wrapper (check-wrapper-validity arg)))
(cond ((null ,dfun-wrappers)
(setq ,dfun-wrappers wrapper))
((not (consp ,dfun-wrappers))
(setq dfun-wrappers-tail (list wrapper))
(setq ,dfun-wrappers (cons ,dfun-wrappers dfun-wrappers-tail)))
(t
(let ((new-dfun-wrappers-tail (list wrapper)))
(setf (cdr dfun-wrappers-tail) new-dfun-wrappers-tail)
(setf dfun-wrappers-tail new-dfun-wrappers-tail))))
,@(when wrappers
`((setq class (wrapper-class* wrapper))
(setq type `(class-eq ,class)))))
,@(when wrappers
`((push wrapper wrappers-rev)
(push class classes-rev)
(push type types-rev)))))
(if invalid-arguments-p
,invalid-arguments-form
(let* (,@(when wrappers
`((,wrappers (nreverse wrappers-rev))
(,classes (nreverse classes-rev))
(,types (mapcar #'(lambda (class)
`(class-eq ,class))
,classes)))))
,@body))))
;;;
;;; Some support stuff for getting a hold of symbols that we need when
;;; building the discriminator codes. Its ok for these to be interned
;;; symbols because we don't capture any user code in the scope in which
;;; these symbols are bound.
;;;
(defvar *dfun-arg-symbols* '(.ARG0. .ARG1. .ARG2. .ARG3.))
(defun dfun-arg-symbol (arg-number)
(or (nth arg-number (the list *dfun-arg-symbols*))
(intern (format nil ".ARG~A." arg-number) *the-pcl-package*)))
(defvar *slot-vector-symbols* '(.SLOTS0. .SLOTS1. .SLOTS2. .SLOTS3.))
(defun slot-vector-symbol (arg-number)
(or (nth arg-number (the list *slot-vector-symbols*))
(intern (format nil ".SLOTS~A." arg-number) *the-pcl-package*)))
(defun make-dfun-lambda-list (metatypes applyp)
(gathering1 (collecting)
(iterate ((i (interval :from 0))
(s (list-elements metatypes)))
(progn s)
(gather1 (dfun-arg-symbol i)))
(when applyp
(gather1 '&rest)
(gather1 '.dfun-rest-arg.))))
(defun make-dlap-lambda-list (metatypes applyp)
(gathering1 (collecting)
(iterate ((i (interval :from 0))
(s (list-elements metatypes)))
(progn s)
(gather1 (dfun-arg-symbol i)))
(when applyp
(gather1 '&rest))))
(defun make-emf-call (metatypes applyp fn-variable &optional emf-type)
(let ((required
(gathering1 (collecting)
(iterate ((i (interval :from 0))
(s (list-elements metatypes)))
(progn s)
(gather1 (dfun-arg-symbol i))))))
`(,(if (eq emf-type 'fast-method-call)
'invoke-effective-method-function-fast
'invoke-effective-method-function)
,fn-variable ,applyp ,@required ,@(when applyp `(.dfun-rest-arg.)))))
(defun make-dfun-call (metatypes applyp fn-variable)
(let ((required
(gathering1 (collecting)
(iterate ((i (interval :from 0))
(s (list-elements metatypes)))
(progn s)
(gather1 (dfun-arg-symbol i))))))
(if applyp
`(function-apply ,fn-variable ,@required .dfun-rest-arg.)
`(function-funcall ,fn-variable ,@required))))
(defun make-dfun-arg-list (metatypes applyp)
(let ((required
(gathering1 (collecting)
(iterate ((i (interval :from 0))
(s (list-elements metatypes)))
(progn s)
(gather1 (dfun-arg-symbol i))))))
(if applyp
`(list* ,@required .dfun-rest-arg.)
`(list ,@required))))
(defun make-fast-method-call-lambda-list (metatypes applyp)
(gathering1 (collecting)
(gather1 '.pv-cell.)
(gather1 '.next-method-call.)
(iterate ((i (interval :from 0))
(s (list-elements metatypes)))
(progn s)
(gather1 (dfun-arg-symbol i)))
(when applyp
(gather1 '.dfun-rest-arg.))))
;;;
;;; Its too bad Common Lisp compilers freak out when you have a defun with
;;; a lot of LABELS in it. If I could do that I could make this code much
;;; easier to read and work with.
;;;
;;; Ahh Scheme...
;;;
;;; In the absence of that, the following little macro makes the code that
;;; follows a little bit more reasonable. I would like to add that having
;;; to practically write my own compiler in order to get just this simple
;;; thing is something of a drag.
;;;
(eval-when (compile load eval)
(defvar *cache* nil)
(defconstant *local-cache-functions*
'((cache () .cache.)
(nkeys () (cache-nkeys .cache.))
(line-size () (cache-line-size .cache.))
(vector () (cache-vector .cache.))
(valuep () (cache-valuep .cache.))
(nlines () (cache-nlines .cache.))
(max-location () (cache-max-location .cache.))
(limit-fn () (cache-limit-fn .cache.))
(size () (cache-size .cache.))
(mask () (cache-mask .cache.))
(field () (cache-field .cache.))
(overflow () (cache-overflow .cache.))
;;
;; Return T IFF this cache location is reserved. The only time
;; this is true is for line number 0 of an nkeys=1 cache.
;;
(line-reserved-p (line)
(declare (fixnum line))
(and (= (nkeys) 1)
(= line 0)))
;;
(location-reserved-p (location)
(declare (fixnum location))
(and (= (nkeys) 1)
(= location 0)))
;;
;; Given a line number, return the cache location. This is the
;; value that is the second argument to cache-vector-ref. Basically,
;; this deals with the offset of nkeys>1 caches and multiplies
;; by line size.
;;
(line-location (line)
(declare (fixnum line))
(when (line-reserved-p line)
(error "line is reserved"))
(if (= (nkeys) 1)
(the fixnum (* line (line-size)))
(the fixnum (1+ (the fixnum (* line (line-size)))))))
;;
;; Given a cache location, return the line. This is the inverse
;; of LINE-LOCATION.
;;
(location-line (location)
(declare (fixnum location))
(if (= (nkeys) 1)
(floor location (line-size))
(floor (the fixnum (1- location)) (line-size))))
;;
;; Given a line number, return the wrappers stored at that line.
;; As usual, if nkeys=1, this returns a single value. Only when
;; nkeys>1 does it return a list. An error is signalled if the
;; line is reserved.
;;
(line-wrappers (line)
(declare (fixnum line))
(when (line-reserved-p line) (error "Line is reserved."))
(location-wrappers (line-location line)))
;;
(location-wrappers (location) ; avoid multiplies caused by line-location
(declare (fixnum location))
(if (= (nkeys) 1)
(cache-vector-ref (vector) location)
(let ((list (make-list (nkeys)))
(vector (vector)))
(declare (simple-vector vector))
(dotimes (i (nkeys) list)
(setf (nth i list) (cache-vector-ref vector (+ location i)))))))
;;
;; Given a line number, return true IFF the line's
;; wrappers are the same as wrappers.
;;
(line-matches-wrappers-p (line wrappers)
(declare (fixnum line))
(and (not (line-reserved-p line))
(location-matches-wrappers-p (line-location line) wrappers)))
;;
(location-matches-wrappers-p (loc wrappers) ; must not be reserved
(declare (fixnum loc))
(let ((cache-vector (vector)))
(declare (simple-vector cache-vector))
(if (= (nkeys) 1)
(eq wrappers (cache-vector-ref cache-vector loc))
(dotimes (i (nkeys) t)
(unless (eq (pop wrappers) (cache-vector-ref cache-vector (+ loc i)))
(return nil))))))
;;
;; Given a line number, return the value stored at that line.
;; If valuep is NIL, this returns NIL. As with line-wrappers,
;; an error is signalled if the line is reserved.
;;
(line-value (line)
(declare (fixnum line))
(when (line-reserved-p line) (error "Line is reserved."))
(location-value (line-location line)))
;;
(location-value (loc)
(declare (fixnum loc))
(and (valuep)
(cache-vector-ref (vector) (+ loc (nkeys)))))
;;
;; Given a line number, return true IFF that line has data in
;; it. The state of the wrappers stored in the line is not
;; checked. An error is signalled if line is reserved.
(line-full-p (line)
(when (line-reserved-p line) (error "Line is reserved."))
(not (null (cache-vector-ref (vector) (line-location line)))))
;;
;; Given a line number, return true IFF the line is full and
;; there are no invalid wrappers in the line, and the line's
;; wrappers are different from wrappers.
;; An error is signalled if the line is reserved.
;;
(line-valid-p (line wrappers)
(declare (fixnum line))
(when (line-reserved-p line) (error "Line is reserved."))
(location-valid-p (line-location line) wrappers))
;;
(location-valid-p (loc wrappers)
(declare (fixnum loc))
(let ((cache-vector (vector))
(wrappers-mismatch-p (null wrappers)))
(declare (simple-vector cache-vector))
(dotimes (i (nkeys) wrappers-mismatch-p)
(let ((wrapper (cache-vector-ref cache-vector (+ loc i))))
(when (or (null wrapper)
(invalid-wrapper-p wrapper))
(return nil))
(unless (and wrappers
(eq wrapper
(if (consp wrappers) (pop wrappers) wrappers)))
(setq wrappers-mismatch-p t))))))
;;
;; How many unreserved lines separate line-1 and line-2.
;;
(line-separation (line-1 line-2)
(declare (fixnum line-1 line-2))
(let ((diff (the fixnum (- line-2 line-1))))
(declare (fixnum diff))
(when (minusp diff)
(setq diff (+ diff (nlines)))
(when (line-reserved-p 0)
(setq diff (1- diff))))
diff))
;;
;; Given a cache line, get the next cache line. This will not
;; return a reserved line.
;;
(next-line (line)
(declare (fixnum line))
(if (= line (the fixnum (1- (nlines))))
(if (line-reserved-p 0) 1 0)
(the fixnum (1+ line))))
;;
(next-location (loc)
(declare (fixnum loc))
(if (= loc (max-location))
(if (= (nkeys) 1)
(line-size)
1)
(the fixnum (+ loc (line-size)))))
;;
;; Given a line which has a valid entry in it, this will return
;; the primary cache line of the wrappers in that line. We just
;; call COMPUTE-PRIMARY-CACHE-LOCATION-FROM-LOCATION, this is an
;; easier packaging up of the call to it.
;;
(line-primary (line)
(declare (fixnum line))
(location-line (line-primary-location line)))
;;
(line-primary-location (line)
(declare (fixnum line))
(compute-primary-cache-location-from-location
(cache) (line-location line)))
))
(defmacro with-local-cache-functions ((cache) &body body)
`(let ((.cache. ,cache))
(declare (type cache .cache.))
(macrolet ,(mapcar #'(lambda (fn)
`(,(car fn) ,(cadr fn)
`(let (,,@(mapcar #'(lambda (var)
``(,',var ,,var))
(cadr fn)))
,@',(cddr fn))))
*local-cache-functions*)
,@body)))
)
;;;
;;; Here is where we actually fill, recache and expand caches.
;;;
;;; The functions FILL-CACHE and PROBE-CACHE are the ONLY external
;;; entrypoints into this code.
;;;
;;; FILL-CACHE returns 1 value: a new cache
;;;
;;; a wrapper field number
;;; a cache
;;; a mask
;;; an absolute cache size (the size of the actual vector)
;;; It tries to re-adjust the cache every time it makes a new fill. The
;;; intuition here is that we want uniformity in the number of probes needed to
;;; find an entry. Furthermore, adjusting has the nice property of throwing out
;;; any entries that are invalid.
;;;
(defvar *cache-expand-threshold* 1.25)
(defun fill-cache (cache wrappers value &optional free-cache-p)
;;(declare (values cache))
(unless wrappers ; fill-cache won't return if wrappers is nil, might as well check.
(error "fill-cache: wrappers arg is NIL!"))
(or (fill-cache-p nil cache wrappers value)
(and (< (ceiling (* (cache-count cache) 1.25))
(if (= (cache-nkeys cache) 1)
(1- (cache-nlines cache))
(cache-nlines cache)))
(adjust-cache cache wrappers value free-cache-p))
(expand-cache cache wrappers value free-cache-p)))
(defvar *check-cache-p* nil)
(defmacro maybe-check-cache (cache)
`(progn
(when *check-cache-p*
(check-cache ,cache))
,cache))
(defun check-cache (cache)
(with-local-cache-functions (cache)
(let ((location (if (= (nkeys) 1) 0 1))
(limit (funcall (limit-fn) (nlines))))
(dotimes (i (nlines) cache)
(when (and (not (location-reserved-p location))
(line-full-p i))
(let* ((home-loc (compute-primary-cache-location-from-location
cache location))
(home (location-line (if (location-reserved-p home-loc)
(next-location home-loc)
home-loc)))
(sep (when home (line-separation home i))))
(when (and sep (> sep limit))
(error "bad cache ~S ~@
value at location ~D is ~D lines from its home. limit is ~D."
cache location sep limit))))
(setq location (next-location location))))))
(defun probe-cache (cache wrappers &optional default limit-fn)
;;(declare (values value))
(unless wrappers (error "probe-cache: wrappers arg is NIL!"))
(with-local-cache-functions (cache)
(let* ((location (compute-primary-cache-location (field) (mask) wrappers))
(limit (funcall (or limit-fn (limit-fn)) (nlines))))
(declare (fixnum location limit))
(when (location-reserved-p location)
(setq location (next-location location)))
(dotimes (i (1+ limit))
(when (location-matches-wrappers-p location wrappers)
(return-from probe-cache (or (not (valuep))
(location-value location))))
(setq location (next-location location)))
(dolist (entry (overflow))
(when (equal (car entry) wrappers)
(return-from probe-cache (or (not (valuep))
(cdr entry)))))
default)))
(defun map-cache (function cache &optional set-p)
(with-local-cache-functions (cache)
(let ((set-p (and set-p (valuep))))
(dotimes (i (nlines) cache)
(unless (or (line-reserved-p i) (not (line-valid-p i nil)))
(let ((value (funcall function (line-wrappers i) (line-value i))))
(when set-p
(setf (cache-vector-ref (vector) (+ (line-location i) (nkeys)))
value)))))
(dolist (entry (overflow))
(let ((value (funcall function (car entry) (cdr entry))))
(when set-p
(setf (cdr entry) value))))))
cache)
(defun cache-count (cache)
(with-local-cache-functions (cache)
(let ((count 0))
(declare (fixnum count))
(dotimes (i (nlines) count)
(unless (line-reserved-p i)
(when (line-full-p i)
(incf count)))))))
(defun entry-in-cache-p (cache wrappers value)
(declare (ignore value))
(with-local-cache-functions (cache)
(dotimes (i (nlines))
(unless (line-reserved-p i)
(when (equal (line-wrappers i) wrappers)
(return t))))))
;;;
;;; returns T or NIL
;;;
(defun fill-cache-p (forcep cache wrappers value)
(with-local-cache-functions (cache)
(let* ((location (compute-primary-cache-location (field) (mask) wrappers))
(primary (location-line location)))
(declare (fixnum location primary))
(multiple-value-bind (free emptyp)
(find-free-cache-line primary cache wrappers)
(when (or forcep emptyp)
(when (not emptyp)
(push (cons (line-wrappers free) (line-value free))
(cache-overflow cache)))
;;(fill-line free wrappers value)
(let ((line free))
(declare (fixnum line))
(when (line-reserved-p line)
(error "Attempt to fill a reserved line."))
(let ((loc (line-location line))
(cache-vector (vector)))
(declare (fixnum loc) (simple-vector cache-vector))
(cond ((= (nkeys) 1)
(setf (cache-vector-ref cache-vector loc) wrappers)
(when (valuep)
(setf (cache-vector-ref cache-vector (1+ loc)) value)))
(t
(let ((i 0))
(declare (fixnum i))
(dolist (w wrappers)
(setf (cache-vector-ref cache-vector (+ loc i)) w)
(setq i (the fixnum (1+ i)))))
(when (valuep)
(setf (cache-vector-ref cache-vector (+ loc (nkeys)))
value))))
(maybe-check-cache cache))))))))
(defun fill-cache-from-cache-p (forcep cache from-cache from-line)
(declare (fixnum from-line))
(with-local-cache-functions (cache)
(let ((primary (location-line (compute-primary-cache-location-from-location
cache (line-location from-line) from-cache))))
(declare (fixnum primary))
(multiple-value-bind (free emptyp)
(find-free-cache-line primary cache)
(when (or forcep emptyp)
(when (not emptyp)
(push (cons (line-wrappers free) (line-value free))
(cache-overflow cache)))
;;(transfer-line from-cache-vector from-line cache-vector free)
(let ((from-cache-vector (cache-vector from-cache))
(to-cache-vector (vector))
(to-line free))
(declare (fixnum to-line))
(if (line-reserved-p to-line)
(error "transfering something into a reserved cache line.")
(let ((from-loc (line-location from-line))
(to-loc (line-location to-line)))
(declare (fixnum from-loc to-loc))
(modify-cache to-cache-vector
(dotimes (i (line-size))
(setf (cache-vector-ref to-cache-vector
(+ to-loc i))
(cache-vector-ref from-cache-vector
(+ from-loc i)))))))
(maybe-check-cache cache)))))))
;;;
;;; Returns NIL or (values <field> <cache-vector>)
;;;
;;; This is only called when it isn't possible to put the entry in the cache
;;; the easy way. That is, this function assumes that FILL-CACHE-P has been
;;; called as returned NIL.
;;;
;;; If this returns NIL, it means that it wasn't possible to find a wrapper
;;; field for which all of the entries could be put in the cache (within the
;;; limit).
;;;
(defun adjust-cache (cache wrappers value free-old-cache-p)
(with-local-cache-functions (cache)
(let ((ncache (get-cache-from-cache cache (nlines) (field))))
(do ((nfield (cache-field ncache) (next-wrapper-cache-number-index nfield)))
((null nfield) (free-cache ncache) nil)
(setf (cache-field ncache) nfield)
(labels ((try-one-fill-from-line (line)
(fill-cache-from-cache-p nil ncache cache line))
(try-one-fill (wrappers value)
(fill-cache-p nil ncache wrappers value)))
(if (and (dotimes (i (nlines) t)
(when (and (null (line-reserved-p i))
(line-valid-p i wrappers))
(unless (try-one-fill-from-line i) (return nil))))
(dolist (wrappers+value (cache-overflow cache) t)
(unless (try-one-fill (car wrappers+value) (cdr wrappers+value))
(return nil)))
(try-one-fill wrappers value))
(progn (when free-old-cache-p (free-cache cache))
(return (maybe-check-cache ncache)))
(flush-cache-vector-internal (cache-vector ncache))))))))
;;;
;;; returns: (values <cache>)
;;;
(defun expand-cache (cache wrappers value free-old-cache-p)
;;(declare (values cache))
(with-local-cache-functions (cache)
(let ((ncache (get-cache-from-cache cache (* (nlines) 2))))
(labels ((do-one-fill-from-line (line)
(unless (fill-cache-from-cache-p nil ncache cache line)
(do-one-fill (line-wrappers line) (line-value line))))
(do-one-fill (wrappers value)
(setq ncache (or (adjust-cache ncache wrappers value t)
(fill-cache-p t ncache wrappers value))))
(try-one-fill (wrappers value)
(fill-cache-p nil ncache wrappers value)))
(dotimes (i (nlines))
(when (and (null (line-reserved-p i))
(line-valid-p i wrappers))
(do-one-fill-from-line i)))
(dolist (wrappers+value (cache-overflow cache))
(unless (try-one-fill (car wrappers+value) (cdr wrappers+value))
(do-one-fill (car wrappers+value) (cdr wrappers+value))))
(unless (try-one-fill wrappers value)
(do-one-fill wrappers value))
(when free-old-cache-p (free-cache cache))
(maybe-check-cache ncache)))))
;;;
;;; This is the heart of the cache filling mechanism. It implements the decisions
;;; about where entries are placed.
;;;
;;; Find a line in the cache at which a new entry can be inserted.
;;;
;;; <line>
;;; <empty?> is <line> in fact empty?
;;;
(defun find-free-cache-line (primary cache &optional wrappers)
;;(declare (values line empty?))
(declare (fixnum primary))
(with-local-cache-functions (cache)
(when (line-reserved-p primary) (setq primary (next-line primary)))
(let ((limit (funcall (limit-fn) (nlines)))
(wrappedp nil)
(lines nil)
(p primary) (s primary))
(declare (fixnum p s limit))
(block find-free
(loop
;; Try to find a free line starting at <s>. <p> is the
;; primary line of the entry we are finding a free
;; line for, it is used to compute the seperations.
(do* ((line s (next-line line))
(nsep (line-separation p s) (1+ nsep)))
(())
(declare (fixnum line nsep))
(when (null (line-valid-p line wrappers)) ;If this line is empty or
(push line lines) ;invalid, just use it.
(return-from find-free))
(when (and wrappedp (>= line primary))
;; have gone all the way around the cache, time to quit
(return-from find-free-cache-line (values primary nil)))
(let ((osep (line-separation (line-primary line) line)))
(when (>= osep limit)
(return-from find-free-cache-line (values primary nil)))
(when (cond ((= nsep limit) t)
((= nsep osep) (zerop (random 2)))
((> nsep osep) t)
(t nil))
;; See if we can displace what is in this line so that we
;; can use the line.
(when (= line (the fixnum (1- (nlines)))) (setq wrappedp t))
(setq p (line-primary line))
(setq s (next-line line))
(push line lines)
(return nil)))
(when (= line (the fixnum (1- (nlines)))) (setq wrappedp t)))))
;; Do all the displacing.
(loop
(when (null (cdr lines)) (return nil))
(let ((dline (pop lines))
(line (car lines)))
(declare (fixnum dline line))
;;Copy from line to dline (dline is known to be free).
(let ((from-loc (line-location line))
(to-loc (line-location dline))
(cache-vector (vector)))
(declare (fixnum from-loc to-loc) (simple-vector cache-vector))
(modify-cache cache-vector
(dotimes (i (line-size))
(setf (cache-vector-ref cache-vector (+ to-loc i))
(cache-vector-ref cache-vector (+ from-loc i)))
(setf (cache-vector-ref cache-vector (+ from-loc i))
nil))))))
(values (car lines) t))))
(defun default-limit-fn (nlines)
(case nlines
((1 2 4) 1)
((8 16) 4)
(otherwise 6)))
(defvar *empty-cache* (make-cache)) ; for defstruct slot initial value forms
;;;
;;; pre-allocate generic function caches. The hope is that this will put
;;; them nicely together in memory, and that that may be a win. Of course
;;; the first gc copy will probably blow that out, this really wants to be
;;; wrapped in something that declares the area static.
;;;
;;; This preallocation only creates about 25% more caches than PCL itself
;;; uses. Some ports may want to preallocate some more of these.
;;;
(eval-when (load)
(dolist (n-size '((1 513)(3 257)(3 129)(14 128)(6 65)(2 64)(7 33)(16 32)
(16 17)(32 16)(64 9)(64 8)(6 5)(128 4)(35 2)))
(let ((n (car n-size))
(size (cadr n-size)))
(mapcar #'free-cache-vector
(mapcar #'get-cache-vector
(make-list n :initial-element size))))))
(defun caches-to-allocate ()
(sort (let ((l nil))
(maphash #'(lambda (size entry)
(push (list (car entry) size) l))
pcl::*free-caches*)
l)
#'> :key #'cadr))
|
[
{
"context": "; DEALINGS IN THE SOFTWARE.\n;\n; Original author: Jared Davis <[email protected]>\n\n(in-package \"STD\")\n(include",
"end": 1398,
"score": 0.9996117353439331,
"start": 1387,
"tag": "NAME",
"value": "Jared Davis"
},
{
"context": "N THE SOFTWARE.\n;\n; Original author: Jared Davis <[email protected]>\n\n(in-package \"STD\")\n(include-book \"da-base\")\n(in",
"end": 1418,
"score": 0.9999332427978516,
"start": 1400,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/std/util/returnspecs.lisp
|
shigoel/acl2
| 1 |
; Standard Utilities Library
; Copyright (C) 2008-2014 Centaur Technology
;
; Contact:
; Centaur Technology Formal Verification Group
; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA.
; http://www.centtech.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: Jared Davis <[email protected]>
(in-package "STD")
(include-book "da-base")
(include-book "look-up")
(local (include-book "misc/assert" :dir :system))
(program)
(defxdoc returns-specifiers
:parents (std/util define)
:short "A concise way to name, document, and prove basic type-like theorems
about a function's return values."
:long "<p>The @(see define) macro and some other @(see std/util) macros
support a @(':returns') option. This option provides a concise way to name,
document, and prove basic type-like theorems about the return values of your
functions. Named return values also allow your function to be used with the
special <see topic='@(url acl2::patbind-ret)'>ret</see> binder for @(see
b*).</p>
<p>The general form is:</p>
@({
:returns return-spec ;; for single-value functions
or :returns (mv return-spec*) ;; for multiple-valued functions
})
<p>There should be exactly one @('return-spec') per return value. Each
return-spec has the form:</p>
@({
name ;; just for naming return values
or (name [option]*) ;; for naming, documenting, and proving theorems
})
<p>where @('name') is a symbol and the options can come in any order. To
distinguish between the two forms of @(':returns'), it is not legal to use
@('mv') as the name of a return value. The options are:</p>
<dl>
<dt>@('<xdoc>'), any string literal</dt>
<dd>You can document each return value with a string literal. The string may
make use of @(see xdoc::markup) and @(see xdoc::preprocessor) directives.
Typically these descriptions should be short and not include
document-structuring tags like @('<p>'), @('<ul>'), @('<h3>'), and so forth.
See the section on xdoc integration, below, for more details.</dd>
<dt>@('<return-type>'), a symbol or term</dt>
<dd>When provided, the return type is used to generate a basic type-like
theorems about the return values.</dd>
<dd><b>Important Note</b> in the multiple-valued case, this approach assumes
you are using the @('tools/mv-nth') book. The theorems we prove target terms
like @('(mv-nth 0 (f ...))') and @('(mv-nth 1 (f ...))'). This will not work
well if @(see mv-nth) is enabled, especially about the 0th return value. For
your convenience, @('define') automatically includes the @('tools/mv-nth')
book. You really should be using it, you know.</dd>
<dd>As a convenient shorthand, you can use a single symbol like @('evenp').
The theorem to be proven in this case might be, e.g., @('(evenp (f x))') for a
single-valued function, or @('(evenp (mv-nth 3 (f x)))') if this is the
fourth (because of zero-indexing) return value of a multiply-valued function.
The symbol @('t') is explicitly allowed and results in no theorem. The symbol
@('nil') and keyword symbols are explicitly invalid as return types.</dd>
<dd>In certain cases, you may wish to prove a more complex theorem, e.g., say
we want to prove this return value is always greater than 5. To support this,
you can write a return type like @('(< 5 ans)'), where @('ans') is the
@('name') of this return value. You can also refer to the names of other
return values in this term. To make it easy to distinguish return types from
other options, the return type term must be a cons and must not begin with
@('quote').</dd>
<dt>@(':hyp hyp-term')</dt>
<dd>This option only makes sense when there is a return-type term. By default,
the return-type theorem is unconditional. If the theorem needs a hypothesis,
you can put it here.</dd>
<dd>Frequently, the hypothesis you want for a type-like theorem is for the
guards of the function to be met. As a convenient shorthand, @('hyp-term') may
be:
<ul>
<li>@(':guard') -- use the function's guard as the hypothesis</li>
<li>@(':fguard') -- like @(':guard'), but @(see force) the entire guard</li>
</ul>
If neither of these is what you want, you can provide an arbitrary
@('hyp-term'). Typically this term should mention only the formals of your
function. The return values of the theorem will not be bound in scope of the
hyp, so trying to refer to them in a hypothesis is generally an error.</dd>
<dt>@(':hints hints-term')</dt>
<dd>This option only makes sense when there is a return-type term. By default,
this is @('nil'), but when specified, the hints are passed to the proof attempt
for the associated return-type.</dd>
<dt>@(':rule-classes classes')</dt>
<dd>This option only makes sense when there is a return-type term. By default,
the return-type theorem is added as a @(':rewrite') rule. If you want to use
other @(see acl2::rule-classes), then you will want to override this default.</dd>
<dt>@(':name name')</dt>
<dd>This allows you to control the name of the associated theorem.</dd>
<dd>The default value of @('name') is <it>type</it>-of-<it>your-function</it>.
For example, @('natp-of-foo').</dd>
</dl>")
(def-primitive-aggregate returnspec
(name ; a symbol, the name of this return value
doc ; a string, "" when omitted
return-type ; t when omitted
hyp ; t when omitted
hints ; nil when omitted
hintsp ; t if hints were provided
rule-classes ; :rewrite when omitted
thm-name ; NIL (to generate a name) or the name for the theorem
)
:tag :return-spec)
(defconst *default-returnspec*
(make-returnspec :name 'ret
:doc ""
:return-type t
:hyp t
:hints nil
:hintsp nil
:rule-classes :rewrite
:thm-name nil))
(defun returnspeclist-p (x)
(declare (xargs :guard t))
(if (atom x)
t
(and (returnspec-p (car x))
(returnspeclist-p (cdr x)))))
(defun returnspeclist->names (x)
(declare (xargs :guard (returnspeclist-p x)))
(if (atom x)
nil
(cons (returnspec->name (car x))
(returnspeclist->names (cdr x)))))
; User-level syntax for returns specifiers
(defun parse-returnspec-item
(fnname ; context for error message
varname ; name of this return value
item ; item in user-level return-spec syntax after keywords are removed,
; i.e., it should be a doc string or a return-type indicator, i.e.,
; a term or a predicate name
terms ; accumulator for return-type indicators
docs ; accumulator for doc strings
)
"Returns (mv terms docs)"
(declare (xargs :guard t))
(b* ((__function__ 'parse-returnspec-item)
((when (eq item t))
;; T is explicitly allowed as a return type
(mv (cons item terms) docs))
((when (or (eq item nil)
(keywordp item)))
;; NIL/keywords are explicitly not allowed
(raise "Error in ~x0: return type for ~x1 is ~x2, which is not ~
allowed." fnname varname item)
(mv terms docs))
((when (symbolp item))
(mv (cons `(,item ,varname) terms) docs))
((when (and (consp item)
(not (eq (car item) 'quote))))
(mv (cons item terms) docs))
((when (stringp item))
(mv terms (cons item docs))))
(raise "Error in ~x0, return type for ~x1: expected return type terms or ~
documentation strings, but found ~x2." fnname varname item)
(mv terms docs)))
(defun parse-returnspec-items (fnname varname items terms docs)
"Returns (mv terms docs)"
(declare (xargs :guard t))
(b* ((__function__ 'parse-returnspec-items)
((when (not items))
(mv terms docs))
((when (atom items))
(raise "Error in ~x0: expected returnspec-items for ~x1 to be ~
nil-terminated, but found ~x2 as the final cdr."
fnname varname items)
(mv terms docs))
((mv terms docs)
(parse-returnspec-item fnname varname (car items) terms docs)))
(parse-returnspec-items fnname varname (cdr items) terms docs)))
(defun parse-returnspec
(fnname ; context for error messages
x ; actual return specifier the user provided
world ; for special extra sanity checking
)
"Returns a returnspec-p."
(declare (xargs :guard (plist-worldp world)))
(b* ((__function__ 'parse-returnspec)
((when (eq x 'mv))
(raise "Error in ~x0: return values may not be named MV." fnname)
*default-returnspec*)
((when (symbolp x))
;; Fine, just a name, no docs/type
;; A user once got very confused why :returns character-listp
;; wasn't proving that his function wasn't returning a character
;; list. So, now, make sure this isn't a defined function.
(b* ((look (getprop x 'acl2::formals :bad 'acl2::current-acl2-world world))
((unless (eq look :bad))
(raise "Error in ~x0: you named a return value ~x1, which is ~
the name of a defined function, but you don't have any ~
return type associated with this value. There's a good ~
chance this you meant this to be the return value's ~
type instead of its name.~%~%If you really want to name ~
this return value ~x1 and not prove anything about it, ~
you can use syntax like ~x2.~%" fnname x (list x t))
*default-returnspec*))
;; Else, seems fine, just a name.
(make-returnspec :name x
:doc ""
:return-type t
:rule-classes :rewrite
:hyp nil
:hints nil
:thm-name nil)))
((when (atom x))
(raise "Error in ~x0: return specifiers must be symbols or lists, but ~
found: ~x1" fnname x)
*default-returnspec*)
((cons varname options) x)
((unless (symbolp varname))
(raise "Error in ~x0: return specifiers must start with a symbol ~
name, so this return specifier is not valid: ~x1" fnname x)
*default-returnspec*)
((when (eq varname 'mv))
(raise "Error in ~x0: return values may not be named MV." fnname)
*default-returnspec*)
((mv kwd-alist other-opts)
;; bozo better context for error message here would be good
(extract-keywords fnname '(:hyp :hints :rule-classes :name) options nil))
(hyp (if (assoc :hyp kwd-alist)
(cdr (assoc :hyp kwd-alist))
t))
((when (and (keywordp hyp)
(not (eq hyp :guard))
(not (eq hyp :fguard))))
;; bozo not really a very good place to check for this.
(raise "Error in ~x0: invalid keyword ~x1 used as a :hyp." fnname hyp)
*default-returnspec*)
((mv hints hintsp)
(if (assoc :hints kwd-alist)
(mv (cdr (assoc :hints kwd-alist)) t)
(mv nil nil)))
(rule-classes (if (assoc :rule-classes kwd-alist)
(cdr (assoc :rule-classes kwd-alist))
:rewrite))
(thm-name (if (assoc :name kwd-alist)
(cdr (assoc :name kwd-alist))
nil))
((mv terms docs)
(parse-returnspec-items fnname varname other-opts nil nil))
(return-type
(cond ((atom terms) ;; no return-type terms, fine, default is t
t)
((atom (cdr terms))
(car terms))
(t
(raise "Error in ~x0: return specifier ~x1 has multiple return ~
type terms, but at most one is allowed: ~&2"
fnname varname terms))))
(xdoc
(cond ((atom docs) ;; no documentation, go figure, default is ""
"")
((atom (cdr docs))
(car docs))
(t
(progn$
(raise "Error in ~x0: return specifier ~x1 has multiple xdoc ~
strings, but at most one is allowed: ~x2."
fnname varname terms)
"")))))
(make-returnspec :name varname
:doc xdoc
:return-type return-type
:rule-classes rule-classes
:hyp hyp
:hints hints
:hintsp hintsp
:thm-name thm-name)))
(defun parse-returnspecs-aux (fnname x world)
"Returns a returnspeclist-p"
;; Assumes they've already been normalized...
(declare (xargs :guard (plist-worldp world)))
(if (atom x)
nil
(cons (parse-returnspec fnname (car x) world)
(parse-returnspecs-aux fnname (cdr x) world))))
(defun normalize-returnspecs (fnname x)
;; We support two forms of returns:
;; :returns return-spec
;; :returns (mv return-spec ... return-spec)
;; We require that return-value names are never MV, so we can just check for MV to
;; tell thich kind of return spec we are dealing with.
;; This function just converts either form into a list of return specs
;; with no MV part.
(declare (xargs :guard t))
(b* ((__function__ 'normalize-returnspecs)
((unless x)
;; Fine, no return spec
nil)
((when (eq x 'mv))
(raise "Error in ~x0: :returns may not be just MV." fnname))
((when (symbolp x))
;; Fine
(list x))
((when (atom x))
(raise "Error in ~x0: :returns may not be ~x1." fnname x))
((when (eq (car x) 'mv))
(if (true-listp (cdr x))
(cdr x)
(raise "Error in ~x0: :returns must be nil-terminated." fnname x))))
(list x)))
(defun parse-returnspecs (fnname x world)
"Returns a returnspeclist-p"
(declare (xargs :guard (plist-worldp world)))
(parse-returnspecs-aux fnname
(normalize-returnspecs fnname x)
world))
(defun arity-check-returns (name name-fn specs world)
(declare (xargs :guard (and (symbolp name)
(symbolp name-fn)
(returnspeclist-p specs)
(plist-worldp world))))
(b* (((when (atom specs))
;; Fine, the user just didn't name/document the return values.
t)
(stobjs-out (look-up-return-vals name-fn world))
((when (equal (len stobjs-out) (len specs)))
;; Fine, arity looks OK.
t)
((when (getprop name-fn 'acl2::non-executablep nil 'acl2::current-acl2-world world))
;; The function is non-executable so stobjs-out doesn't necessarily say
;; anything coherent, nothing to really check.
t))
(er hard? 'arity-check-returns
"Error in ~x0: ACL2 thinks this function has ~x1 return ~
values, but :returns has ~x2 entries!"
name
(len stobjs-out)
(len specs))))
(defsection untranslate-and
(defun untranslate-and (x)
(declare (xargs :guard t))
(cond ((atom x)
;; (and x) --> x
(list x))
((and (consp x)
(eq (first x) 'if)
(equal (len x) 4)
(equal (fourth x) ''nil))
;; (and x y ...) --> (if x (and y ...) nil)
(cons (second x)
(untranslate-and (third x))))
(t
(list x))))
(local
(progn
(assert! (equal (untranslate-and 'x) '(x)))
(assert! (equal (untranslate-and 't) '(t)))
(assert! (equal (untranslate-and '(if x y z)) '((if x y z))))
(assert! (equal (untranslate-and '(if x y 'nil)) '(x y)))
(assert! (equal (untranslate-and '(if x (if a b c) 'nil)) '(x (if a b c))))
(assert! (equal (untranslate-and '(if x (if a b 'nil) 'nil)) '(x a b))))))
(defun force-each (x)
(declare (xargs :guard t))
(if (atom x)
nil
(cons `(force ,(car x))
(force-each (cdr x)))))
(defun fancy-force-hyp (x)
(declare (xargs :guard t))
(b* ((hyp-list (untranslate-and x)))
(cons 'and (force-each hyp-list))))
(defun fancy-hyp (x)
(declare (xargs :guard t))
(b* ((hyp-list (untranslate-and x)))
(cons 'and hyp-list)))
(defun returnspec-thm-body (fnname binds x world)
(declare (xargs :guard (and (symbolp fnname)
(returnspec-p x)
(plist-worldp world))))
(b* (((returnspec x) x)
((when (equal x.return-type t)) t)
(hyp (cond
((eq x.hyp :guard) (fancy-hyp (look-up-guard fnname world)))
((eq x.hyp :fguard) (fancy-force-hyp (look-up-guard fnname world)))
(t x.hyp)))
(concl `(b* (,binds)
,x.return-type)))
(if (eq hyp t)
concl
`(implies ,hyp ,concl))))
(defun returnspec-generate-name (name x singlep badname-okp)
;; Get the name for a return-spec theorem.
;; Usually we can produce a good name like:
;; natp-of-fn
;; natp-of-fn.new-x
;; Or similar. But, for more complex return-types, say something like
;; (equal (len new-x) (len x))
;; we are too dumb to generate a good name.
;;
;; Badname-okp indicates whether we're willing to accept a "bad", generic
;; name of the form "return-type-of-fn" or "return-type-of-fn.new-x" or
;; similar.
;;
;; We'll tolerate bad names if the user is just giving a :returns specifier
;; in a function, mainly for backwards compatibility. (i.e., badname-okp
;; will be true).
;;
;; However, for the new, subsequent return-specs, we'll require explicit
;; names for complex conclusions. (i.e., badname-okp will be nil).
(b* (((returnspec x) x)
((when x.thm-name)
;; The user provided an explicit name, so use that.
x.thm-name)
(multi-suffix (if singlep
""
(concatenate 'string "." (symbol-name x.name))))
((when (and (tuplep 2 x.return-type)
(symbolp (first x.return-type))
(equal (second x.return-type) x.name)))
;; Simple return type like (natp ans)
(intern-in-package-of-symbol
(concatenate 'string
(symbol-name (first x.return-type))
"-OF-"
(symbol-name name)
multi-suffix)
name))
((unless badname-okp)
(er hard? 'returnspec-generate-name
"Return spec for ~x0, ~x1, must be given an explicit name."
name x.return-type)))
;; Complex return type
(intern-in-package-of-symbol
(concatenate 'string "RETURN-TYPE-OF-" (symbol-name name) multi-suffix)
name)))
(defun returnspec-default-default-hint (fnname id world)
(and (eql (len (acl2::recursivep fnname t world)) 1) ;; singly recursive
(let* ((pool-lst (acl2::access acl2::clause-id id :pool-lst)))
(and (eql 0 (acl2::access acl2::clause-id id :forcing-round))
(cond ((not pool-lst)
(let ((formals (look-up-formals fnname world)))
`(:induct (,fnname . ,formals)
:in-theory (disable (:d ,fnname)))))
((equal pool-lst '(1))
`(:computed-hint-replacement
((and stable-under-simplificationp
(expand-calls ,fnname)))
:in-theory (disable (:d ,fnname)))))))))
(defun returnspec-default-hints (fnname world)
(let ((entry (cdr (assoc 'returnspec (table-alist 'std::default-hints-table world)))))
(subst fnname 'fnname entry)))
(defmacro set-returnspec-default-hints (hint)
`(table std::default-hints-table 'returnspec ',hint))
(set-returnspec-default-hints
((returnspec-default-default-hint 'fnname acl2::id world)))
(defun returnspec-sublis (subst x)
"Like sublis, but only substitutes symbols, and looks them up both by value and by name."
(if (atom x)
(if (symbolp x)
(let ((look (assoc-equal x subst)))
(if look
(cdr look)
(let ((look (assoc-equal (symbol-name x) subst)))
(if look
(cdr look)
x))))
x)
(cons-with-hint (returnspec-sublis subst (car x))
(returnspec-sublis subst (cdr x))
x)))
(defun returnspec-single-thm (name name-fn x body-subst hint-subst badname-okp world)
"Returns EVENTS"
;; Only valid to call AFTER the function has been submitted, because we look
;; up the guard/formals from the world.
(declare (xargs :guard (and (symbolp name)
(symbolp name-fn)
(returnspec-p x)
(plist-worldp world))))
(b* (((returnspec x) x)
(formals (look-up-formals name-fn world))
(binds `(,x.name (,name-fn . ,formals)))
(formula (returnspec-sublis body-subst (returnspec-thm-body name-fn binds x world)))
((when (eq formula t)) nil)
(hints (if x.hintsp (returnspec-sublis hint-subst x.hints)
(returnspec-default-hints name-fn world))))
`((defthm ,(returnspec-generate-name name x t badname-okp)
,formula
:hints ,hints
:rule-classes ,(returnspec-sublis hint-subst x.rule-classes)))))
(defun returnspec-multi-thm (name name-fn binds x body-subst hint-subst badname-okp world)
"Returns EVENTS"
(declare (xargs :guard (and (symbolp name)
(symbolp name-fn)
(returnspec-p x)
(plist-worldp world))))
(b* (((returnspec x) x)
(formula (returnspec-sublis body-subst (returnspec-thm-body name-fn binds x world)))
((when (equal formula t)) nil)
(hints (if x.hintsp
(returnspec-sublis hint-subst x.hints)
(returnspec-default-hints name-fn world))))
`((defthm ,(returnspec-generate-name name x nil badname-okp)
,formula
:hints ,hints
:rule-classes ,(returnspec-sublis hint-subst x.rule-classes)))))
(defun returnspec-multi-thms (name name-fn binds x body-subst hint-subst badname-okp world)
"Returns EVENTS"
(declare (xargs :guard (and (symbolp name)
(symbolp name-fn)
(returnspeclist-p x)
(plist-worldp world))))
(if (atom x)
nil
(append (returnspec-multi-thm name name-fn binds (car x) body-subst hint-subst badname-okp world)
(returnspec-multi-thms name name-fn binds (cdr x) body-subst hint-subst badname-okp world))))
(defun make-symbol-ignorable (x)
(declare (xargs :guard (symbolp x)))
(intern-in-package-of-symbol
(concatenate 'string "?" (symbol-name x))
x))
(defun make-symbols-ignorable (x)
(declare (xargs :guard (symbol-listp x)))
(if (atom x)
nil
(cons (make-symbol-ignorable (car x))
(make-symbols-ignorable (cdr x)))))
(defun returnspec-mv-nth-subst (names idx call)
(if (atom names)
nil
(cons (cons (car names) `(mv-nth ,idx ,call))
(returnspec-mv-nth-subst (cdr names) (1+ idx) call))))
(defun returnspec-symbol-packages (syms)
(if (atom syms)
nil
(add-to-set-equal (symbol-package-name (car syms))
(returnspec-symbol-packages (cdr syms)))))
(defun returnspec-call-sym-pairs (packages call)
(if (atom packages)
nil
(cons (cons (intern$ "<CALL>" (car packages)) call)
(returnspec-call-sym-pairs (cdr packages) call))))
(defun returnspec-return-value-subst (name name-fn formals names)
(declare (xargs :guard (and (symbolp name)
(symbol-listp names))))
;; NOTE: These are intended for use with returnspec-sublis, which only
;; replaces symbols, but will also look up the name of a symbol. So a
;; binding whose key is a string affects all symbols with that name, whereas
;; bindings of symbols only affect those exact symbols.
(b* ((call (cons name-fn formals))
(both-subst `(("<CALL>" . ,call)
("<FN>" . ,name)
("<FN!>" . ,name-fn)
("<VALUES>" . ,names)))
((when (eql (len names) 1))
(mv both-subst (cons (cons (car names) call) both-subst))))
(mv both-subst (append both-subst (returnspec-mv-nth-subst names 0 call)))))
(defun returnspec-thms (name name-fn specs world)
"Returns EVENTS"
(declare (xargs :guard (and (symbolp name)
(symbolp name-fn)
(returnspeclist-p specs)
(plist-worldp world))))
(b* ((- (arity-check-returns name name-fn specs world))
((unless specs)
nil)
(badname-okp t)
(names (returnspeclist->names specs))
(formals (look-up-formals name-fn world))
((mv body-subst hint-subst) (returnspec-return-value-subst name name-fn formals names))
((when (equal (len specs) 1))
(returnspec-single-thm name name-fn (car specs) body-subst hint-subst badname-okp world))
(ignorable-names (make-symbols-ignorable names))
(binds `((mv . ,ignorable-names) (,name-fn . ,formals))))
(returnspec-multi-thms name name-fn binds specs body-subst hint-subst badname-okp world)))
|
11059
|
; Standard Utilities Library
; Copyright (C) 2008-2014 Centaur Technology
;
; Contact:
; Centaur Technology Formal Verification Group
; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA.
; http://www.centtech.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: <NAME> <<EMAIL>>
(in-package "STD")
(include-book "da-base")
(include-book "look-up")
(local (include-book "misc/assert" :dir :system))
(program)
(defxdoc returns-specifiers
:parents (std/util define)
:short "A concise way to name, document, and prove basic type-like theorems
about a function's return values."
:long "<p>The @(see define) macro and some other @(see std/util) macros
support a @(':returns') option. This option provides a concise way to name,
document, and prove basic type-like theorems about the return values of your
functions. Named return values also allow your function to be used with the
special <see topic='@(url acl2::patbind-ret)'>ret</see> binder for @(see
b*).</p>
<p>The general form is:</p>
@({
:returns return-spec ;; for single-value functions
or :returns (mv return-spec*) ;; for multiple-valued functions
})
<p>There should be exactly one @('return-spec') per return value. Each
return-spec has the form:</p>
@({
name ;; just for naming return values
or (name [option]*) ;; for naming, documenting, and proving theorems
})
<p>where @('name') is a symbol and the options can come in any order. To
distinguish between the two forms of @(':returns'), it is not legal to use
@('mv') as the name of a return value. The options are:</p>
<dl>
<dt>@('<xdoc>'), any string literal</dt>
<dd>You can document each return value with a string literal. The string may
make use of @(see xdoc::markup) and @(see xdoc::preprocessor) directives.
Typically these descriptions should be short and not include
document-structuring tags like @('<p>'), @('<ul>'), @('<h3>'), and so forth.
See the section on xdoc integration, below, for more details.</dd>
<dt>@('<return-type>'), a symbol or term</dt>
<dd>When provided, the return type is used to generate a basic type-like
theorems about the return values.</dd>
<dd><b>Important Note</b> in the multiple-valued case, this approach assumes
you are using the @('tools/mv-nth') book. The theorems we prove target terms
like @('(mv-nth 0 (f ...))') and @('(mv-nth 1 (f ...))'). This will not work
well if @(see mv-nth) is enabled, especially about the 0th return value. For
your convenience, @('define') automatically includes the @('tools/mv-nth')
book. You really should be using it, you know.</dd>
<dd>As a convenient shorthand, you can use a single symbol like @('evenp').
The theorem to be proven in this case might be, e.g., @('(evenp (f x))') for a
single-valued function, or @('(evenp (mv-nth 3 (f x)))') if this is the
fourth (because of zero-indexing) return value of a multiply-valued function.
The symbol @('t') is explicitly allowed and results in no theorem. The symbol
@('nil') and keyword symbols are explicitly invalid as return types.</dd>
<dd>In certain cases, you may wish to prove a more complex theorem, e.g., say
we want to prove this return value is always greater than 5. To support this,
you can write a return type like @('(< 5 ans)'), where @('ans') is the
@('name') of this return value. You can also refer to the names of other
return values in this term. To make it easy to distinguish return types from
other options, the return type term must be a cons and must not begin with
@('quote').</dd>
<dt>@(':hyp hyp-term')</dt>
<dd>This option only makes sense when there is a return-type term. By default,
the return-type theorem is unconditional. If the theorem needs a hypothesis,
you can put it here.</dd>
<dd>Frequently, the hypothesis you want for a type-like theorem is for the
guards of the function to be met. As a convenient shorthand, @('hyp-term') may
be:
<ul>
<li>@(':guard') -- use the function's guard as the hypothesis</li>
<li>@(':fguard') -- like @(':guard'), but @(see force) the entire guard</li>
</ul>
If neither of these is what you want, you can provide an arbitrary
@('hyp-term'). Typically this term should mention only the formals of your
function. The return values of the theorem will not be bound in scope of the
hyp, so trying to refer to them in a hypothesis is generally an error.</dd>
<dt>@(':hints hints-term')</dt>
<dd>This option only makes sense when there is a return-type term. By default,
this is @('nil'), but when specified, the hints are passed to the proof attempt
for the associated return-type.</dd>
<dt>@(':rule-classes classes')</dt>
<dd>This option only makes sense when there is a return-type term. By default,
the return-type theorem is added as a @(':rewrite') rule. If you want to use
other @(see acl2::rule-classes), then you will want to override this default.</dd>
<dt>@(':name name')</dt>
<dd>This allows you to control the name of the associated theorem.</dd>
<dd>The default value of @('name') is <it>type</it>-of-<it>your-function</it>.
For example, @('natp-of-foo').</dd>
</dl>")
(def-primitive-aggregate returnspec
(name ; a symbol, the name of this return value
doc ; a string, "" when omitted
return-type ; t when omitted
hyp ; t when omitted
hints ; nil when omitted
hintsp ; t if hints were provided
rule-classes ; :rewrite when omitted
thm-name ; NIL (to generate a name) or the name for the theorem
)
:tag :return-spec)
(defconst *default-returnspec*
(make-returnspec :name 'ret
:doc ""
:return-type t
:hyp t
:hints nil
:hintsp nil
:rule-classes :rewrite
:thm-name nil))
(defun returnspeclist-p (x)
(declare (xargs :guard t))
(if (atom x)
t
(and (returnspec-p (car x))
(returnspeclist-p (cdr x)))))
(defun returnspeclist->names (x)
(declare (xargs :guard (returnspeclist-p x)))
(if (atom x)
nil
(cons (returnspec->name (car x))
(returnspeclist->names (cdr x)))))
; User-level syntax for returns specifiers
(defun parse-returnspec-item
(fnname ; context for error message
varname ; name of this return value
item ; item in user-level return-spec syntax after keywords are removed,
; i.e., it should be a doc string or a return-type indicator, i.e.,
; a term or a predicate name
terms ; accumulator for return-type indicators
docs ; accumulator for doc strings
)
"Returns (mv terms docs)"
(declare (xargs :guard t))
(b* ((__function__ 'parse-returnspec-item)
((when (eq item t))
;; T is explicitly allowed as a return type
(mv (cons item terms) docs))
((when (or (eq item nil)
(keywordp item)))
;; NIL/keywords are explicitly not allowed
(raise "Error in ~x0: return type for ~x1 is ~x2, which is not ~
allowed." fnname varname item)
(mv terms docs))
((when (symbolp item))
(mv (cons `(,item ,varname) terms) docs))
((when (and (consp item)
(not (eq (car item) 'quote))))
(mv (cons item terms) docs))
((when (stringp item))
(mv terms (cons item docs))))
(raise "Error in ~x0, return type for ~x1: expected return type terms or ~
documentation strings, but found ~x2." fnname varname item)
(mv terms docs)))
(defun parse-returnspec-items (fnname varname items terms docs)
"Returns (mv terms docs)"
(declare (xargs :guard t))
(b* ((__function__ 'parse-returnspec-items)
((when (not items))
(mv terms docs))
((when (atom items))
(raise "Error in ~x0: expected returnspec-items for ~x1 to be ~
nil-terminated, but found ~x2 as the final cdr."
fnname varname items)
(mv terms docs))
((mv terms docs)
(parse-returnspec-item fnname varname (car items) terms docs)))
(parse-returnspec-items fnname varname (cdr items) terms docs)))
(defun parse-returnspec
(fnname ; context for error messages
x ; actual return specifier the user provided
world ; for special extra sanity checking
)
"Returns a returnspec-p."
(declare (xargs :guard (plist-worldp world)))
(b* ((__function__ 'parse-returnspec)
((when (eq x 'mv))
(raise "Error in ~x0: return values may not be named MV." fnname)
*default-returnspec*)
((when (symbolp x))
;; Fine, just a name, no docs/type
;; A user once got very confused why :returns character-listp
;; wasn't proving that his function wasn't returning a character
;; list. So, now, make sure this isn't a defined function.
(b* ((look (getprop x 'acl2::formals :bad 'acl2::current-acl2-world world))
((unless (eq look :bad))
(raise "Error in ~x0: you named a return value ~x1, which is ~
the name of a defined function, but you don't have any ~
return type associated with this value. There's a good ~
chance this you meant this to be the return value's ~
type instead of its name.~%~%If you really want to name ~
this return value ~x1 and not prove anything about it, ~
you can use syntax like ~x2.~%" fnname x (list x t))
*default-returnspec*))
;; Else, seems fine, just a name.
(make-returnspec :name x
:doc ""
:return-type t
:rule-classes :rewrite
:hyp nil
:hints nil
:thm-name nil)))
((when (atom x))
(raise "Error in ~x0: return specifiers must be symbols or lists, but ~
found: ~x1" fnname x)
*default-returnspec*)
((cons varname options) x)
((unless (symbolp varname))
(raise "Error in ~x0: return specifiers must start with a symbol ~
name, so this return specifier is not valid: ~x1" fnname x)
*default-returnspec*)
((when (eq varname 'mv))
(raise "Error in ~x0: return values may not be named MV." fnname)
*default-returnspec*)
((mv kwd-alist other-opts)
;; bozo better context for error message here would be good
(extract-keywords fnname '(:hyp :hints :rule-classes :name) options nil))
(hyp (if (assoc :hyp kwd-alist)
(cdr (assoc :hyp kwd-alist))
t))
((when (and (keywordp hyp)
(not (eq hyp :guard))
(not (eq hyp :fguard))))
;; bozo not really a very good place to check for this.
(raise "Error in ~x0: invalid keyword ~x1 used as a :hyp." fnname hyp)
*default-returnspec*)
((mv hints hintsp)
(if (assoc :hints kwd-alist)
(mv (cdr (assoc :hints kwd-alist)) t)
(mv nil nil)))
(rule-classes (if (assoc :rule-classes kwd-alist)
(cdr (assoc :rule-classes kwd-alist))
:rewrite))
(thm-name (if (assoc :name kwd-alist)
(cdr (assoc :name kwd-alist))
nil))
((mv terms docs)
(parse-returnspec-items fnname varname other-opts nil nil))
(return-type
(cond ((atom terms) ;; no return-type terms, fine, default is t
t)
((atom (cdr terms))
(car terms))
(t
(raise "Error in ~x0: return specifier ~x1 has multiple return ~
type terms, but at most one is allowed: ~&2"
fnname varname terms))))
(xdoc
(cond ((atom docs) ;; no documentation, go figure, default is ""
"")
((atom (cdr docs))
(car docs))
(t
(progn$
(raise "Error in ~x0: return specifier ~x1 has multiple xdoc ~
strings, but at most one is allowed: ~x2."
fnname varname terms)
"")))))
(make-returnspec :name varname
:doc xdoc
:return-type return-type
:rule-classes rule-classes
:hyp hyp
:hints hints
:hintsp hintsp
:thm-name thm-name)))
(defun parse-returnspecs-aux (fnname x world)
"Returns a returnspeclist-p"
;; Assumes they've already been normalized...
(declare (xargs :guard (plist-worldp world)))
(if (atom x)
nil
(cons (parse-returnspec fnname (car x) world)
(parse-returnspecs-aux fnname (cdr x) world))))
(defun normalize-returnspecs (fnname x)
;; We support two forms of returns:
;; :returns return-spec
;; :returns (mv return-spec ... return-spec)
;; We require that return-value names are never MV, so we can just check for MV to
;; tell thich kind of return spec we are dealing with.
;; This function just converts either form into a list of return specs
;; with no MV part.
(declare (xargs :guard t))
(b* ((__function__ 'normalize-returnspecs)
((unless x)
;; Fine, no return spec
nil)
((when (eq x 'mv))
(raise "Error in ~x0: :returns may not be just MV." fnname))
((when (symbolp x))
;; Fine
(list x))
((when (atom x))
(raise "Error in ~x0: :returns may not be ~x1." fnname x))
((when (eq (car x) 'mv))
(if (true-listp (cdr x))
(cdr x)
(raise "Error in ~x0: :returns must be nil-terminated." fnname x))))
(list x)))
(defun parse-returnspecs (fnname x world)
"Returns a returnspeclist-p"
(declare (xargs :guard (plist-worldp world)))
(parse-returnspecs-aux fnname
(normalize-returnspecs fnname x)
world))
(defun arity-check-returns (name name-fn specs world)
(declare (xargs :guard (and (symbolp name)
(symbolp name-fn)
(returnspeclist-p specs)
(plist-worldp world))))
(b* (((when (atom specs))
;; Fine, the user just didn't name/document the return values.
t)
(stobjs-out (look-up-return-vals name-fn world))
((when (equal (len stobjs-out) (len specs)))
;; Fine, arity looks OK.
t)
((when (getprop name-fn 'acl2::non-executablep nil 'acl2::current-acl2-world world))
;; The function is non-executable so stobjs-out doesn't necessarily say
;; anything coherent, nothing to really check.
t))
(er hard? 'arity-check-returns
"Error in ~x0: ACL2 thinks this function has ~x1 return ~
values, but :returns has ~x2 entries!"
name
(len stobjs-out)
(len specs))))
(defsection untranslate-and
(defun untranslate-and (x)
(declare (xargs :guard t))
(cond ((atom x)
;; (and x) --> x
(list x))
((and (consp x)
(eq (first x) 'if)
(equal (len x) 4)
(equal (fourth x) ''nil))
;; (and x y ...) --> (if x (and y ...) nil)
(cons (second x)
(untranslate-and (third x))))
(t
(list x))))
(local
(progn
(assert! (equal (untranslate-and 'x) '(x)))
(assert! (equal (untranslate-and 't) '(t)))
(assert! (equal (untranslate-and '(if x y z)) '((if x y z))))
(assert! (equal (untranslate-and '(if x y 'nil)) '(x y)))
(assert! (equal (untranslate-and '(if x (if a b c) 'nil)) '(x (if a b c))))
(assert! (equal (untranslate-and '(if x (if a b 'nil) 'nil)) '(x a b))))))
(defun force-each (x)
(declare (xargs :guard t))
(if (atom x)
nil
(cons `(force ,(car x))
(force-each (cdr x)))))
(defun fancy-force-hyp (x)
(declare (xargs :guard t))
(b* ((hyp-list (untranslate-and x)))
(cons 'and (force-each hyp-list))))
(defun fancy-hyp (x)
(declare (xargs :guard t))
(b* ((hyp-list (untranslate-and x)))
(cons 'and hyp-list)))
(defun returnspec-thm-body (fnname binds x world)
(declare (xargs :guard (and (symbolp fnname)
(returnspec-p x)
(plist-worldp world))))
(b* (((returnspec x) x)
((when (equal x.return-type t)) t)
(hyp (cond
((eq x.hyp :guard) (fancy-hyp (look-up-guard fnname world)))
((eq x.hyp :fguard) (fancy-force-hyp (look-up-guard fnname world)))
(t x.hyp)))
(concl `(b* (,binds)
,x.return-type)))
(if (eq hyp t)
concl
`(implies ,hyp ,concl))))
(defun returnspec-generate-name (name x singlep badname-okp)
;; Get the name for a return-spec theorem.
;; Usually we can produce a good name like:
;; natp-of-fn
;; natp-of-fn.new-x
;; Or similar. But, for more complex return-types, say something like
;; (equal (len new-x) (len x))
;; we are too dumb to generate a good name.
;;
;; Badname-okp indicates whether we're willing to accept a "bad", generic
;; name of the form "return-type-of-fn" or "return-type-of-fn.new-x" or
;; similar.
;;
;; We'll tolerate bad names if the user is just giving a :returns specifier
;; in a function, mainly for backwards compatibility. (i.e., badname-okp
;; will be true).
;;
;; However, for the new, subsequent return-specs, we'll require explicit
;; names for complex conclusions. (i.e., badname-okp will be nil).
(b* (((returnspec x) x)
((when x.thm-name)
;; The user provided an explicit name, so use that.
x.thm-name)
(multi-suffix (if singlep
""
(concatenate 'string "." (symbol-name x.name))))
((when (and (tuplep 2 x.return-type)
(symbolp (first x.return-type))
(equal (second x.return-type) x.name)))
;; Simple return type like (natp ans)
(intern-in-package-of-symbol
(concatenate 'string
(symbol-name (first x.return-type))
"-OF-"
(symbol-name name)
multi-suffix)
name))
((unless badname-okp)
(er hard? 'returnspec-generate-name
"Return spec for ~x0, ~x1, must be given an explicit name."
name x.return-type)))
;; Complex return type
(intern-in-package-of-symbol
(concatenate 'string "RETURN-TYPE-OF-" (symbol-name name) multi-suffix)
name)))
(defun returnspec-default-default-hint (fnname id world)
(and (eql (len (acl2::recursivep fnname t world)) 1) ;; singly recursive
(let* ((pool-lst (acl2::access acl2::clause-id id :pool-lst)))
(and (eql 0 (acl2::access acl2::clause-id id :forcing-round))
(cond ((not pool-lst)
(let ((formals (look-up-formals fnname world)))
`(:induct (,fnname . ,formals)
:in-theory (disable (:d ,fnname)))))
((equal pool-lst '(1))
`(:computed-hint-replacement
((and stable-under-simplificationp
(expand-calls ,fnname)))
:in-theory (disable (:d ,fnname)))))))))
(defun returnspec-default-hints (fnname world)
(let ((entry (cdr (assoc 'returnspec (table-alist 'std::default-hints-table world)))))
(subst fnname 'fnname entry)))
(defmacro set-returnspec-default-hints (hint)
`(table std::default-hints-table 'returnspec ',hint))
(set-returnspec-default-hints
((returnspec-default-default-hint 'fnname acl2::id world)))
(defun returnspec-sublis (subst x)
"Like sublis, but only substitutes symbols, and looks them up both by value and by name."
(if (atom x)
(if (symbolp x)
(let ((look (assoc-equal x subst)))
(if look
(cdr look)
(let ((look (assoc-equal (symbol-name x) subst)))
(if look
(cdr look)
x))))
x)
(cons-with-hint (returnspec-sublis subst (car x))
(returnspec-sublis subst (cdr x))
x)))
(defun returnspec-single-thm (name name-fn x body-subst hint-subst badname-okp world)
"Returns EVENTS"
;; Only valid to call AFTER the function has been submitted, because we look
;; up the guard/formals from the world.
(declare (xargs :guard (and (symbolp name)
(symbolp name-fn)
(returnspec-p x)
(plist-worldp world))))
(b* (((returnspec x) x)
(formals (look-up-formals name-fn world))
(binds `(,x.name (,name-fn . ,formals)))
(formula (returnspec-sublis body-subst (returnspec-thm-body name-fn binds x world)))
((when (eq formula t)) nil)
(hints (if x.hintsp (returnspec-sublis hint-subst x.hints)
(returnspec-default-hints name-fn world))))
`((defthm ,(returnspec-generate-name name x t badname-okp)
,formula
:hints ,hints
:rule-classes ,(returnspec-sublis hint-subst x.rule-classes)))))
(defun returnspec-multi-thm (name name-fn binds x body-subst hint-subst badname-okp world)
"Returns EVENTS"
(declare (xargs :guard (and (symbolp name)
(symbolp name-fn)
(returnspec-p x)
(plist-worldp world))))
(b* (((returnspec x) x)
(formula (returnspec-sublis body-subst (returnspec-thm-body name-fn binds x world)))
((when (equal formula t)) nil)
(hints (if x.hintsp
(returnspec-sublis hint-subst x.hints)
(returnspec-default-hints name-fn world))))
`((defthm ,(returnspec-generate-name name x nil badname-okp)
,formula
:hints ,hints
:rule-classes ,(returnspec-sublis hint-subst x.rule-classes)))))
(defun returnspec-multi-thms (name name-fn binds x body-subst hint-subst badname-okp world)
"Returns EVENTS"
(declare (xargs :guard (and (symbolp name)
(symbolp name-fn)
(returnspeclist-p x)
(plist-worldp world))))
(if (atom x)
nil
(append (returnspec-multi-thm name name-fn binds (car x) body-subst hint-subst badname-okp world)
(returnspec-multi-thms name name-fn binds (cdr x) body-subst hint-subst badname-okp world))))
(defun make-symbol-ignorable (x)
(declare (xargs :guard (symbolp x)))
(intern-in-package-of-symbol
(concatenate 'string "?" (symbol-name x))
x))
(defun make-symbols-ignorable (x)
(declare (xargs :guard (symbol-listp x)))
(if (atom x)
nil
(cons (make-symbol-ignorable (car x))
(make-symbols-ignorable (cdr x)))))
(defun returnspec-mv-nth-subst (names idx call)
(if (atom names)
nil
(cons (cons (car names) `(mv-nth ,idx ,call))
(returnspec-mv-nth-subst (cdr names) (1+ idx) call))))
(defun returnspec-symbol-packages (syms)
(if (atom syms)
nil
(add-to-set-equal (symbol-package-name (car syms))
(returnspec-symbol-packages (cdr syms)))))
(defun returnspec-call-sym-pairs (packages call)
(if (atom packages)
nil
(cons (cons (intern$ "<CALL>" (car packages)) call)
(returnspec-call-sym-pairs (cdr packages) call))))
(defun returnspec-return-value-subst (name name-fn formals names)
(declare (xargs :guard (and (symbolp name)
(symbol-listp names))))
;; NOTE: These are intended for use with returnspec-sublis, which only
;; replaces symbols, but will also look up the name of a symbol. So a
;; binding whose key is a string affects all symbols with that name, whereas
;; bindings of symbols only affect those exact symbols.
(b* ((call (cons name-fn formals))
(both-subst `(("<CALL>" . ,call)
("<FN>" . ,name)
("<FN!>" . ,name-fn)
("<VALUES>" . ,names)))
((when (eql (len names) 1))
(mv both-subst (cons (cons (car names) call) both-subst))))
(mv both-subst (append both-subst (returnspec-mv-nth-subst names 0 call)))))
(defun returnspec-thms (name name-fn specs world)
"Returns EVENTS"
(declare (xargs :guard (and (symbolp name)
(symbolp name-fn)
(returnspeclist-p specs)
(plist-worldp world))))
(b* ((- (arity-check-returns name name-fn specs world))
((unless specs)
nil)
(badname-okp t)
(names (returnspeclist->names specs))
(formals (look-up-formals name-fn world))
((mv body-subst hint-subst) (returnspec-return-value-subst name name-fn formals names))
((when (equal (len specs) 1))
(returnspec-single-thm name name-fn (car specs) body-subst hint-subst badname-okp world))
(ignorable-names (make-symbols-ignorable names))
(binds `((mv . ,ignorable-names) (,name-fn . ,formals))))
(returnspec-multi-thms name name-fn binds specs body-subst hint-subst badname-okp world)))
| true |
; Standard Utilities Library
; Copyright (C) 2008-2014 Centaur Technology
;
; Contact:
; Centaur Technology Formal Verification Group
; 7600-C N. Capital of Texas Highway, Suite 300, Austin, TX 78731, USA.
; http://www.centtech.com/
;
; License: (An MIT/X11-style license)
;
; Permission is hereby granted, free of charge, to any person obtaining a
; copy of this software and associated documentation files (the "Software"),
; to deal in the Software without restriction, including without limitation
; the rights to use, copy, modify, merge, publish, distribute, sublicense,
; and/or sell copies of the Software, and to permit persons to whom the
; Software is furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in
; all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
; DEALINGS IN THE SOFTWARE.
;
; Original author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
(in-package "STD")
(include-book "da-base")
(include-book "look-up")
(local (include-book "misc/assert" :dir :system))
(program)
(defxdoc returns-specifiers
:parents (std/util define)
:short "A concise way to name, document, and prove basic type-like theorems
about a function's return values."
:long "<p>The @(see define) macro and some other @(see std/util) macros
support a @(':returns') option. This option provides a concise way to name,
document, and prove basic type-like theorems about the return values of your
functions. Named return values also allow your function to be used with the
special <see topic='@(url acl2::patbind-ret)'>ret</see> binder for @(see
b*).</p>
<p>The general form is:</p>
@({
:returns return-spec ;; for single-value functions
or :returns (mv return-spec*) ;; for multiple-valued functions
})
<p>There should be exactly one @('return-spec') per return value. Each
return-spec has the form:</p>
@({
name ;; just for naming return values
or (name [option]*) ;; for naming, documenting, and proving theorems
})
<p>where @('name') is a symbol and the options can come in any order. To
distinguish between the two forms of @(':returns'), it is not legal to use
@('mv') as the name of a return value. The options are:</p>
<dl>
<dt>@('<xdoc>'), any string literal</dt>
<dd>You can document each return value with a string literal. The string may
make use of @(see xdoc::markup) and @(see xdoc::preprocessor) directives.
Typically these descriptions should be short and not include
document-structuring tags like @('<p>'), @('<ul>'), @('<h3>'), and so forth.
See the section on xdoc integration, below, for more details.</dd>
<dt>@('<return-type>'), a symbol or term</dt>
<dd>When provided, the return type is used to generate a basic type-like
theorems about the return values.</dd>
<dd><b>Important Note</b> in the multiple-valued case, this approach assumes
you are using the @('tools/mv-nth') book. The theorems we prove target terms
like @('(mv-nth 0 (f ...))') and @('(mv-nth 1 (f ...))'). This will not work
well if @(see mv-nth) is enabled, especially about the 0th return value. For
your convenience, @('define') automatically includes the @('tools/mv-nth')
book. You really should be using it, you know.</dd>
<dd>As a convenient shorthand, you can use a single symbol like @('evenp').
The theorem to be proven in this case might be, e.g., @('(evenp (f x))') for a
single-valued function, or @('(evenp (mv-nth 3 (f x)))') if this is the
fourth (because of zero-indexing) return value of a multiply-valued function.
The symbol @('t') is explicitly allowed and results in no theorem. The symbol
@('nil') and keyword symbols are explicitly invalid as return types.</dd>
<dd>In certain cases, you may wish to prove a more complex theorem, e.g., say
we want to prove this return value is always greater than 5. To support this,
you can write a return type like @('(< 5 ans)'), where @('ans') is the
@('name') of this return value. You can also refer to the names of other
return values in this term. To make it easy to distinguish return types from
other options, the return type term must be a cons and must not begin with
@('quote').</dd>
<dt>@(':hyp hyp-term')</dt>
<dd>This option only makes sense when there is a return-type term. By default,
the return-type theorem is unconditional. If the theorem needs a hypothesis,
you can put it here.</dd>
<dd>Frequently, the hypothesis you want for a type-like theorem is for the
guards of the function to be met. As a convenient shorthand, @('hyp-term') may
be:
<ul>
<li>@(':guard') -- use the function's guard as the hypothesis</li>
<li>@(':fguard') -- like @(':guard'), but @(see force) the entire guard</li>
</ul>
If neither of these is what you want, you can provide an arbitrary
@('hyp-term'). Typically this term should mention only the formals of your
function. The return values of the theorem will not be bound in scope of the
hyp, so trying to refer to them in a hypothesis is generally an error.</dd>
<dt>@(':hints hints-term')</dt>
<dd>This option only makes sense when there is a return-type term. By default,
this is @('nil'), but when specified, the hints are passed to the proof attempt
for the associated return-type.</dd>
<dt>@(':rule-classes classes')</dt>
<dd>This option only makes sense when there is a return-type term. By default,
the return-type theorem is added as a @(':rewrite') rule. If you want to use
other @(see acl2::rule-classes), then you will want to override this default.</dd>
<dt>@(':name name')</dt>
<dd>This allows you to control the name of the associated theorem.</dd>
<dd>The default value of @('name') is <it>type</it>-of-<it>your-function</it>.
For example, @('natp-of-foo').</dd>
</dl>")
(def-primitive-aggregate returnspec
(name ; a symbol, the name of this return value
doc ; a string, "" when omitted
return-type ; t when omitted
hyp ; t when omitted
hints ; nil when omitted
hintsp ; t if hints were provided
rule-classes ; :rewrite when omitted
thm-name ; NIL (to generate a name) or the name for the theorem
)
:tag :return-spec)
(defconst *default-returnspec*
(make-returnspec :name 'ret
:doc ""
:return-type t
:hyp t
:hints nil
:hintsp nil
:rule-classes :rewrite
:thm-name nil))
(defun returnspeclist-p (x)
(declare (xargs :guard t))
(if (atom x)
t
(and (returnspec-p (car x))
(returnspeclist-p (cdr x)))))
(defun returnspeclist->names (x)
(declare (xargs :guard (returnspeclist-p x)))
(if (atom x)
nil
(cons (returnspec->name (car x))
(returnspeclist->names (cdr x)))))
; User-level syntax for returns specifiers
(defun parse-returnspec-item
(fnname ; context for error message
varname ; name of this return value
item ; item in user-level return-spec syntax after keywords are removed,
; i.e., it should be a doc string or a return-type indicator, i.e.,
; a term or a predicate name
terms ; accumulator for return-type indicators
docs ; accumulator for doc strings
)
"Returns (mv terms docs)"
(declare (xargs :guard t))
(b* ((__function__ 'parse-returnspec-item)
((when (eq item t))
;; T is explicitly allowed as a return type
(mv (cons item terms) docs))
((when (or (eq item nil)
(keywordp item)))
;; NIL/keywords are explicitly not allowed
(raise "Error in ~x0: return type for ~x1 is ~x2, which is not ~
allowed." fnname varname item)
(mv terms docs))
((when (symbolp item))
(mv (cons `(,item ,varname) terms) docs))
((when (and (consp item)
(not (eq (car item) 'quote))))
(mv (cons item terms) docs))
((when (stringp item))
(mv terms (cons item docs))))
(raise "Error in ~x0, return type for ~x1: expected return type terms or ~
documentation strings, but found ~x2." fnname varname item)
(mv terms docs)))
(defun parse-returnspec-items (fnname varname items terms docs)
"Returns (mv terms docs)"
(declare (xargs :guard t))
(b* ((__function__ 'parse-returnspec-items)
((when (not items))
(mv terms docs))
((when (atom items))
(raise "Error in ~x0: expected returnspec-items for ~x1 to be ~
nil-terminated, but found ~x2 as the final cdr."
fnname varname items)
(mv terms docs))
((mv terms docs)
(parse-returnspec-item fnname varname (car items) terms docs)))
(parse-returnspec-items fnname varname (cdr items) terms docs)))
(defun parse-returnspec
(fnname ; context for error messages
x ; actual return specifier the user provided
world ; for special extra sanity checking
)
"Returns a returnspec-p."
(declare (xargs :guard (plist-worldp world)))
(b* ((__function__ 'parse-returnspec)
((when (eq x 'mv))
(raise "Error in ~x0: return values may not be named MV." fnname)
*default-returnspec*)
((when (symbolp x))
;; Fine, just a name, no docs/type
;; A user once got very confused why :returns character-listp
;; wasn't proving that his function wasn't returning a character
;; list. So, now, make sure this isn't a defined function.
(b* ((look (getprop x 'acl2::formals :bad 'acl2::current-acl2-world world))
((unless (eq look :bad))
(raise "Error in ~x0: you named a return value ~x1, which is ~
the name of a defined function, but you don't have any ~
return type associated with this value. There's a good ~
chance this you meant this to be the return value's ~
type instead of its name.~%~%If you really want to name ~
this return value ~x1 and not prove anything about it, ~
you can use syntax like ~x2.~%" fnname x (list x t))
*default-returnspec*))
;; Else, seems fine, just a name.
(make-returnspec :name x
:doc ""
:return-type t
:rule-classes :rewrite
:hyp nil
:hints nil
:thm-name nil)))
((when (atom x))
(raise "Error in ~x0: return specifiers must be symbols or lists, but ~
found: ~x1" fnname x)
*default-returnspec*)
((cons varname options) x)
((unless (symbolp varname))
(raise "Error in ~x0: return specifiers must start with a symbol ~
name, so this return specifier is not valid: ~x1" fnname x)
*default-returnspec*)
((when (eq varname 'mv))
(raise "Error in ~x0: return values may not be named MV." fnname)
*default-returnspec*)
((mv kwd-alist other-opts)
;; bozo better context for error message here would be good
(extract-keywords fnname '(:hyp :hints :rule-classes :name) options nil))
(hyp (if (assoc :hyp kwd-alist)
(cdr (assoc :hyp kwd-alist))
t))
((when (and (keywordp hyp)
(not (eq hyp :guard))
(not (eq hyp :fguard))))
;; bozo not really a very good place to check for this.
(raise "Error in ~x0: invalid keyword ~x1 used as a :hyp." fnname hyp)
*default-returnspec*)
((mv hints hintsp)
(if (assoc :hints kwd-alist)
(mv (cdr (assoc :hints kwd-alist)) t)
(mv nil nil)))
(rule-classes (if (assoc :rule-classes kwd-alist)
(cdr (assoc :rule-classes kwd-alist))
:rewrite))
(thm-name (if (assoc :name kwd-alist)
(cdr (assoc :name kwd-alist))
nil))
((mv terms docs)
(parse-returnspec-items fnname varname other-opts nil nil))
(return-type
(cond ((atom terms) ;; no return-type terms, fine, default is t
t)
((atom (cdr terms))
(car terms))
(t
(raise "Error in ~x0: return specifier ~x1 has multiple return ~
type terms, but at most one is allowed: ~&2"
fnname varname terms))))
(xdoc
(cond ((atom docs) ;; no documentation, go figure, default is ""
"")
((atom (cdr docs))
(car docs))
(t
(progn$
(raise "Error in ~x0: return specifier ~x1 has multiple xdoc ~
strings, but at most one is allowed: ~x2."
fnname varname terms)
"")))))
(make-returnspec :name varname
:doc xdoc
:return-type return-type
:rule-classes rule-classes
:hyp hyp
:hints hints
:hintsp hintsp
:thm-name thm-name)))
(defun parse-returnspecs-aux (fnname x world)
"Returns a returnspeclist-p"
;; Assumes they've already been normalized...
(declare (xargs :guard (plist-worldp world)))
(if (atom x)
nil
(cons (parse-returnspec fnname (car x) world)
(parse-returnspecs-aux fnname (cdr x) world))))
(defun normalize-returnspecs (fnname x)
;; We support two forms of returns:
;; :returns return-spec
;; :returns (mv return-spec ... return-spec)
;; We require that return-value names are never MV, so we can just check for MV to
;; tell thich kind of return spec we are dealing with.
;; This function just converts either form into a list of return specs
;; with no MV part.
(declare (xargs :guard t))
(b* ((__function__ 'normalize-returnspecs)
((unless x)
;; Fine, no return spec
nil)
((when (eq x 'mv))
(raise "Error in ~x0: :returns may not be just MV." fnname))
((when (symbolp x))
;; Fine
(list x))
((when (atom x))
(raise "Error in ~x0: :returns may not be ~x1." fnname x))
((when (eq (car x) 'mv))
(if (true-listp (cdr x))
(cdr x)
(raise "Error in ~x0: :returns must be nil-terminated." fnname x))))
(list x)))
(defun parse-returnspecs (fnname x world)
"Returns a returnspeclist-p"
(declare (xargs :guard (plist-worldp world)))
(parse-returnspecs-aux fnname
(normalize-returnspecs fnname x)
world))
(defun arity-check-returns (name name-fn specs world)
(declare (xargs :guard (and (symbolp name)
(symbolp name-fn)
(returnspeclist-p specs)
(plist-worldp world))))
(b* (((when (atom specs))
;; Fine, the user just didn't name/document the return values.
t)
(stobjs-out (look-up-return-vals name-fn world))
((when (equal (len stobjs-out) (len specs)))
;; Fine, arity looks OK.
t)
((when (getprop name-fn 'acl2::non-executablep nil 'acl2::current-acl2-world world))
;; The function is non-executable so stobjs-out doesn't necessarily say
;; anything coherent, nothing to really check.
t))
(er hard? 'arity-check-returns
"Error in ~x0: ACL2 thinks this function has ~x1 return ~
values, but :returns has ~x2 entries!"
name
(len stobjs-out)
(len specs))))
(defsection untranslate-and
(defun untranslate-and (x)
(declare (xargs :guard t))
(cond ((atom x)
;; (and x) --> x
(list x))
((and (consp x)
(eq (first x) 'if)
(equal (len x) 4)
(equal (fourth x) ''nil))
;; (and x y ...) --> (if x (and y ...) nil)
(cons (second x)
(untranslate-and (third x))))
(t
(list x))))
(local
(progn
(assert! (equal (untranslate-and 'x) '(x)))
(assert! (equal (untranslate-and 't) '(t)))
(assert! (equal (untranslate-and '(if x y z)) '((if x y z))))
(assert! (equal (untranslate-and '(if x y 'nil)) '(x y)))
(assert! (equal (untranslate-and '(if x (if a b c) 'nil)) '(x (if a b c))))
(assert! (equal (untranslate-and '(if x (if a b 'nil) 'nil)) '(x a b))))))
(defun force-each (x)
(declare (xargs :guard t))
(if (atom x)
nil
(cons `(force ,(car x))
(force-each (cdr x)))))
(defun fancy-force-hyp (x)
(declare (xargs :guard t))
(b* ((hyp-list (untranslate-and x)))
(cons 'and (force-each hyp-list))))
(defun fancy-hyp (x)
(declare (xargs :guard t))
(b* ((hyp-list (untranslate-and x)))
(cons 'and hyp-list)))
(defun returnspec-thm-body (fnname binds x world)
(declare (xargs :guard (and (symbolp fnname)
(returnspec-p x)
(plist-worldp world))))
(b* (((returnspec x) x)
((when (equal x.return-type t)) t)
(hyp (cond
((eq x.hyp :guard) (fancy-hyp (look-up-guard fnname world)))
((eq x.hyp :fguard) (fancy-force-hyp (look-up-guard fnname world)))
(t x.hyp)))
(concl `(b* (,binds)
,x.return-type)))
(if (eq hyp t)
concl
`(implies ,hyp ,concl))))
(defun returnspec-generate-name (name x singlep badname-okp)
;; Get the name for a return-spec theorem.
;; Usually we can produce a good name like:
;; natp-of-fn
;; natp-of-fn.new-x
;; Or similar. But, for more complex return-types, say something like
;; (equal (len new-x) (len x))
;; we are too dumb to generate a good name.
;;
;; Badname-okp indicates whether we're willing to accept a "bad", generic
;; name of the form "return-type-of-fn" or "return-type-of-fn.new-x" or
;; similar.
;;
;; We'll tolerate bad names if the user is just giving a :returns specifier
;; in a function, mainly for backwards compatibility. (i.e., badname-okp
;; will be true).
;;
;; However, for the new, subsequent return-specs, we'll require explicit
;; names for complex conclusions. (i.e., badname-okp will be nil).
(b* (((returnspec x) x)
((when x.thm-name)
;; The user provided an explicit name, so use that.
x.thm-name)
(multi-suffix (if singlep
""
(concatenate 'string "." (symbol-name x.name))))
((when (and (tuplep 2 x.return-type)
(symbolp (first x.return-type))
(equal (second x.return-type) x.name)))
;; Simple return type like (natp ans)
(intern-in-package-of-symbol
(concatenate 'string
(symbol-name (first x.return-type))
"-OF-"
(symbol-name name)
multi-suffix)
name))
((unless badname-okp)
(er hard? 'returnspec-generate-name
"Return spec for ~x0, ~x1, must be given an explicit name."
name x.return-type)))
;; Complex return type
(intern-in-package-of-symbol
(concatenate 'string "RETURN-TYPE-OF-" (symbol-name name) multi-suffix)
name)))
(defun returnspec-default-default-hint (fnname id world)
(and (eql (len (acl2::recursivep fnname t world)) 1) ;; singly recursive
(let* ((pool-lst (acl2::access acl2::clause-id id :pool-lst)))
(and (eql 0 (acl2::access acl2::clause-id id :forcing-round))
(cond ((not pool-lst)
(let ((formals (look-up-formals fnname world)))
`(:induct (,fnname . ,formals)
:in-theory (disable (:d ,fnname)))))
((equal pool-lst '(1))
`(:computed-hint-replacement
((and stable-under-simplificationp
(expand-calls ,fnname)))
:in-theory (disable (:d ,fnname)))))))))
(defun returnspec-default-hints (fnname world)
(let ((entry (cdr (assoc 'returnspec (table-alist 'std::default-hints-table world)))))
(subst fnname 'fnname entry)))
(defmacro set-returnspec-default-hints (hint)
`(table std::default-hints-table 'returnspec ',hint))
(set-returnspec-default-hints
((returnspec-default-default-hint 'fnname acl2::id world)))
(defun returnspec-sublis (subst x)
"Like sublis, but only substitutes symbols, and looks them up both by value and by name."
(if (atom x)
(if (symbolp x)
(let ((look (assoc-equal x subst)))
(if look
(cdr look)
(let ((look (assoc-equal (symbol-name x) subst)))
(if look
(cdr look)
x))))
x)
(cons-with-hint (returnspec-sublis subst (car x))
(returnspec-sublis subst (cdr x))
x)))
(defun returnspec-single-thm (name name-fn x body-subst hint-subst badname-okp world)
"Returns EVENTS"
;; Only valid to call AFTER the function has been submitted, because we look
;; up the guard/formals from the world.
(declare (xargs :guard (and (symbolp name)
(symbolp name-fn)
(returnspec-p x)
(plist-worldp world))))
(b* (((returnspec x) x)
(formals (look-up-formals name-fn world))
(binds `(,x.name (,name-fn . ,formals)))
(formula (returnspec-sublis body-subst (returnspec-thm-body name-fn binds x world)))
((when (eq formula t)) nil)
(hints (if x.hintsp (returnspec-sublis hint-subst x.hints)
(returnspec-default-hints name-fn world))))
`((defthm ,(returnspec-generate-name name x t badname-okp)
,formula
:hints ,hints
:rule-classes ,(returnspec-sublis hint-subst x.rule-classes)))))
(defun returnspec-multi-thm (name name-fn binds x body-subst hint-subst badname-okp world)
"Returns EVENTS"
(declare (xargs :guard (and (symbolp name)
(symbolp name-fn)
(returnspec-p x)
(plist-worldp world))))
(b* (((returnspec x) x)
(formula (returnspec-sublis body-subst (returnspec-thm-body name-fn binds x world)))
((when (equal formula t)) nil)
(hints (if x.hintsp
(returnspec-sublis hint-subst x.hints)
(returnspec-default-hints name-fn world))))
`((defthm ,(returnspec-generate-name name x nil badname-okp)
,formula
:hints ,hints
:rule-classes ,(returnspec-sublis hint-subst x.rule-classes)))))
(defun returnspec-multi-thms (name name-fn binds x body-subst hint-subst badname-okp world)
"Returns EVENTS"
(declare (xargs :guard (and (symbolp name)
(symbolp name-fn)
(returnspeclist-p x)
(plist-worldp world))))
(if (atom x)
nil
(append (returnspec-multi-thm name name-fn binds (car x) body-subst hint-subst badname-okp world)
(returnspec-multi-thms name name-fn binds (cdr x) body-subst hint-subst badname-okp world))))
(defun make-symbol-ignorable (x)
(declare (xargs :guard (symbolp x)))
(intern-in-package-of-symbol
(concatenate 'string "?" (symbol-name x))
x))
(defun make-symbols-ignorable (x)
(declare (xargs :guard (symbol-listp x)))
(if (atom x)
nil
(cons (make-symbol-ignorable (car x))
(make-symbols-ignorable (cdr x)))))
(defun returnspec-mv-nth-subst (names idx call)
(if (atom names)
nil
(cons (cons (car names) `(mv-nth ,idx ,call))
(returnspec-mv-nth-subst (cdr names) (1+ idx) call))))
(defun returnspec-symbol-packages (syms)
(if (atom syms)
nil
(add-to-set-equal (symbol-package-name (car syms))
(returnspec-symbol-packages (cdr syms)))))
(defun returnspec-call-sym-pairs (packages call)
(if (atom packages)
nil
(cons (cons (intern$ "<CALL>" (car packages)) call)
(returnspec-call-sym-pairs (cdr packages) call))))
(defun returnspec-return-value-subst (name name-fn formals names)
(declare (xargs :guard (and (symbolp name)
(symbol-listp names))))
;; NOTE: These are intended for use with returnspec-sublis, which only
;; replaces symbols, but will also look up the name of a symbol. So a
;; binding whose key is a string affects all symbols with that name, whereas
;; bindings of symbols only affect those exact symbols.
(b* ((call (cons name-fn formals))
(both-subst `(("<CALL>" . ,call)
("<FN>" . ,name)
("<FN!>" . ,name-fn)
("<VALUES>" . ,names)))
((when (eql (len names) 1))
(mv both-subst (cons (cons (car names) call) both-subst))))
(mv both-subst (append both-subst (returnspec-mv-nth-subst names 0 call)))))
(defun returnspec-thms (name name-fn specs world)
"Returns EVENTS"
(declare (xargs :guard (and (symbolp name)
(symbolp name-fn)
(returnspeclist-p specs)
(plist-worldp world))))
(b* ((- (arity-check-returns name name-fn specs world))
((unless specs)
nil)
(badname-okp t)
(names (returnspeclist->names specs))
(formals (look-up-formals name-fn world))
((mv body-subst hint-subst) (returnspec-return-value-subst name name-fn formals names))
((when (equal (len specs) 1))
(returnspec-single-thm name name-fn (car specs) body-subst hint-subst badname-okp world))
(ignorable-names (make-symbols-ignorable names))
(binds `((mv . ,ignorable-names) (,name-fn . ,formals))))
(returnspec-multi-thms name name-fn binds specs body-subst hint-subst badname-okp world)))
|
[
{
"context": "******************************\n;;;\n;;; Written by: Dan Corkill\n;;;\n;;; Copyright (C) 2003-2013, Dan Corkill <cor",
"end": 692,
"score": 0.9998806715011597,
"start": 681,
"tag": "NAME",
"value": "Dan Corkill"
},
{
"context": "n by: Dan Corkill\n;;;\n;;; Copyright (C) 2003-2013, Dan Corkill <[email protected]> \n;;;\n;;; Developed and supp",
"end": 737,
"score": 0.9998717308044434,
"start": 726,
"tag": "NAME",
"value": "Dan Corkill"
},
{
"context": "ill\n;;;\n;;; Copyright (C) 2003-2013, Dan Corkill <[email protected]> \n;;;\n;;; Developed and supported by the GBBopen ",
"end": 758,
"score": 0.9999285936355591,
"start": 739,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "enhancements, and extensions should be sent to\n;;; [email protected].\n;;;\n;;; On-line documentation for these portable",
"end": 1157,
"score": 0.9998732805252075,
"start": 1138,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "\n ;; scheduled-function)--thanks to Wendall Marvel for reporting\n ;; this bug:\n ",
"end": 8577,
"score": 0.9995514154434204,
"start": 8563,
"tag": "NAME",
"value": "Wendall Marvel"
}
] |
source/tools/scheduled-periodic-functions.lisp
|
earl-ducaine/gbbopen
| 25 |
;;;; -*- Mode:Common-Lisp; Package:PORTABLE-THREADS; Syntax:common-lisp -*-
;;;; *-* File: /usr/local/gbbopen/source/tools/scheduled-periodic-functions.lisp *-*
;;;; *-* Edited-By: cork *-*
;;;; *-* Last-Edit: Wed Oct 30 16:02:13 2013 *-*
;;;; *-* Machine: phoenix *-*
;;;; **************************************************************************
;;;; **************************************************************************
;;;; *
;;;; * Scheduled & Periodic Functions
;;;; *
;;;; **************************************************************************
;;;; **************************************************************************
;;;
;;; Written by: Dan Corkill
;;;
;;; Copyright (C) 2003-2013, Dan Corkill <[email protected]>
;;;
;;; Developed and supported by the GBBopen Project (http://GBBopen.org) and
;;; donated to the CL Gardeners portable threads initiative
;;; (http://wiki.alu.org/Portable_Threads). (Licenced under the Apache 2.0
;;; license, see http://GBBopen.org/downloads/LICENSE for license details.)
;;;
;;; Bug reports, suggestions, enhancements, and extensions should be sent to
;;; [email protected].
;;;
;;; On-line documentation for these portable thread interface entities is
;;; available at http://gbbopen.org/hyperdoc/index.html
;;;
;;; This file can be used in conjunction with the stand-alone
;;; portable-threads.lisp file (no additional libraries are requried).
;;;
;;; * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
;;;
;;; 12-18-09 Separated from portable-threads.lisp. (Corkill)
;;; 10-30-13 Retain scheduled-function in ALL-SCHEDULED-FUNCTIONS until after
;;; the scheduled execution has completed. (Corkill)
;;;
;;; * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(in-package :portable-threads)
;;; ---------------------------------------------------------------------------
(eval-when (:compile-toplevel :load-toplevel :execute)
(export '(*periodic-function-verbose*
*schedule-function-verbose*
all-scheduled-functions
#+exported-below
encode-time-of-day ; exported near the end of this file
kill-periodic-function
make-scheduled-function
nearly-forever-seconds
pause-scheduled-function-scheduler
restart-scheduled-function-scheduler
resume-scheduled-function-scheduler
schedule-function
schedule-function-relative
scheduled-function ; structure (not documented)
scheduled-function-context
scheduled-function-invocation-time
scheduled-function-marker
scheduled-function-marker-test
scheduled-function-name
scheduled-function-name-test
scheduled-function-repeat-interval
scheduled-function-scheduler-paused-p
scheduled-function-scheduler-running-p
spawn-periodic-function
unschedule-function)))
;;; ===========================================================================
;;; Scheduled Functions (built entirely on top of Portable Threads substrate)
(defstruct (scheduled-function
(:constructor %make-scheduled-function
(function name name-test marker marker-test context))
(:copier nil))
name
name-test
marker
marker-test
function
invocation-time
repeat-interval
verbose
context)
(defmethod print-object ((obj scheduled-function) stream)
(if *print-readably*
(call-next-method)
(print-unreadable-object (obj stream :type t)
(format stream "~:[<unnamed>~;~:*~s~]~@[ (marker: ~s)~] ["
(scheduled-function-name obj)
(scheduled-function-marker obj))
(pretty-invocation-time (scheduled-function-invocation-time obj)
stream)
(format stream "]"))))
;;; ---------------------------------------------------------------------------
(defparameter *month-name-vector*
(vector "Jan" "Feb" "Mar" "Apr" "May" "Jun"
"Jul" "Aug" "Sep" "Oct" "Nov" "Dec"))
;;; ---------------------------------------------------------------------------
(defun pretty-invocation-time (ut stream)
(if ut
(multiple-value-bind (isecond iminute ihour idate imonth iyear)
(decode-universal-time ut)
(declare (fixnum isecond iminute ihour idate imonth iyear))
(multiple-value-bind (second minute hour date month year)
(decode-universal-time (get-universal-time))
(declare (ignore second minute hour)
(fixnum date month year))
(cond
;; today?
((and (= date idate)
(= month imonth)
(= year iyear))
(format stream "~2,'0d:~2,'0d:~2,'0d"
ihour
iminute
isecond))
;; someday:
(t (let ((imonth-name (svref (the (simple-array t (*))
*month-name-vector*)
(the fixnum (1- imonth)))))
(format stream "~a ~d, ~d ~2,'0d:~2,'0d:~2,'0d"
imonth-name
idate
iyear
ihour
iminute
isecond))))))
(format stream "unscheduled")))
;;; ---------------------------------------------------------------------------
(defvar *scheduled-functions* nil)
(defvar *schedule-function-verbose* nil)
(defvar *scheduled-functions-paused?* nil)
#-threads-not-available
(defvar *scheduled-functions-cv* (make-condition-variable))
(defvar *scheduled-function-scheduler-thread* nil)
;;; ---------------------------------------------------------------------------
(defun all-scheduled-functions ()
;;; Returns the (unprotected) list of scheduled scheduled-functions.
*scheduled-functions*)
;;; ---------------------------------------------------------------------------
(defun make-scheduled-function (function &key
(name (and (symbolp function)
function))
(name-test #'eql)
marker
(marker-test #'eql)
context)
#+threads-not-available
(declare (ignore name name-test marker marker-test context))
#-threads-not-available
(%make-scheduled-function function name name-test marker marker-test context)
#+threads-not-available
(threads-not-available 'make-scheduled-function))
;;; ---------------------------------------------------------------------------
#-threads-not-available
(defun invoke-scheduled-function (scheduled-function)
(with-simple-restart (continue "Resume scheduled-function scheduling")
(funcall (scheduled-function-function scheduled-function)
scheduled-function)))
;;; ---------------------------------------------------------------------------
#-threads-not-available
(defun scheduled-function-scheduler ()
;;; The scheduled-function scheduler (run by the scheduled-function-scheduler
;;; thread)
(let ((scheduled-function-to-run nil))
(when *schedule-function-verbose*
(format *trace-output*
"~&;; Starting the scheduled-function scheduler...~%"))
(loop
(with-lock-held (*scheduled-functions-cv*)
(cond
;; nothing to schedule or paused, wait until signaled:
((or *scheduled-functions-paused?*
(null *scheduled-functions*))
(condition-variable-wait *scheduled-functions-cv*))
;; something to schedule:
(t (let ((invocation-time (scheduled-function-invocation-time
(first *scheduled-functions*)))
(now (get-universal-time)))
(cond
;; wait until invocation-time arrives or until signaled:
((> invocation-time now)
(condition-variable-wait-with-timeout
*scheduled-functions-cv*
(- invocation-time now))
;; recheck that any scheduled functions remain (in case we
;; have been awakened due to unscheduling the only
;; scheduled-function)--thanks to Wendall Marvel for reporting
;; this bug:
(when *scheduled-functions*
;; recheck that it's actually time to run the first
;; scheduled function (in case we have been awakened due to
;; a schedule change rather than due to reaching the
;; originally scheduled time of the next
;; scheduled-function):
(let ((invocation-time (scheduled-function-invocation-time
(first *scheduled-functions*)))
(now (get-universal-time)))
(when (<= invocation-time now)
(setf scheduled-function-to-run
(car *scheduled-functions*))))))
;; no need to wait:
(t (setf scheduled-function-to-run
(car *scheduled-functions*))))))))
;; funcall the scheduled function (outside of the CV lock):
(when scheduled-function-to-run
(unwind-protect (invoke-scheduled-function scheduled-function-to-run)
(with-lock-held (*scheduled-functions-cv*)
;; Remove the scheduled function (potentially to be reinserted if repeated):
(setf *scheduled-functions* (delete scheduled-function-to-run *scheduled-functions*
:count 1
:test #'eq))
(let ((repeat-interval (scheduled-function-repeat-interval
scheduled-function-to-run)))
(cond
;; reschedule, if a repeat interval was specified:
(repeat-interval
;; The following keeps invocations closest to intended, but
;; leads to rapidly repeating "catch up" invocations if the
;; scheduler has been blocked or terminated/restarted:
#+this-keeps-times-in-alignment
(incf (scheduled-function-invocation-time
scheduled-function-to-run)
repeat-interval)
;; This version avoids "catch up" invocations, but can drift
;; over time (we use this version):
#-this-keeps-times-in-alignment
(setf (scheduled-function-invocation-time
scheduled-function-to-run)
(+ (get-universal-time) repeat-interval))
;; Be verbose (it would be better to do this output outside of
;; the CV lock):
(when (or *schedule-function-verbose*
(scheduled-function-verbose scheduled-function-to-run))
(format *trace-output*
"~&;; Scheduling ~s~@[ (marker: ~s)~] at ~
repeat-interval ~s...~%"
scheduled-function-to-run
(scheduled-function-marker scheduled-function-to-run)
repeat-interval)
(force-output *trace-output*))
(insert-scheduled-function scheduled-function-to-run nil))
;; otherwise, clear the invocation time:
(t (setf (scheduled-function-invocation-time
scheduled-function-to-run)
nil))))
(setf scheduled-function-to-run nil)))))))
;;; ---------------------------------------------------------------------------
#-threads-not-available
(defun awaken-scheduled-function-scheduler ()
;;; Awaken the scheduled-function-scheduler thread due to a change.
;;; If the thread isn't alive, start (or restart) it up.
(if (and (threadp *scheduled-function-scheduler-thread*)
(thread-alive-p *scheduled-function-scheduler-thread*))
(condition-variable-signal *scheduled-functions-cv*)
(setf *scheduled-function-scheduler-thread*
(spawn-thread "Scheduled-Function Scheduler"
'scheduled-function-scheduler))))
;;; ---------------------------------------------------------------------------
#-threads-not-available
(defun insert-scheduled-function (scheduled-function verbose)
;;; Do the work of inserting a scheduled function into the list of
;;; *scheduled-functions*. The *scheduled-function-cv* lock must be held
;;; when calling this function.
(cond
;; empty list:
((null *scheduled-functions*)
(when verbose
(format *trace-output*
"~&;; Scheduling ~s~@[ (marker: ~s)~] as the next ~
scheduled-function...~%"
scheduled-function
(scheduled-function-marker scheduled-function))
(force-output *trace-output*))
(setf *scheduled-functions* (list scheduled-function))
;; schedule it:
(awaken-scheduled-function-scheduler))
;; find position in list:
(t (let ((invocation-time
(scheduled-function-invocation-time scheduled-function)))
(cond
;; front insertion:
((< invocation-time (scheduled-function-invocation-time
(car *scheduled-functions*)))
(when verbose
(format *trace-output*
"~&;; Scheduling ~s as the next scheduled-function...~%"
scheduled-function)
(force-output *trace-output*))
(setf *scheduled-functions*
(cons scheduled-function *scheduled-functions*))
;; schedule it:
(awaken-scheduled-function-scheduler))
;; splice into the list:
(t (when verbose
(format *trace-output*
"~&;; Adding ~s~@[ (marker: ~s)~] as a ~
scheduled-function...~%"
scheduled-function
(scheduled-function-marker scheduled-function))
(force-output *trace-output*))
(do ((sublist *scheduled-functions* (cdr sublist)))
((null (cdr sublist))
(setf (cdr sublist) (list scheduled-function)))
(when (< invocation-time
(scheduled-function-invocation-time (cadr sublist)))
(setf (cdr sublist) (cons scheduled-function (cdr sublist)))
(return)))))))))
;;; ---------------------------------------------------------------------------
#-threads-not-available
(defun delete-scheduled-function (name-or-scheduled-function marker verbose)
;;; Do the work of deleting a scheduled function from the list of
;;; *scheduled-functions*. The *scheduled-function-cv* lock must be held
;;; when calling this function.
(let ((the-deleted-scheduled-function nil))
(flet ((on-deletion (scheduled-function)
(when verbose
(format *trace-output*
"~&;; Unscheduling ~s~@[ (marker: ~s)~]...~%"
scheduled-function
marker)
(force-output *trace-output*))
;; Clear the invocation and repeat-interval values:
(setf (scheduled-function-invocation-time scheduled-function)
nil)
(setf (scheduled-function-repeat-interval scheduled-function)
nil)
;; Record the deleted function (which also returns true):
(setf the-deleted-scheduled-function scheduled-function)))
(setf *scheduled-functions*
(flet ((scheduled-function-fn (scheduled-function)
(when (eq scheduled-function name-or-scheduled-function)
(on-deletion scheduled-function)))
(scheduled-function-structure-fn (scheduled-function)
(when (and
(funcall
(scheduled-function-name-test scheduled-function)
(scheduled-function-name scheduled-function)
name-or-scheduled-function)
(funcall
(scheduled-function-marker-test scheduled-function)
marker
(scheduled-function-marker scheduled-function)))
(on-deletion scheduled-function))))
(declare (dynamic-extent #'scheduled-function-fn
#'scheduled-function-structure-fn))
(delete-if
(if (scheduled-function-p name-or-scheduled-function)
#'scheduled-function-fn
#'scheduled-function-structure-fn)
*scheduled-functions*
:count 1))))
;; return the deleted scheduled-function (or nil, if unsuccessful):
the-deleted-scheduled-function))
;;; ---------------------------------------------------------------------------
#-threads-not-available
(defun schedule-function-internal (name-or-scheduled-function marker context
context-supplied-p invocation-time
repeat-interval verbose)
(or (with-lock-held (*scheduled-functions-cv*)
(let* ((next-scheduled-function (first *scheduled-functions*))
(unscheduled-scheduled-function
(delete-scheduled-function name-or-scheduled-function marker
verbose))
(scheduled-function (or unscheduled-scheduled-function
name-or-scheduled-function)))
;; Was the specified function scheduled?
(when (scheduled-function-p scheduled-function)
(setf (scheduled-function-invocation-time scheduled-function)
invocation-time)
(setf (scheduled-function-repeat-interval scheduled-function)
repeat-interval)
(when context-supplied-p
(setf (scheduled-function-context scheduled-function) context))
(setf (scheduled-function-verbose scheduled-function) verbose)
(insert-scheduled-function scheduled-function verbose)
;; awaken scheduler if this scheduled-function was the next to be
;; run and now it is not the next to be run:
(when (and (eq next-scheduled-function scheduled-function)
(not (eq (first *scheduled-functions*)
scheduled-function)))
(awaken-scheduled-function-scheduler))
;; return success (outside of the lock):
't)))
;; warn if unable to find the scheduled function (outside of the lock):
(warn "Unable to find scheduled-function: ~s~@[ (marker: ~s)~]."
name-or-scheduled-function
marker)))
;;; ---------------------------------------------------------------------------
(defun schedule-function (name-or-scheduled-function invocation-time
&key marker
(context nil context-supplied-p)
repeat-interval
(verbose *schedule-function-verbose*))
#+threads-not-available
(declare (ignore name-or-scheduled-function invocation-time marker context
context-supplied-p repeat-interval verbose))
#-threads-not-available
(progn
(check-type invocation-time integer)
(check-type repeat-interval (or null integer))
(schedule-function-internal name-or-scheduled-function
marker
context
context-supplied-p
invocation-time
repeat-interval
verbose)
(values))
#+threads-not-available
(threads-not-available 'schedule-function))
;;; ---------------------------------------------------------------------------
(defun schedule-function-relative (name-or-scheduled-function interval
&key marker
(context nil context-supplied-p)
repeat-interval
(verbose *schedule-function-verbose*))
;;; Syntactic sugar that simply adds `interval' to the current time before
;;; scheduling the scheduled-function.
#+threads-not-available
(declare (ignore name-or-scheduled-function interval marker context
context-supplied-p repeat-interval verbose))
#-threads-not-available
(progn
(check-type interval integer)
(check-type repeat-interval (or null integer))
(schedule-function-internal name-or-scheduled-function
marker
context
context-supplied-p
(+ (get-universal-time) interval)
repeat-interval
verbose)
(values))
#+threads-not-available
(threads-not-available 'schedule-function-relative))
;;; ---------------------------------------------------------------------------
(defun unschedule-function (name-or-scheduled-function
&key marker
(warnp 't)
(verbose *schedule-function-verbose*))
#+threads-not-available
(declare (ignore name-or-scheduled-function marker warnp verbose))
#-threads-not-available
(or (with-lock-held (*scheduled-functions-cv*)
(let* ((next-scheduled-function (first *scheduled-functions*))
(unscheduled-function
(delete-scheduled-function name-or-scheduled-function marker
verbose)))
;; when unscheduled successfully:
(when unscheduled-function
;; awaken the scheduler if the next-scheduled-function became the
;; first one due to the unscheduling:
(unless (eq next-scheduled-function (first *scheduled-functions*))
(awaken-scheduled-function-scheduler))
;; return the unscheduled function if we unscheduled:
unscheduled-function)))
;; warn if unable to find the scheduled function (outside of the lock):
(when warnp
(warn "Scheduled-function ~s~@[ (marker: ~s)~] was not scheduled; ~
no action taken."
name-or-scheduled-function
marker)
;; ensure nil is returned:
nil))
#+threads-not-available
(threads-not-available 'unschedule-function))
;;; ---------------------------------------------------------------------------
(defun pause-scheduled-function-scheduler ()
#-threads-not-available
(with-lock-held (*scheduled-functions-cv*)
(when *schedule-function-verbose*
(format *trace-output*
"~&;; Pausing the scheduled-function scheduler...~%"))
(setf *scheduled-functions-paused?* 't)
(values))
#+threads-not-available
(threads-not-available 'pause-scheduled-function-scheduler))
;;; ---------------------------------------------------------------------------
(defun resume-scheduled-function-scheduler ()
#-threads-not-available
(with-lock-held (*scheduled-functions-cv*)
(when *schedule-function-verbose*
(format *trace-output*
"~&;; Resuming the scheduled-function scheduler...~%"))
(setf *scheduled-functions-paused?* nil)
(condition-variable-signal *scheduled-functions-cv*)
(values))
#+threads-not-available
(threads-not-available 'resume-scheduled-function-scheduler))
;;; ---------------------------------------------------------------------------
(defun scheduled-function-scheduler-paused-p ()
#-threads-not-available
*scheduled-functions-paused?*
#+threads-not-available
(threads-not-available 'scheduled-function-scheduler-paused-p))
;;; ---------------------------------------------------------------------------
(defun scheduled-function-scheduler-running-p ()
#-threads-not-available
(and (threadp *scheduled-function-scheduler-thread*)
(thread-alive-p *scheduled-function-scheduler-thread*))
#+threads-not-available
(threads-not-available 'scheduled-function-scheduler-running-p))
;;; ---------------------------------------------------------------------------
(defun restart-scheduled-function-scheduler ()
#-threads-not-available
(if (scheduled-function-scheduler-running-p)
(format t "~%;; The scheduled-function scheduler is already running.~%")
(with-lock-held (*scheduled-functions-cv*)
(when *schedule-function-verbose*
(format *trace-output*
"~&;; Restarting the scheduled-function scheduler...~%"))
(awaken-scheduled-function-scheduler)))
#+threads-not-available
(threads-not-available 'restart-scheduled-function-scheduler))
;;; ===========================================================================
;;; Periodic Functions (also built entirely on top of Portable Threads)
(defvar *periodic-function-verbose* nil)
;;; ---------------------------------------------------------------------------
(defun spawn-periodic-function (function interval
&key (count nil)
(name (and (symbolp function)
function))
(verbose *periodic-function-verbose*))
#+threads-not-available
(declare (ignore interval count name verbose))
#-threads-not-available
(when verbose
(format *trace-output*
"~&;; Spawning periodic-function thread for~@[ ~s~]...~%"
name)
(force-output *trace-output*))
#-threads-not-available
(spawn-thread
(format nil "Periodic Function~@[ ~a~]" name)
#'(lambda ()
(let ((*periodic-function-verbose* verbose)
(*periodic-function-name* name))
(declare (special *periodic-function-name*))
(catch 'kill-periodic-function
(loop
(when (and count (minusp (decf count)))
(return))
(sleep interval)
(with-simple-restart (continue "Resume periodic-function")
(funcall function))))
(when *periodic-function-verbose*
(format *trace-output*
"~&;; Exiting periodic-function thread~@[ ~s~]~%"
name)
(force-output *trace-output*)))))
#+threads-not-available
(threads-not-available 'spawn-periodic-function))
;;; ---------------------------------------------------------------------------
(defun kill-periodic-function ()
#-threads-not-available
(locally (declare (special *periodic-function-name*))
(handler-case
(progn
(when *periodic-function-verbose*
(format *trace-output*
"~&;; Killing periodic-function~@[ ~s~]...~%"
(and (boundp '*periodic-function-name*)
*periodic-function-name*))
(force-output *trace-output*))
(throw 'kill-periodic-function nil))
(control-error ()
(error "~s must be called within a periodic function"
'kill-periodic-function))))
#+threads-not-available
(threads-not-available 'kill-periodic-function))
;;; ===========================================================================
;;; Handy function to encode (second minute hour) time of day into a
;;; universal time. If that time has already passed, the next day is
;;; assumed.
;;;
;;; (ENCODE-TIME-OF-DAY is duplicated here (as %ENCODE-TIME-OF-DAY) from
;;; GBBopen Tools, for stand-alone use.)
(defun %encode-time-of-day (second minute hour &optional universal-time)
;; get the decoded current time of day:
(multiple-value-bind (current-second current-minute current-hour
date month year)
(if universal-time
(decode-universal-time universal-time)
(get-decoded-time))
;; substitute the supplied hour, minute, and second values:
(let ((tentative-result
(encode-universal-time second minute hour date month year)))
(flet ((seconds-into-day (hour minute second)
(the fixnum (+ (the fixnum (* (the fixnum hour) 3600))
(the fixnum (* (the fixnum minute) 60))
(the fixnum second)))))
;; if the time of day has already passed for today, assume
;; tomorrow is intended:
(if (> (seconds-into-day current-hour current-minute current-second)
(seconds-into-day hour minute second))
(+ tentative-result #.(* 60 60 24))
tentative-result)))))
;;; ---------------------------------------------------------------------------
;;; Cruft to use GBBopen Tool's ENCODE-TIME-OF-DAY, if present; otherwise,
;;; the above %ENCODE-TIME-OF-DAY definition is used:
(let* ((gbbopen-tools-package (find-package ':gbbopen-tools))
(symbol (when gbbopen-tools-package
(find-symbol (symbol-name '#:encode-time-of-day)
gbbopen-tools-package))))
(cond
((and symbol (fboundp symbol))
(import `(,symbol) gbbopen-tools-package)
(export `(,symbol) gbbopen-tools-package))
(t (setf (symbol-function (intern (symbol-name '#:encode-time-of-day)))
(symbol-function '%encode-time-of-day))
(export (list (intern (symbol-name '#:encode-time-of-day))))))
(unintern '%encode-time-of-day))
;;; ===========================================================================
;;; Scheduled/periodic-functions are fully loaded:
(pushnew ':scheduled/periodic-functions *features*)
;;; ===========================================================================
;;; End of File
;;; ===========================================================================
|
60257
|
;;;; -*- Mode:Common-Lisp; Package:PORTABLE-THREADS; Syntax:common-lisp -*-
;;;; *-* File: /usr/local/gbbopen/source/tools/scheduled-periodic-functions.lisp *-*
;;;; *-* Edited-By: cork *-*
;;;; *-* Last-Edit: Wed Oct 30 16:02:13 2013 *-*
;;;; *-* Machine: phoenix *-*
;;;; **************************************************************************
;;;; **************************************************************************
;;;; *
;;;; * Scheduled & Periodic Functions
;;;; *
;;;; **************************************************************************
;;;; **************************************************************************
;;;
;;; Written by: <NAME>
;;;
;;; Copyright (C) 2003-2013, <NAME> <<EMAIL>>
;;;
;;; Developed and supported by the GBBopen Project (http://GBBopen.org) and
;;; donated to the CL Gardeners portable threads initiative
;;; (http://wiki.alu.org/Portable_Threads). (Licenced under the Apache 2.0
;;; license, see http://GBBopen.org/downloads/LICENSE for license details.)
;;;
;;; Bug reports, suggestions, enhancements, and extensions should be sent to
;;; <EMAIL>.
;;;
;;; On-line documentation for these portable thread interface entities is
;;; available at http://gbbopen.org/hyperdoc/index.html
;;;
;;; This file can be used in conjunction with the stand-alone
;;; portable-threads.lisp file (no additional libraries are requried).
;;;
;;; * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
;;;
;;; 12-18-09 Separated from portable-threads.lisp. (Corkill)
;;; 10-30-13 Retain scheduled-function in ALL-SCHEDULED-FUNCTIONS until after
;;; the scheduled execution has completed. (Corkill)
;;;
;;; * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(in-package :portable-threads)
;;; ---------------------------------------------------------------------------
(eval-when (:compile-toplevel :load-toplevel :execute)
(export '(*periodic-function-verbose*
*schedule-function-verbose*
all-scheduled-functions
#+exported-below
encode-time-of-day ; exported near the end of this file
kill-periodic-function
make-scheduled-function
nearly-forever-seconds
pause-scheduled-function-scheduler
restart-scheduled-function-scheduler
resume-scheduled-function-scheduler
schedule-function
schedule-function-relative
scheduled-function ; structure (not documented)
scheduled-function-context
scheduled-function-invocation-time
scheduled-function-marker
scheduled-function-marker-test
scheduled-function-name
scheduled-function-name-test
scheduled-function-repeat-interval
scheduled-function-scheduler-paused-p
scheduled-function-scheduler-running-p
spawn-periodic-function
unschedule-function)))
;;; ===========================================================================
;;; Scheduled Functions (built entirely on top of Portable Threads substrate)
(defstruct (scheduled-function
(:constructor %make-scheduled-function
(function name name-test marker marker-test context))
(:copier nil))
name
name-test
marker
marker-test
function
invocation-time
repeat-interval
verbose
context)
(defmethod print-object ((obj scheduled-function) stream)
(if *print-readably*
(call-next-method)
(print-unreadable-object (obj stream :type t)
(format stream "~:[<unnamed>~;~:*~s~]~@[ (marker: ~s)~] ["
(scheduled-function-name obj)
(scheduled-function-marker obj))
(pretty-invocation-time (scheduled-function-invocation-time obj)
stream)
(format stream "]"))))
;;; ---------------------------------------------------------------------------
(defparameter *month-name-vector*
(vector "Jan" "Feb" "Mar" "Apr" "May" "Jun"
"Jul" "Aug" "Sep" "Oct" "Nov" "Dec"))
;;; ---------------------------------------------------------------------------
(defun pretty-invocation-time (ut stream)
(if ut
(multiple-value-bind (isecond iminute ihour idate imonth iyear)
(decode-universal-time ut)
(declare (fixnum isecond iminute ihour idate imonth iyear))
(multiple-value-bind (second minute hour date month year)
(decode-universal-time (get-universal-time))
(declare (ignore second minute hour)
(fixnum date month year))
(cond
;; today?
((and (= date idate)
(= month imonth)
(= year iyear))
(format stream "~2,'0d:~2,'0d:~2,'0d"
ihour
iminute
isecond))
;; someday:
(t (let ((imonth-name (svref (the (simple-array t (*))
*month-name-vector*)
(the fixnum (1- imonth)))))
(format stream "~a ~d, ~d ~2,'0d:~2,'0d:~2,'0d"
imonth-name
idate
iyear
ihour
iminute
isecond))))))
(format stream "unscheduled")))
;;; ---------------------------------------------------------------------------
(defvar *scheduled-functions* nil)
(defvar *schedule-function-verbose* nil)
(defvar *scheduled-functions-paused?* nil)
#-threads-not-available
(defvar *scheduled-functions-cv* (make-condition-variable))
(defvar *scheduled-function-scheduler-thread* nil)
;;; ---------------------------------------------------------------------------
(defun all-scheduled-functions ()
;;; Returns the (unprotected) list of scheduled scheduled-functions.
*scheduled-functions*)
;;; ---------------------------------------------------------------------------
(defun make-scheduled-function (function &key
(name (and (symbolp function)
function))
(name-test #'eql)
marker
(marker-test #'eql)
context)
#+threads-not-available
(declare (ignore name name-test marker marker-test context))
#-threads-not-available
(%make-scheduled-function function name name-test marker marker-test context)
#+threads-not-available
(threads-not-available 'make-scheduled-function))
;;; ---------------------------------------------------------------------------
#-threads-not-available
(defun invoke-scheduled-function (scheduled-function)
(with-simple-restart (continue "Resume scheduled-function scheduling")
(funcall (scheduled-function-function scheduled-function)
scheduled-function)))
;;; ---------------------------------------------------------------------------
#-threads-not-available
(defun scheduled-function-scheduler ()
;;; The scheduled-function scheduler (run by the scheduled-function-scheduler
;;; thread)
(let ((scheduled-function-to-run nil))
(when *schedule-function-verbose*
(format *trace-output*
"~&;; Starting the scheduled-function scheduler...~%"))
(loop
(with-lock-held (*scheduled-functions-cv*)
(cond
;; nothing to schedule or paused, wait until signaled:
((or *scheduled-functions-paused?*
(null *scheduled-functions*))
(condition-variable-wait *scheduled-functions-cv*))
;; something to schedule:
(t (let ((invocation-time (scheduled-function-invocation-time
(first *scheduled-functions*)))
(now (get-universal-time)))
(cond
;; wait until invocation-time arrives or until signaled:
((> invocation-time now)
(condition-variable-wait-with-timeout
*scheduled-functions-cv*
(- invocation-time now))
;; recheck that any scheduled functions remain (in case we
;; have been awakened due to unscheduling the only
;; scheduled-function)--thanks to <NAME> for reporting
;; this bug:
(when *scheduled-functions*
;; recheck that it's actually time to run the first
;; scheduled function (in case we have been awakened due to
;; a schedule change rather than due to reaching the
;; originally scheduled time of the next
;; scheduled-function):
(let ((invocation-time (scheduled-function-invocation-time
(first *scheduled-functions*)))
(now (get-universal-time)))
(when (<= invocation-time now)
(setf scheduled-function-to-run
(car *scheduled-functions*))))))
;; no need to wait:
(t (setf scheduled-function-to-run
(car *scheduled-functions*))))))))
;; funcall the scheduled function (outside of the CV lock):
(when scheduled-function-to-run
(unwind-protect (invoke-scheduled-function scheduled-function-to-run)
(with-lock-held (*scheduled-functions-cv*)
;; Remove the scheduled function (potentially to be reinserted if repeated):
(setf *scheduled-functions* (delete scheduled-function-to-run *scheduled-functions*
:count 1
:test #'eq))
(let ((repeat-interval (scheduled-function-repeat-interval
scheduled-function-to-run)))
(cond
;; reschedule, if a repeat interval was specified:
(repeat-interval
;; The following keeps invocations closest to intended, but
;; leads to rapidly repeating "catch up" invocations if the
;; scheduler has been blocked or terminated/restarted:
#+this-keeps-times-in-alignment
(incf (scheduled-function-invocation-time
scheduled-function-to-run)
repeat-interval)
;; This version avoids "catch up" invocations, but can drift
;; over time (we use this version):
#-this-keeps-times-in-alignment
(setf (scheduled-function-invocation-time
scheduled-function-to-run)
(+ (get-universal-time) repeat-interval))
;; Be verbose (it would be better to do this output outside of
;; the CV lock):
(when (or *schedule-function-verbose*
(scheduled-function-verbose scheduled-function-to-run))
(format *trace-output*
"~&;; Scheduling ~s~@[ (marker: ~s)~] at ~
repeat-interval ~s...~%"
scheduled-function-to-run
(scheduled-function-marker scheduled-function-to-run)
repeat-interval)
(force-output *trace-output*))
(insert-scheduled-function scheduled-function-to-run nil))
;; otherwise, clear the invocation time:
(t (setf (scheduled-function-invocation-time
scheduled-function-to-run)
nil))))
(setf scheduled-function-to-run nil)))))))
;;; ---------------------------------------------------------------------------
#-threads-not-available
(defun awaken-scheduled-function-scheduler ()
;;; Awaken the scheduled-function-scheduler thread due to a change.
;;; If the thread isn't alive, start (or restart) it up.
(if (and (threadp *scheduled-function-scheduler-thread*)
(thread-alive-p *scheduled-function-scheduler-thread*))
(condition-variable-signal *scheduled-functions-cv*)
(setf *scheduled-function-scheduler-thread*
(spawn-thread "Scheduled-Function Scheduler"
'scheduled-function-scheduler))))
;;; ---------------------------------------------------------------------------
#-threads-not-available
(defun insert-scheduled-function (scheduled-function verbose)
;;; Do the work of inserting a scheduled function into the list of
;;; *scheduled-functions*. The *scheduled-function-cv* lock must be held
;;; when calling this function.
(cond
;; empty list:
((null *scheduled-functions*)
(when verbose
(format *trace-output*
"~&;; Scheduling ~s~@[ (marker: ~s)~] as the next ~
scheduled-function...~%"
scheduled-function
(scheduled-function-marker scheduled-function))
(force-output *trace-output*))
(setf *scheduled-functions* (list scheduled-function))
;; schedule it:
(awaken-scheduled-function-scheduler))
;; find position in list:
(t (let ((invocation-time
(scheduled-function-invocation-time scheduled-function)))
(cond
;; front insertion:
((< invocation-time (scheduled-function-invocation-time
(car *scheduled-functions*)))
(when verbose
(format *trace-output*
"~&;; Scheduling ~s as the next scheduled-function...~%"
scheduled-function)
(force-output *trace-output*))
(setf *scheduled-functions*
(cons scheduled-function *scheduled-functions*))
;; schedule it:
(awaken-scheduled-function-scheduler))
;; splice into the list:
(t (when verbose
(format *trace-output*
"~&;; Adding ~s~@[ (marker: ~s)~] as a ~
scheduled-function...~%"
scheduled-function
(scheduled-function-marker scheduled-function))
(force-output *trace-output*))
(do ((sublist *scheduled-functions* (cdr sublist)))
((null (cdr sublist))
(setf (cdr sublist) (list scheduled-function)))
(when (< invocation-time
(scheduled-function-invocation-time (cadr sublist)))
(setf (cdr sublist) (cons scheduled-function (cdr sublist)))
(return)))))))))
;;; ---------------------------------------------------------------------------
#-threads-not-available
(defun delete-scheduled-function (name-or-scheduled-function marker verbose)
;;; Do the work of deleting a scheduled function from the list of
;;; *scheduled-functions*. The *scheduled-function-cv* lock must be held
;;; when calling this function.
(let ((the-deleted-scheduled-function nil))
(flet ((on-deletion (scheduled-function)
(when verbose
(format *trace-output*
"~&;; Unscheduling ~s~@[ (marker: ~s)~]...~%"
scheduled-function
marker)
(force-output *trace-output*))
;; Clear the invocation and repeat-interval values:
(setf (scheduled-function-invocation-time scheduled-function)
nil)
(setf (scheduled-function-repeat-interval scheduled-function)
nil)
;; Record the deleted function (which also returns true):
(setf the-deleted-scheduled-function scheduled-function)))
(setf *scheduled-functions*
(flet ((scheduled-function-fn (scheduled-function)
(when (eq scheduled-function name-or-scheduled-function)
(on-deletion scheduled-function)))
(scheduled-function-structure-fn (scheduled-function)
(when (and
(funcall
(scheduled-function-name-test scheduled-function)
(scheduled-function-name scheduled-function)
name-or-scheduled-function)
(funcall
(scheduled-function-marker-test scheduled-function)
marker
(scheduled-function-marker scheduled-function)))
(on-deletion scheduled-function))))
(declare (dynamic-extent #'scheduled-function-fn
#'scheduled-function-structure-fn))
(delete-if
(if (scheduled-function-p name-or-scheduled-function)
#'scheduled-function-fn
#'scheduled-function-structure-fn)
*scheduled-functions*
:count 1))))
;; return the deleted scheduled-function (or nil, if unsuccessful):
the-deleted-scheduled-function))
;;; ---------------------------------------------------------------------------
#-threads-not-available
(defun schedule-function-internal (name-or-scheduled-function marker context
context-supplied-p invocation-time
repeat-interval verbose)
(or (with-lock-held (*scheduled-functions-cv*)
(let* ((next-scheduled-function (first *scheduled-functions*))
(unscheduled-scheduled-function
(delete-scheduled-function name-or-scheduled-function marker
verbose))
(scheduled-function (or unscheduled-scheduled-function
name-or-scheduled-function)))
;; Was the specified function scheduled?
(when (scheduled-function-p scheduled-function)
(setf (scheduled-function-invocation-time scheduled-function)
invocation-time)
(setf (scheduled-function-repeat-interval scheduled-function)
repeat-interval)
(when context-supplied-p
(setf (scheduled-function-context scheduled-function) context))
(setf (scheduled-function-verbose scheduled-function) verbose)
(insert-scheduled-function scheduled-function verbose)
;; awaken scheduler if this scheduled-function was the next to be
;; run and now it is not the next to be run:
(when (and (eq next-scheduled-function scheduled-function)
(not (eq (first *scheduled-functions*)
scheduled-function)))
(awaken-scheduled-function-scheduler))
;; return success (outside of the lock):
't)))
;; warn if unable to find the scheduled function (outside of the lock):
(warn "Unable to find scheduled-function: ~s~@[ (marker: ~s)~]."
name-or-scheduled-function
marker)))
;;; ---------------------------------------------------------------------------
(defun schedule-function (name-or-scheduled-function invocation-time
&key marker
(context nil context-supplied-p)
repeat-interval
(verbose *schedule-function-verbose*))
#+threads-not-available
(declare (ignore name-or-scheduled-function invocation-time marker context
context-supplied-p repeat-interval verbose))
#-threads-not-available
(progn
(check-type invocation-time integer)
(check-type repeat-interval (or null integer))
(schedule-function-internal name-or-scheduled-function
marker
context
context-supplied-p
invocation-time
repeat-interval
verbose)
(values))
#+threads-not-available
(threads-not-available 'schedule-function))
;;; ---------------------------------------------------------------------------
(defun schedule-function-relative (name-or-scheduled-function interval
&key marker
(context nil context-supplied-p)
repeat-interval
(verbose *schedule-function-verbose*))
;;; Syntactic sugar that simply adds `interval' to the current time before
;;; scheduling the scheduled-function.
#+threads-not-available
(declare (ignore name-or-scheduled-function interval marker context
context-supplied-p repeat-interval verbose))
#-threads-not-available
(progn
(check-type interval integer)
(check-type repeat-interval (or null integer))
(schedule-function-internal name-or-scheduled-function
marker
context
context-supplied-p
(+ (get-universal-time) interval)
repeat-interval
verbose)
(values))
#+threads-not-available
(threads-not-available 'schedule-function-relative))
;;; ---------------------------------------------------------------------------
(defun unschedule-function (name-or-scheduled-function
&key marker
(warnp 't)
(verbose *schedule-function-verbose*))
#+threads-not-available
(declare (ignore name-or-scheduled-function marker warnp verbose))
#-threads-not-available
(or (with-lock-held (*scheduled-functions-cv*)
(let* ((next-scheduled-function (first *scheduled-functions*))
(unscheduled-function
(delete-scheduled-function name-or-scheduled-function marker
verbose)))
;; when unscheduled successfully:
(when unscheduled-function
;; awaken the scheduler if the next-scheduled-function became the
;; first one due to the unscheduling:
(unless (eq next-scheduled-function (first *scheduled-functions*))
(awaken-scheduled-function-scheduler))
;; return the unscheduled function if we unscheduled:
unscheduled-function)))
;; warn if unable to find the scheduled function (outside of the lock):
(when warnp
(warn "Scheduled-function ~s~@[ (marker: ~s)~] was not scheduled; ~
no action taken."
name-or-scheduled-function
marker)
;; ensure nil is returned:
nil))
#+threads-not-available
(threads-not-available 'unschedule-function))
;;; ---------------------------------------------------------------------------
(defun pause-scheduled-function-scheduler ()
#-threads-not-available
(with-lock-held (*scheduled-functions-cv*)
(when *schedule-function-verbose*
(format *trace-output*
"~&;; Pausing the scheduled-function scheduler...~%"))
(setf *scheduled-functions-paused?* 't)
(values))
#+threads-not-available
(threads-not-available 'pause-scheduled-function-scheduler))
;;; ---------------------------------------------------------------------------
(defun resume-scheduled-function-scheduler ()
#-threads-not-available
(with-lock-held (*scheduled-functions-cv*)
(when *schedule-function-verbose*
(format *trace-output*
"~&;; Resuming the scheduled-function scheduler...~%"))
(setf *scheduled-functions-paused?* nil)
(condition-variable-signal *scheduled-functions-cv*)
(values))
#+threads-not-available
(threads-not-available 'resume-scheduled-function-scheduler))
;;; ---------------------------------------------------------------------------
(defun scheduled-function-scheduler-paused-p ()
#-threads-not-available
*scheduled-functions-paused?*
#+threads-not-available
(threads-not-available 'scheduled-function-scheduler-paused-p))
;;; ---------------------------------------------------------------------------
(defun scheduled-function-scheduler-running-p ()
#-threads-not-available
(and (threadp *scheduled-function-scheduler-thread*)
(thread-alive-p *scheduled-function-scheduler-thread*))
#+threads-not-available
(threads-not-available 'scheduled-function-scheduler-running-p))
;;; ---------------------------------------------------------------------------
(defun restart-scheduled-function-scheduler ()
#-threads-not-available
(if (scheduled-function-scheduler-running-p)
(format t "~%;; The scheduled-function scheduler is already running.~%")
(with-lock-held (*scheduled-functions-cv*)
(when *schedule-function-verbose*
(format *trace-output*
"~&;; Restarting the scheduled-function scheduler...~%"))
(awaken-scheduled-function-scheduler)))
#+threads-not-available
(threads-not-available 'restart-scheduled-function-scheduler))
;;; ===========================================================================
;;; Periodic Functions (also built entirely on top of Portable Threads)
(defvar *periodic-function-verbose* nil)
;;; ---------------------------------------------------------------------------
(defun spawn-periodic-function (function interval
&key (count nil)
(name (and (symbolp function)
function))
(verbose *periodic-function-verbose*))
#+threads-not-available
(declare (ignore interval count name verbose))
#-threads-not-available
(when verbose
(format *trace-output*
"~&;; Spawning periodic-function thread for~@[ ~s~]...~%"
name)
(force-output *trace-output*))
#-threads-not-available
(spawn-thread
(format nil "Periodic Function~@[ ~a~]" name)
#'(lambda ()
(let ((*periodic-function-verbose* verbose)
(*periodic-function-name* name))
(declare (special *periodic-function-name*))
(catch 'kill-periodic-function
(loop
(when (and count (minusp (decf count)))
(return))
(sleep interval)
(with-simple-restart (continue "Resume periodic-function")
(funcall function))))
(when *periodic-function-verbose*
(format *trace-output*
"~&;; Exiting periodic-function thread~@[ ~s~]~%"
name)
(force-output *trace-output*)))))
#+threads-not-available
(threads-not-available 'spawn-periodic-function))
;;; ---------------------------------------------------------------------------
(defun kill-periodic-function ()
#-threads-not-available
(locally (declare (special *periodic-function-name*))
(handler-case
(progn
(when *periodic-function-verbose*
(format *trace-output*
"~&;; Killing periodic-function~@[ ~s~]...~%"
(and (boundp '*periodic-function-name*)
*periodic-function-name*))
(force-output *trace-output*))
(throw 'kill-periodic-function nil))
(control-error ()
(error "~s must be called within a periodic function"
'kill-periodic-function))))
#+threads-not-available
(threads-not-available 'kill-periodic-function))
;;; ===========================================================================
;;; Handy function to encode (second minute hour) time of day into a
;;; universal time. If that time has already passed, the next day is
;;; assumed.
;;;
;;; (ENCODE-TIME-OF-DAY is duplicated here (as %ENCODE-TIME-OF-DAY) from
;;; GBBopen Tools, for stand-alone use.)
(defun %encode-time-of-day (second minute hour &optional universal-time)
;; get the decoded current time of day:
(multiple-value-bind (current-second current-minute current-hour
date month year)
(if universal-time
(decode-universal-time universal-time)
(get-decoded-time))
;; substitute the supplied hour, minute, and second values:
(let ((tentative-result
(encode-universal-time second minute hour date month year)))
(flet ((seconds-into-day (hour minute second)
(the fixnum (+ (the fixnum (* (the fixnum hour) 3600))
(the fixnum (* (the fixnum minute) 60))
(the fixnum second)))))
;; if the time of day has already passed for today, assume
;; tomorrow is intended:
(if (> (seconds-into-day current-hour current-minute current-second)
(seconds-into-day hour minute second))
(+ tentative-result #.(* 60 60 24))
tentative-result)))))
;;; ---------------------------------------------------------------------------
;;; Cruft to use GBBopen Tool's ENCODE-TIME-OF-DAY, if present; otherwise,
;;; the above %ENCODE-TIME-OF-DAY definition is used:
(let* ((gbbopen-tools-package (find-package ':gbbopen-tools))
(symbol (when gbbopen-tools-package
(find-symbol (symbol-name '#:encode-time-of-day)
gbbopen-tools-package))))
(cond
((and symbol (fboundp symbol))
(import `(,symbol) gbbopen-tools-package)
(export `(,symbol) gbbopen-tools-package))
(t (setf (symbol-function (intern (symbol-name '#:encode-time-of-day)))
(symbol-function '%encode-time-of-day))
(export (list (intern (symbol-name '#:encode-time-of-day))))))
(unintern '%encode-time-of-day))
;;; ===========================================================================
;;; Scheduled/periodic-functions are fully loaded:
(pushnew ':scheduled/periodic-functions *features*)
;;; ===========================================================================
;;; End of File
;;; ===========================================================================
| true |
;;;; -*- Mode:Common-Lisp; Package:PORTABLE-THREADS; Syntax:common-lisp -*-
;;;; *-* File: /usr/local/gbbopen/source/tools/scheduled-periodic-functions.lisp *-*
;;;; *-* Edited-By: cork *-*
;;;; *-* Last-Edit: Wed Oct 30 16:02:13 2013 *-*
;;;; *-* Machine: phoenix *-*
;;;; **************************************************************************
;;;; **************************************************************************
;;;; *
;;;; * Scheduled & Periodic Functions
;;;; *
;;;; **************************************************************************
;;;; **************************************************************************
;;;
;;; Written by: PI:NAME:<NAME>END_PI
;;;
;;; Copyright (C) 2003-2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;;
;;; Developed and supported by the GBBopen Project (http://GBBopen.org) and
;;; donated to the CL Gardeners portable threads initiative
;;; (http://wiki.alu.org/Portable_Threads). (Licenced under the Apache 2.0
;;; license, see http://GBBopen.org/downloads/LICENSE for license details.)
;;;
;;; Bug reports, suggestions, enhancements, and extensions should be sent to
;;; PI:EMAIL:<EMAIL>END_PI.
;;;
;;; On-line documentation for these portable thread interface entities is
;;; available at http://gbbopen.org/hyperdoc/index.html
;;;
;;; This file can be used in conjunction with the stand-alone
;;; portable-threads.lisp file (no additional libraries are requried).
;;;
;;; * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
;;;
;;; 12-18-09 Separated from portable-threads.lisp. (Corkill)
;;; 10-30-13 Retain scheduled-function in ALL-SCHEDULED-FUNCTIONS until after
;;; the scheduled execution has completed. (Corkill)
;;;
;;; * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(in-package :portable-threads)
;;; ---------------------------------------------------------------------------
(eval-when (:compile-toplevel :load-toplevel :execute)
(export '(*periodic-function-verbose*
*schedule-function-verbose*
all-scheduled-functions
#+exported-below
encode-time-of-day ; exported near the end of this file
kill-periodic-function
make-scheduled-function
nearly-forever-seconds
pause-scheduled-function-scheduler
restart-scheduled-function-scheduler
resume-scheduled-function-scheduler
schedule-function
schedule-function-relative
scheduled-function ; structure (not documented)
scheduled-function-context
scheduled-function-invocation-time
scheduled-function-marker
scheduled-function-marker-test
scheduled-function-name
scheduled-function-name-test
scheduled-function-repeat-interval
scheduled-function-scheduler-paused-p
scheduled-function-scheduler-running-p
spawn-periodic-function
unschedule-function)))
;;; ===========================================================================
;;; Scheduled Functions (built entirely on top of Portable Threads substrate)
(defstruct (scheduled-function
(:constructor %make-scheduled-function
(function name name-test marker marker-test context))
(:copier nil))
name
name-test
marker
marker-test
function
invocation-time
repeat-interval
verbose
context)
(defmethod print-object ((obj scheduled-function) stream)
(if *print-readably*
(call-next-method)
(print-unreadable-object (obj stream :type t)
(format stream "~:[<unnamed>~;~:*~s~]~@[ (marker: ~s)~] ["
(scheduled-function-name obj)
(scheduled-function-marker obj))
(pretty-invocation-time (scheduled-function-invocation-time obj)
stream)
(format stream "]"))))
;;; ---------------------------------------------------------------------------
(defparameter *month-name-vector*
(vector "Jan" "Feb" "Mar" "Apr" "May" "Jun"
"Jul" "Aug" "Sep" "Oct" "Nov" "Dec"))
;;; ---------------------------------------------------------------------------
(defun pretty-invocation-time (ut stream)
(if ut
(multiple-value-bind (isecond iminute ihour idate imonth iyear)
(decode-universal-time ut)
(declare (fixnum isecond iminute ihour idate imonth iyear))
(multiple-value-bind (second minute hour date month year)
(decode-universal-time (get-universal-time))
(declare (ignore second minute hour)
(fixnum date month year))
(cond
;; today?
((and (= date idate)
(= month imonth)
(= year iyear))
(format stream "~2,'0d:~2,'0d:~2,'0d"
ihour
iminute
isecond))
;; someday:
(t (let ((imonth-name (svref (the (simple-array t (*))
*month-name-vector*)
(the fixnum (1- imonth)))))
(format stream "~a ~d, ~d ~2,'0d:~2,'0d:~2,'0d"
imonth-name
idate
iyear
ihour
iminute
isecond))))))
(format stream "unscheduled")))
;;; ---------------------------------------------------------------------------
(defvar *scheduled-functions* nil)
(defvar *schedule-function-verbose* nil)
(defvar *scheduled-functions-paused?* nil)
#-threads-not-available
(defvar *scheduled-functions-cv* (make-condition-variable))
(defvar *scheduled-function-scheduler-thread* nil)
;;; ---------------------------------------------------------------------------
(defun all-scheduled-functions ()
;;; Returns the (unprotected) list of scheduled scheduled-functions.
*scheduled-functions*)
;;; ---------------------------------------------------------------------------
(defun make-scheduled-function (function &key
(name (and (symbolp function)
function))
(name-test #'eql)
marker
(marker-test #'eql)
context)
#+threads-not-available
(declare (ignore name name-test marker marker-test context))
#-threads-not-available
(%make-scheduled-function function name name-test marker marker-test context)
#+threads-not-available
(threads-not-available 'make-scheduled-function))
;;; ---------------------------------------------------------------------------
#-threads-not-available
(defun invoke-scheduled-function (scheduled-function)
(with-simple-restart (continue "Resume scheduled-function scheduling")
(funcall (scheduled-function-function scheduled-function)
scheduled-function)))
;;; ---------------------------------------------------------------------------
#-threads-not-available
(defun scheduled-function-scheduler ()
;;; The scheduled-function scheduler (run by the scheduled-function-scheduler
;;; thread)
(let ((scheduled-function-to-run nil))
(when *schedule-function-verbose*
(format *trace-output*
"~&;; Starting the scheduled-function scheduler...~%"))
(loop
(with-lock-held (*scheduled-functions-cv*)
(cond
;; nothing to schedule or paused, wait until signaled:
((or *scheduled-functions-paused?*
(null *scheduled-functions*))
(condition-variable-wait *scheduled-functions-cv*))
;; something to schedule:
(t (let ((invocation-time (scheduled-function-invocation-time
(first *scheduled-functions*)))
(now (get-universal-time)))
(cond
;; wait until invocation-time arrives or until signaled:
((> invocation-time now)
(condition-variable-wait-with-timeout
*scheduled-functions-cv*
(- invocation-time now))
;; recheck that any scheduled functions remain (in case we
;; have been awakened due to unscheduling the only
;; scheduled-function)--thanks to PI:NAME:<NAME>END_PI for reporting
;; this bug:
(when *scheduled-functions*
;; recheck that it's actually time to run the first
;; scheduled function (in case we have been awakened due to
;; a schedule change rather than due to reaching the
;; originally scheduled time of the next
;; scheduled-function):
(let ((invocation-time (scheduled-function-invocation-time
(first *scheduled-functions*)))
(now (get-universal-time)))
(when (<= invocation-time now)
(setf scheduled-function-to-run
(car *scheduled-functions*))))))
;; no need to wait:
(t (setf scheduled-function-to-run
(car *scheduled-functions*))))))))
;; funcall the scheduled function (outside of the CV lock):
(when scheduled-function-to-run
(unwind-protect (invoke-scheduled-function scheduled-function-to-run)
(with-lock-held (*scheduled-functions-cv*)
;; Remove the scheduled function (potentially to be reinserted if repeated):
(setf *scheduled-functions* (delete scheduled-function-to-run *scheduled-functions*
:count 1
:test #'eq))
(let ((repeat-interval (scheduled-function-repeat-interval
scheduled-function-to-run)))
(cond
;; reschedule, if a repeat interval was specified:
(repeat-interval
;; The following keeps invocations closest to intended, but
;; leads to rapidly repeating "catch up" invocations if the
;; scheduler has been blocked or terminated/restarted:
#+this-keeps-times-in-alignment
(incf (scheduled-function-invocation-time
scheduled-function-to-run)
repeat-interval)
;; This version avoids "catch up" invocations, but can drift
;; over time (we use this version):
#-this-keeps-times-in-alignment
(setf (scheduled-function-invocation-time
scheduled-function-to-run)
(+ (get-universal-time) repeat-interval))
;; Be verbose (it would be better to do this output outside of
;; the CV lock):
(when (or *schedule-function-verbose*
(scheduled-function-verbose scheduled-function-to-run))
(format *trace-output*
"~&;; Scheduling ~s~@[ (marker: ~s)~] at ~
repeat-interval ~s...~%"
scheduled-function-to-run
(scheduled-function-marker scheduled-function-to-run)
repeat-interval)
(force-output *trace-output*))
(insert-scheduled-function scheduled-function-to-run nil))
;; otherwise, clear the invocation time:
(t (setf (scheduled-function-invocation-time
scheduled-function-to-run)
nil))))
(setf scheduled-function-to-run nil)))))))
;;; ---------------------------------------------------------------------------
#-threads-not-available
(defun awaken-scheduled-function-scheduler ()
;;; Awaken the scheduled-function-scheduler thread due to a change.
;;; If the thread isn't alive, start (or restart) it up.
(if (and (threadp *scheduled-function-scheduler-thread*)
(thread-alive-p *scheduled-function-scheduler-thread*))
(condition-variable-signal *scheduled-functions-cv*)
(setf *scheduled-function-scheduler-thread*
(spawn-thread "Scheduled-Function Scheduler"
'scheduled-function-scheduler))))
;;; ---------------------------------------------------------------------------
#-threads-not-available
(defun insert-scheduled-function (scheduled-function verbose)
;;; Do the work of inserting a scheduled function into the list of
;;; *scheduled-functions*. The *scheduled-function-cv* lock must be held
;;; when calling this function.
(cond
;; empty list:
((null *scheduled-functions*)
(when verbose
(format *trace-output*
"~&;; Scheduling ~s~@[ (marker: ~s)~] as the next ~
scheduled-function...~%"
scheduled-function
(scheduled-function-marker scheduled-function))
(force-output *trace-output*))
(setf *scheduled-functions* (list scheduled-function))
;; schedule it:
(awaken-scheduled-function-scheduler))
;; find position in list:
(t (let ((invocation-time
(scheduled-function-invocation-time scheduled-function)))
(cond
;; front insertion:
((< invocation-time (scheduled-function-invocation-time
(car *scheduled-functions*)))
(when verbose
(format *trace-output*
"~&;; Scheduling ~s as the next scheduled-function...~%"
scheduled-function)
(force-output *trace-output*))
(setf *scheduled-functions*
(cons scheduled-function *scheduled-functions*))
;; schedule it:
(awaken-scheduled-function-scheduler))
;; splice into the list:
(t (when verbose
(format *trace-output*
"~&;; Adding ~s~@[ (marker: ~s)~] as a ~
scheduled-function...~%"
scheduled-function
(scheduled-function-marker scheduled-function))
(force-output *trace-output*))
(do ((sublist *scheduled-functions* (cdr sublist)))
((null (cdr sublist))
(setf (cdr sublist) (list scheduled-function)))
(when (< invocation-time
(scheduled-function-invocation-time (cadr sublist)))
(setf (cdr sublist) (cons scheduled-function (cdr sublist)))
(return)))))))))
;;; ---------------------------------------------------------------------------
#-threads-not-available
(defun delete-scheduled-function (name-or-scheduled-function marker verbose)
;;; Do the work of deleting a scheduled function from the list of
;;; *scheduled-functions*. The *scheduled-function-cv* lock must be held
;;; when calling this function.
(let ((the-deleted-scheduled-function nil))
(flet ((on-deletion (scheduled-function)
(when verbose
(format *trace-output*
"~&;; Unscheduling ~s~@[ (marker: ~s)~]...~%"
scheduled-function
marker)
(force-output *trace-output*))
;; Clear the invocation and repeat-interval values:
(setf (scheduled-function-invocation-time scheduled-function)
nil)
(setf (scheduled-function-repeat-interval scheduled-function)
nil)
;; Record the deleted function (which also returns true):
(setf the-deleted-scheduled-function scheduled-function)))
(setf *scheduled-functions*
(flet ((scheduled-function-fn (scheduled-function)
(when (eq scheduled-function name-or-scheduled-function)
(on-deletion scheduled-function)))
(scheduled-function-structure-fn (scheduled-function)
(when (and
(funcall
(scheduled-function-name-test scheduled-function)
(scheduled-function-name scheduled-function)
name-or-scheduled-function)
(funcall
(scheduled-function-marker-test scheduled-function)
marker
(scheduled-function-marker scheduled-function)))
(on-deletion scheduled-function))))
(declare (dynamic-extent #'scheduled-function-fn
#'scheduled-function-structure-fn))
(delete-if
(if (scheduled-function-p name-or-scheduled-function)
#'scheduled-function-fn
#'scheduled-function-structure-fn)
*scheduled-functions*
:count 1))))
;; return the deleted scheduled-function (or nil, if unsuccessful):
the-deleted-scheduled-function))
;;; ---------------------------------------------------------------------------
#-threads-not-available
(defun schedule-function-internal (name-or-scheduled-function marker context
context-supplied-p invocation-time
repeat-interval verbose)
(or (with-lock-held (*scheduled-functions-cv*)
(let* ((next-scheduled-function (first *scheduled-functions*))
(unscheduled-scheduled-function
(delete-scheduled-function name-or-scheduled-function marker
verbose))
(scheduled-function (or unscheduled-scheduled-function
name-or-scheduled-function)))
;; Was the specified function scheduled?
(when (scheduled-function-p scheduled-function)
(setf (scheduled-function-invocation-time scheduled-function)
invocation-time)
(setf (scheduled-function-repeat-interval scheduled-function)
repeat-interval)
(when context-supplied-p
(setf (scheduled-function-context scheduled-function) context))
(setf (scheduled-function-verbose scheduled-function) verbose)
(insert-scheduled-function scheduled-function verbose)
;; awaken scheduler if this scheduled-function was the next to be
;; run and now it is not the next to be run:
(when (and (eq next-scheduled-function scheduled-function)
(not (eq (first *scheduled-functions*)
scheduled-function)))
(awaken-scheduled-function-scheduler))
;; return success (outside of the lock):
't)))
;; warn if unable to find the scheduled function (outside of the lock):
(warn "Unable to find scheduled-function: ~s~@[ (marker: ~s)~]."
name-or-scheduled-function
marker)))
;;; ---------------------------------------------------------------------------
(defun schedule-function (name-or-scheduled-function invocation-time
&key marker
(context nil context-supplied-p)
repeat-interval
(verbose *schedule-function-verbose*))
#+threads-not-available
(declare (ignore name-or-scheduled-function invocation-time marker context
context-supplied-p repeat-interval verbose))
#-threads-not-available
(progn
(check-type invocation-time integer)
(check-type repeat-interval (or null integer))
(schedule-function-internal name-or-scheduled-function
marker
context
context-supplied-p
invocation-time
repeat-interval
verbose)
(values))
#+threads-not-available
(threads-not-available 'schedule-function))
;;; ---------------------------------------------------------------------------
(defun schedule-function-relative (name-or-scheduled-function interval
&key marker
(context nil context-supplied-p)
repeat-interval
(verbose *schedule-function-verbose*))
;;; Syntactic sugar that simply adds `interval' to the current time before
;;; scheduling the scheduled-function.
#+threads-not-available
(declare (ignore name-or-scheduled-function interval marker context
context-supplied-p repeat-interval verbose))
#-threads-not-available
(progn
(check-type interval integer)
(check-type repeat-interval (or null integer))
(schedule-function-internal name-or-scheduled-function
marker
context
context-supplied-p
(+ (get-universal-time) interval)
repeat-interval
verbose)
(values))
#+threads-not-available
(threads-not-available 'schedule-function-relative))
;;; ---------------------------------------------------------------------------
(defun unschedule-function (name-or-scheduled-function
&key marker
(warnp 't)
(verbose *schedule-function-verbose*))
#+threads-not-available
(declare (ignore name-or-scheduled-function marker warnp verbose))
#-threads-not-available
(or (with-lock-held (*scheduled-functions-cv*)
(let* ((next-scheduled-function (first *scheduled-functions*))
(unscheduled-function
(delete-scheduled-function name-or-scheduled-function marker
verbose)))
;; when unscheduled successfully:
(when unscheduled-function
;; awaken the scheduler if the next-scheduled-function became the
;; first one due to the unscheduling:
(unless (eq next-scheduled-function (first *scheduled-functions*))
(awaken-scheduled-function-scheduler))
;; return the unscheduled function if we unscheduled:
unscheduled-function)))
;; warn if unable to find the scheduled function (outside of the lock):
(when warnp
(warn "Scheduled-function ~s~@[ (marker: ~s)~] was not scheduled; ~
no action taken."
name-or-scheduled-function
marker)
;; ensure nil is returned:
nil))
#+threads-not-available
(threads-not-available 'unschedule-function))
;;; ---------------------------------------------------------------------------
(defun pause-scheduled-function-scheduler ()
#-threads-not-available
(with-lock-held (*scheduled-functions-cv*)
(when *schedule-function-verbose*
(format *trace-output*
"~&;; Pausing the scheduled-function scheduler...~%"))
(setf *scheduled-functions-paused?* 't)
(values))
#+threads-not-available
(threads-not-available 'pause-scheduled-function-scheduler))
;;; ---------------------------------------------------------------------------
(defun resume-scheduled-function-scheduler ()
#-threads-not-available
(with-lock-held (*scheduled-functions-cv*)
(when *schedule-function-verbose*
(format *trace-output*
"~&;; Resuming the scheduled-function scheduler...~%"))
(setf *scheduled-functions-paused?* nil)
(condition-variable-signal *scheduled-functions-cv*)
(values))
#+threads-not-available
(threads-not-available 'resume-scheduled-function-scheduler))
;;; ---------------------------------------------------------------------------
(defun scheduled-function-scheduler-paused-p ()
#-threads-not-available
*scheduled-functions-paused?*
#+threads-not-available
(threads-not-available 'scheduled-function-scheduler-paused-p))
;;; ---------------------------------------------------------------------------
(defun scheduled-function-scheduler-running-p ()
#-threads-not-available
(and (threadp *scheduled-function-scheduler-thread*)
(thread-alive-p *scheduled-function-scheduler-thread*))
#+threads-not-available
(threads-not-available 'scheduled-function-scheduler-running-p))
;;; ---------------------------------------------------------------------------
(defun restart-scheduled-function-scheduler ()
#-threads-not-available
(if (scheduled-function-scheduler-running-p)
(format t "~%;; The scheduled-function scheduler is already running.~%")
(with-lock-held (*scheduled-functions-cv*)
(when *schedule-function-verbose*
(format *trace-output*
"~&;; Restarting the scheduled-function scheduler...~%"))
(awaken-scheduled-function-scheduler)))
#+threads-not-available
(threads-not-available 'restart-scheduled-function-scheduler))
;;; ===========================================================================
;;; Periodic Functions (also built entirely on top of Portable Threads)
(defvar *periodic-function-verbose* nil)
;;; ---------------------------------------------------------------------------
(defun spawn-periodic-function (function interval
&key (count nil)
(name (and (symbolp function)
function))
(verbose *periodic-function-verbose*))
#+threads-not-available
(declare (ignore interval count name verbose))
#-threads-not-available
(when verbose
(format *trace-output*
"~&;; Spawning periodic-function thread for~@[ ~s~]...~%"
name)
(force-output *trace-output*))
#-threads-not-available
(spawn-thread
(format nil "Periodic Function~@[ ~a~]" name)
#'(lambda ()
(let ((*periodic-function-verbose* verbose)
(*periodic-function-name* name))
(declare (special *periodic-function-name*))
(catch 'kill-periodic-function
(loop
(when (and count (minusp (decf count)))
(return))
(sleep interval)
(with-simple-restart (continue "Resume periodic-function")
(funcall function))))
(when *periodic-function-verbose*
(format *trace-output*
"~&;; Exiting periodic-function thread~@[ ~s~]~%"
name)
(force-output *trace-output*)))))
#+threads-not-available
(threads-not-available 'spawn-periodic-function))
;;; ---------------------------------------------------------------------------
(defun kill-periodic-function ()
#-threads-not-available
(locally (declare (special *periodic-function-name*))
(handler-case
(progn
(when *periodic-function-verbose*
(format *trace-output*
"~&;; Killing periodic-function~@[ ~s~]...~%"
(and (boundp '*periodic-function-name*)
*periodic-function-name*))
(force-output *trace-output*))
(throw 'kill-periodic-function nil))
(control-error ()
(error "~s must be called within a periodic function"
'kill-periodic-function))))
#+threads-not-available
(threads-not-available 'kill-periodic-function))
;;; ===========================================================================
;;; Handy function to encode (second minute hour) time of day into a
;;; universal time. If that time has already passed, the next day is
;;; assumed.
;;;
;;; (ENCODE-TIME-OF-DAY is duplicated here (as %ENCODE-TIME-OF-DAY) from
;;; GBBopen Tools, for stand-alone use.)
(defun %encode-time-of-day (second minute hour &optional universal-time)
;; get the decoded current time of day:
(multiple-value-bind (current-second current-minute current-hour
date month year)
(if universal-time
(decode-universal-time universal-time)
(get-decoded-time))
;; substitute the supplied hour, minute, and second values:
(let ((tentative-result
(encode-universal-time second minute hour date month year)))
(flet ((seconds-into-day (hour minute second)
(the fixnum (+ (the fixnum (* (the fixnum hour) 3600))
(the fixnum (* (the fixnum minute) 60))
(the fixnum second)))))
;; if the time of day has already passed for today, assume
;; tomorrow is intended:
(if (> (seconds-into-day current-hour current-minute current-second)
(seconds-into-day hour minute second))
(+ tentative-result #.(* 60 60 24))
tentative-result)))))
;;; ---------------------------------------------------------------------------
;;; Cruft to use GBBopen Tool's ENCODE-TIME-OF-DAY, if present; otherwise,
;;; the above %ENCODE-TIME-OF-DAY definition is used:
(let* ((gbbopen-tools-package (find-package ':gbbopen-tools))
(symbol (when gbbopen-tools-package
(find-symbol (symbol-name '#:encode-time-of-day)
gbbopen-tools-package))))
(cond
((and symbol (fboundp symbol))
(import `(,symbol) gbbopen-tools-package)
(export `(,symbol) gbbopen-tools-package))
(t (setf (symbol-function (intern (symbol-name '#:encode-time-of-day)))
(symbol-function '%encode-time-of-day))
(export (list (intern (symbol-name '#:encode-time-of-day))))))
(unintern '%encode-time-of-day))
;;; ===========================================================================
;;; Scheduled/periodic-functions are fully loaded:
(pushnew ':scheduled/periodic-functions *features*)
;;; ===========================================================================
;;; End of File
;;; ===========================================================================
|
[
{
"context": ";-*- Mode: Lisp -*-\n;;;; Author: Paul Dietz\n;;;; Created: Tue Jan 13 20:09:50 2004\n;;;; Cont",
"end": 49,
"score": 0.9998613595962524,
"start": 39,
"tag": "NAME",
"value": "Paul Dietz"
}
] |
programs/ansi-test/streams/stream-element-type.lsp
|
TeamSPoon/wam_common_lisp_devel_workspace
| 8 |
;-*- Mode: Lisp -*-
;;;; Author: Paul Dietz
;;;; Created: Tue Jan 13 20:09:50 2004
;;;; Contains: Tests for STREAM-ELEMENT-TYPE
(in-package :cl-test)
(deftest stream-element-type.1
(loop for s in (list *debug-io* *error-output* *query-io*
*standard-input* *standard-output*
*trace-output* *terminal-io*)
for results = (multiple-value-list (stream-element-type s))
unless (and (eql (length results) 1)
(car results))
collect s)
nil)
(deftest stream-element-type.2
(let ((pn "foo.txt"))
(loop for i from 1 to 100
for etype = `(unsigned-byte ,i)
for s = (progn (delete-all-versions pn)
(open pn :direction :output
:element-type etype))
unless
(multiple-value-bind (sub good)
(subtypep etype (stream-element-type s))
(close s)
(or sub (not good)))
collect i))
nil)
(deftest stream-element-type.3
(let ((pn "foo.txt"))
(loop for i from 1 to 100
for etype = `(signed-byte ,i)
for s = (progn (delete-all-versions pn)
(open pn :direction :output
:element-type etype))
unless
(multiple-value-bind (sub good)
(subtypep etype (stream-element-type s))
(close s)
(or sub (not good)))
collect i))
nil)
(deftest stream-element-type.4
(let ((pn "foo.txt"))
(loop for i from 1 to 100
for etype = `(integer 0 ,i)
for s = (progn (delete-all-versions pn)
(open pn :direction :output
:element-type etype))
unless
(multiple-value-bind (sub good)
(subtypep etype (stream-element-type s))
(close s)
(or sub (not good)))
collect i))
nil)
(deftest stream-element-type.5
:notes (:assume-no-simple-streams)
(let ((pn "foo.txt"))
(delete-all-versions pn)
(let ((s (open pn :direction :output)))
(let ((etype (stream-element-type s)))
(unwind-protect
(equalt (multiple-value-list (subtypep* 'character etype))
'(nil t))
(close s)))))
nil)
(deftest stream-element-type.6
:notes (:assume-no-simple-streams)
(let ((pn "foo.txt"))
(delete-all-versions pn)
(let ((s (open pn :direction :output
:element-type :default)))
(let ((etype (stream-element-type s)))
(unwind-protect
(multiple-value-bind (sub1 good1) (subtypep* etype 'integer)
(multiple-value-bind (sub2 good2) (subtypep* etype 'character)
(or (not good1)
(not good2)
sub1 sub2)))
(close s)))))
t)
(deftest stream-element-type.error.1
(signals-error (stream-element-type) program-error)
t)
(deftest stream-element-type.error.2
(signals-error (stream-element-type *standard-input* nil) program-error)
t)
(deftest stream-element-type.error.3
(check-type-error #'stream-element-type #'streamp)
nil)
|
6101
|
;-*- Mode: Lisp -*-
;;;; Author: <NAME>
;;;; Created: Tue Jan 13 20:09:50 2004
;;;; Contains: Tests for STREAM-ELEMENT-TYPE
(in-package :cl-test)
(deftest stream-element-type.1
(loop for s in (list *debug-io* *error-output* *query-io*
*standard-input* *standard-output*
*trace-output* *terminal-io*)
for results = (multiple-value-list (stream-element-type s))
unless (and (eql (length results) 1)
(car results))
collect s)
nil)
(deftest stream-element-type.2
(let ((pn "foo.txt"))
(loop for i from 1 to 100
for etype = `(unsigned-byte ,i)
for s = (progn (delete-all-versions pn)
(open pn :direction :output
:element-type etype))
unless
(multiple-value-bind (sub good)
(subtypep etype (stream-element-type s))
(close s)
(or sub (not good)))
collect i))
nil)
(deftest stream-element-type.3
(let ((pn "foo.txt"))
(loop for i from 1 to 100
for etype = `(signed-byte ,i)
for s = (progn (delete-all-versions pn)
(open pn :direction :output
:element-type etype))
unless
(multiple-value-bind (sub good)
(subtypep etype (stream-element-type s))
(close s)
(or sub (not good)))
collect i))
nil)
(deftest stream-element-type.4
(let ((pn "foo.txt"))
(loop for i from 1 to 100
for etype = `(integer 0 ,i)
for s = (progn (delete-all-versions pn)
(open pn :direction :output
:element-type etype))
unless
(multiple-value-bind (sub good)
(subtypep etype (stream-element-type s))
(close s)
(or sub (not good)))
collect i))
nil)
(deftest stream-element-type.5
:notes (:assume-no-simple-streams)
(let ((pn "foo.txt"))
(delete-all-versions pn)
(let ((s (open pn :direction :output)))
(let ((etype (stream-element-type s)))
(unwind-protect
(equalt (multiple-value-list (subtypep* 'character etype))
'(nil t))
(close s)))))
nil)
(deftest stream-element-type.6
:notes (:assume-no-simple-streams)
(let ((pn "foo.txt"))
(delete-all-versions pn)
(let ((s (open pn :direction :output
:element-type :default)))
(let ((etype (stream-element-type s)))
(unwind-protect
(multiple-value-bind (sub1 good1) (subtypep* etype 'integer)
(multiple-value-bind (sub2 good2) (subtypep* etype 'character)
(or (not good1)
(not good2)
sub1 sub2)))
(close s)))))
t)
(deftest stream-element-type.error.1
(signals-error (stream-element-type) program-error)
t)
(deftest stream-element-type.error.2
(signals-error (stream-element-type *standard-input* nil) program-error)
t)
(deftest stream-element-type.error.3
(check-type-error #'stream-element-type #'streamp)
nil)
| true |
;-*- Mode: Lisp -*-
;;;; Author: PI:NAME:<NAME>END_PI
;;;; Created: Tue Jan 13 20:09:50 2004
;;;; Contains: Tests for STREAM-ELEMENT-TYPE
(in-package :cl-test)
(deftest stream-element-type.1
(loop for s in (list *debug-io* *error-output* *query-io*
*standard-input* *standard-output*
*trace-output* *terminal-io*)
for results = (multiple-value-list (stream-element-type s))
unless (and (eql (length results) 1)
(car results))
collect s)
nil)
(deftest stream-element-type.2
(let ((pn "foo.txt"))
(loop for i from 1 to 100
for etype = `(unsigned-byte ,i)
for s = (progn (delete-all-versions pn)
(open pn :direction :output
:element-type etype))
unless
(multiple-value-bind (sub good)
(subtypep etype (stream-element-type s))
(close s)
(or sub (not good)))
collect i))
nil)
(deftest stream-element-type.3
(let ((pn "foo.txt"))
(loop for i from 1 to 100
for etype = `(signed-byte ,i)
for s = (progn (delete-all-versions pn)
(open pn :direction :output
:element-type etype))
unless
(multiple-value-bind (sub good)
(subtypep etype (stream-element-type s))
(close s)
(or sub (not good)))
collect i))
nil)
(deftest stream-element-type.4
(let ((pn "foo.txt"))
(loop for i from 1 to 100
for etype = `(integer 0 ,i)
for s = (progn (delete-all-versions pn)
(open pn :direction :output
:element-type etype))
unless
(multiple-value-bind (sub good)
(subtypep etype (stream-element-type s))
(close s)
(or sub (not good)))
collect i))
nil)
(deftest stream-element-type.5
:notes (:assume-no-simple-streams)
(let ((pn "foo.txt"))
(delete-all-versions pn)
(let ((s (open pn :direction :output)))
(let ((etype (stream-element-type s)))
(unwind-protect
(equalt (multiple-value-list (subtypep* 'character etype))
'(nil t))
(close s)))))
nil)
(deftest stream-element-type.6
:notes (:assume-no-simple-streams)
(let ((pn "foo.txt"))
(delete-all-versions pn)
(let ((s (open pn :direction :output
:element-type :default)))
(let ((etype (stream-element-type s)))
(unwind-protect
(multiple-value-bind (sub1 good1) (subtypep* etype 'integer)
(multiple-value-bind (sub2 good2) (subtypep* etype 'character)
(or (not good1)
(not good2)
sub1 sub2)))
(close s)))))
t)
(deftest stream-element-type.error.1
(signals-error (stream-element-type) program-error)
t)
(deftest stream-element-type.error.2
(signals-error (stream-element-type *standard-input* nil) program-error)
t)
(deftest stream-element-type.error.3
(check-type-error #'stream-element-type #'streamp)
nil)
|
[
{
"context": ";;;;\n;;;\n;; @file use-nleq.lisp\n;; @author Mitch Richling <https://www.mitchr.me>\n;; @brief Non-linear ",
"end": 306,
"score": 0.9998891353607178,
"start": 292,
"tag": "NAME",
"value": "Mitch Richling"
},
{
"context": "rblock\n;; Copyright (c) 1997,1998,2004,2013,2015, Mitchell Jay Richling <https://www.mitchr.me> All rights reserved.\n;;\n;",
"end": 530,
"score": 0.9998918771743774,
"start": 509,
"tag": "NAME",
"value": "Mitchell Jay Richling"
}
] |
use-nleq.lisp
|
richmit/mjrcalc
| 17 |
;; -*- Mode:Lisp; Syntax:ANSI-Common-LISP; Coding:us-ascii-unix; fill-column:158 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;; @file use-nleq.lisp
;; @author Mitch Richling <https://www.mitchr.me>
;; @brief Non-linear equation root finding.@EOL
;; @std Common Lisp
;; @see tst-nleq.lisp
;; @copyright
;; @parblock
;; Copyright (c) 1997,1998,2004,2013,2015, Mitchell Jay Richling <https://www.mitchr.me> All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
;;
;; 1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer.
;;
;; 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;;
;; 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software
;; without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
;; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
;; OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
;; DAMAGE.
;; @endparblock
;; @todo Expose mjr_nleq_infix-string-to-diff-lambda -- it may be usefull in other packages, like :MJR_FSAMP.@EOL@EOL
;; @todo Rethink the way the functions in this package exit. No more "errors"! Just return enough data to the caller so that it can figure out what
;; happened, and behave appropriately. This will transform these functions into something that works better as a library. I still want this to
;; work well interactively, so the returns must be meaningful and human readable.
;; Perhaps (values WHY best-x-guess y-value-at-best-x-guess ..).@EOL@EOL
;; @todo Create a function like mjr_nleq_infix-string-to-diff-lambda, but that works with use-ndiff.lisp to compute.@EOL@EOL
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defpackage :MJR_NLEQ
(:USE :COMMON-LISP
:MJR_EPS
:MJR_CHK
:MJR_CMP
:MJR_MXP
:MJR_CAS)
(:DOCUMENTATION "Brief: Non-linear equation root finding.;")
(:EXPORT #:mjr_nleq_help
#:mjr_nleq_root-bsect
#:mjr_nleq_root-newton
#:mjr_nleq_root-laguerre
#:mjr_nleq_fixed-point-itr
;; Helpers
;; #:mjr_nleq_infix-string-to-diff-lambda
))
(in-package :MJR_NLEQ)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_nleq_help ()
"Functions in this package attempt to localize a solution/root of a given function.
The functions return the following values: x-best-guess fun-value-at-x-best-guess reason-for-search-ended
If a solution/root was found (i.e. fun-value-at-x-best-guess was within :YEPS of zero), then reason-for-search-ended will NIL. Any other
value (which will be an informative string) requires a closer examination of x-best-guess fun-value-at-x-best-guess before one can
determine if they are acceptable."
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_nleq_infix-string-to-diff-lambda (the-string var num-diff)
"Take an MXP infix string, and return a lambda acceptable for MJR_NLEQ_ROOT-NEWTON or MJR_NLEQ_ROOT-LAGUERRE.
If THE-STRING is not a string, then THE-STRING is returned as is.
If THE-STRING contains the sub-string 'values(', it is assumed that the expression returns the required derivatives. Otherwise
it is assumed to be F only, and symbolic derivatives are taken before the lambda is constructed."
(if (stringp the-string)
(if (search "values(" the-string)
(mjr_mxp_tree-to-lambda (mjr_mxp_infix-to-tree the-string) var)
(mjr_mxp_trees-to-values-lambda (mjr_cas_diff-list (mjr_mxp_infix-to-tree the-string) var num-diff) (list var)))
the-string))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_nleq_root-bsect (f x0 x1 &key (xeps 0.0001) (yeps 0.0001) (max-itr 1000) (show-progress nil) (use-false-position nil))
"Use bisection, or false position if :USE-FALSE-POSITION is non-NIL, to localize a root of FUN between X0 and X1.
See mjr_nleq_help for a description of the three value return from this function.
While :USE-FALSE-POSITION is normally faster than regular bisection, it can fail to make progress in cases where regular bisection would have worked. This is
because the new x value can be too close to a boundary and trigger an exit on XEPS or YEPS."
;; Maxima code for computing false position.
;; (%i69) eq:y=m*x+b;
;; (%o69) y = m*x+b
;; (%i70) solve(subst(y=0, subst(solve([subst([x=x1, y=y1], eq), subst([x=x2,y=y2], eq)], [m, b]), eq)), x);
;; (%o70) [x = (x1*y2-x2*y1)/(y2-y1)]
(let ((f (mjr_nleq_infix-string-to-diff-lambda f "x" 0)))
(flet ((nxt-x (x0 x1 y0 y1) (let ((fpc (if (and use-false-position (mjr_chk_!= y1 y0))
(/ (- (* x0 y1) (* x1 y0)) (- y1 y0)))))
(if (and fpc (not (mjr_eps_= x0 fpc xeps)) (not (mjr_eps_= x1 fpc xeps)))
fpc
(/ (+ x0 x1) 2)))))
(loop with y0 = (funcall f x0)
with y1 = (funcall f x1)
with x-cur = (nxt-x x0 x1 y0 y1)
with x-old = nil
with y-old = nil
for i-cur from 0
do (let ((y-cur (funcall f x-cur)))
(if (mjr_eps_=0 y-cur yeps) (return (values x-cur y-cur nil)))
(if (and x-old (mjr_eps_= x-cur x-old xeps)) (return (values x-cur y-cur "X-DELTA=0")))
(if (mjr_eps_= x0 x1 xeps) (return (values x-cur y-cur "X0=X1")))
(if (mjr_eps_= x0 x-cur xeps) (return (values x-cur y-cur "X0=X")))
(if (mjr_eps_= x1 x-cur xeps) (return (values x-cur y-cur "X1=X")))
(if (mjr_eps_= y0 y1 yeps) (return (values x-cur y-cur "Y0=Y1")))
(if (mjr_eps_= y0 y-cur yeps) (return (values x-cur y-cur "Y0=Y")))
(if (mjr_eps_= y1 y-cur yeps) (return (values x-cur y-cur "Y1=Y")))
(if show-progress
(format 't "~5d ~60@s ~60@s ~%" i-cur x-cur y-cur))
(setf x-old x-cur)
(cond ((mjr_cmp_< y0 y1) (if (mjr_cmp_< y-cur 0)
(setq x0 x-cur y0 y-cur)
(setq x1 x-cur y1 y-cur)))
((mjr_cmp_> y0 y1) (if (mjr_cmp_< y-cur 0)
(setq x1 x-cur y1 y-cur)
(setq x0 x-cur y0 y-cur)))
('t (return (values x-cur y-cur "Y0=Y1?"))))
(setf x-cur (nxt-x x0 x1 y0 y1))
(if (>= i-cur max-itr) (return (values x-cur y-cur "MAX-ITR")))
(if (and y-old (mjr_eps_= y-cur y-old yeps)) (return (values x-cur y-cur "Y-DELTA=0")))
(setf y-old y-cur))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_nleq_root-newton (fdf x0 &key (xeps 0.0001) (yeps 0.0001) (max-itr 1000) (show-progress nil))
"Use newton's method to localize a root of the f near (hopefully anyhow) X0. fdf returns the value of f and df/dx.
See mjr_nleq_help for a description of the three value return from this function."
(let ((fdf (mjr_nleq_infix-string-to-diff-lambda fdf "x" 1)))
(loop with x-cur = x0
with x-old = nil
with y-old = nil
for i-cur from 0
do (multiple-value-bind (y-cur df) (funcall fdf x-cur)
(if (mjr_eps_=0 y-cur yeps) (return (values x-cur y-cur nil)))
(if (mjr_eps_=0 df yeps) (return (values x-cur y-cur "dy=0")))
(if (mjr_chk_!=0 df)
(progn
(if (and x-old (mjr_eps_= x-cur x-old xeps)) (return (values x-cur y-cur "X-DELTA=0")))
(if show-progress
(format 't "~5d ~60@s ~60@s ~%" i-cur x-cur y-cur))
(setf x-old x-cur)
(setf x-cur (- x-cur (/ y-cur df)))
(if (>= i-cur max-itr) (return (values x-cur y-cur "MAX-ITR")))
(if (and y-old (mjr_eps_= y-cur y-old yeps)) (return (values x-cur y-cur "Y-DELTA=0")))
(setf y-old y-cur))
(error "ERROR: mjr_nleq_root-newton: division by zero (dy) detected. Value of YEPS may be too small."))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_nleq_root-laguerre (fdfddf n x0 &key (xeps 0.0001) (yeps 0.0001) (max-itr 1000) (show-progress nil))
"Use laguerre's method to localize a root of f near (hopefully anyhow) X0. fdfddf returns (values f df/dx ddf/dx)
N is the degree of the polynomial FUN -- or just some number bigger than 1 if FUN is not a polynomial. :)
See mjr_nleq_help for a description of the three value return from this function."
(let ((fdfddf (mjr_nleq_infix-string-to-diff-lambda fdfddf "x" 2)))
(loop with x-cur = x0
with x-old = nil
with y-old = nil
for i-cur from 0
do (multiple-value-bind (y-cur df ddf) (funcall fdfddf x-cur)
(if (mjr_eps_=0 y-cur yeps) (return (values x-cur y-cur nil)))
(if (mjr_eps_=0 df yeps) (return (values x-cur y-cur "dy=0")))
(if (and x-old (mjr_eps_= x-cur x-old xeps)) (return (values x-cur y-cur "X-DELTA=0")))
(if show-progress
(format 't "~5d ~60@s ~60@s ~%" i-cur x-cur y-cur))
(setf x-old x-cur)
(setf x-cur
(let* ((G (/ df y-cur))
(Gsq (* G G))
(H (- Gsq (/ ddf y-cur)))
(dsbp (sqrt (* (- n 1) (- (* n H) Gsq))))
(Am (mjr_cmp_abs-max (- G dsbp) (+ G dsbp))))
(- x-cur (/ n Am))))
(if (>= i-cur max-itr) (return (values x-cur y-cur "MAX-ITR")))
(if (and y-old (mjr_eps_= y-cur y-old yeps)) (return (values x-cur y-cur "Y-DELTA=0")))
(setf y-old y-cur)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_nleq_fixed-point-itr (f x0 &key (xeps 0.0001) (yeps 0.0001) (max-itr 1000) (show-progress nil))
"Use fixed point iteration to localize a a fixed point (a root of f(x)-x) near (hopefully anyhow) X0.
See mjr_nleq_help for a description of the three value return from this function."
(let ((f (mjr_nleq_infix-string-to-diff-lambda f "x" 0)))
(loop with x-cur = x0
with x-old = nil
with y-old = nil
for i-cur from 0
do (let ((y-cur (funcall f x-cur)))
(if (mjr_eps_= x-cur y-cur yeps) (return (values x-cur y-cur nil)))
(if (and x-old (mjr_eps_= x-cur x-old xeps)) (return (values x-cur y-cur "X-DELTA=0")))
(if show-progress
(format 't "~5d ~60@s ~60@s ~%" i-cur x-cur y-cur))
(setf x-old x-cur)
(setf x-cur y-cur)
(if (>= i-cur max-itr) (return (values x-cur y-cur "MAX-ITR")))
(if (and y-old (mjr_eps_= y-cur y-old yeps)) (return (values x-cur y-cur "Y-DELTA=0")))
(setf y-old y-cur)))))
|
62465
|
;; -*- Mode:Lisp; Syntax:ANSI-Common-LISP; Coding:us-ascii-unix; fill-column:158 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;; @file use-nleq.lisp
;; @author <NAME> <https://www.mitchr.me>
;; @brief Non-linear equation root finding.@EOL
;; @std Common Lisp
;; @see tst-nleq.lisp
;; @copyright
;; @parblock
;; Copyright (c) 1997,1998,2004,2013,2015, <NAME> <https://www.mitchr.me> All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
;;
;; 1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer.
;;
;; 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;;
;; 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software
;; without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
;; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
;; OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
;; DAMAGE.
;; @endparblock
;; @todo Expose mjr_nleq_infix-string-to-diff-lambda -- it may be usefull in other packages, like :MJR_FSAMP.@EOL@EOL
;; @todo Rethink the way the functions in this package exit. No more "errors"! Just return enough data to the caller so that it can figure out what
;; happened, and behave appropriately. This will transform these functions into something that works better as a library. I still want this to
;; work well interactively, so the returns must be meaningful and human readable.
;; Perhaps (values WHY best-x-guess y-value-at-best-x-guess ..).@EOL@EOL
;; @todo Create a function like mjr_nleq_infix-string-to-diff-lambda, but that works with use-ndiff.lisp to compute.@EOL@EOL
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defpackage :MJR_NLEQ
(:USE :COMMON-LISP
:MJR_EPS
:MJR_CHK
:MJR_CMP
:MJR_MXP
:MJR_CAS)
(:DOCUMENTATION "Brief: Non-linear equation root finding.;")
(:EXPORT #:mjr_nleq_help
#:mjr_nleq_root-bsect
#:mjr_nleq_root-newton
#:mjr_nleq_root-laguerre
#:mjr_nleq_fixed-point-itr
;; Helpers
;; #:mjr_nleq_infix-string-to-diff-lambda
))
(in-package :MJR_NLEQ)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_nleq_help ()
"Functions in this package attempt to localize a solution/root of a given function.
The functions return the following values: x-best-guess fun-value-at-x-best-guess reason-for-search-ended
If a solution/root was found (i.e. fun-value-at-x-best-guess was within :YEPS of zero), then reason-for-search-ended will NIL. Any other
value (which will be an informative string) requires a closer examination of x-best-guess fun-value-at-x-best-guess before one can
determine if they are acceptable."
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_nleq_infix-string-to-diff-lambda (the-string var num-diff)
"Take an MXP infix string, and return a lambda acceptable for MJR_NLEQ_ROOT-NEWTON or MJR_NLEQ_ROOT-LAGUERRE.
If THE-STRING is not a string, then THE-STRING is returned as is.
If THE-STRING contains the sub-string 'values(', it is assumed that the expression returns the required derivatives. Otherwise
it is assumed to be F only, and symbolic derivatives are taken before the lambda is constructed."
(if (stringp the-string)
(if (search "values(" the-string)
(mjr_mxp_tree-to-lambda (mjr_mxp_infix-to-tree the-string) var)
(mjr_mxp_trees-to-values-lambda (mjr_cas_diff-list (mjr_mxp_infix-to-tree the-string) var num-diff) (list var)))
the-string))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_nleq_root-bsect (f x0 x1 &key (xeps 0.0001) (yeps 0.0001) (max-itr 1000) (show-progress nil) (use-false-position nil))
"Use bisection, or false position if :USE-FALSE-POSITION is non-NIL, to localize a root of FUN between X0 and X1.
See mjr_nleq_help for a description of the three value return from this function.
While :USE-FALSE-POSITION is normally faster than regular bisection, it can fail to make progress in cases where regular bisection would have worked. This is
because the new x value can be too close to a boundary and trigger an exit on XEPS or YEPS."
;; Maxima code for computing false position.
;; (%i69) eq:y=m*x+b;
;; (%o69) y = m*x+b
;; (%i70) solve(subst(y=0, subst(solve([subst([x=x1, y=y1], eq), subst([x=x2,y=y2], eq)], [m, b]), eq)), x);
;; (%o70) [x = (x1*y2-x2*y1)/(y2-y1)]
(let ((f (mjr_nleq_infix-string-to-diff-lambda f "x" 0)))
(flet ((nxt-x (x0 x1 y0 y1) (let ((fpc (if (and use-false-position (mjr_chk_!= y1 y0))
(/ (- (* x0 y1) (* x1 y0)) (- y1 y0)))))
(if (and fpc (not (mjr_eps_= x0 fpc xeps)) (not (mjr_eps_= x1 fpc xeps)))
fpc
(/ (+ x0 x1) 2)))))
(loop with y0 = (funcall f x0)
with y1 = (funcall f x1)
with x-cur = (nxt-x x0 x1 y0 y1)
with x-old = nil
with y-old = nil
for i-cur from 0
do (let ((y-cur (funcall f x-cur)))
(if (mjr_eps_=0 y-cur yeps) (return (values x-cur y-cur nil)))
(if (and x-old (mjr_eps_= x-cur x-old xeps)) (return (values x-cur y-cur "X-DELTA=0")))
(if (mjr_eps_= x0 x1 xeps) (return (values x-cur y-cur "X0=X1")))
(if (mjr_eps_= x0 x-cur xeps) (return (values x-cur y-cur "X0=X")))
(if (mjr_eps_= x1 x-cur xeps) (return (values x-cur y-cur "X1=X")))
(if (mjr_eps_= y0 y1 yeps) (return (values x-cur y-cur "Y0=Y1")))
(if (mjr_eps_= y0 y-cur yeps) (return (values x-cur y-cur "Y0=Y")))
(if (mjr_eps_= y1 y-cur yeps) (return (values x-cur y-cur "Y1=Y")))
(if show-progress
(format 't "~5d ~60@s ~60@s ~%" i-cur x-cur y-cur))
(setf x-old x-cur)
(cond ((mjr_cmp_< y0 y1) (if (mjr_cmp_< y-cur 0)
(setq x0 x-cur y0 y-cur)
(setq x1 x-cur y1 y-cur)))
((mjr_cmp_> y0 y1) (if (mjr_cmp_< y-cur 0)
(setq x1 x-cur y1 y-cur)
(setq x0 x-cur y0 y-cur)))
('t (return (values x-cur y-cur "Y0=Y1?"))))
(setf x-cur (nxt-x x0 x1 y0 y1))
(if (>= i-cur max-itr) (return (values x-cur y-cur "MAX-ITR")))
(if (and y-old (mjr_eps_= y-cur y-old yeps)) (return (values x-cur y-cur "Y-DELTA=0")))
(setf y-old y-cur))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_nleq_root-newton (fdf x0 &key (xeps 0.0001) (yeps 0.0001) (max-itr 1000) (show-progress nil))
"Use newton's method to localize a root of the f near (hopefully anyhow) X0. fdf returns the value of f and df/dx.
See mjr_nleq_help for a description of the three value return from this function."
(let ((fdf (mjr_nleq_infix-string-to-diff-lambda fdf "x" 1)))
(loop with x-cur = x0
with x-old = nil
with y-old = nil
for i-cur from 0
do (multiple-value-bind (y-cur df) (funcall fdf x-cur)
(if (mjr_eps_=0 y-cur yeps) (return (values x-cur y-cur nil)))
(if (mjr_eps_=0 df yeps) (return (values x-cur y-cur "dy=0")))
(if (mjr_chk_!=0 df)
(progn
(if (and x-old (mjr_eps_= x-cur x-old xeps)) (return (values x-cur y-cur "X-DELTA=0")))
(if show-progress
(format 't "~5d ~60@s ~60@s ~%" i-cur x-cur y-cur))
(setf x-old x-cur)
(setf x-cur (- x-cur (/ y-cur df)))
(if (>= i-cur max-itr) (return (values x-cur y-cur "MAX-ITR")))
(if (and y-old (mjr_eps_= y-cur y-old yeps)) (return (values x-cur y-cur "Y-DELTA=0")))
(setf y-old y-cur))
(error "ERROR: mjr_nleq_root-newton: division by zero (dy) detected. Value of YEPS may be too small."))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_nleq_root-laguerre (fdfddf n x0 &key (xeps 0.0001) (yeps 0.0001) (max-itr 1000) (show-progress nil))
"Use laguerre's method to localize a root of f near (hopefully anyhow) X0. fdfddf returns (values f df/dx ddf/dx)
N is the degree of the polynomial FUN -- or just some number bigger than 1 if FUN is not a polynomial. :)
See mjr_nleq_help for a description of the three value return from this function."
(let ((fdfddf (mjr_nleq_infix-string-to-diff-lambda fdfddf "x" 2)))
(loop with x-cur = x0
with x-old = nil
with y-old = nil
for i-cur from 0
do (multiple-value-bind (y-cur df ddf) (funcall fdfddf x-cur)
(if (mjr_eps_=0 y-cur yeps) (return (values x-cur y-cur nil)))
(if (mjr_eps_=0 df yeps) (return (values x-cur y-cur "dy=0")))
(if (and x-old (mjr_eps_= x-cur x-old xeps)) (return (values x-cur y-cur "X-DELTA=0")))
(if show-progress
(format 't "~5d ~60@s ~60@s ~%" i-cur x-cur y-cur))
(setf x-old x-cur)
(setf x-cur
(let* ((G (/ df y-cur))
(Gsq (* G G))
(H (- Gsq (/ ddf y-cur)))
(dsbp (sqrt (* (- n 1) (- (* n H) Gsq))))
(Am (mjr_cmp_abs-max (- G dsbp) (+ G dsbp))))
(- x-cur (/ n Am))))
(if (>= i-cur max-itr) (return (values x-cur y-cur "MAX-ITR")))
(if (and y-old (mjr_eps_= y-cur y-old yeps)) (return (values x-cur y-cur "Y-DELTA=0")))
(setf y-old y-cur)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_nleq_fixed-point-itr (f x0 &key (xeps 0.0001) (yeps 0.0001) (max-itr 1000) (show-progress nil))
"Use fixed point iteration to localize a a fixed point (a root of f(x)-x) near (hopefully anyhow) X0.
See mjr_nleq_help for a description of the three value return from this function."
(let ((f (mjr_nleq_infix-string-to-diff-lambda f "x" 0)))
(loop with x-cur = x0
with x-old = nil
with y-old = nil
for i-cur from 0
do (let ((y-cur (funcall f x-cur)))
(if (mjr_eps_= x-cur y-cur yeps) (return (values x-cur y-cur nil)))
(if (and x-old (mjr_eps_= x-cur x-old xeps)) (return (values x-cur y-cur "X-DELTA=0")))
(if show-progress
(format 't "~5d ~60@s ~60@s ~%" i-cur x-cur y-cur))
(setf x-old x-cur)
(setf x-cur y-cur)
(if (>= i-cur max-itr) (return (values x-cur y-cur "MAX-ITR")))
(if (and y-old (mjr_eps_= y-cur y-old yeps)) (return (values x-cur y-cur "Y-DELTA=0")))
(setf y-old y-cur)))))
| true |
;; -*- Mode:Lisp; Syntax:ANSI-Common-LISP; Coding:us-ascii-unix; fill-column:158 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;; @file use-nleq.lisp
;; @author PI:NAME:<NAME>END_PI <https://www.mitchr.me>
;; @brief Non-linear equation root finding.@EOL
;; @std Common Lisp
;; @see tst-nleq.lisp
;; @copyright
;; @parblock
;; Copyright (c) 1997,1998,2004,2013,2015, PI:NAME:<NAME>END_PI <https://www.mitchr.me> All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
;;
;; 1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer.
;;
;; 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;;
;; 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software
;; without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
;; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
;; OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
;; DAMAGE.
;; @endparblock
;; @todo Expose mjr_nleq_infix-string-to-diff-lambda -- it may be usefull in other packages, like :MJR_FSAMP.@EOL@EOL
;; @todo Rethink the way the functions in this package exit. No more "errors"! Just return enough data to the caller so that it can figure out what
;; happened, and behave appropriately. This will transform these functions into something that works better as a library. I still want this to
;; work well interactively, so the returns must be meaningful and human readable.
;; Perhaps (values WHY best-x-guess y-value-at-best-x-guess ..).@EOL@EOL
;; @todo Create a function like mjr_nleq_infix-string-to-diff-lambda, but that works with use-ndiff.lisp to compute.@EOL@EOL
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defpackage :MJR_NLEQ
(:USE :COMMON-LISP
:MJR_EPS
:MJR_CHK
:MJR_CMP
:MJR_MXP
:MJR_CAS)
(:DOCUMENTATION "Brief: Non-linear equation root finding.;")
(:EXPORT #:mjr_nleq_help
#:mjr_nleq_root-bsect
#:mjr_nleq_root-newton
#:mjr_nleq_root-laguerre
#:mjr_nleq_fixed-point-itr
;; Helpers
;; #:mjr_nleq_infix-string-to-diff-lambda
))
(in-package :MJR_NLEQ)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_nleq_help ()
"Functions in this package attempt to localize a solution/root of a given function.
The functions return the following values: x-best-guess fun-value-at-x-best-guess reason-for-search-ended
If a solution/root was found (i.e. fun-value-at-x-best-guess was within :YEPS of zero), then reason-for-search-ended will NIL. Any other
value (which will be an informative string) requires a closer examination of x-best-guess fun-value-at-x-best-guess before one can
determine if they are acceptable."
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_nleq_infix-string-to-diff-lambda (the-string var num-diff)
"Take an MXP infix string, and return a lambda acceptable for MJR_NLEQ_ROOT-NEWTON or MJR_NLEQ_ROOT-LAGUERRE.
If THE-STRING is not a string, then THE-STRING is returned as is.
If THE-STRING contains the sub-string 'values(', it is assumed that the expression returns the required derivatives. Otherwise
it is assumed to be F only, and symbolic derivatives are taken before the lambda is constructed."
(if (stringp the-string)
(if (search "values(" the-string)
(mjr_mxp_tree-to-lambda (mjr_mxp_infix-to-tree the-string) var)
(mjr_mxp_trees-to-values-lambda (mjr_cas_diff-list (mjr_mxp_infix-to-tree the-string) var num-diff) (list var)))
the-string))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_nleq_root-bsect (f x0 x1 &key (xeps 0.0001) (yeps 0.0001) (max-itr 1000) (show-progress nil) (use-false-position nil))
"Use bisection, or false position if :USE-FALSE-POSITION is non-NIL, to localize a root of FUN between X0 and X1.
See mjr_nleq_help for a description of the three value return from this function.
While :USE-FALSE-POSITION is normally faster than regular bisection, it can fail to make progress in cases where regular bisection would have worked. This is
because the new x value can be too close to a boundary and trigger an exit on XEPS or YEPS."
;; Maxima code for computing false position.
;; (%i69) eq:y=m*x+b;
;; (%o69) y = m*x+b
;; (%i70) solve(subst(y=0, subst(solve([subst([x=x1, y=y1], eq), subst([x=x2,y=y2], eq)], [m, b]), eq)), x);
;; (%o70) [x = (x1*y2-x2*y1)/(y2-y1)]
(let ((f (mjr_nleq_infix-string-to-diff-lambda f "x" 0)))
(flet ((nxt-x (x0 x1 y0 y1) (let ((fpc (if (and use-false-position (mjr_chk_!= y1 y0))
(/ (- (* x0 y1) (* x1 y0)) (- y1 y0)))))
(if (and fpc (not (mjr_eps_= x0 fpc xeps)) (not (mjr_eps_= x1 fpc xeps)))
fpc
(/ (+ x0 x1) 2)))))
(loop with y0 = (funcall f x0)
with y1 = (funcall f x1)
with x-cur = (nxt-x x0 x1 y0 y1)
with x-old = nil
with y-old = nil
for i-cur from 0
do (let ((y-cur (funcall f x-cur)))
(if (mjr_eps_=0 y-cur yeps) (return (values x-cur y-cur nil)))
(if (and x-old (mjr_eps_= x-cur x-old xeps)) (return (values x-cur y-cur "X-DELTA=0")))
(if (mjr_eps_= x0 x1 xeps) (return (values x-cur y-cur "X0=X1")))
(if (mjr_eps_= x0 x-cur xeps) (return (values x-cur y-cur "X0=X")))
(if (mjr_eps_= x1 x-cur xeps) (return (values x-cur y-cur "X1=X")))
(if (mjr_eps_= y0 y1 yeps) (return (values x-cur y-cur "Y0=Y1")))
(if (mjr_eps_= y0 y-cur yeps) (return (values x-cur y-cur "Y0=Y")))
(if (mjr_eps_= y1 y-cur yeps) (return (values x-cur y-cur "Y1=Y")))
(if show-progress
(format 't "~5d ~60@s ~60@s ~%" i-cur x-cur y-cur))
(setf x-old x-cur)
(cond ((mjr_cmp_< y0 y1) (if (mjr_cmp_< y-cur 0)
(setq x0 x-cur y0 y-cur)
(setq x1 x-cur y1 y-cur)))
((mjr_cmp_> y0 y1) (if (mjr_cmp_< y-cur 0)
(setq x1 x-cur y1 y-cur)
(setq x0 x-cur y0 y-cur)))
('t (return (values x-cur y-cur "Y0=Y1?"))))
(setf x-cur (nxt-x x0 x1 y0 y1))
(if (>= i-cur max-itr) (return (values x-cur y-cur "MAX-ITR")))
(if (and y-old (mjr_eps_= y-cur y-old yeps)) (return (values x-cur y-cur "Y-DELTA=0")))
(setf y-old y-cur))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_nleq_root-newton (fdf x0 &key (xeps 0.0001) (yeps 0.0001) (max-itr 1000) (show-progress nil))
"Use newton's method to localize a root of the f near (hopefully anyhow) X0. fdf returns the value of f and df/dx.
See mjr_nleq_help for a description of the three value return from this function."
(let ((fdf (mjr_nleq_infix-string-to-diff-lambda fdf "x" 1)))
(loop with x-cur = x0
with x-old = nil
with y-old = nil
for i-cur from 0
do (multiple-value-bind (y-cur df) (funcall fdf x-cur)
(if (mjr_eps_=0 y-cur yeps) (return (values x-cur y-cur nil)))
(if (mjr_eps_=0 df yeps) (return (values x-cur y-cur "dy=0")))
(if (mjr_chk_!=0 df)
(progn
(if (and x-old (mjr_eps_= x-cur x-old xeps)) (return (values x-cur y-cur "X-DELTA=0")))
(if show-progress
(format 't "~5d ~60@s ~60@s ~%" i-cur x-cur y-cur))
(setf x-old x-cur)
(setf x-cur (- x-cur (/ y-cur df)))
(if (>= i-cur max-itr) (return (values x-cur y-cur "MAX-ITR")))
(if (and y-old (mjr_eps_= y-cur y-old yeps)) (return (values x-cur y-cur "Y-DELTA=0")))
(setf y-old y-cur))
(error "ERROR: mjr_nleq_root-newton: division by zero (dy) detected. Value of YEPS may be too small."))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_nleq_root-laguerre (fdfddf n x0 &key (xeps 0.0001) (yeps 0.0001) (max-itr 1000) (show-progress nil))
"Use laguerre's method to localize a root of f near (hopefully anyhow) X0. fdfddf returns (values f df/dx ddf/dx)
N is the degree of the polynomial FUN -- or just some number bigger than 1 if FUN is not a polynomial. :)
See mjr_nleq_help for a description of the three value return from this function."
(let ((fdfddf (mjr_nleq_infix-string-to-diff-lambda fdfddf "x" 2)))
(loop with x-cur = x0
with x-old = nil
with y-old = nil
for i-cur from 0
do (multiple-value-bind (y-cur df ddf) (funcall fdfddf x-cur)
(if (mjr_eps_=0 y-cur yeps) (return (values x-cur y-cur nil)))
(if (mjr_eps_=0 df yeps) (return (values x-cur y-cur "dy=0")))
(if (and x-old (mjr_eps_= x-cur x-old xeps)) (return (values x-cur y-cur "X-DELTA=0")))
(if show-progress
(format 't "~5d ~60@s ~60@s ~%" i-cur x-cur y-cur))
(setf x-old x-cur)
(setf x-cur
(let* ((G (/ df y-cur))
(Gsq (* G G))
(H (- Gsq (/ ddf y-cur)))
(dsbp (sqrt (* (- n 1) (- (* n H) Gsq))))
(Am (mjr_cmp_abs-max (- G dsbp) (+ G dsbp))))
(- x-cur (/ n Am))))
(if (>= i-cur max-itr) (return (values x-cur y-cur "MAX-ITR")))
(if (and y-old (mjr_eps_= y-cur y-old yeps)) (return (values x-cur y-cur "Y-DELTA=0")))
(setf y-old y-cur)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun mjr_nleq_fixed-point-itr (f x0 &key (xeps 0.0001) (yeps 0.0001) (max-itr 1000) (show-progress nil))
"Use fixed point iteration to localize a a fixed point (a root of f(x)-x) near (hopefully anyhow) X0.
See mjr_nleq_help for a description of the three value return from this function."
(let ((f (mjr_nleq_infix-string-to-diff-lambda f "x" 0)))
(loop with x-cur = x0
with x-old = nil
with y-old = nil
for i-cur from 0
do (let ((y-cur (funcall f x-cur)))
(if (mjr_eps_= x-cur y-cur yeps) (return (values x-cur y-cur nil)))
(if (and x-old (mjr_eps_= x-cur x-old xeps)) (return (values x-cur y-cur "X-DELTA=0")))
(if show-progress
(format 't "~5d ~60@s ~60@s ~%" i-cur x-cur y-cur))
(setf x-old x-cur)
(setf x-cur y-cur)
(if (>= i-cur max-itr) (return (values x-cur y-cur "MAX-ITR")))
(if (and y-old (mjr_eps_= y-cur y-old yeps)) (return (values x-cur y-cur "Y-DELTA=0")))
(setf y-old y-cur)))))
|
[
{
"context": "Lisp; Base: 10 -*-\n\n;; How to use this:\n;; \n;; Get Marc Battyani's \"cl-typesetting\" and \"cl-pdf\" packages:\n;; h",
"end": 105,
"score": 0.9183928966522217,
"start": 92,
"tag": "NAME",
"value": "Marc Battyani"
},
{
"context": "concept.com/asp/html/cl-typesetting.html\n;;\n;; and Miles Egan's xmls parser:\n;; http://common-lisp.net/",
"end": 228,
"score": 0.6205958127975464,
"start": 223,
"tag": "NAME",
"value": "Miles"
},
{
"context": "com/asp/html/cl-typesetting.html\n;;\n;; and Miles Egan's xmls parser:\n;; http://common-lisp.net/proje",
"end": 233,
"score": 0.6431013941764832,
"start": 230,
"tag": "NAME",
"value": "gan"
},
{
"context": "ystem :xml-render\n :name \"xml-render\"\n :author \"Klaus Weidner <[email protected]>\"\n :version \"2.1.1\"\n :maintain",
"end": 640,
"score": 0.9998989701271057,
"start": 627,
"tag": "NAME",
"value": "Klaus Weidner"
},
{
"context": "er\n :name \"xml-render\"\n :author \"Klaus Weidner <[email protected]>\"\n :version \"2.1.1\"\n :maintainer \"Klaus Weidner",
"end": 657,
"score": 0.9999336004257202,
"start": 642,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "[email protected]>\"\n :version \"2.1.1\"\n :maintainer \"Klaus Weidner <[email protected]>\"\n :licence \"BSD like license\"\n",
"end": 707,
"score": 0.9998998045921326,
"start": 694,
"tag": "NAME",
"value": "Klaus Weidner"
},
{
"context": "\n :version \"2.1.1\"\n :maintainer \"Klaus Weidner <[email protected]>\"\n :licence \"BSD like license\"\n :description \"n",
"end": 724,
"score": 0.9999337196350098,
"start": 709,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
contrib/xhtml-renderer/xml-render.asd
|
mbattyani/cl-typesetting
| 39 |
;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
;; How to use this:
;;
;; Get Marc Battyani's "cl-typesetting" and "cl-pdf" packages:
;; http://www.fractalconcept.com/asp/html/cl-typesetting.html
;;
;; and Miles Egan's xmls parser:
;; http://common-lisp.net/project/xmls/
;;
;; Then load this package and use as follows:
;; (tt::xhtml-to-pdf "everything.html" "/tmp/output.pdf")
;;
;; If you have clisp, you may want to use the included shell script
;; "html2pdf" for command line use. Read the script comments for more details.
(in-package :asdf)
(defsystem :xml-render
:name "xml-render"
:author "Klaus Weidner <[email protected]>"
:version "2.1.1"
:maintainer "Klaus Weidner <[email protected]>"
:licence "BSD like license"
:description "none"
:long-description ""
:perform (load-op :after (op xml-render)
(pushnew :xml-render cl:*features*))
:components ((:file "xml-xform"))
:depends-on (:cl-typesetting
:xmls))
|
50760
|
;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
;; How to use this:
;;
;; Get <NAME>'s "cl-typesetting" and "cl-pdf" packages:
;; http://www.fractalconcept.com/asp/html/cl-typesetting.html
;;
;; and <NAME> E<NAME>'s xmls parser:
;; http://common-lisp.net/project/xmls/
;;
;; Then load this package and use as follows:
;; (tt::xhtml-to-pdf "everything.html" "/tmp/output.pdf")
;;
;; If you have clisp, you may want to use the included shell script
;; "html2pdf" for command line use. Read the script comments for more details.
(in-package :asdf)
(defsystem :xml-render
:name "xml-render"
:author "<NAME> <<EMAIL>>"
:version "2.1.1"
:maintainer "<NAME> <<EMAIL>>"
:licence "BSD like license"
:description "none"
:long-description ""
:perform (load-op :after (op xml-render)
(pushnew :xml-render cl:*features*))
:components ((:file "xml-xform"))
:depends-on (:cl-typesetting
:xmls))
| true |
;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
;; How to use this:
;;
;; Get PI:NAME:<NAME>END_PI's "cl-typesetting" and "cl-pdf" packages:
;; http://www.fractalconcept.com/asp/html/cl-typesetting.html
;;
;; and PI:NAME:<NAME>END_PI EPI:NAME:<NAME>END_PI's xmls parser:
;; http://common-lisp.net/project/xmls/
;;
;; Then load this package and use as follows:
;; (tt::xhtml-to-pdf "everything.html" "/tmp/output.pdf")
;;
;; If you have clisp, you may want to use the included shell script
;; "html2pdf" for command line use. Read the script comments for more details.
(in-package :asdf)
(defsystem :xml-render
:name "xml-render"
:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:version "2.1.1"
:maintainer "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:licence "BSD like license"
:description "none"
:long-description ""
:perform (load-op :after (op xml-render)
(pushnew :xml-render cl:*features*))
:components ((:file "xml-xform"))
:depends-on (:cl-typesetting
:xmls))
|
[
{
"context": ";-*- Mode: Lisp -*-\n;;;; Author: Paul Dietz\n;;;; Created: Sun Jan 26 21:30:42 2003\n;;;; Cont",
"end": 49,
"score": 0.9998586177825928,
"start": 39,
"tag": "NAME",
"value": "Paul Dietz"
}
] |
ansi-tests/hash-table.lsp
|
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD
| 10 |
;-*- Mode: Lisp -*-
;;;; Author: Paul Dietz
;;;; Created: Sun Jan 26 21:30:42 2003
;;;; Contains: Tests of HASH-TABLE and related interface
(in-package :cl-test)
(deftest hash-table.1
(notnot-mv (find-class 'hash-table))
t)
(deftest hash-table.2
(loop for e in '(nil t 1 10.0 (a b c) #(a b c) #*1011
#0aNIL #2a((a b)(c d)) #p"foo"
"bar" #\a 3/5 #c(1.0 2.0))
when (typep e 'hash-table)
collect e)
nil)
(deftest hash-table.3
(let ((c (find-class 'hash-table)))
(loop for e in '(nil t 1 10.0 (a b c) #(a b c) #*1011
#0aNIL #2a((a b)(c d)) #p"foo"
"bar" #\a 3/5 #c(1.0 2.0))
when (typep e c)
collect e))
nil)
(deftest hash-table.4
(notnot-mv (typep (make-hash-table) 'hash-table))
t)
(deftest hash-table.5
(notnot-mv (typep (make-hash-table) (find-class 'hash-table)))
t)
|
86435
|
;-*- Mode: Lisp -*-
;;;; Author: <NAME>
;;;; Created: Sun Jan 26 21:30:42 2003
;;;; Contains: Tests of HASH-TABLE and related interface
(in-package :cl-test)
(deftest hash-table.1
(notnot-mv (find-class 'hash-table))
t)
(deftest hash-table.2
(loop for e in '(nil t 1 10.0 (a b c) #(a b c) #*1011
#0aNIL #2a((a b)(c d)) #p"foo"
"bar" #\a 3/5 #c(1.0 2.0))
when (typep e 'hash-table)
collect e)
nil)
(deftest hash-table.3
(let ((c (find-class 'hash-table)))
(loop for e in '(nil t 1 10.0 (a b c) #(a b c) #*1011
#0aNIL #2a((a b)(c d)) #p"foo"
"bar" #\a 3/5 #c(1.0 2.0))
when (typep e c)
collect e))
nil)
(deftest hash-table.4
(notnot-mv (typep (make-hash-table) 'hash-table))
t)
(deftest hash-table.5
(notnot-mv (typep (make-hash-table) (find-class 'hash-table)))
t)
| true |
;-*- Mode: Lisp -*-
;;;; Author: PI:NAME:<NAME>END_PI
;;;; Created: Sun Jan 26 21:30:42 2003
;;;; Contains: Tests of HASH-TABLE and related interface
(in-package :cl-test)
(deftest hash-table.1
(notnot-mv (find-class 'hash-table))
t)
(deftest hash-table.2
(loop for e in '(nil t 1 10.0 (a b c) #(a b c) #*1011
#0aNIL #2a((a b)(c d)) #p"foo"
"bar" #\a 3/5 #c(1.0 2.0))
when (typep e 'hash-table)
collect e)
nil)
(deftest hash-table.3
(let ((c (find-class 'hash-table)))
(loop for e in '(nil t 1 10.0 (a b c) #(a b c) #*1011
#0aNIL #2a((a b)(c d)) #p"foo"
"bar" #\a 3/5 #c(1.0 2.0))
when (typep e c)
collect e))
nil)
(deftest hash-table.4
(notnot-mv (typep (make-hash-table) 'hash-table))
t)
(deftest hash-table.5
(notnot-mv (typep (make-hash-table) (find-class 'hash-table)))
t)
|
[
{
"context": "\n :description \"Describe cl-nng here\"\n :author \"Your Name <[email protected]>\"\n :license \"Specify lic",
"end": 133,
"score": 0.9901712536811829,
"start": 124,
"tag": "NAME",
"value": "Your Name"
},
{
"context": "tion \"Describe cl-nng here\"\n :author \"Your Name <[email protected]>\"\n :license \"Specify license here\"\n :version \"",
"end": 156,
"score": 0.99991375207901,
"start": 135,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
cl-nng.asd
|
stacksmith/cl-nng
| 0 |
;;;; cl-nng.asd
(asdf:load-system '#:cffi-grovel)
(asdf:defsystem #:cl-nng
:description "Describe cl-nng here"
:author "Your Name <[email protected]>"
:license "Specify license here"
:version "0.0.1"
:serial t
:depends-on (:alexandria :cffi )
:components ((:file "package")
;; (:file "c-api")
;;(cffi-grovel:grovel-file "nng-grovel" )
(:file "lib")
(:file "cl-nng")
(:file "nng-cffi")
(:file "nng-http")
(:file "nng-main")
(:file "demo/http-client/http-client")
))
|
68292
|
;;;; cl-nng.asd
(asdf:load-system '#:cffi-grovel)
(asdf:defsystem #:cl-nng
:description "Describe cl-nng here"
:author "<NAME> <<EMAIL>>"
:license "Specify license here"
:version "0.0.1"
:serial t
:depends-on (:alexandria :cffi )
:components ((:file "package")
;; (:file "c-api")
;;(cffi-grovel:grovel-file "nng-grovel" )
(:file "lib")
(:file "cl-nng")
(:file "nng-cffi")
(:file "nng-http")
(:file "nng-main")
(:file "demo/http-client/http-client")
))
| true |
;;;; cl-nng.asd
(asdf:load-system '#:cffi-grovel)
(asdf:defsystem #:cl-nng
:description "Describe cl-nng here"
:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:license "Specify license here"
:version "0.0.1"
:serial t
:depends-on (:alexandria :cffi )
:components ((:file "package")
;; (:file "c-api")
;;(cffi-grovel:grovel-file "nng-grovel" )
(:file "lib")
(:file "cl-nng")
(:file "nng-cffi")
(:file "nng-http")
(:file "nng-main")
(:file "demo/http-client/http-client")
))
|
[
{
"context": "l-count (nconst 0))\n\t\t ;; Hack to fix bug that Andrzej Filinski found.\n\t\t ;; This should return an empty vect",
"end": 6130,
"score": 0.9996854066848755,
"start": 6114,
"tag": "NAME",
"value": "Andrzej Filinski"
}
] |
nesl/src/ptrans.lisp
|
gblelloch/nesl
| 8 |
;;;
;;; Copyright (c) 1992, 1993, 1994 Carnegie Mellon University
;;; All Rights Reserved.
;;;
;;; See COPYRIGHT file for further information.
;;;
(in-package :nesl-lisp)
;; Returns all the variables in a binding expression.
;; For example (bindvars-exp '(pair (pair x y) z))
;; will return (x y z).
(defun bindvars-exp (varlist)
(if (atom varlist)
(list varlist)
(mapcan 'bindvars-exp (cdr varlist))))
;;;;;;;;;;;;;;;;;;;;;;;;
;;; the following ext functions find all the free variables in a body
;;;;;;;;;;;;;;;;;;;;;;;;
(defun ext-let-or-over (exp env)
(nconc (ext-exp (second (second exp)) env)
(ext-exp (third exp)
(nconc (bindvars-exp (first (second exp)))
env))))
(defun ext-func (exp env)
(let ((func-ext (ext-exp (first exp) env))
(arg-ext (ext-exp (second exp) env)))
(nconc func-ext arg-ext)))
(defun ext-pair (exp env)
(append (ext-exp (second exp) env) (ext-exp (third exp) env)))
(defun ext-symbol (exp env)
(if (not (find exp env)) (list exp) nil))
(defun ext-if (exp env)
(append (ext-exp (second exp) env)
(ext-exp (third exp) env)
(ext-exp (fourth exp) env)))
(defun ext-exp (exp env)
(cond ((nesl-constant-p exp) nil)
((symbolp exp)
(ext-symbol exp env))
((pscode-p exp) nil)
((listp exp)
(cond ((eql (car exp) 'if)
(ext-if exp env))
((eql (car exp) 'let)
(ext-let-or-over exp env))
((eql (car exp) 'over)
(ext-let-or-over exp env))
((eql (car exp) 'pair)
(ext-pair exp env))
((eql (car exp) 'closure)
(ext-pair exp env))
(t (ext-func exp env))))
(t (nesl-error "Invalid expression, ~s." exp))))
;;;;;;;;;;;;;;;;;;;;;;;;
;;; the following simp function find if an expression just contains pairs
;;;;;;;;;;;;;;;;;;;;;;;;
(defun simp-exp (exp)
(cond ((nesl-constant-p exp) t)
((symbolp exp) t)
((pscode-p exp) t)
((listp exp)
(cond ((eql (car exp) 'if) nil)
((eql (car exp) 'let) nil)
((eql (car exp) 'over) nil)
((eql (car exp) 'pair)
(and (simp-exp (second exp)) (simp-exp (third exp))))
((eql (car exp) 'closure)
(simp-exp (third exp)))
(t nil)))
(t (nesl-error "Invalid expression, ~s." exp))))
;;;;;;;;;;;;;;;;;;;;;;;;
;;; the following conv functions do the flattening of nested parallelism
;;;;;;;;;;;;;;;;;;;;;;;;
(defun conv-over (exp pflag env)
(let* ((binding (second exp))
(body (conv-exp (third exp) t env))
(free-body (remove-duplicates
(ext-exp (third exp) (bindvars-exp (first binding))))))
`(let ((vector (pair segdes ,(first binding)))
,(conv-exp (second binding) pflag env))
,(zip-let-bindings
(mapcar (if pflag
#'(lambda (a)
`(,a ((parallel . ,(get-pscode 'prim-dist))
(pair (pair ,a segdes)
seg_len))))
#'(lambda (a) `(,a (,(get-pscode 'prim-dist )
(pair ,a segdes)))))
free-body)
`(let (seg_len ,(if pflag
`(,(get-pscode 'make-segdes)
(,(get-pscode 'prim-+-reduce)
(pair
(,(get-pscode 'prim-seg-lengths)segdes)
seg_len)))
'segdes))
(,(get-pscode 'vector)
(pair segdes ,body)))))))
(defun conv-let (expression pflag env)
`(let (,(first (second expression))
,(conv-exp (second (second expression)) pflag env))
,(conv-exp (third expression) pflag env)))
(defun conv-pair (exp pflag env)
(list (first exp)
(conv-exp (second exp) pflag env)
(conv-exp (third exp) pflag env)))
(defun pname (name) (cons 'parallel name))
(defun conv-left-exp (expression pflag env)
(if (and (pscode-p expression)
(is-function-type? (code-type (pscode-serial expression))))
expression
(conv-exp expression pflag env)))
(defun conv-func (expression pflag env)
;;; NOTE THAT THIS HAS TO BE FIXED AT SOME POINT
;;; SO THAT THE FUN IS CALLED WITH PFLAG
(let ((fun (conv-left-exp (first expression) pflag env))
(arg (conv-exp (second expression) pflag env)))
(if pflag
`(,(pname fun) (pair ,arg seg_len))
`(,fun ,arg))))
(defun nconst (a) (coerce-nesl-constant a))
(defun ps= (a b) `(,(get-pscode '=) (pair ,a ,b)))
(defun vect (segdes vals) `(,(get-pscode 'vector) (pair ,segdes ,vals)))
(defun iseq (len)
`(,(get-pscode 'prim-iseq) (pair ,(nconst 0) (pair ,(nconst 1) ,len))))
(defun pack-i (idx flag segdes)
`(,(get-pscode 'pack_scalar)
(,(get-pscode 'vector) (pair ,segdes (pair ,idx ,flag)))))
(defun pack-ni (idx flag segdes)
`(,(get-pscode 'pack_scalar)
(,(get-pscode 'vector) (pair ,segdes (pair ,idx (,(get-pscode 'not)
,flag))))))
(defun geti (vals idx) `(,(get-pscode '->) (pair ,vals ,idx)))
(defun vselect (cond then else)
`(,(get-pscode 'vselect)
(pair ,cond (pair ,then (pair ,else seg_len)))))
(defun puti (vals idx dest)
`(let ((vector (pair junk-segdes result))
(,(get-pscode 'put) (pair ,vals (pair ,idx ,(vect 'seg_len dest)))))
result))
(defun cond-exec (vars idx body)
(if (null vars)
`(let ((vector (pair seg_len junk-val)) ,idx) ,(vect 'seg_len body))
(let ((var (car vars)))
`(let ((vector (pair junk-segdes ,var)) ,(geti (vect 'seg_len var) idx))
,(cond-exec (cdr vars) idx body)))))
(defun cond-merge (v1 i1 v2 i2)
`(let ((vector (pair junk-segdes result))
(,(get-pscode 'join) (pair ,v1 (pair ,i1 (pair ,v2 ,i2)))))
result))
(defun conv-if (expression pflag env)
(let ((cond (conv-exp (second expression) pflag env))
(then (conv-exp (third expression) pflag env))
(else (conv-exp (fourth expression) pflag env)))
(if (not pflag)
`(if ,cond ,then ,else)
(let ((then-vars (remove-duplicates (ext-exp (third expression) nil)))
(else-vars (remove-duplicates (ext-exp (fourth expression) nil)))
(then-simple? (simp-exp (third expression)))
(else-simple? (simp-exp (fourth expression))))
`(let (cond ,cond)
(let (total-count (,(get-pscode 'prim-seg-lengths) seg_len))
(let (true-count (,(get-pscode 'prim-count)
(pair cond seg_len)))
(let (false-count (,(get-pscode '-)
(pair total-count true-count)))
(if ,(ps= 'total-count (nconst 0))
;; Hack to fix bug that Andrzej Filinski found.
;; This should return an empty vector of the appropriate
;; type, but unfortunately we don't know the type here.
then-body-hack
(if ,(ps= 'true-count 'total-count)
,then
(if ,(ps= 'false-count 'total-count)
,else
,(if then-simple?
(if else-simple?
(vselect 'cond then else)
`(let (idx ,(iseq 'seg_len))
(let (else-idx ,(pack-ni 'idx 'cond 'seg_len))
,(puti (cond-exec else-vars 'else-idx else)
'else-idx then))))
(if else-simple?
`(let (idx ,(iseq 'seg_len))
(let (then-idx ,(pack-i 'idx 'cond 'seg_len))
,(puti (cond-exec then-vars 'then-idx then)
'then-idx else)))
`(let (idx ,(iseq 'seg_len))
(let (then-idx ,(pack-i 'idx 'cond 'seg_len))
(let (else-idx ,(pack-ni 'idx 'cond 'seg_len))
,(cond-merge
(cond-exec then-vars 'then-idx then)
'then-idx
(cond-exec else-vars 'else-idx else)
'else-idx)))))))))))))))))
;; If we have a constant expression (no free variables), and pflag is true,
;; then we have to distribute the expression across all parallel
;; occurences.
(defun conv-constant (constant pflag env)
(if pflag
`(,(get-pscode 'prim-dist)
(pair ,(conv-exp constant nil env) seg_len))
(coerce-nesl-constant constant)))
;;(defun is-const-exp (expression)
;; (and (listp expression)
;; (pscode-p (car expression))
;; (eql (code-name (pscode-serial (car expression))) 'vector)
;; (not (ext-exp expression nil))))
(defun is-const-exp (expression)
(not (ext-exp expression nil)))
(defun conv-exp (expression pflag env)
(cond (;; this is true if there are no free variables in the body
(and pflag (is-const-exp expression))
(conv-constant expression pflag env))
((nesl-constant-p expression)
(conv-constant expression pflag env))
((symbolp expression) expression)
((pscode-p expression) expression)
((listp expression)
(cond ((eql (car expression) 'let)
(conv-let expression pflag env))
((eql (car expression) 'over)
(conv-over expression pflag env))
((eql (car expression) 'if)
(conv-if expression pflag env))
((eql (car expression) 'pair)
(conv-pair expression pflag env))
((eql (car expression) 'closure)
(conv-pair expression pflag env))
;;((eql (car expression) 'sif)
;;`(if ,@(conv-list (cdr expression) pflag env)))
(t (conv-func expression pflag env))))
(t (nesl-error "Invalid expression, ~s." expression))))
;; Can get rid of this once everything is pre type-checked.
(defun conv-body (variables body pflag)
(when (and pflag (ext-exp body (bindvars-exp (first variables))))
(nesl-error "Internal Error: unbound variables: ~a."
(ext-exp body (bindvars-exp (first variables)))))
(conv-exp body pflag nil))
(defun conv-type (type pflag)
(if (and pflag (listp (car type)) (eql (caar type) 'function))
(let ((type-exp (car type))
(context (cdr type)))
(cons `(function ,(second type-exp) ,(third type-exp)
(pair ,(fourth type-exp) segdes))
context))
type))
(defun conv-names (names pflag)
(if pflag
(list (first names) `(pair ,(second names) seg_len))
names))
|
86834
|
;;;
;;; Copyright (c) 1992, 1993, 1994 Carnegie Mellon University
;;; All Rights Reserved.
;;;
;;; See COPYRIGHT file for further information.
;;;
(in-package :nesl-lisp)
;; Returns all the variables in a binding expression.
;; For example (bindvars-exp '(pair (pair x y) z))
;; will return (x y z).
(defun bindvars-exp (varlist)
(if (atom varlist)
(list varlist)
(mapcan 'bindvars-exp (cdr varlist))))
;;;;;;;;;;;;;;;;;;;;;;;;
;;; the following ext functions find all the free variables in a body
;;;;;;;;;;;;;;;;;;;;;;;;
(defun ext-let-or-over (exp env)
(nconc (ext-exp (second (second exp)) env)
(ext-exp (third exp)
(nconc (bindvars-exp (first (second exp)))
env))))
(defun ext-func (exp env)
(let ((func-ext (ext-exp (first exp) env))
(arg-ext (ext-exp (second exp) env)))
(nconc func-ext arg-ext)))
(defun ext-pair (exp env)
(append (ext-exp (second exp) env) (ext-exp (third exp) env)))
(defun ext-symbol (exp env)
(if (not (find exp env)) (list exp) nil))
(defun ext-if (exp env)
(append (ext-exp (second exp) env)
(ext-exp (third exp) env)
(ext-exp (fourth exp) env)))
(defun ext-exp (exp env)
(cond ((nesl-constant-p exp) nil)
((symbolp exp)
(ext-symbol exp env))
((pscode-p exp) nil)
((listp exp)
(cond ((eql (car exp) 'if)
(ext-if exp env))
((eql (car exp) 'let)
(ext-let-or-over exp env))
((eql (car exp) 'over)
(ext-let-or-over exp env))
((eql (car exp) 'pair)
(ext-pair exp env))
((eql (car exp) 'closure)
(ext-pair exp env))
(t (ext-func exp env))))
(t (nesl-error "Invalid expression, ~s." exp))))
;;;;;;;;;;;;;;;;;;;;;;;;
;;; the following simp function find if an expression just contains pairs
;;;;;;;;;;;;;;;;;;;;;;;;
(defun simp-exp (exp)
(cond ((nesl-constant-p exp) t)
((symbolp exp) t)
((pscode-p exp) t)
((listp exp)
(cond ((eql (car exp) 'if) nil)
((eql (car exp) 'let) nil)
((eql (car exp) 'over) nil)
((eql (car exp) 'pair)
(and (simp-exp (second exp)) (simp-exp (third exp))))
((eql (car exp) 'closure)
(simp-exp (third exp)))
(t nil)))
(t (nesl-error "Invalid expression, ~s." exp))))
;;;;;;;;;;;;;;;;;;;;;;;;
;;; the following conv functions do the flattening of nested parallelism
;;;;;;;;;;;;;;;;;;;;;;;;
(defun conv-over (exp pflag env)
(let* ((binding (second exp))
(body (conv-exp (third exp) t env))
(free-body (remove-duplicates
(ext-exp (third exp) (bindvars-exp (first binding))))))
`(let ((vector (pair segdes ,(first binding)))
,(conv-exp (second binding) pflag env))
,(zip-let-bindings
(mapcar (if pflag
#'(lambda (a)
`(,a ((parallel . ,(get-pscode 'prim-dist))
(pair (pair ,a segdes)
seg_len))))
#'(lambda (a) `(,a (,(get-pscode 'prim-dist )
(pair ,a segdes)))))
free-body)
`(let (seg_len ,(if pflag
`(,(get-pscode 'make-segdes)
(,(get-pscode 'prim-+-reduce)
(pair
(,(get-pscode 'prim-seg-lengths)segdes)
seg_len)))
'segdes))
(,(get-pscode 'vector)
(pair segdes ,body)))))))
(defun conv-let (expression pflag env)
`(let (,(first (second expression))
,(conv-exp (second (second expression)) pflag env))
,(conv-exp (third expression) pflag env)))
(defun conv-pair (exp pflag env)
(list (first exp)
(conv-exp (second exp) pflag env)
(conv-exp (third exp) pflag env)))
(defun pname (name) (cons 'parallel name))
(defun conv-left-exp (expression pflag env)
(if (and (pscode-p expression)
(is-function-type? (code-type (pscode-serial expression))))
expression
(conv-exp expression pflag env)))
(defun conv-func (expression pflag env)
;;; NOTE THAT THIS HAS TO BE FIXED AT SOME POINT
;;; SO THAT THE FUN IS CALLED WITH PFLAG
(let ((fun (conv-left-exp (first expression) pflag env))
(arg (conv-exp (second expression) pflag env)))
(if pflag
`(,(pname fun) (pair ,arg seg_len))
`(,fun ,arg))))
(defun nconst (a) (coerce-nesl-constant a))
(defun ps= (a b) `(,(get-pscode '=) (pair ,a ,b)))
(defun vect (segdes vals) `(,(get-pscode 'vector) (pair ,segdes ,vals)))
(defun iseq (len)
`(,(get-pscode 'prim-iseq) (pair ,(nconst 0) (pair ,(nconst 1) ,len))))
(defun pack-i (idx flag segdes)
`(,(get-pscode 'pack_scalar)
(,(get-pscode 'vector) (pair ,segdes (pair ,idx ,flag)))))
(defun pack-ni (idx flag segdes)
`(,(get-pscode 'pack_scalar)
(,(get-pscode 'vector) (pair ,segdes (pair ,idx (,(get-pscode 'not)
,flag))))))
(defun geti (vals idx) `(,(get-pscode '->) (pair ,vals ,idx)))
(defun vselect (cond then else)
`(,(get-pscode 'vselect)
(pair ,cond (pair ,then (pair ,else seg_len)))))
(defun puti (vals idx dest)
`(let ((vector (pair junk-segdes result))
(,(get-pscode 'put) (pair ,vals (pair ,idx ,(vect 'seg_len dest)))))
result))
(defun cond-exec (vars idx body)
(if (null vars)
`(let ((vector (pair seg_len junk-val)) ,idx) ,(vect 'seg_len body))
(let ((var (car vars)))
`(let ((vector (pair junk-segdes ,var)) ,(geti (vect 'seg_len var) idx))
,(cond-exec (cdr vars) idx body)))))
(defun cond-merge (v1 i1 v2 i2)
`(let ((vector (pair junk-segdes result))
(,(get-pscode 'join) (pair ,v1 (pair ,i1 (pair ,v2 ,i2)))))
result))
(defun conv-if (expression pflag env)
(let ((cond (conv-exp (second expression) pflag env))
(then (conv-exp (third expression) pflag env))
(else (conv-exp (fourth expression) pflag env)))
(if (not pflag)
`(if ,cond ,then ,else)
(let ((then-vars (remove-duplicates (ext-exp (third expression) nil)))
(else-vars (remove-duplicates (ext-exp (fourth expression) nil)))
(then-simple? (simp-exp (third expression)))
(else-simple? (simp-exp (fourth expression))))
`(let (cond ,cond)
(let (total-count (,(get-pscode 'prim-seg-lengths) seg_len))
(let (true-count (,(get-pscode 'prim-count)
(pair cond seg_len)))
(let (false-count (,(get-pscode '-)
(pair total-count true-count)))
(if ,(ps= 'total-count (nconst 0))
;; Hack to fix bug that <NAME> found.
;; This should return an empty vector of the appropriate
;; type, but unfortunately we don't know the type here.
then-body-hack
(if ,(ps= 'true-count 'total-count)
,then
(if ,(ps= 'false-count 'total-count)
,else
,(if then-simple?
(if else-simple?
(vselect 'cond then else)
`(let (idx ,(iseq 'seg_len))
(let (else-idx ,(pack-ni 'idx 'cond 'seg_len))
,(puti (cond-exec else-vars 'else-idx else)
'else-idx then))))
(if else-simple?
`(let (idx ,(iseq 'seg_len))
(let (then-idx ,(pack-i 'idx 'cond 'seg_len))
,(puti (cond-exec then-vars 'then-idx then)
'then-idx else)))
`(let (idx ,(iseq 'seg_len))
(let (then-idx ,(pack-i 'idx 'cond 'seg_len))
(let (else-idx ,(pack-ni 'idx 'cond 'seg_len))
,(cond-merge
(cond-exec then-vars 'then-idx then)
'then-idx
(cond-exec else-vars 'else-idx else)
'else-idx)))))))))))))))))
;; If we have a constant expression (no free variables), and pflag is true,
;; then we have to distribute the expression across all parallel
;; occurences.
(defun conv-constant (constant pflag env)
(if pflag
`(,(get-pscode 'prim-dist)
(pair ,(conv-exp constant nil env) seg_len))
(coerce-nesl-constant constant)))
;;(defun is-const-exp (expression)
;; (and (listp expression)
;; (pscode-p (car expression))
;; (eql (code-name (pscode-serial (car expression))) 'vector)
;; (not (ext-exp expression nil))))
(defun is-const-exp (expression)
(not (ext-exp expression nil)))
(defun conv-exp (expression pflag env)
(cond (;; this is true if there are no free variables in the body
(and pflag (is-const-exp expression))
(conv-constant expression pflag env))
((nesl-constant-p expression)
(conv-constant expression pflag env))
((symbolp expression) expression)
((pscode-p expression) expression)
((listp expression)
(cond ((eql (car expression) 'let)
(conv-let expression pflag env))
((eql (car expression) 'over)
(conv-over expression pflag env))
((eql (car expression) 'if)
(conv-if expression pflag env))
((eql (car expression) 'pair)
(conv-pair expression pflag env))
((eql (car expression) 'closure)
(conv-pair expression pflag env))
;;((eql (car expression) 'sif)
;;`(if ,@(conv-list (cdr expression) pflag env)))
(t (conv-func expression pflag env))))
(t (nesl-error "Invalid expression, ~s." expression))))
;; Can get rid of this once everything is pre type-checked.
(defun conv-body (variables body pflag)
(when (and pflag (ext-exp body (bindvars-exp (first variables))))
(nesl-error "Internal Error: unbound variables: ~a."
(ext-exp body (bindvars-exp (first variables)))))
(conv-exp body pflag nil))
(defun conv-type (type pflag)
(if (and pflag (listp (car type)) (eql (caar type) 'function))
(let ((type-exp (car type))
(context (cdr type)))
(cons `(function ,(second type-exp) ,(third type-exp)
(pair ,(fourth type-exp) segdes))
context))
type))
(defun conv-names (names pflag)
(if pflag
(list (first names) `(pair ,(second names) seg_len))
names))
| true |
;;;
;;; Copyright (c) 1992, 1993, 1994 Carnegie Mellon University
;;; All Rights Reserved.
;;;
;;; See COPYRIGHT file for further information.
;;;
(in-package :nesl-lisp)
;; Returns all the variables in a binding expression.
;; For example (bindvars-exp '(pair (pair x y) z))
;; will return (x y z).
(defun bindvars-exp (varlist)
(if (atom varlist)
(list varlist)
(mapcan 'bindvars-exp (cdr varlist))))
;;;;;;;;;;;;;;;;;;;;;;;;
;;; the following ext functions find all the free variables in a body
;;;;;;;;;;;;;;;;;;;;;;;;
(defun ext-let-or-over (exp env)
(nconc (ext-exp (second (second exp)) env)
(ext-exp (third exp)
(nconc (bindvars-exp (first (second exp)))
env))))
(defun ext-func (exp env)
(let ((func-ext (ext-exp (first exp) env))
(arg-ext (ext-exp (second exp) env)))
(nconc func-ext arg-ext)))
(defun ext-pair (exp env)
(append (ext-exp (second exp) env) (ext-exp (third exp) env)))
(defun ext-symbol (exp env)
(if (not (find exp env)) (list exp) nil))
(defun ext-if (exp env)
(append (ext-exp (second exp) env)
(ext-exp (third exp) env)
(ext-exp (fourth exp) env)))
(defun ext-exp (exp env)
(cond ((nesl-constant-p exp) nil)
((symbolp exp)
(ext-symbol exp env))
((pscode-p exp) nil)
((listp exp)
(cond ((eql (car exp) 'if)
(ext-if exp env))
((eql (car exp) 'let)
(ext-let-or-over exp env))
((eql (car exp) 'over)
(ext-let-or-over exp env))
((eql (car exp) 'pair)
(ext-pair exp env))
((eql (car exp) 'closure)
(ext-pair exp env))
(t (ext-func exp env))))
(t (nesl-error "Invalid expression, ~s." exp))))
;;;;;;;;;;;;;;;;;;;;;;;;
;;; the following simp function find if an expression just contains pairs
;;;;;;;;;;;;;;;;;;;;;;;;
(defun simp-exp (exp)
(cond ((nesl-constant-p exp) t)
((symbolp exp) t)
((pscode-p exp) t)
((listp exp)
(cond ((eql (car exp) 'if) nil)
((eql (car exp) 'let) nil)
((eql (car exp) 'over) nil)
((eql (car exp) 'pair)
(and (simp-exp (second exp)) (simp-exp (third exp))))
((eql (car exp) 'closure)
(simp-exp (third exp)))
(t nil)))
(t (nesl-error "Invalid expression, ~s." exp))))
;;;;;;;;;;;;;;;;;;;;;;;;
;;; the following conv functions do the flattening of nested parallelism
;;;;;;;;;;;;;;;;;;;;;;;;
(defun conv-over (exp pflag env)
(let* ((binding (second exp))
(body (conv-exp (third exp) t env))
(free-body (remove-duplicates
(ext-exp (third exp) (bindvars-exp (first binding))))))
`(let ((vector (pair segdes ,(first binding)))
,(conv-exp (second binding) pflag env))
,(zip-let-bindings
(mapcar (if pflag
#'(lambda (a)
`(,a ((parallel . ,(get-pscode 'prim-dist))
(pair (pair ,a segdes)
seg_len))))
#'(lambda (a) `(,a (,(get-pscode 'prim-dist )
(pair ,a segdes)))))
free-body)
`(let (seg_len ,(if pflag
`(,(get-pscode 'make-segdes)
(,(get-pscode 'prim-+-reduce)
(pair
(,(get-pscode 'prim-seg-lengths)segdes)
seg_len)))
'segdes))
(,(get-pscode 'vector)
(pair segdes ,body)))))))
(defun conv-let (expression pflag env)
`(let (,(first (second expression))
,(conv-exp (second (second expression)) pflag env))
,(conv-exp (third expression) pflag env)))
(defun conv-pair (exp pflag env)
(list (first exp)
(conv-exp (second exp) pflag env)
(conv-exp (third exp) pflag env)))
(defun pname (name) (cons 'parallel name))
(defun conv-left-exp (expression pflag env)
(if (and (pscode-p expression)
(is-function-type? (code-type (pscode-serial expression))))
expression
(conv-exp expression pflag env)))
(defun conv-func (expression pflag env)
;;; NOTE THAT THIS HAS TO BE FIXED AT SOME POINT
;;; SO THAT THE FUN IS CALLED WITH PFLAG
(let ((fun (conv-left-exp (first expression) pflag env))
(arg (conv-exp (second expression) pflag env)))
(if pflag
`(,(pname fun) (pair ,arg seg_len))
`(,fun ,arg))))
(defun nconst (a) (coerce-nesl-constant a))
(defun ps= (a b) `(,(get-pscode '=) (pair ,a ,b)))
(defun vect (segdes vals) `(,(get-pscode 'vector) (pair ,segdes ,vals)))
(defun iseq (len)
`(,(get-pscode 'prim-iseq) (pair ,(nconst 0) (pair ,(nconst 1) ,len))))
(defun pack-i (idx flag segdes)
`(,(get-pscode 'pack_scalar)
(,(get-pscode 'vector) (pair ,segdes (pair ,idx ,flag)))))
(defun pack-ni (idx flag segdes)
`(,(get-pscode 'pack_scalar)
(,(get-pscode 'vector) (pair ,segdes (pair ,idx (,(get-pscode 'not)
,flag))))))
(defun geti (vals idx) `(,(get-pscode '->) (pair ,vals ,idx)))
(defun vselect (cond then else)
`(,(get-pscode 'vselect)
(pair ,cond (pair ,then (pair ,else seg_len)))))
(defun puti (vals idx dest)
`(let ((vector (pair junk-segdes result))
(,(get-pscode 'put) (pair ,vals (pair ,idx ,(vect 'seg_len dest)))))
result))
(defun cond-exec (vars idx body)
(if (null vars)
`(let ((vector (pair seg_len junk-val)) ,idx) ,(vect 'seg_len body))
(let ((var (car vars)))
`(let ((vector (pair junk-segdes ,var)) ,(geti (vect 'seg_len var) idx))
,(cond-exec (cdr vars) idx body)))))
(defun cond-merge (v1 i1 v2 i2)
`(let ((vector (pair junk-segdes result))
(,(get-pscode 'join) (pair ,v1 (pair ,i1 (pair ,v2 ,i2)))))
result))
(defun conv-if (expression pflag env)
(let ((cond (conv-exp (second expression) pflag env))
(then (conv-exp (third expression) pflag env))
(else (conv-exp (fourth expression) pflag env)))
(if (not pflag)
`(if ,cond ,then ,else)
(let ((then-vars (remove-duplicates (ext-exp (third expression) nil)))
(else-vars (remove-duplicates (ext-exp (fourth expression) nil)))
(then-simple? (simp-exp (third expression)))
(else-simple? (simp-exp (fourth expression))))
`(let (cond ,cond)
(let (total-count (,(get-pscode 'prim-seg-lengths) seg_len))
(let (true-count (,(get-pscode 'prim-count)
(pair cond seg_len)))
(let (false-count (,(get-pscode '-)
(pair total-count true-count)))
(if ,(ps= 'total-count (nconst 0))
;; Hack to fix bug that PI:NAME:<NAME>END_PI found.
;; This should return an empty vector of the appropriate
;; type, but unfortunately we don't know the type here.
then-body-hack
(if ,(ps= 'true-count 'total-count)
,then
(if ,(ps= 'false-count 'total-count)
,else
,(if then-simple?
(if else-simple?
(vselect 'cond then else)
`(let (idx ,(iseq 'seg_len))
(let (else-idx ,(pack-ni 'idx 'cond 'seg_len))
,(puti (cond-exec else-vars 'else-idx else)
'else-idx then))))
(if else-simple?
`(let (idx ,(iseq 'seg_len))
(let (then-idx ,(pack-i 'idx 'cond 'seg_len))
,(puti (cond-exec then-vars 'then-idx then)
'then-idx else)))
`(let (idx ,(iseq 'seg_len))
(let (then-idx ,(pack-i 'idx 'cond 'seg_len))
(let (else-idx ,(pack-ni 'idx 'cond 'seg_len))
,(cond-merge
(cond-exec then-vars 'then-idx then)
'then-idx
(cond-exec else-vars 'else-idx else)
'else-idx)))))))))))))))))
;; If we have a constant expression (no free variables), and pflag is true,
;; then we have to distribute the expression across all parallel
;; occurences.
(defun conv-constant (constant pflag env)
(if pflag
`(,(get-pscode 'prim-dist)
(pair ,(conv-exp constant nil env) seg_len))
(coerce-nesl-constant constant)))
;;(defun is-const-exp (expression)
;; (and (listp expression)
;; (pscode-p (car expression))
;; (eql (code-name (pscode-serial (car expression))) 'vector)
;; (not (ext-exp expression nil))))
(defun is-const-exp (expression)
(not (ext-exp expression nil)))
(defun conv-exp (expression pflag env)
(cond (;; this is true if there are no free variables in the body
(and pflag (is-const-exp expression))
(conv-constant expression pflag env))
((nesl-constant-p expression)
(conv-constant expression pflag env))
((symbolp expression) expression)
((pscode-p expression) expression)
((listp expression)
(cond ((eql (car expression) 'let)
(conv-let expression pflag env))
((eql (car expression) 'over)
(conv-over expression pflag env))
((eql (car expression) 'if)
(conv-if expression pflag env))
((eql (car expression) 'pair)
(conv-pair expression pflag env))
((eql (car expression) 'closure)
(conv-pair expression pflag env))
;;((eql (car expression) 'sif)
;;`(if ,@(conv-list (cdr expression) pflag env)))
(t (conv-func expression pflag env))))
(t (nesl-error "Invalid expression, ~s." expression))))
;; Can get rid of this once everything is pre type-checked.
(defun conv-body (variables body pflag)
(when (and pflag (ext-exp body (bindvars-exp (first variables))))
(nesl-error "Internal Error: unbound variables: ~a."
(ext-exp body (bindvars-exp (first variables)))))
(conv-exp body pflag nil))
(defun conv-type (type pflag)
(if (and pflag (listp (car type)) (eql (caar type) 'function))
(let ((type-exp (car type))
(context (cdr type)))
(cons `(function ,(second type-exp) ,(third type-exp)
(pair ,(fourth type-exp) segdes))
context))
type))
(defun conv-names (names pflag)
(if pflag
(list (first names) `(pair ,(second names) seg_len))
names))
|
[
{
"context": "ls\n :name \"gp_utils\"\n :version \"1.0\"\n :author \"Jeffrey Massung\"\n :license \"Apache 2.0\"\n :description \"Graphics",
"end": 158,
"score": 0.9998865127563477,
"start": 143,
"tag": "NAME",
"value": "Jeffrey Massung"
}
] |
gp_utils.asd
|
massung/gp_utils
| 3 |
(defpackage :gp-utils-asd
(:use :cl :asdf))
(in-package :gp-utils-asd)
(defsystem :gp_utils
:name "gp_utils"
:version "1.0"
:author "Jeffrey Massung"
:license "Apache 2.0"
:description "Graphics Port Utilities for LispWorks."
:serial t
:components ((:file "gp_utils")))
|
95263
|
(defpackage :gp-utils-asd
(:use :cl :asdf))
(in-package :gp-utils-asd)
(defsystem :gp_utils
:name "gp_utils"
:version "1.0"
:author "<NAME>"
:license "Apache 2.0"
:description "Graphics Port Utilities for LispWorks."
:serial t
:components ((:file "gp_utils")))
| true |
(defpackage :gp-utils-asd
(:use :cl :asdf))
(in-package :gp-utils-asd)
(defsystem :gp_utils
:name "gp_utils"
:version "1.0"
:author "PI:NAME:<NAME>END_PI"
:license "Apache 2.0"
:description "Graphics Port Utilities for LispWorks."
:serial t
:components ((:file "gp_utils")))
|
[
{
"context": "ode: Lisp; Package: CCL -*-\n;;;\n;;; Copyright 2009 Clozure Associates\n;;;\n;;; Licensed under the Apache License, Versio",
"end": 77,
"score": 0.8738062381744385,
"start": 59,
"tag": "NAME",
"value": "Clozure Associates"
},
{
"context": "arwinx8632-backend* *known-x8632-backends* :key #'backend-name)\n\n#+linuxx86-target\n(defvar *linuxx8632-back",
"end": 2372,
"score": 0.531400740146637,
"start": 2365,
"tag": "KEY",
"value": "backend"
}
] |
compiler/X86/X8632/x8632-backend.lisp
|
digikar99/ccl
| 732 |
;;;-*- Mode: Lisp; Package: CCL -*-
;;;
;;; Copyright 2009 Clozure Associates
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
(in-package "CCL")
(eval-when (:compile-toplevel :load-toplevel :execute)
(require "BACKEND"))
(eval-when (:compile-toplevel :execute)
(require "NXENV")
(require "X8632ENV"))
(defvar *x8632-vinsn-templates* (make-hash-table :test #'eq))
(defvar *known-x8632-backends* ())
#+darwinx86-target
(defvar *darwinx8632-backend*
(make-backend :lookup-opcode 'lookup-x86-opcode
:lookup-macro #'false
:lap-opcodes x86::*x86-opcode-templates*
:define-vinsn 'define-x86-vinsn
:p2-dispatch *x862-specials*
:p2-vinsn-templates *x8632-vinsn-templates*
:p2-template-hash-name '*x8632-vinsn-templates*
:p2-compile 'x862-compile
:platform-syscall-mask (logior platform-os-darwin platform-cpu-x86 platform-word-size-32)
:target-specific-features
'(:x8632 :x86-target :darwin-target :darwinx86-target :x8632-target
:darwinx8632-target
:little-endian-target
:32-bit-target)
:target-fasl-pathname (make-pathname :type "dx32fsl")
:target-platform (logior platform-cpu-x86
platform-os-darwin
platform-word-size-32)
:target-os :darwinx86
:name :darwinx8632
:target-arch-name :x8632
:target-foreign-type-data nil
:target-arch x8632::*x8632-target-arch*
:lisp-context-register x8632::fs
:num-arg-regs 2
))
#+darwinx86-target
(pushnew *darwinx8632-backend* *known-x8632-backends* :key #'backend-name)
#+linuxx86-target
(defvar *linuxx8632-backend*
(make-backend :lookup-opcode 'lookup-x86-opcode
:lookup-macro #'false
:lap-opcodes x86::*x86-opcode-templates*
:define-vinsn 'define-x86-vinsn
:p2-dispatch *x862-specials*
:p2-vinsn-templates *x8632-vinsn-templates*
:p2-template-hash-name '*x8632-vinsn-templates*
:p2-compile 'x862-compile
:platform-syscall-mask (logior platform-os-linux platform-cpu-x86 platform-word-size-32)
:target-specific-features
'(:x8632 :x86-target :linux-target :linuxx86-target :x8632-target
:linuxx8632-target
:little-endian-target
:32-bit-target)
:target-fasl-pathname (make-pathname :type "lx32fsl")
:target-platform (logior platform-cpu-x86
platform-os-linux
platform-word-size-32)
:target-os :linuxx86
:name :linuxx8632
:target-arch-name :x8632
:target-foreign-type-data nil
:target-arch x8632::*x8632-target-arch*
:lisp-context-register x8632::fs
:num-arg-regs 2
))
#+linuxx86-target
(pushnew *linuxx8632-backend* *known-x8632-backends* :key #'backend-name)
#+windows-target
(defvar *win32-backend*
(make-backend :lookup-opcode 'lookup-x86-opcode
:lookup-macro #'false
:lap-opcodes x86::*x86-opcode-templates*
:define-vinsn 'define-x86-vinsn
:p2-dispatch *x862-specials*
:p2-vinsn-templates *x8632-vinsn-templates*
:p2-template-hash-name '*x8632-vinsn-templates*
:p2-compile 'x862-compile
:platform-syscall-mask (logior platform-os-windows platform-cpu-x86 platform-word-size-32)
:target-specific-features
'(:x8632 :x86-target :windows-target :win32-target :x8632-target
:windowsx8632-target
:little-endian-target
:32-bit-target)
:target-fasl-pathname (make-pathname :type "wx32fsl")
:target-platform (logior platform-cpu-x86
platform-os-windows
platform-word-size-32)
:target-os :win32
:name :win32
:target-arch-name :x8632
:target-foreign-type-data nil
:target-arch x8632::*x8632-target-arch*
:lisp-context-register x8632::fs
:num-arg-regs 2
))
#+windows-target
(pushnew *win32-backend* *known-x8632-backends* :key #'backend-name)
#+solaris-target
(defvar *solaris-x8632-backend*
(make-backend :lookup-opcode 'lookup-x86-opcode
:lookup-macro #'false
:lap-opcodes x86::*x86-opcode-templates*
:define-vinsn 'define-x86-vinsn
:p2-dispatch *x862-specials*
:p2-vinsn-templates *x8632-vinsn-templates*
:p2-template-hash-name '*x8632-vinsn-templates*
:p2-compile 'x862-compile
:platform-syscall-mask (logior platform-os-solaris platform-cpu-x86 platform-word-size-32)
:target-specific-features
'(:x8632 :x86-target :solaris-target :x8632-target
:solarisx8632-target
:little-endian-target
:32-bit-target)
:target-fasl-pathname (make-pathname :type "sx32fsl")
:target-platform (logior platform-cpu-x86
platform-os-solaris
platform-word-size-32)
:target-os :solarisx8632
:name :solarisx8632
:target-arch-name :x8632
:target-foreign-type-data nil
:target-arch x8632::*x8632-target-arch*
:lisp-context-register x8632::fs
:num-arg-regs 2
))
#+solaris-target
(pushnew *solaris-x8632-backend* *known-x8632-backends* :key #'backend-name)
#+freebsd-target
(defvar *freebsd-x8632-backend*
(make-backend :lookup-opcode 'lookup-x86-opcode
:lookup-macro #'false
:lap-opcodes x86::*x86-opcode-templates*
:define-vinsn 'define-x86-vinsn
:p2-dispatch *x862-specials*
:p2-vinsn-templates *x8632-vinsn-templates*
:p2-template-hash-name '*x8632-vinsn-templates*
:p2-compile 'x862-compile
:platform-syscall-mask (logior platform-os-freebsd platform-cpu-x86 platform-word-size-32)
:target-specific-features
'(:x8632 :x86-target :freebsd-target :x8632-target
:freebsdx8632-target
:little-endian-target
:32-bit-target)
:target-fasl-pathname (make-pathname :type "fx32fsl")
:target-platform (logior platform-cpu-x86
platform-os-freebsd
platform-word-size-32)
:target-os :freebsdx8632
:name :freebsdx8632
:target-arch-name :x8632
:target-foreign-type-data nil
:target-arch x8632::*x8632-target-arch*
:lisp-context-register x8632::fs
:num-arg-regs 2
))
#+freebsd-target
(pushnew *freebsd-x8632-backend* *known-x8632-backends* :key #'backend-name)
(defvar *x8632-backend* (car *known-x8632-backends*))
(defun fixup-x8632-backend ()
(dolist (b *known-x8632-backends*)
(setf #| (backend-lap-opcodes b) x86::*x86-opcodes* |#
(backend-p2-dispatch b) *x862-specials*
(backend-p2-vinsn-templates b) *x8632-vinsn-templates*)
(or (backend-lap-macros b) (setf (backend-lap-macros b)
(make-hash-table :test #'equalp)))))
(fixup-x8632-backend)
#+x8632-target
(setq *host-backend* *x8632-backend* *target-backend* *x8632-backend*)
(defun setup-x8632-ftd (backend)
(or (backend-target-foreign-type-data backend)
(let* ((name (backend-name backend))
(ftd
(case name
(:darwinx8632
(make-ftd :interface-db-directory "ccl:darwin-x86-headers;"
:interface-package-name "X86-DARWIN32"
:attributes '(:bits-per-word 32
:signed-char t
:struct-by-value t
:prepend-underscore t)
:ff-call-expand-function
(intern "EXPAND-FF-CALL" "X86-DARWIN32")
:ff-call-struct-return-by-implicit-arg-function
(intern "RECORD-TYPE-RETURNS-STRUCTURE-AS-FIRST-ARG"
"X86-DARWIN32")
:callback-bindings-function
(intern "GENERATE-CALLBACK-BINDINGS" "X86-DARWIN32")
:callback-return-value-function
(intern "GENERATE-CALLBACK-RETURN-VALUE" "X86-DARWIN32")))
(:linuxx8632
(make-ftd :interface-db-directory "ccl:x86-headers;"
:interface-package-name "X86-LINUX32"
:attributes '(:bits-per-word 32
:signed-char nil
:struct-by-value t
:float-results-in-x87 t)
:ff-call-expand-function
(intern "EXPAND-FF-CALL" "X86-LINUX32")
:ff-call-struct-return-by-implicit-arg-function
(intern "RECORD-TYPE-RETURNS-STRUCTURE-AS-FIRST-ARG"
"X86-LINUX32")
:callback-bindings-function
(intern "GENERATE-CALLBACK-BINDINGS" "X86-LINUX32")
:callback-return-value-function
(intern "GENERATE-CALLBACK-RETURN-VALUE" "X86-LINUX32")))
(:win32
(make-ftd :interface-db-directory "ccl:win32-headers;"
:interface-package-name "WIN32"
:attributes '(:bits-per-word 32
:signed-char nil
:struct-by-value t
:float-results-in-x87 t)
:ff-call-expand-function
(intern "EXPAND-FF-CALL" "WIN32")
:ff-call-struct-return-by-implicit-arg-function
(intern "RECORD-TYPE-RETURNS-STRUCTURE-AS-FIRST-ARG"
"WIN32")
:callback-bindings-function
(intern "GENERATE-CALLBACK-BINDINGS" "WIN32")
:callback-return-value-function
(intern "GENERATE-CALLBACK-RETURN-VALUE" "WIN32")))
(:solarisx8632
(make-ftd :interface-db-directory "ccl:solarisx86-headers;"
:interface-package-name "X86-SOLARIS32"
:attributes '(:bits-per-word 32
:signed-char nil
:struct-by-value t
:float-results-in-x87 t)
:ff-call-expand-function
(intern "EXPAND-FF-CALL" "X86-SOLARIS32")
:ff-call-struct-return-by-implicit-arg-function
(intern "RECORD-TYPE-RETURNS-STRUCTURE-AS-FIRST-ARG"
"X86-SOLARIS32")
:callback-bindings-function
(intern "GENERATE-CALLBACK-BINDINGS" "X86-SOLARIS32")
:callback-return-value-function
(intern "GENERATE-CALLBACK-RETURN-VALUE" "X86-SOLARIS32")))
(:freebsdx8632
(make-ftd :interface-db-directory "ccl:freebsd-headers;"
:interface-package-name "X86-FREEBSD32"
:attributes '(:bits-per-word 32
:signed-char nil
:struct-by-value t
:float-results-in-x87 t)
:ff-call-expand-function
(intern "EXPAND-FF-CALL" "X86-FREEBSD32")
:ff-call-struct-return-by-implicit-arg-function
(intern "RECORD-TYPE-RETURNS-STRUCTURE-AS-FIRST-ARG"
"X86-FREEBSD32")
:callback-bindings-function
(intern "GENERATE-CALLBACK-BINDINGS" "X86-FREEBSD32")
:callback-return-value-function
(intern "GENERATE-CALLBACK-RETURN-VALUE" "X86-FREEBSD32")))
)))
(install-standard-foreign-types ftd)
(use-interface-dir :libc ftd)
(setf (backend-target-foreign-type-data backend) ftd))))
#-x8632-target
(setup-x8632-ftd *x8632-backend*)
(pushnew *x8632-backend* *known-backends* :key #'backend-name)
;;; FFI stuff. The vanilla i386 ABI always returns structures as a
;;; hidden first argument. Some systems (Darwin, FreeBSD) use a
;;; variant that returns small (<= 64 bit) structures in registers.
;;; A returned structure is passed as a hidden first argument.
(defun x8632::record-type-returns-structure-as-first-arg (rtype)
(declare (ignore rtype))
t)
;;; All arguments are passed on the stack.
(defun x8632::expand-ff-call (callform args
&key (arg-coerce #'null-coerce-foreign-arg)
(result-coerce #'null-coerce-foreign-result))
(let* ((result-type-spec (or (car (last args)) :void))
(struct-by-value-p nil)
(result-op nil)
(result-temp nil)
(result-form nil))
(multiple-value-bind (result-type error)
(ignore-errors (parse-foreign-type result-type-spec))
(if error
(setq result-type-spec :void result-type *void-foreign-type*)
(setq args (butlast args)))
(collect ((argforms))
(when (typep result-type 'foreign-record-type)
(setq result-form (pop args))
(if (funcall (ftd-ff-call-struct-return-by-implicit-arg-function
*target-ftd*) result-type)
(progn
(setq result-type *void-foreign-type*
result-type-spec :void)
(argforms :address)
(argforms result-form))
(progn
(ecase (foreign-type-bits result-type)
(8 (setq result-type-spec :unsigned-byte
result-op '%get-unsigned-byte))
(16 (setq result-type-spec :unsigned-halfword
result-op '%get-unsigned-word))
(32 (setq result-type-spec :unsigned-fullword
result-op '%get-unsigned-long))
(64 (setq result-type-spec :unsigned-doubleword
result-op '%%get-unsigned-longlong)))
(setq result-type (parse-foreign-type result-type-spec))
(setq result-temp (gensym))
(setq struct-by-value-p t))))
(unless (evenp (length args))
(error "~s should be an even-length list of alternating foreign types and values" args))
(do* ((args args (cddr args)))
((null args))
(let* ((arg-type-spec (car args))
(arg-value-form (cadr args)))
(if (or (member arg-type-spec *foreign-representation-type-keywords*
:test #'eq)
(typep arg-type-spec 'unsigned-byte))
(progn
(argforms arg-type-spec)
(argforms arg-value-form))
(let* ((ftype (parse-foreign-type arg-type-spec))
(bits (ensure-foreign-type-bits ftype)))
(when (and (typep ftype 'foreign-record-type)
(eq (foreign-record-type-kind ftype)
:transparent-union))
(ensure-foreign-type-bits ftype)
(setq ftype (foreign-record-field-type
(car (foreign-record-type-fields ftype)))
arg-type-spec (foreign-type-to-representation-type
ftype)
bits (ensure-foreign-type-bits ftype)))
(if (typep ftype 'foreign-record-type)
(argforms (ceiling bits 32))
(argforms (foreign-type-to-representation-type ftype)))
(argforms (funcall arg-coerce arg-type-spec arg-value-form))))))
(argforms (foreign-type-to-representation-type result-type))
(let* ((call (funcall result-coerce result-type-spec
`(,@callform ,@(argforms)))))
(if struct-by-value-p
`(let* ((,result-temp (%null-ptr)))
(declare (dynamic-extent ,result-temp)
(type macptr ,result-temp))
(%setf-macptr ,result-temp ,result-form)
(setf (,result-op ,result-temp 0)
,call))
call))))))
;;; Return 8 values:
;;; A list of RLET bindings
;;; A list of LET* bindings
;;; A list of DYNAMIC-EXTENT declarations for the LET* bindings
;;; A list of initializaton forms for (some) structure args (not used on x8632)
;;; A FOREIGN-TYPE representing the "actual" return type.
;;; A form which can be used to initialize FP-ARGS-PTR, relative
;;; to STACK-PTR. (not used on x8632)
;;; The byte offset of the foreign return address, relative to STACK-PTR
;;; The number of argument bytes pushed on the stack by the caller, or NIL
;;; if this can't be determined. (Only meaningful on Windows.)
(defun x8632::generate-callback-bindings (stack-ptr fp-args-ptr argvars
argspecs result-spec
struct-result-name)
(declare (ignore fp-args-ptr))
(collect ((lets)
(rlets)
(dynamic-extent-names))
(let* ((rtype (parse-foreign-type result-spec)))
(when (typep rtype 'foreign-record-type)
(if (funcall (ftd-ff-call-struct-return-by-implicit-arg-function
*target-ftd*) rtype)
(setq argvars (cons struct-result-name argvars)
argspecs (cons :address argspecs)
rtype *void-foreign-type*)
(rlets (list struct-result-name (foreign-record-type-name rtype)))))
(do* ((argvars argvars (cdr argvars))
(argspecs argspecs (cdr argspecs))
(offset 8))
((null argvars)
(values (rlets) (lets) (dynamic-extent-names) nil rtype nil 4
(- offset 8)))
(let* ((name (car argvars))
(spec (car argspecs))
(argtype (parse-foreign-type spec))
(bits (require-foreign-type-bits argtype))
(double nil))
(if (typep argtype 'foreign-record-type)
(let* ((form `(%inc-ptr ,stack-ptr
,(prog1 offset
(incf offset
(* 4 (ceiling bits 32)))))))
(when name (lets (list name form))))
(let* ((form `(,
(ecase (foreign-type-to-representation-type argtype)
(:single-float '%get-single-float)
(:double-float (setq double t) '%get-double-float)
(:signed-doubleword (setq double t)
'%%get-signed-longlong)
(:signed-fullword '%get-signed-long)
(:signed-halfword '%get-signed-word)
(:signed-byte '%get-signed-byte)
(:unsigned-doubleword (setq double t)
'%%get-unsigned-longlong)
(:unsigned-fullword '%get-unsigned-long)
(:unsigned-halfword '%get-unsigned-word)
(:unsigned-byte '%get-unsigned-byte)
(:address '%get-ptr))
,stack-ptr
,offset)))
(when name (lets (list name form)))
(incf offset 4)
(when double (incf offset 4)))))))))
(defun x8632::generate-callback-return-value (stack-ptr fp-args-ptr result
return-type struct-return-arg)
(declare (ignore fp-args-ptr))
(unless (eq return-type *void-foreign-type*)
(if (typep return-type 'foreign-record-type)
;; If the struct result is returned via a hidden argument, the
;; return type would have been mapped to :VOID. On some
;; systems, small (<= 64 bits) structs are returned by value,
;; which we arrange to retrieve here.
(ecase (ensure-foreign-type-bits return-type)
(8 `(setf (%get-unsigned-byte ,stack-ptr -8)
(%get-unsigned-byte ,struct-return-arg 0)))
(16 `(setf (%get-unsigned-word ,stack-ptr -8)
(%get-unsigned-word ,struct-return-arg 0)))
(32 `(setf (%get-unsigned-long ,stack-ptr -8)
(%get-unsigned-long ,struct-return-arg 0)))
(64 `(setf (%%get-unsigned-longlong ,stack-ptr -8)
(%%get-unsigned-longlong ,struct-return-arg 0))))
(let* ((return-type-keyword (foreign-type-to-representation-type
return-type)))
(collect ((forms))
(forms 'progn)
(case return-type-keyword
(:single-float
(forms `(setf (%get-unsigned-byte ,stack-ptr -16) 1)))
(:double-float
(forms `(setf (%get-unsigned-byte ,stack-ptr -16) 2))))
(forms
`(setf (,
(case return-type-keyword
(:address '%get-ptr)
(:signed-doubleword '%%get-signed-longlong)
(:unsigned-doubleword '%%get-unsigned-longlong)
(:double-float '%get-double-float)
(:single-float '%get-single-float)
(:unsigned-fullword '%get-unsigned-long)
(t '%get-signed-long)
) ,stack-ptr -8) ,result))
(forms))))))
#+x8632-target
(require "X8632-VINSNS")
(provide "X8632-BACKEND")
|
35686
|
;;;-*- Mode: Lisp; Package: CCL -*-
;;;
;;; Copyright 2009 <NAME>
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
(in-package "CCL")
(eval-when (:compile-toplevel :load-toplevel :execute)
(require "BACKEND"))
(eval-when (:compile-toplevel :execute)
(require "NXENV")
(require "X8632ENV"))
(defvar *x8632-vinsn-templates* (make-hash-table :test #'eq))
(defvar *known-x8632-backends* ())
#+darwinx86-target
(defvar *darwinx8632-backend*
(make-backend :lookup-opcode 'lookup-x86-opcode
:lookup-macro #'false
:lap-opcodes x86::*x86-opcode-templates*
:define-vinsn 'define-x86-vinsn
:p2-dispatch *x862-specials*
:p2-vinsn-templates *x8632-vinsn-templates*
:p2-template-hash-name '*x8632-vinsn-templates*
:p2-compile 'x862-compile
:platform-syscall-mask (logior platform-os-darwin platform-cpu-x86 platform-word-size-32)
:target-specific-features
'(:x8632 :x86-target :darwin-target :darwinx86-target :x8632-target
:darwinx8632-target
:little-endian-target
:32-bit-target)
:target-fasl-pathname (make-pathname :type "dx32fsl")
:target-platform (logior platform-cpu-x86
platform-os-darwin
platform-word-size-32)
:target-os :darwinx86
:name :darwinx8632
:target-arch-name :x8632
:target-foreign-type-data nil
:target-arch x8632::*x8632-target-arch*
:lisp-context-register x8632::fs
:num-arg-regs 2
))
#+darwinx86-target
(pushnew *darwinx8632-backend* *known-x8632-backends* :key #'<KEY>-name)
#+linuxx86-target
(defvar *linuxx8632-backend*
(make-backend :lookup-opcode 'lookup-x86-opcode
:lookup-macro #'false
:lap-opcodes x86::*x86-opcode-templates*
:define-vinsn 'define-x86-vinsn
:p2-dispatch *x862-specials*
:p2-vinsn-templates *x8632-vinsn-templates*
:p2-template-hash-name '*x8632-vinsn-templates*
:p2-compile 'x862-compile
:platform-syscall-mask (logior platform-os-linux platform-cpu-x86 platform-word-size-32)
:target-specific-features
'(:x8632 :x86-target :linux-target :linuxx86-target :x8632-target
:linuxx8632-target
:little-endian-target
:32-bit-target)
:target-fasl-pathname (make-pathname :type "lx32fsl")
:target-platform (logior platform-cpu-x86
platform-os-linux
platform-word-size-32)
:target-os :linuxx86
:name :linuxx8632
:target-arch-name :x8632
:target-foreign-type-data nil
:target-arch x8632::*x8632-target-arch*
:lisp-context-register x8632::fs
:num-arg-regs 2
))
#+linuxx86-target
(pushnew *linuxx8632-backend* *known-x8632-backends* :key #'backend-name)
#+windows-target
(defvar *win32-backend*
(make-backend :lookup-opcode 'lookup-x86-opcode
:lookup-macro #'false
:lap-opcodes x86::*x86-opcode-templates*
:define-vinsn 'define-x86-vinsn
:p2-dispatch *x862-specials*
:p2-vinsn-templates *x8632-vinsn-templates*
:p2-template-hash-name '*x8632-vinsn-templates*
:p2-compile 'x862-compile
:platform-syscall-mask (logior platform-os-windows platform-cpu-x86 platform-word-size-32)
:target-specific-features
'(:x8632 :x86-target :windows-target :win32-target :x8632-target
:windowsx8632-target
:little-endian-target
:32-bit-target)
:target-fasl-pathname (make-pathname :type "wx32fsl")
:target-platform (logior platform-cpu-x86
platform-os-windows
platform-word-size-32)
:target-os :win32
:name :win32
:target-arch-name :x8632
:target-foreign-type-data nil
:target-arch x8632::*x8632-target-arch*
:lisp-context-register x8632::fs
:num-arg-regs 2
))
#+windows-target
(pushnew *win32-backend* *known-x8632-backends* :key #'backend-name)
#+solaris-target
(defvar *solaris-x8632-backend*
(make-backend :lookup-opcode 'lookup-x86-opcode
:lookup-macro #'false
:lap-opcodes x86::*x86-opcode-templates*
:define-vinsn 'define-x86-vinsn
:p2-dispatch *x862-specials*
:p2-vinsn-templates *x8632-vinsn-templates*
:p2-template-hash-name '*x8632-vinsn-templates*
:p2-compile 'x862-compile
:platform-syscall-mask (logior platform-os-solaris platform-cpu-x86 platform-word-size-32)
:target-specific-features
'(:x8632 :x86-target :solaris-target :x8632-target
:solarisx8632-target
:little-endian-target
:32-bit-target)
:target-fasl-pathname (make-pathname :type "sx32fsl")
:target-platform (logior platform-cpu-x86
platform-os-solaris
platform-word-size-32)
:target-os :solarisx8632
:name :solarisx8632
:target-arch-name :x8632
:target-foreign-type-data nil
:target-arch x8632::*x8632-target-arch*
:lisp-context-register x8632::fs
:num-arg-regs 2
))
#+solaris-target
(pushnew *solaris-x8632-backend* *known-x8632-backends* :key #'backend-name)
#+freebsd-target
(defvar *freebsd-x8632-backend*
(make-backend :lookup-opcode 'lookup-x86-opcode
:lookup-macro #'false
:lap-opcodes x86::*x86-opcode-templates*
:define-vinsn 'define-x86-vinsn
:p2-dispatch *x862-specials*
:p2-vinsn-templates *x8632-vinsn-templates*
:p2-template-hash-name '*x8632-vinsn-templates*
:p2-compile 'x862-compile
:platform-syscall-mask (logior platform-os-freebsd platform-cpu-x86 platform-word-size-32)
:target-specific-features
'(:x8632 :x86-target :freebsd-target :x8632-target
:freebsdx8632-target
:little-endian-target
:32-bit-target)
:target-fasl-pathname (make-pathname :type "fx32fsl")
:target-platform (logior platform-cpu-x86
platform-os-freebsd
platform-word-size-32)
:target-os :freebsdx8632
:name :freebsdx8632
:target-arch-name :x8632
:target-foreign-type-data nil
:target-arch x8632::*x8632-target-arch*
:lisp-context-register x8632::fs
:num-arg-regs 2
))
#+freebsd-target
(pushnew *freebsd-x8632-backend* *known-x8632-backends* :key #'backend-name)
(defvar *x8632-backend* (car *known-x8632-backends*))
(defun fixup-x8632-backend ()
(dolist (b *known-x8632-backends*)
(setf #| (backend-lap-opcodes b) x86::*x86-opcodes* |#
(backend-p2-dispatch b) *x862-specials*
(backend-p2-vinsn-templates b) *x8632-vinsn-templates*)
(or (backend-lap-macros b) (setf (backend-lap-macros b)
(make-hash-table :test #'equalp)))))
(fixup-x8632-backend)
#+x8632-target
(setq *host-backend* *x8632-backend* *target-backend* *x8632-backend*)
(defun setup-x8632-ftd (backend)
(or (backend-target-foreign-type-data backend)
(let* ((name (backend-name backend))
(ftd
(case name
(:darwinx8632
(make-ftd :interface-db-directory "ccl:darwin-x86-headers;"
:interface-package-name "X86-DARWIN32"
:attributes '(:bits-per-word 32
:signed-char t
:struct-by-value t
:prepend-underscore t)
:ff-call-expand-function
(intern "EXPAND-FF-CALL" "X86-DARWIN32")
:ff-call-struct-return-by-implicit-arg-function
(intern "RECORD-TYPE-RETURNS-STRUCTURE-AS-FIRST-ARG"
"X86-DARWIN32")
:callback-bindings-function
(intern "GENERATE-CALLBACK-BINDINGS" "X86-DARWIN32")
:callback-return-value-function
(intern "GENERATE-CALLBACK-RETURN-VALUE" "X86-DARWIN32")))
(:linuxx8632
(make-ftd :interface-db-directory "ccl:x86-headers;"
:interface-package-name "X86-LINUX32"
:attributes '(:bits-per-word 32
:signed-char nil
:struct-by-value t
:float-results-in-x87 t)
:ff-call-expand-function
(intern "EXPAND-FF-CALL" "X86-LINUX32")
:ff-call-struct-return-by-implicit-arg-function
(intern "RECORD-TYPE-RETURNS-STRUCTURE-AS-FIRST-ARG"
"X86-LINUX32")
:callback-bindings-function
(intern "GENERATE-CALLBACK-BINDINGS" "X86-LINUX32")
:callback-return-value-function
(intern "GENERATE-CALLBACK-RETURN-VALUE" "X86-LINUX32")))
(:win32
(make-ftd :interface-db-directory "ccl:win32-headers;"
:interface-package-name "WIN32"
:attributes '(:bits-per-word 32
:signed-char nil
:struct-by-value t
:float-results-in-x87 t)
:ff-call-expand-function
(intern "EXPAND-FF-CALL" "WIN32")
:ff-call-struct-return-by-implicit-arg-function
(intern "RECORD-TYPE-RETURNS-STRUCTURE-AS-FIRST-ARG"
"WIN32")
:callback-bindings-function
(intern "GENERATE-CALLBACK-BINDINGS" "WIN32")
:callback-return-value-function
(intern "GENERATE-CALLBACK-RETURN-VALUE" "WIN32")))
(:solarisx8632
(make-ftd :interface-db-directory "ccl:solarisx86-headers;"
:interface-package-name "X86-SOLARIS32"
:attributes '(:bits-per-word 32
:signed-char nil
:struct-by-value t
:float-results-in-x87 t)
:ff-call-expand-function
(intern "EXPAND-FF-CALL" "X86-SOLARIS32")
:ff-call-struct-return-by-implicit-arg-function
(intern "RECORD-TYPE-RETURNS-STRUCTURE-AS-FIRST-ARG"
"X86-SOLARIS32")
:callback-bindings-function
(intern "GENERATE-CALLBACK-BINDINGS" "X86-SOLARIS32")
:callback-return-value-function
(intern "GENERATE-CALLBACK-RETURN-VALUE" "X86-SOLARIS32")))
(:freebsdx8632
(make-ftd :interface-db-directory "ccl:freebsd-headers;"
:interface-package-name "X86-FREEBSD32"
:attributes '(:bits-per-word 32
:signed-char nil
:struct-by-value t
:float-results-in-x87 t)
:ff-call-expand-function
(intern "EXPAND-FF-CALL" "X86-FREEBSD32")
:ff-call-struct-return-by-implicit-arg-function
(intern "RECORD-TYPE-RETURNS-STRUCTURE-AS-FIRST-ARG"
"X86-FREEBSD32")
:callback-bindings-function
(intern "GENERATE-CALLBACK-BINDINGS" "X86-FREEBSD32")
:callback-return-value-function
(intern "GENERATE-CALLBACK-RETURN-VALUE" "X86-FREEBSD32")))
)))
(install-standard-foreign-types ftd)
(use-interface-dir :libc ftd)
(setf (backend-target-foreign-type-data backend) ftd))))
#-x8632-target
(setup-x8632-ftd *x8632-backend*)
(pushnew *x8632-backend* *known-backends* :key #'backend-name)
;;; FFI stuff. The vanilla i386 ABI always returns structures as a
;;; hidden first argument. Some systems (Darwin, FreeBSD) use a
;;; variant that returns small (<= 64 bit) structures in registers.
;;; A returned structure is passed as a hidden first argument.
(defun x8632::record-type-returns-structure-as-first-arg (rtype)
(declare (ignore rtype))
t)
;;; All arguments are passed on the stack.
(defun x8632::expand-ff-call (callform args
&key (arg-coerce #'null-coerce-foreign-arg)
(result-coerce #'null-coerce-foreign-result))
(let* ((result-type-spec (or (car (last args)) :void))
(struct-by-value-p nil)
(result-op nil)
(result-temp nil)
(result-form nil))
(multiple-value-bind (result-type error)
(ignore-errors (parse-foreign-type result-type-spec))
(if error
(setq result-type-spec :void result-type *void-foreign-type*)
(setq args (butlast args)))
(collect ((argforms))
(when (typep result-type 'foreign-record-type)
(setq result-form (pop args))
(if (funcall (ftd-ff-call-struct-return-by-implicit-arg-function
*target-ftd*) result-type)
(progn
(setq result-type *void-foreign-type*
result-type-spec :void)
(argforms :address)
(argforms result-form))
(progn
(ecase (foreign-type-bits result-type)
(8 (setq result-type-spec :unsigned-byte
result-op '%get-unsigned-byte))
(16 (setq result-type-spec :unsigned-halfword
result-op '%get-unsigned-word))
(32 (setq result-type-spec :unsigned-fullword
result-op '%get-unsigned-long))
(64 (setq result-type-spec :unsigned-doubleword
result-op '%%get-unsigned-longlong)))
(setq result-type (parse-foreign-type result-type-spec))
(setq result-temp (gensym))
(setq struct-by-value-p t))))
(unless (evenp (length args))
(error "~s should be an even-length list of alternating foreign types and values" args))
(do* ((args args (cddr args)))
((null args))
(let* ((arg-type-spec (car args))
(arg-value-form (cadr args)))
(if (or (member arg-type-spec *foreign-representation-type-keywords*
:test #'eq)
(typep arg-type-spec 'unsigned-byte))
(progn
(argforms arg-type-spec)
(argforms arg-value-form))
(let* ((ftype (parse-foreign-type arg-type-spec))
(bits (ensure-foreign-type-bits ftype)))
(when (and (typep ftype 'foreign-record-type)
(eq (foreign-record-type-kind ftype)
:transparent-union))
(ensure-foreign-type-bits ftype)
(setq ftype (foreign-record-field-type
(car (foreign-record-type-fields ftype)))
arg-type-spec (foreign-type-to-representation-type
ftype)
bits (ensure-foreign-type-bits ftype)))
(if (typep ftype 'foreign-record-type)
(argforms (ceiling bits 32))
(argforms (foreign-type-to-representation-type ftype)))
(argforms (funcall arg-coerce arg-type-spec arg-value-form))))))
(argforms (foreign-type-to-representation-type result-type))
(let* ((call (funcall result-coerce result-type-spec
`(,@callform ,@(argforms)))))
(if struct-by-value-p
`(let* ((,result-temp (%null-ptr)))
(declare (dynamic-extent ,result-temp)
(type macptr ,result-temp))
(%setf-macptr ,result-temp ,result-form)
(setf (,result-op ,result-temp 0)
,call))
call))))))
;;; Return 8 values:
;;; A list of RLET bindings
;;; A list of LET* bindings
;;; A list of DYNAMIC-EXTENT declarations for the LET* bindings
;;; A list of initializaton forms for (some) structure args (not used on x8632)
;;; A FOREIGN-TYPE representing the "actual" return type.
;;; A form which can be used to initialize FP-ARGS-PTR, relative
;;; to STACK-PTR. (not used on x8632)
;;; The byte offset of the foreign return address, relative to STACK-PTR
;;; The number of argument bytes pushed on the stack by the caller, or NIL
;;; if this can't be determined. (Only meaningful on Windows.)
(defun x8632::generate-callback-bindings (stack-ptr fp-args-ptr argvars
argspecs result-spec
struct-result-name)
(declare (ignore fp-args-ptr))
(collect ((lets)
(rlets)
(dynamic-extent-names))
(let* ((rtype (parse-foreign-type result-spec)))
(when (typep rtype 'foreign-record-type)
(if (funcall (ftd-ff-call-struct-return-by-implicit-arg-function
*target-ftd*) rtype)
(setq argvars (cons struct-result-name argvars)
argspecs (cons :address argspecs)
rtype *void-foreign-type*)
(rlets (list struct-result-name (foreign-record-type-name rtype)))))
(do* ((argvars argvars (cdr argvars))
(argspecs argspecs (cdr argspecs))
(offset 8))
((null argvars)
(values (rlets) (lets) (dynamic-extent-names) nil rtype nil 4
(- offset 8)))
(let* ((name (car argvars))
(spec (car argspecs))
(argtype (parse-foreign-type spec))
(bits (require-foreign-type-bits argtype))
(double nil))
(if (typep argtype 'foreign-record-type)
(let* ((form `(%inc-ptr ,stack-ptr
,(prog1 offset
(incf offset
(* 4 (ceiling bits 32)))))))
(when name (lets (list name form))))
(let* ((form `(,
(ecase (foreign-type-to-representation-type argtype)
(:single-float '%get-single-float)
(:double-float (setq double t) '%get-double-float)
(:signed-doubleword (setq double t)
'%%get-signed-longlong)
(:signed-fullword '%get-signed-long)
(:signed-halfword '%get-signed-word)
(:signed-byte '%get-signed-byte)
(:unsigned-doubleword (setq double t)
'%%get-unsigned-longlong)
(:unsigned-fullword '%get-unsigned-long)
(:unsigned-halfword '%get-unsigned-word)
(:unsigned-byte '%get-unsigned-byte)
(:address '%get-ptr))
,stack-ptr
,offset)))
(when name (lets (list name form)))
(incf offset 4)
(when double (incf offset 4)))))))))
(defun x8632::generate-callback-return-value (stack-ptr fp-args-ptr result
return-type struct-return-arg)
(declare (ignore fp-args-ptr))
(unless (eq return-type *void-foreign-type*)
(if (typep return-type 'foreign-record-type)
;; If the struct result is returned via a hidden argument, the
;; return type would have been mapped to :VOID. On some
;; systems, small (<= 64 bits) structs are returned by value,
;; which we arrange to retrieve here.
(ecase (ensure-foreign-type-bits return-type)
(8 `(setf (%get-unsigned-byte ,stack-ptr -8)
(%get-unsigned-byte ,struct-return-arg 0)))
(16 `(setf (%get-unsigned-word ,stack-ptr -8)
(%get-unsigned-word ,struct-return-arg 0)))
(32 `(setf (%get-unsigned-long ,stack-ptr -8)
(%get-unsigned-long ,struct-return-arg 0)))
(64 `(setf (%%get-unsigned-longlong ,stack-ptr -8)
(%%get-unsigned-longlong ,struct-return-arg 0))))
(let* ((return-type-keyword (foreign-type-to-representation-type
return-type)))
(collect ((forms))
(forms 'progn)
(case return-type-keyword
(:single-float
(forms `(setf (%get-unsigned-byte ,stack-ptr -16) 1)))
(:double-float
(forms `(setf (%get-unsigned-byte ,stack-ptr -16) 2))))
(forms
`(setf (,
(case return-type-keyword
(:address '%get-ptr)
(:signed-doubleword '%%get-signed-longlong)
(:unsigned-doubleword '%%get-unsigned-longlong)
(:double-float '%get-double-float)
(:single-float '%get-single-float)
(:unsigned-fullword '%get-unsigned-long)
(t '%get-signed-long)
) ,stack-ptr -8) ,result))
(forms))))))
#+x8632-target
(require "X8632-VINSNS")
(provide "X8632-BACKEND")
| true |
;;;-*- Mode: Lisp; Package: CCL -*-
;;;
;;; Copyright 2009 PI:NAME:<NAME>END_PI
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
(in-package "CCL")
(eval-when (:compile-toplevel :load-toplevel :execute)
(require "BACKEND"))
(eval-when (:compile-toplevel :execute)
(require "NXENV")
(require "X8632ENV"))
(defvar *x8632-vinsn-templates* (make-hash-table :test #'eq))
(defvar *known-x8632-backends* ())
#+darwinx86-target
(defvar *darwinx8632-backend*
(make-backend :lookup-opcode 'lookup-x86-opcode
:lookup-macro #'false
:lap-opcodes x86::*x86-opcode-templates*
:define-vinsn 'define-x86-vinsn
:p2-dispatch *x862-specials*
:p2-vinsn-templates *x8632-vinsn-templates*
:p2-template-hash-name '*x8632-vinsn-templates*
:p2-compile 'x862-compile
:platform-syscall-mask (logior platform-os-darwin platform-cpu-x86 platform-word-size-32)
:target-specific-features
'(:x8632 :x86-target :darwin-target :darwinx86-target :x8632-target
:darwinx8632-target
:little-endian-target
:32-bit-target)
:target-fasl-pathname (make-pathname :type "dx32fsl")
:target-platform (logior platform-cpu-x86
platform-os-darwin
platform-word-size-32)
:target-os :darwinx86
:name :darwinx8632
:target-arch-name :x8632
:target-foreign-type-data nil
:target-arch x8632::*x8632-target-arch*
:lisp-context-register x8632::fs
:num-arg-regs 2
))
#+darwinx86-target
(pushnew *darwinx8632-backend* *known-x8632-backends* :key #'PI:KEY:<KEY>END_PI-name)
#+linuxx86-target
(defvar *linuxx8632-backend*
(make-backend :lookup-opcode 'lookup-x86-opcode
:lookup-macro #'false
:lap-opcodes x86::*x86-opcode-templates*
:define-vinsn 'define-x86-vinsn
:p2-dispatch *x862-specials*
:p2-vinsn-templates *x8632-vinsn-templates*
:p2-template-hash-name '*x8632-vinsn-templates*
:p2-compile 'x862-compile
:platform-syscall-mask (logior platform-os-linux platform-cpu-x86 platform-word-size-32)
:target-specific-features
'(:x8632 :x86-target :linux-target :linuxx86-target :x8632-target
:linuxx8632-target
:little-endian-target
:32-bit-target)
:target-fasl-pathname (make-pathname :type "lx32fsl")
:target-platform (logior platform-cpu-x86
platform-os-linux
platform-word-size-32)
:target-os :linuxx86
:name :linuxx8632
:target-arch-name :x8632
:target-foreign-type-data nil
:target-arch x8632::*x8632-target-arch*
:lisp-context-register x8632::fs
:num-arg-regs 2
))
#+linuxx86-target
(pushnew *linuxx8632-backend* *known-x8632-backends* :key #'backend-name)
#+windows-target
(defvar *win32-backend*
(make-backend :lookup-opcode 'lookup-x86-opcode
:lookup-macro #'false
:lap-opcodes x86::*x86-opcode-templates*
:define-vinsn 'define-x86-vinsn
:p2-dispatch *x862-specials*
:p2-vinsn-templates *x8632-vinsn-templates*
:p2-template-hash-name '*x8632-vinsn-templates*
:p2-compile 'x862-compile
:platform-syscall-mask (logior platform-os-windows platform-cpu-x86 platform-word-size-32)
:target-specific-features
'(:x8632 :x86-target :windows-target :win32-target :x8632-target
:windowsx8632-target
:little-endian-target
:32-bit-target)
:target-fasl-pathname (make-pathname :type "wx32fsl")
:target-platform (logior platform-cpu-x86
platform-os-windows
platform-word-size-32)
:target-os :win32
:name :win32
:target-arch-name :x8632
:target-foreign-type-data nil
:target-arch x8632::*x8632-target-arch*
:lisp-context-register x8632::fs
:num-arg-regs 2
))
#+windows-target
(pushnew *win32-backend* *known-x8632-backends* :key #'backend-name)
#+solaris-target
(defvar *solaris-x8632-backend*
(make-backend :lookup-opcode 'lookup-x86-opcode
:lookup-macro #'false
:lap-opcodes x86::*x86-opcode-templates*
:define-vinsn 'define-x86-vinsn
:p2-dispatch *x862-specials*
:p2-vinsn-templates *x8632-vinsn-templates*
:p2-template-hash-name '*x8632-vinsn-templates*
:p2-compile 'x862-compile
:platform-syscall-mask (logior platform-os-solaris platform-cpu-x86 platform-word-size-32)
:target-specific-features
'(:x8632 :x86-target :solaris-target :x8632-target
:solarisx8632-target
:little-endian-target
:32-bit-target)
:target-fasl-pathname (make-pathname :type "sx32fsl")
:target-platform (logior platform-cpu-x86
platform-os-solaris
platform-word-size-32)
:target-os :solarisx8632
:name :solarisx8632
:target-arch-name :x8632
:target-foreign-type-data nil
:target-arch x8632::*x8632-target-arch*
:lisp-context-register x8632::fs
:num-arg-regs 2
))
#+solaris-target
(pushnew *solaris-x8632-backend* *known-x8632-backends* :key #'backend-name)
#+freebsd-target
(defvar *freebsd-x8632-backend*
(make-backend :lookup-opcode 'lookup-x86-opcode
:lookup-macro #'false
:lap-opcodes x86::*x86-opcode-templates*
:define-vinsn 'define-x86-vinsn
:p2-dispatch *x862-specials*
:p2-vinsn-templates *x8632-vinsn-templates*
:p2-template-hash-name '*x8632-vinsn-templates*
:p2-compile 'x862-compile
:platform-syscall-mask (logior platform-os-freebsd platform-cpu-x86 platform-word-size-32)
:target-specific-features
'(:x8632 :x86-target :freebsd-target :x8632-target
:freebsdx8632-target
:little-endian-target
:32-bit-target)
:target-fasl-pathname (make-pathname :type "fx32fsl")
:target-platform (logior platform-cpu-x86
platform-os-freebsd
platform-word-size-32)
:target-os :freebsdx8632
:name :freebsdx8632
:target-arch-name :x8632
:target-foreign-type-data nil
:target-arch x8632::*x8632-target-arch*
:lisp-context-register x8632::fs
:num-arg-regs 2
))
#+freebsd-target
(pushnew *freebsd-x8632-backend* *known-x8632-backends* :key #'backend-name)
(defvar *x8632-backend* (car *known-x8632-backends*))
(defun fixup-x8632-backend ()
(dolist (b *known-x8632-backends*)
(setf #| (backend-lap-opcodes b) x86::*x86-opcodes* |#
(backend-p2-dispatch b) *x862-specials*
(backend-p2-vinsn-templates b) *x8632-vinsn-templates*)
(or (backend-lap-macros b) (setf (backend-lap-macros b)
(make-hash-table :test #'equalp)))))
(fixup-x8632-backend)
#+x8632-target
(setq *host-backend* *x8632-backend* *target-backend* *x8632-backend*)
(defun setup-x8632-ftd (backend)
(or (backend-target-foreign-type-data backend)
(let* ((name (backend-name backend))
(ftd
(case name
(:darwinx8632
(make-ftd :interface-db-directory "ccl:darwin-x86-headers;"
:interface-package-name "X86-DARWIN32"
:attributes '(:bits-per-word 32
:signed-char t
:struct-by-value t
:prepend-underscore t)
:ff-call-expand-function
(intern "EXPAND-FF-CALL" "X86-DARWIN32")
:ff-call-struct-return-by-implicit-arg-function
(intern "RECORD-TYPE-RETURNS-STRUCTURE-AS-FIRST-ARG"
"X86-DARWIN32")
:callback-bindings-function
(intern "GENERATE-CALLBACK-BINDINGS" "X86-DARWIN32")
:callback-return-value-function
(intern "GENERATE-CALLBACK-RETURN-VALUE" "X86-DARWIN32")))
(:linuxx8632
(make-ftd :interface-db-directory "ccl:x86-headers;"
:interface-package-name "X86-LINUX32"
:attributes '(:bits-per-word 32
:signed-char nil
:struct-by-value t
:float-results-in-x87 t)
:ff-call-expand-function
(intern "EXPAND-FF-CALL" "X86-LINUX32")
:ff-call-struct-return-by-implicit-arg-function
(intern "RECORD-TYPE-RETURNS-STRUCTURE-AS-FIRST-ARG"
"X86-LINUX32")
:callback-bindings-function
(intern "GENERATE-CALLBACK-BINDINGS" "X86-LINUX32")
:callback-return-value-function
(intern "GENERATE-CALLBACK-RETURN-VALUE" "X86-LINUX32")))
(:win32
(make-ftd :interface-db-directory "ccl:win32-headers;"
:interface-package-name "WIN32"
:attributes '(:bits-per-word 32
:signed-char nil
:struct-by-value t
:float-results-in-x87 t)
:ff-call-expand-function
(intern "EXPAND-FF-CALL" "WIN32")
:ff-call-struct-return-by-implicit-arg-function
(intern "RECORD-TYPE-RETURNS-STRUCTURE-AS-FIRST-ARG"
"WIN32")
:callback-bindings-function
(intern "GENERATE-CALLBACK-BINDINGS" "WIN32")
:callback-return-value-function
(intern "GENERATE-CALLBACK-RETURN-VALUE" "WIN32")))
(:solarisx8632
(make-ftd :interface-db-directory "ccl:solarisx86-headers;"
:interface-package-name "X86-SOLARIS32"
:attributes '(:bits-per-word 32
:signed-char nil
:struct-by-value t
:float-results-in-x87 t)
:ff-call-expand-function
(intern "EXPAND-FF-CALL" "X86-SOLARIS32")
:ff-call-struct-return-by-implicit-arg-function
(intern "RECORD-TYPE-RETURNS-STRUCTURE-AS-FIRST-ARG"
"X86-SOLARIS32")
:callback-bindings-function
(intern "GENERATE-CALLBACK-BINDINGS" "X86-SOLARIS32")
:callback-return-value-function
(intern "GENERATE-CALLBACK-RETURN-VALUE" "X86-SOLARIS32")))
(:freebsdx8632
(make-ftd :interface-db-directory "ccl:freebsd-headers;"
:interface-package-name "X86-FREEBSD32"
:attributes '(:bits-per-word 32
:signed-char nil
:struct-by-value t
:float-results-in-x87 t)
:ff-call-expand-function
(intern "EXPAND-FF-CALL" "X86-FREEBSD32")
:ff-call-struct-return-by-implicit-arg-function
(intern "RECORD-TYPE-RETURNS-STRUCTURE-AS-FIRST-ARG"
"X86-FREEBSD32")
:callback-bindings-function
(intern "GENERATE-CALLBACK-BINDINGS" "X86-FREEBSD32")
:callback-return-value-function
(intern "GENERATE-CALLBACK-RETURN-VALUE" "X86-FREEBSD32")))
)))
(install-standard-foreign-types ftd)
(use-interface-dir :libc ftd)
(setf (backend-target-foreign-type-data backend) ftd))))
#-x8632-target
(setup-x8632-ftd *x8632-backend*)
(pushnew *x8632-backend* *known-backends* :key #'backend-name)
;;; FFI stuff. The vanilla i386 ABI always returns structures as a
;;; hidden first argument. Some systems (Darwin, FreeBSD) use a
;;; variant that returns small (<= 64 bit) structures in registers.
;;; A returned structure is passed as a hidden first argument.
(defun x8632::record-type-returns-structure-as-first-arg (rtype)
(declare (ignore rtype))
t)
;;; All arguments are passed on the stack.
(defun x8632::expand-ff-call (callform args
&key (arg-coerce #'null-coerce-foreign-arg)
(result-coerce #'null-coerce-foreign-result))
(let* ((result-type-spec (or (car (last args)) :void))
(struct-by-value-p nil)
(result-op nil)
(result-temp nil)
(result-form nil))
(multiple-value-bind (result-type error)
(ignore-errors (parse-foreign-type result-type-spec))
(if error
(setq result-type-spec :void result-type *void-foreign-type*)
(setq args (butlast args)))
(collect ((argforms))
(when (typep result-type 'foreign-record-type)
(setq result-form (pop args))
(if (funcall (ftd-ff-call-struct-return-by-implicit-arg-function
*target-ftd*) result-type)
(progn
(setq result-type *void-foreign-type*
result-type-spec :void)
(argforms :address)
(argforms result-form))
(progn
(ecase (foreign-type-bits result-type)
(8 (setq result-type-spec :unsigned-byte
result-op '%get-unsigned-byte))
(16 (setq result-type-spec :unsigned-halfword
result-op '%get-unsigned-word))
(32 (setq result-type-spec :unsigned-fullword
result-op '%get-unsigned-long))
(64 (setq result-type-spec :unsigned-doubleword
result-op '%%get-unsigned-longlong)))
(setq result-type (parse-foreign-type result-type-spec))
(setq result-temp (gensym))
(setq struct-by-value-p t))))
(unless (evenp (length args))
(error "~s should be an even-length list of alternating foreign types and values" args))
(do* ((args args (cddr args)))
((null args))
(let* ((arg-type-spec (car args))
(arg-value-form (cadr args)))
(if (or (member arg-type-spec *foreign-representation-type-keywords*
:test #'eq)
(typep arg-type-spec 'unsigned-byte))
(progn
(argforms arg-type-spec)
(argforms arg-value-form))
(let* ((ftype (parse-foreign-type arg-type-spec))
(bits (ensure-foreign-type-bits ftype)))
(when (and (typep ftype 'foreign-record-type)
(eq (foreign-record-type-kind ftype)
:transparent-union))
(ensure-foreign-type-bits ftype)
(setq ftype (foreign-record-field-type
(car (foreign-record-type-fields ftype)))
arg-type-spec (foreign-type-to-representation-type
ftype)
bits (ensure-foreign-type-bits ftype)))
(if (typep ftype 'foreign-record-type)
(argforms (ceiling bits 32))
(argforms (foreign-type-to-representation-type ftype)))
(argforms (funcall arg-coerce arg-type-spec arg-value-form))))))
(argforms (foreign-type-to-representation-type result-type))
(let* ((call (funcall result-coerce result-type-spec
`(,@callform ,@(argforms)))))
(if struct-by-value-p
`(let* ((,result-temp (%null-ptr)))
(declare (dynamic-extent ,result-temp)
(type macptr ,result-temp))
(%setf-macptr ,result-temp ,result-form)
(setf (,result-op ,result-temp 0)
,call))
call))))))
;;; Return 8 values:
;;; A list of RLET bindings
;;; A list of LET* bindings
;;; A list of DYNAMIC-EXTENT declarations for the LET* bindings
;;; A list of initializaton forms for (some) structure args (not used on x8632)
;;; A FOREIGN-TYPE representing the "actual" return type.
;;; A form which can be used to initialize FP-ARGS-PTR, relative
;;; to STACK-PTR. (not used on x8632)
;;; The byte offset of the foreign return address, relative to STACK-PTR
;;; The number of argument bytes pushed on the stack by the caller, or NIL
;;; if this can't be determined. (Only meaningful on Windows.)
(defun x8632::generate-callback-bindings (stack-ptr fp-args-ptr argvars
argspecs result-spec
struct-result-name)
(declare (ignore fp-args-ptr))
(collect ((lets)
(rlets)
(dynamic-extent-names))
(let* ((rtype (parse-foreign-type result-spec)))
(when (typep rtype 'foreign-record-type)
(if (funcall (ftd-ff-call-struct-return-by-implicit-arg-function
*target-ftd*) rtype)
(setq argvars (cons struct-result-name argvars)
argspecs (cons :address argspecs)
rtype *void-foreign-type*)
(rlets (list struct-result-name (foreign-record-type-name rtype)))))
(do* ((argvars argvars (cdr argvars))
(argspecs argspecs (cdr argspecs))
(offset 8))
((null argvars)
(values (rlets) (lets) (dynamic-extent-names) nil rtype nil 4
(- offset 8)))
(let* ((name (car argvars))
(spec (car argspecs))
(argtype (parse-foreign-type spec))
(bits (require-foreign-type-bits argtype))
(double nil))
(if (typep argtype 'foreign-record-type)
(let* ((form `(%inc-ptr ,stack-ptr
,(prog1 offset
(incf offset
(* 4 (ceiling bits 32)))))))
(when name (lets (list name form))))
(let* ((form `(,
(ecase (foreign-type-to-representation-type argtype)
(:single-float '%get-single-float)
(:double-float (setq double t) '%get-double-float)
(:signed-doubleword (setq double t)
'%%get-signed-longlong)
(:signed-fullword '%get-signed-long)
(:signed-halfword '%get-signed-word)
(:signed-byte '%get-signed-byte)
(:unsigned-doubleword (setq double t)
'%%get-unsigned-longlong)
(:unsigned-fullword '%get-unsigned-long)
(:unsigned-halfword '%get-unsigned-word)
(:unsigned-byte '%get-unsigned-byte)
(:address '%get-ptr))
,stack-ptr
,offset)))
(when name (lets (list name form)))
(incf offset 4)
(when double (incf offset 4)))))))))
(defun x8632::generate-callback-return-value (stack-ptr fp-args-ptr result
return-type struct-return-arg)
(declare (ignore fp-args-ptr))
(unless (eq return-type *void-foreign-type*)
(if (typep return-type 'foreign-record-type)
;; If the struct result is returned via a hidden argument, the
;; return type would have been mapped to :VOID. On some
;; systems, small (<= 64 bits) structs are returned by value,
;; which we arrange to retrieve here.
(ecase (ensure-foreign-type-bits return-type)
(8 `(setf (%get-unsigned-byte ,stack-ptr -8)
(%get-unsigned-byte ,struct-return-arg 0)))
(16 `(setf (%get-unsigned-word ,stack-ptr -8)
(%get-unsigned-word ,struct-return-arg 0)))
(32 `(setf (%get-unsigned-long ,stack-ptr -8)
(%get-unsigned-long ,struct-return-arg 0)))
(64 `(setf (%%get-unsigned-longlong ,stack-ptr -8)
(%%get-unsigned-longlong ,struct-return-arg 0))))
(let* ((return-type-keyword (foreign-type-to-representation-type
return-type)))
(collect ((forms))
(forms 'progn)
(case return-type-keyword
(:single-float
(forms `(setf (%get-unsigned-byte ,stack-ptr -16) 1)))
(:double-float
(forms `(setf (%get-unsigned-byte ,stack-ptr -16) 2))))
(forms
`(setf (,
(case return-type-keyword
(:address '%get-ptr)
(:signed-doubleword '%%get-signed-longlong)
(:unsigned-doubleword '%%get-unsigned-longlong)
(:double-float '%get-double-float)
(:single-float '%get-single-float)
(:unsigned-fullword '%get-unsigned-long)
(t '%get-signed-long)
) ,stack-ptr -8) ,result))
(forms))))))
#+x8632-target
(require "X8632-VINSNS")
(provide "X8632-BACKEND")
|
[
{
"context": ";;;; game-theory.lisp\n;;;;\n;;;; Copyright (c) 2017 Jeremiah LaRocco <[email protected]>\n\n(in-package #:game-",
"end": 67,
"score": 0.9998846054077148,
"start": 51,
"tag": "NAME",
"value": "Jeremiah LaRocco"
},
{
"context": "sp\n;;;;\n;;;; Copyright (c) 2017 Jeremiah LaRocco <[email protected]>\n\n(in-package #:game-theory)\n\n(defclass 2-player-",
"end": 95,
"score": 0.9999330639839172,
"start": 69,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
game-theory.lisp
|
jl2/game-theory
| 0 |
;;;; game-theory.lisp
;;;;
;;;; Copyright (c) 2017 Jeremiah LaRocco <[email protected]>
(in-package #:game-theory)
(defclass 2-player-game ()
((payoffs :initarg :payoffs)))
(defun create-game (first-player second-player)
(when (or (/= (mcols first-player) (mcols second-player))
(/= (mrows first-player) (mrows second-player)))
(error "first-player and second-player must have the same dimensions."))
(make-instance '2-player-game :payoffs (make-array 2 :initial-contents (list first-player second-player))))
(defun play (game times)
(let ((p1-score 0)
(p2-score 0))
(with-slots (payoffs) game
(dotimes (i times)
(let ((p1-choice (random (mcols (aref payoffs 0))))
(p2-choice (random (mrows (aref payoffs 1)))))
(incf p1-score (mcref (aref payoffs 0) p1-choice p2-choice))
(incf p2-score (mcref (aref payoffs 1) p1-choice p2-choice)))))
(values p1-score p2-score)))
(defun show-game (game)
(with-slots (payoffs) game
(let ((p1 (aref payoffs 0))
(p2 (aref payoffs 1)))
(dotimes (i (mcols p1))
(dotimes (j (mrows p2))
(format t "(~4f ~4f) " (mcref p1 i j) (mcref p2 i j)))
(format t "~%")))))
|
15804
|
;;;; game-theory.lisp
;;;;
;;;; Copyright (c) 2017 <NAME> <<EMAIL>>
(in-package #:game-theory)
(defclass 2-player-game ()
((payoffs :initarg :payoffs)))
(defun create-game (first-player second-player)
(when (or (/= (mcols first-player) (mcols second-player))
(/= (mrows first-player) (mrows second-player)))
(error "first-player and second-player must have the same dimensions."))
(make-instance '2-player-game :payoffs (make-array 2 :initial-contents (list first-player second-player))))
(defun play (game times)
(let ((p1-score 0)
(p2-score 0))
(with-slots (payoffs) game
(dotimes (i times)
(let ((p1-choice (random (mcols (aref payoffs 0))))
(p2-choice (random (mrows (aref payoffs 1)))))
(incf p1-score (mcref (aref payoffs 0) p1-choice p2-choice))
(incf p2-score (mcref (aref payoffs 1) p1-choice p2-choice)))))
(values p1-score p2-score)))
(defun show-game (game)
(with-slots (payoffs) game
(let ((p1 (aref payoffs 0))
(p2 (aref payoffs 1)))
(dotimes (i (mcols p1))
(dotimes (j (mrows p2))
(format t "(~4f ~4f) " (mcref p1 i j) (mcref p2 i j)))
(format t "~%")))))
| true |
;;;; game-theory.lisp
;;;;
;;;; Copyright (c) 2017 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
(in-package #:game-theory)
(defclass 2-player-game ()
((payoffs :initarg :payoffs)))
(defun create-game (first-player second-player)
(when (or (/= (mcols first-player) (mcols second-player))
(/= (mrows first-player) (mrows second-player)))
(error "first-player and second-player must have the same dimensions."))
(make-instance '2-player-game :payoffs (make-array 2 :initial-contents (list first-player second-player))))
(defun play (game times)
(let ((p1-score 0)
(p2-score 0))
(with-slots (payoffs) game
(dotimes (i times)
(let ((p1-choice (random (mcols (aref payoffs 0))))
(p2-choice (random (mrows (aref payoffs 1)))))
(incf p1-score (mcref (aref payoffs 0) p1-choice p2-choice))
(incf p2-score (mcref (aref payoffs 1) p1-choice p2-choice)))))
(values p1-score p2-score)))
(defun show-game (game)
(with-slots (payoffs) game
(let ((p1 (aref payoffs 0))
(p2 (aref payoffs 1)))
(dotimes (i (mcols p1))
(dotimes (j (mrows p2))
(format t "(~4f ~4f) " (mcref p1 i j) (mcref p2 i j)))
(format t "~%")))))
|
[
{
"context": "ing and retrieval API.\n;;;\n;;; Copyright (c) 2006, Alexey Dvoychenkov\n;;; Copyright (c) 2006, Luis Oliveira <loliveira",
"end": 160,
"score": 0.9998268485069275,
"start": 142,
"tag": "NAME",
"value": "Alexey Dvoychenkov"
},
{
"context": ") 2006, Alexey Dvoychenkov\n;;; Copyright (c) 2006, Luis Oliveira <[email protected]>\n;;;\n;;; Redistributi",
"end": 198,
"score": 0.9998820424079895,
"start": 185,
"tag": "NAME",
"value": "Luis Oliveira"
},
{
"context": "oychenkov\n;;; Copyright (c) 2006, Luis Oliveira <[email protected]>\n;;;\n;;; Redistribution and use in source and bin",
"end": 226,
"score": 0.9999319911003113,
"start": 201,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
glut/state.lisp
|
azimut/cl-opengl
| 174 |
;;; -*- Mode: Lisp; indent-tabs-mode: nil -*-
;;;
;;; state.lisp --- GLUT Window state setting and retrieval API.
;;;
;;; Copyright (c) 2006, Alexey Dvoychenkov
;;; Copyright (c) 2006, Luis Oliveira <[email protected]>
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; o Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; o Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;; o Neither the name of the author nor the names of the contributors may
;;; be used to endorse or promote products derived from this software
;;; without specific prior written permission.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
;;; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
;;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package #:cl-glut)
;;; Unimplemented freeglut extensions:
;;;
;;; FGAPI void* FGAPIENTRY glutGetWindowData( void );
;;; FGAPI void FGAPIENTRY glutSetWindowData(void* data);
;;; FGAPI void* FGAPIENTRY glutGetMenuData( void );
;;; FGAPI void FGAPIENTRY glutSetMenuData(void* data);
;;; Setting Options
(defparameter *window-close-action* nil)
;; freeglut ext
(defcenum (options %gl:enum)
(:init-window-x #x01F4)
:init-window-y
:init-window-width
:init-window-height
:init-display-mode
:action-on-window-close
(:multisample 128)
(:rendering-context #x01FD)
:direct-rendering
(:window-cursor #x007A))
;;; freeglut ext
#-darwin
(defcfun ("glutSetOption" set-option) :void
(option options)
(value :int))
#+darwin
(defun set-option (val1 val2)
(declare (ignore val1 val2))
(warn "GLUT:SET-OPTION not supported in GLUT.framework"))
;;; Also provide some utility functions around glutSetOption().
;; freeglut ext
(defcenum rendering-context
:create-new-context
:use-current-context)
;; freeglut ext
(defcenum rendering-context-options
:force-indirect-context
:allow-direct-context
:try-direct-context
:force-direct-context)
;; freeglut ext
(defcenum window-close-behaviour
:action-exit
:action-glutmainloop-returns
:action-continue-execution)
(defbitfield (display-mode :unsigned-int)
(:rgb 0)
(:rgba 0)
(:index 1)
(:single 0)
(:double 2)
(:accum 4)
(:alpha 8)
(:depth 16)
(:stencil 32)
(:multisample 128)
(:stereo 256)
(:luminance 512)
(:aux1 #x1000) ; freeglut ext
(:aux2 #x2000) ; freeglut ext
(:aux3 #x4000) ; freeglut ext
(:aux4 #x8000)) ; freeglut ext
(defun set-display-mode (&rest options)
(set-option :init-display-mode
(foreign-bitfield-value 'display-mode options)))
(defun set-action-on-window-close (action)
#-darwin
(set-option :action-on-window-close
(foreign-enum-value 'window-close-behaviour action))
(setf *window-close-action* action))
(defun set-rendering-context (option)
(set-option :rendering-context
(foreign-enum-value 'rendering-context option)))
(defun set-direct-rendering (option)
(set-option :direct-rendering
(foreign-enum-value 'rendering-context-options option)))
;;; Getting Options
(defcenum (get-param %gl:enum)
(:window-x #x0064)
:window-y
:window-width
:window-height
:window-buffer-size
:window-stencil-size
:window-depth-size
:window-red-size
:window-green-size
:window-blue-size
:window-alpha-size
:window-accum-red-size
:window-accum-green-size
:window-accum-blue-size
:window-accum-alpha-size
:window-doublebuffer
:window-rgba
:window-parent
:window-num-children
:window-colormap-size
:window-num-samples
:window-stereo
:window-cursor
(:screen-width #x00C8)
:screen-height
:screen-width-mm
:screen-height-mm
(:menu-num-items #x012C)
(:display-mode-possible #x0190)
(:init-window-x #x01F4)
:init-window-y
:init-window-width
:init-window-height
:init-display-mode
(:elapsed-time #x02BC)
(:window-format-id #x007B)
:init-state
(:action-on-window-close #x01F9) ; freeglut ext
:window-border-width ; freeglut ext
:window-header-height ; freeglut ext
:version ; freeglut ext
#-darwin :rendering-context ; freeglut ext
:direct-rendering)
(defcfun ("glutGet" get) :int
(query get-param))
;;; Utility functions around glutGet().
(defun getp (query)
(if (= (get query) 0)
nil
t))
(defun get-window-cursor ()
(foreign-enum-keyword 'cursor (get :window-cursor)))
(defun get-init-display-mode ()
(foreign-bitfield-symbols 'display-mode (get :init-display-mode)))
;;; Other Getters
(defcenum (device-get-param %gl:enum)
(:has-keyboard #x0258)
:has-mouse
:has-spaceball
:has-dial-and-button-box
:has-tablet
:num-mouse-buttons
:num-spaceball-buttons
:num-button-box-buttons
:num-dials
:num-tablet-buttons
:device-ignore-key-repeat
:device-key-repeat
:has-joystick
:owns-joystick
:joystick-buttons
:joystick-axes
:joystick-poll-rate)
(defcfun ("glutDeviceGet" device-get) :int
(query device-get-param))
(defun device-getp (query)
(if (= (device-get query) 0)
nil
t))
(defcenum (layer-get-param %gl:enum)
(:overlay-possible #x0320)
:layer-in-use
:has-overlay
:transparent-index
:normal-damaged
:overlay-damaged)
(defcfun ("glutLayerGet" layer-get) :int
(query layer-get-param))
(defun layer-getp (query)
(if (= (layer-get query) 0)
nil
t))
(defun get-layer-in-use ()
(foreign-enum-keyword 'layer-type (layer-get :layer-in-use)))
(defcfun ("glutGetModifiers" %glutGetModifiers) :int)
(declaim (inline get-modifiers))
(defun get-modifiers ()
(foreign-bitfield-symbols 'modifiers (%glutGetModifiers)))
;;; No idea if this is more efficient space-wise...
(declaim (inline get-modifier-values))
(defun get-modifier-values ()
(let ((mask (%glutGetModifiers)))
(values (= 1 (logand mask 1)) ; shift
(= 2 (logand mask 2)) ; ctrl
(= 4 (logand mask 4))))) ; alt
(defcfun ("glutExtensionSupported" extension-supported-p) :boolean
(extension-name :string))
;;; freeglut ext
(defcfun ("glutGetProcAddress" get-proc-address) :pointer
(proc-name :string))
|
82254
|
;;; -*- Mode: Lisp; indent-tabs-mode: nil -*-
;;;
;;; state.lisp --- GLUT Window state setting and retrieval API.
;;;
;;; Copyright (c) 2006, <NAME>
;;; Copyright (c) 2006, <NAME> <<EMAIL>>
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; o Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; o Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;; o Neither the name of the author nor the names of the contributors may
;;; be used to endorse or promote products derived from this software
;;; without specific prior written permission.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
;;; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
;;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package #:cl-glut)
;;; Unimplemented freeglut extensions:
;;;
;;; FGAPI void* FGAPIENTRY glutGetWindowData( void );
;;; FGAPI void FGAPIENTRY glutSetWindowData(void* data);
;;; FGAPI void* FGAPIENTRY glutGetMenuData( void );
;;; FGAPI void FGAPIENTRY glutSetMenuData(void* data);
;;; Setting Options
(defparameter *window-close-action* nil)
;; freeglut ext
(defcenum (options %gl:enum)
(:init-window-x #x01F4)
:init-window-y
:init-window-width
:init-window-height
:init-display-mode
:action-on-window-close
(:multisample 128)
(:rendering-context #x01FD)
:direct-rendering
(:window-cursor #x007A))
;;; freeglut ext
#-darwin
(defcfun ("glutSetOption" set-option) :void
(option options)
(value :int))
#+darwin
(defun set-option (val1 val2)
(declare (ignore val1 val2))
(warn "GLUT:SET-OPTION not supported in GLUT.framework"))
;;; Also provide some utility functions around glutSetOption().
;; freeglut ext
(defcenum rendering-context
:create-new-context
:use-current-context)
;; freeglut ext
(defcenum rendering-context-options
:force-indirect-context
:allow-direct-context
:try-direct-context
:force-direct-context)
;; freeglut ext
(defcenum window-close-behaviour
:action-exit
:action-glutmainloop-returns
:action-continue-execution)
(defbitfield (display-mode :unsigned-int)
(:rgb 0)
(:rgba 0)
(:index 1)
(:single 0)
(:double 2)
(:accum 4)
(:alpha 8)
(:depth 16)
(:stencil 32)
(:multisample 128)
(:stereo 256)
(:luminance 512)
(:aux1 #x1000) ; freeglut ext
(:aux2 #x2000) ; freeglut ext
(:aux3 #x4000) ; freeglut ext
(:aux4 #x8000)) ; freeglut ext
(defun set-display-mode (&rest options)
(set-option :init-display-mode
(foreign-bitfield-value 'display-mode options)))
(defun set-action-on-window-close (action)
#-darwin
(set-option :action-on-window-close
(foreign-enum-value 'window-close-behaviour action))
(setf *window-close-action* action))
(defun set-rendering-context (option)
(set-option :rendering-context
(foreign-enum-value 'rendering-context option)))
(defun set-direct-rendering (option)
(set-option :direct-rendering
(foreign-enum-value 'rendering-context-options option)))
;;; Getting Options
(defcenum (get-param %gl:enum)
(:window-x #x0064)
:window-y
:window-width
:window-height
:window-buffer-size
:window-stencil-size
:window-depth-size
:window-red-size
:window-green-size
:window-blue-size
:window-alpha-size
:window-accum-red-size
:window-accum-green-size
:window-accum-blue-size
:window-accum-alpha-size
:window-doublebuffer
:window-rgba
:window-parent
:window-num-children
:window-colormap-size
:window-num-samples
:window-stereo
:window-cursor
(:screen-width #x00C8)
:screen-height
:screen-width-mm
:screen-height-mm
(:menu-num-items #x012C)
(:display-mode-possible #x0190)
(:init-window-x #x01F4)
:init-window-y
:init-window-width
:init-window-height
:init-display-mode
(:elapsed-time #x02BC)
(:window-format-id #x007B)
:init-state
(:action-on-window-close #x01F9) ; freeglut ext
:window-border-width ; freeglut ext
:window-header-height ; freeglut ext
:version ; freeglut ext
#-darwin :rendering-context ; freeglut ext
:direct-rendering)
(defcfun ("glutGet" get) :int
(query get-param))
;;; Utility functions around glutGet().
(defun getp (query)
(if (= (get query) 0)
nil
t))
(defun get-window-cursor ()
(foreign-enum-keyword 'cursor (get :window-cursor)))
(defun get-init-display-mode ()
(foreign-bitfield-symbols 'display-mode (get :init-display-mode)))
;;; Other Getters
(defcenum (device-get-param %gl:enum)
(:has-keyboard #x0258)
:has-mouse
:has-spaceball
:has-dial-and-button-box
:has-tablet
:num-mouse-buttons
:num-spaceball-buttons
:num-button-box-buttons
:num-dials
:num-tablet-buttons
:device-ignore-key-repeat
:device-key-repeat
:has-joystick
:owns-joystick
:joystick-buttons
:joystick-axes
:joystick-poll-rate)
(defcfun ("glutDeviceGet" device-get) :int
(query device-get-param))
(defun device-getp (query)
(if (= (device-get query) 0)
nil
t))
(defcenum (layer-get-param %gl:enum)
(:overlay-possible #x0320)
:layer-in-use
:has-overlay
:transparent-index
:normal-damaged
:overlay-damaged)
(defcfun ("glutLayerGet" layer-get) :int
(query layer-get-param))
(defun layer-getp (query)
(if (= (layer-get query) 0)
nil
t))
(defun get-layer-in-use ()
(foreign-enum-keyword 'layer-type (layer-get :layer-in-use)))
(defcfun ("glutGetModifiers" %glutGetModifiers) :int)
(declaim (inline get-modifiers))
(defun get-modifiers ()
(foreign-bitfield-symbols 'modifiers (%glutGetModifiers)))
;;; No idea if this is more efficient space-wise...
(declaim (inline get-modifier-values))
(defun get-modifier-values ()
(let ((mask (%glutGetModifiers)))
(values (= 1 (logand mask 1)) ; shift
(= 2 (logand mask 2)) ; ctrl
(= 4 (logand mask 4))))) ; alt
(defcfun ("glutExtensionSupported" extension-supported-p) :boolean
(extension-name :string))
;;; freeglut ext
(defcfun ("glutGetProcAddress" get-proc-address) :pointer
(proc-name :string))
| true |
;;; -*- Mode: Lisp; indent-tabs-mode: nil -*-
;;;
;;; state.lisp --- GLUT Window state setting and retrieval API.
;;;
;;; Copyright (c) 2006, PI:NAME:<NAME>END_PI
;;; Copyright (c) 2006, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; o Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; o Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;; o Neither the name of the author nor the names of the contributors may
;;; be used to endorse or promote products derived from this software
;;; without specific prior written permission.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
;;; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
;;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package #:cl-glut)
;;; Unimplemented freeglut extensions:
;;;
;;; FGAPI void* FGAPIENTRY glutGetWindowData( void );
;;; FGAPI void FGAPIENTRY glutSetWindowData(void* data);
;;; FGAPI void* FGAPIENTRY glutGetMenuData( void );
;;; FGAPI void FGAPIENTRY glutSetMenuData(void* data);
;;; Setting Options
(defparameter *window-close-action* nil)
;; freeglut ext
(defcenum (options %gl:enum)
(:init-window-x #x01F4)
:init-window-y
:init-window-width
:init-window-height
:init-display-mode
:action-on-window-close
(:multisample 128)
(:rendering-context #x01FD)
:direct-rendering
(:window-cursor #x007A))
;;; freeglut ext
#-darwin
(defcfun ("glutSetOption" set-option) :void
(option options)
(value :int))
#+darwin
(defun set-option (val1 val2)
(declare (ignore val1 val2))
(warn "GLUT:SET-OPTION not supported in GLUT.framework"))
;;; Also provide some utility functions around glutSetOption().
;; freeglut ext
(defcenum rendering-context
:create-new-context
:use-current-context)
;; freeglut ext
(defcenum rendering-context-options
:force-indirect-context
:allow-direct-context
:try-direct-context
:force-direct-context)
;; freeglut ext
(defcenum window-close-behaviour
:action-exit
:action-glutmainloop-returns
:action-continue-execution)
(defbitfield (display-mode :unsigned-int)
(:rgb 0)
(:rgba 0)
(:index 1)
(:single 0)
(:double 2)
(:accum 4)
(:alpha 8)
(:depth 16)
(:stencil 32)
(:multisample 128)
(:stereo 256)
(:luminance 512)
(:aux1 #x1000) ; freeglut ext
(:aux2 #x2000) ; freeglut ext
(:aux3 #x4000) ; freeglut ext
(:aux4 #x8000)) ; freeglut ext
(defun set-display-mode (&rest options)
(set-option :init-display-mode
(foreign-bitfield-value 'display-mode options)))
(defun set-action-on-window-close (action)
#-darwin
(set-option :action-on-window-close
(foreign-enum-value 'window-close-behaviour action))
(setf *window-close-action* action))
(defun set-rendering-context (option)
(set-option :rendering-context
(foreign-enum-value 'rendering-context option)))
(defun set-direct-rendering (option)
(set-option :direct-rendering
(foreign-enum-value 'rendering-context-options option)))
;;; Getting Options
(defcenum (get-param %gl:enum)
(:window-x #x0064)
:window-y
:window-width
:window-height
:window-buffer-size
:window-stencil-size
:window-depth-size
:window-red-size
:window-green-size
:window-blue-size
:window-alpha-size
:window-accum-red-size
:window-accum-green-size
:window-accum-blue-size
:window-accum-alpha-size
:window-doublebuffer
:window-rgba
:window-parent
:window-num-children
:window-colormap-size
:window-num-samples
:window-stereo
:window-cursor
(:screen-width #x00C8)
:screen-height
:screen-width-mm
:screen-height-mm
(:menu-num-items #x012C)
(:display-mode-possible #x0190)
(:init-window-x #x01F4)
:init-window-y
:init-window-width
:init-window-height
:init-display-mode
(:elapsed-time #x02BC)
(:window-format-id #x007B)
:init-state
(:action-on-window-close #x01F9) ; freeglut ext
:window-border-width ; freeglut ext
:window-header-height ; freeglut ext
:version ; freeglut ext
#-darwin :rendering-context ; freeglut ext
:direct-rendering)
(defcfun ("glutGet" get) :int
(query get-param))
;;; Utility functions around glutGet().
(defun getp (query)
(if (= (get query) 0)
nil
t))
(defun get-window-cursor ()
(foreign-enum-keyword 'cursor (get :window-cursor)))
(defun get-init-display-mode ()
(foreign-bitfield-symbols 'display-mode (get :init-display-mode)))
;;; Other Getters
(defcenum (device-get-param %gl:enum)
(:has-keyboard #x0258)
:has-mouse
:has-spaceball
:has-dial-and-button-box
:has-tablet
:num-mouse-buttons
:num-spaceball-buttons
:num-button-box-buttons
:num-dials
:num-tablet-buttons
:device-ignore-key-repeat
:device-key-repeat
:has-joystick
:owns-joystick
:joystick-buttons
:joystick-axes
:joystick-poll-rate)
(defcfun ("glutDeviceGet" device-get) :int
(query device-get-param))
(defun device-getp (query)
(if (= (device-get query) 0)
nil
t))
(defcenum (layer-get-param %gl:enum)
(:overlay-possible #x0320)
:layer-in-use
:has-overlay
:transparent-index
:normal-damaged
:overlay-damaged)
(defcfun ("glutLayerGet" layer-get) :int
(query layer-get-param))
(defun layer-getp (query)
(if (= (layer-get query) 0)
nil
t))
(defun get-layer-in-use ()
(foreign-enum-keyword 'layer-type (layer-get :layer-in-use)))
(defcfun ("glutGetModifiers" %glutGetModifiers) :int)
(declaim (inline get-modifiers))
(defun get-modifiers ()
(foreign-bitfield-symbols 'modifiers (%glutGetModifiers)))
;;; No idea if this is more efficient space-wise...
(declaim (inline get-modifier-values))
(defun get-modifier-values ()
(let ((mask (%glutGetModifiers)))
(values (= 1 (logand mask 1)) ; shift
(= 2 (logand mask 2)) ; ctrl
(= 4 (logand mask 4))))) ; alt
(defcfun ("glutExtensionSupported" extension-supported-p) :boolean
(extension-name :string))
;;; freeglut ext
(defcfun ("glutGetProcAddress" get-proc-address) :pointer
(proc-name :string))
|
[
{
"context": "andom-state\n (c) 2015 Shirakumo http://tymoon.eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n",
"end": 96,
"score": 0.9998297095298767,
"start": 78,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "umo http://tymoon.eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(asdf:defsystem random-s",
"end": 121,
"score": 0.9998770356178284,
"start": 107,
"tag": "NAME",
"value": "Nicolas Hafner"
},
{
"context": ".eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(asdf:defsystem random-state\n :version \"0.1",
"end": 141,
"score": 0.999883234500885,
"start": 123,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "system random-state\n :version \"0.1.0\"\n :author \"Nicolas Hafner <[email protected]>\"\n :license \"zlib\"\n :descri",
"end": 220,
"score": 0.9998800754547119,
"start": 206,
"tag": "NAME",
"value": "Nicolas Hafner"
},
{
"context": "ate\n :version \"0.1.0\"\n :author \"Nicolas Hafner <[email protected]>\"\n :license \"zlib\"\n :description \"Portable rand",
"end": 240,
"score": 0.9998683929443359,
"start": 222,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
random-state.asd
|
Shinmera/random-state
| 18 |
#|
This file is a part of random-state
(c) 2015 Shirakumo http://tymoon.eu ([email protected])
Author: Nicolas Hafner <[email protected]>
|#
(asdf:defsystem random-state
:version "0.1.0"
:author "Nicolas Hafner <[email protected]>"
:license "zlib"
:description "Portable random number generation."
:homepage "https://Shinmera.github.io/random-state/"
:bug-tracker "https://github.com/Shinmera/random-state/issues"
:source-control (:git "https://github.com/Shinmera/random-state.git")
:serial T
:components ((:file "package")
(:file "toolkit")
(:file "generator")
(:file "linear-congruence")
(:file "mersenne-twister")
(:file "middle-square")
(:file "pcg")
(:file "rc4")
(:file "tt800")
(:file "documentation"))
:depends-on (:documentation-utils))
|
42535
|
#|
This file is a part of random-state
(c) 2015 Shirakumo http://tymoon.eu (<EMAIL>)
Author: <NAME> <<EMAIL>>
|#
(asdf:defsystem random-state
:version "0.1.0"
:author "<NAME> <<EMAIL>>"
:license "zlib"
:description "Portable random number generation."
:homepage "https://Shinmera.github.io/random-state/"
:bug-tracker "https://github.com/Shinmera/random-state/issues"
:source-control (:git "https://github.com/Shinmera/random-state.git")
:serial T
:components ((:file "package")
(:file "toolkit")
(:file "generator")
(:file "linear-congruence")
(:file "mersenne-twister")
(:file "middle-square")
(:file "pcg")
(:file "rc4")
(:file "tt800")
(:file "documentation"))
:depends-on (:documentation-utils))
| true |
#|
This file is a part of random-state
(c) 2015 Shirakumo http://tymoon.eu (PI:EMAIL:<EMAIL>END_PI)
Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
|#
(asdf:defsystem random-state
:version "0.1.0"
:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:license "zlib"
:description "Portable random number generation."
:homepage "https://Shinmera.github.io/random-state/"
:bug-tracker "https://github.com/Shinmera/random-state/issues"
:source-control (:git "https://github.com/Shinmera/random-state.git")
:serial T
:components ((:file "package")
(:file "toolkit")
(:file "generator")
(:file "linear-congruence")
(:file "mersenne-twister")
(:file "middle-square")
(:file "pcg")
(:file "rc4")
(:file "tt800")
(:file "documentation"))
:depends-on (:documentation-utils))
|
[
{
"context": "013 Advanced Mirco Devices, Inc. \n;\n; Contact:\n; David Russinoff\n; 1106 W 9th St., Austin, TX 78703\n; http://w",
"end": 164,
"score": 0.9998607635498047,
"start": 149,
"tag": "NAME",
"value": "David Russinoff"
},
{
"context": "ite 500, Boston, MA\n; 02110-1335, USA.\n;\n; Author: David M. Russinoff ([email protected])\n\n(in-package \"ACL2\")\n\n(set-",
"end": 1010,
"score": 0.9998762011528015,
"start": 992,
"tag": "NAME",
"value": "David M. Russinoff"
},
{
"context": " 02110-1335, USA.\n;\n; Author: David M. Russinoff ([email protected])\n\n(in-package \"ACL2\")\n\n(set-enforce-redundancy t)",
"end": 1031,
"score": 0.9999328255653381,
"start": 1012,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/rtl/rel9/support/lib1/openers.lisp
|
ragerdl/acl2-defthm-rc2
| 1 |
; RTL - A Formal Theory of Register-Transfer Logic and Computer Arithmetic
; Copyright (C) 1995-2013 Advanced Mirco Devices, Inc.
;
; Contact:
; David Russinoff
; 1106 W 9th St., Austin, TX 78703
; http://www.russsinoff.com/
;
; This program is free software; you can redistribute it and/or modify it under
; the terms of the GNU General Public License as published by the Free Software
; Foundation; either version 2 of the License, or (at your option) any later
; version.
;
; This program is distributed in the hope that it will be useful but WITHOUT ANY
; WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
; PARTICULAR PURPOSE. See the GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License along with
; this program; see the file "gpl.txt" in this directory. If not, write to the
; Free Software Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA
; 02110-1335, USA.
;
; Author: David M. Russinoff ([email protected])
(in-package "ACL2")
(set-enforce-redundancy t)
(local (include-book "../support/openers"))
(program)
; In this file, an event-control (evctl) data structure is either (posedge
; clk), (negedge clk), or (even n).
(defun negate-event-control (evctl)
(if (equal evctl '(even n))
(list 'not evctl)
(let* ((edge0 (car evctl))
(clk (cadr evctl))
(edge (case edge0
(posedge 'pedge)
(negedge 'nedge)
(otherwise
(er hard 'gen-model-preamble-common
"Unable to handle edge specifier ~x0."
edge0)))))
`(not (,edge (,clk (1- n)) (,clk n))))))
(defun negate-event-control-list (x)
(declare (xargs :guard (true-listp x)))
(if (endp x)
nil
(cons (negate-event-control (car x))
(negate-event-control-list (cdr x)))))
(defmacro def$open (name type &rest evctl-lst)
(if (eq type :skipped)
`(value-triple '(def$open ,name :skipped))
(let ((evctl-lst (if (eq type :input)
(assert$ (null evctl-lst)
'((even n)))
evctl-lst)))
`(defthm ,(intern-in-package-of-symbol
(concatenate 'string (symbol-name name) "$OPEN")
name)
(implies (and (integerp n)
(< 0 n)
,@(negate-event-control-list evctl-lst))
(equal (,name n)
(,name (1- n))))
:hints (("Goal"
:expand ((,name n)
,@(and (eq type :wire) `((,name (1- n)))))))))))
|
76030
|
; RTL - A Formal Theory of Register-Transfer Logic and Computer Arithmetic
; Copyright (C) 1995-2013 Advanced Mirco Devices, Inc.
;
; Contact:
; <NAME>
; 1106 W 9th St., Austin, TX 78703
; http://www.russsinoff.com/
;
; This program is free software; you can redistribute it and/or modify it under
; the terms of the GNU General Public License as published by the Free Software
; Foundation; either version 2 of the License, or (at your option) any later
; version.
;
; This program is distributed in the hope that it will be useful but WITHOUT ANY
; WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
; PARTICULAR PURPOSE. See the GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License along with
; this program; see the file "gpl.txt" in this directory. If not, write to the
; Free Software Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA
; 02110-1335, USA.
;
; Author: <NAME> (<EMAIL>)
(in-package "ACL2")
(set-enforce-redundancy t)
(local (include-book "../support/openers"))
(program)
; In this file, an event-control (evctl) data structure is either (posedge
; clk), (negedge clk), or (even n).
(defun negate-event-control (evctl)
(if (equal evctl '(even n))
(list 'not evctl)
(let* ((edge0 (car evctl))
(clk (cadr evctl))
(edge (case edge0
(posedge 'pedge)
(negedge 'nedge)
(otherwise
(er hard 'gen-model-preamble-common
"Unable to handle edge specifier ~x0."
edge0)))))
`(not (,edge (,clk (1- n)) (,clk n))))))
(defun negate-event-control-list (x)
(declare (xargs :guard (true-listp x)))
(if (endp x)
nil
(cons (negate-event-control (car x))
(negate-event-control-list (cdr x)))))
(defmacro def$open (name type &rest evctl-lst)
(if (eq type :skipped)
`(value-triple '(def$open ,name :skipped))
(let ((evctl-lst (if (eq type :input)
(assert$ (null evctl-lst)
'((even n)))
evctl-lst)))
`(defthm ,(intern-in-package-of-symbol
(concatenate 'string (symbol-name name) "$OPEN")
name)
(implies (and (integerp n)
(< 0 n)
,@(negate-event-control-list evctl-lst))
(equal (,name n)
(,name (1- n))))
:hints (("Goal"
:expand ((,name n)
,@(and (eq type :wire) `((,name (1- n)))))))))))
| true |
; RTL - A Formal Theory of Register-Transfer Logic and Computer Arithmetic
; Copyright (C) 1995-2013 Advanced Mirco Devices, Inc.
;
; Contact:
; PI:NAME:<NAME>END_PI
; 1106 W 9th St., Austin, TX 78703
; http://www.russsinoff.com/
;
; This program is free software; you can redistribute it and/or modify it under
; the terms of the GNU General Public License as published by the Free Software
; Foundation; either version 2 of the License, or (at your option) any later
; version.
;
; This program is distributed in the hope that it will be useful but WITHOUT ANY
; WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
; PARTICULAR PURPOSE. See the GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License along with
; this program; see the file "gpl.txt" in this directory. If not, write to the
; Free Software Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA
; 02110-1335, USA.
;
; Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
(in-package "ACL2")
(set-enforce-redundancy t)
(local (include-book "../support/openers"))
(program)
; In this file, an event-control (evctl) data structure is either (posedge
; clk), (negedge clk), or (even n).
(defun negate-event-control (evctl)
(if (equal evctl '(even n))
(list 'not evctl)
(let* ((edge0 (car evctl))
(clk (cadr evctl))
(edge (case edge0
(posedge 'pedge)
(negedge 'nedge)
(otherwise
(er hard 'gen-model-preamble-common
"Unable to handle edge specifier ~x0."
edge0)))))
`(not (,edge (,clk (1- n)) (,clk n))))))
(defun negate-event-control-list (x)
(declare (xargs :guard (true-listp x)))
(if (endp x)
nil
(cons (negate-event-control (car x))
(negate-event-control-list (cdr x)))))
(defmacro def$open (name type &rest evctl-lst)
(if (eq type :skipped)
`(value-triple '(def$open ,name :skipped))
(let ((evctl-lst (if (eq type :input)
(assert$ (null evctl-lst)
'((even n)))
evctl-lst)))
`(defthm ,(intern-in-package-of-symbol
(concatenate 'string (symbol-name name) "$OPEN")
name)
(implies (and (integerp n)
(< 0 n)
,@(negate-event-control-list evctl-lst))
(equal (,name n)
(,name (1- n))))
:hints (("Goal"
:expand ((,name n)
,@(and (eq type :wire) `((,name (1- n)))))))))))
|
[
{
"context": " Array-Utils\n(c) 2014 Shirakumo http://tymoon.eu ([email protected])\nAuthor: Nicolas Hafner <[email protected]>\n|#\n\n",
"end": 93,
"score": 0.9998817443847656,
"start": 75,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "kumo http://tymoon.eu ([email protected])\nAuthor: Nicolas Hafner <[email protected]>\n|#\n\n(in-package #:cl-user)\n(",
"end": 117,
"score": 0.9998889565467834,
"start": 103,
"tag": "NAME",
"value": "Nicolas Hafner"
},
{
"context": "n.eu ([email protected])\nAuthor: Nicolas Hafner <[email protected]>\n|#\n\n(in-package #:cl-user)\n(defpackage #:array-u",
"end": 137,
"score": 0.9999020099639893,
"start": 119,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
utils.lisp
|
ccgcyber/array-utils
| 3 |
#|
This file is a part of Array-Utils
(c) 2014 Shirakumo http://tymoon.eu ([email protected])
Author: Nicolas Hafner <[email protected]>
|#
(in-package #:cl-user)
(defpackage #:array-utils
(:nicknames #:org.shirakumo.array-utils)
(:use #:cl)
(:export
#:ensure-array-size
#:array-shift
#:vector-push-extend-front
#:vector-push-extend-position
#:vector-pop-front
#:vector-pop-front*
#:vector-pop-position
#:vector-pop-position*
#:vector-append))
(in-package #:org.shirakumo.array-utils)
(defun ensure-array-size (array new-space)
(when (array-has-fill-pointer-p array)
(unless (array-in-bounds-p array new-space)
(adjust-array array new-space))
(incf (fill-pointer array)
(- new-space (fill-pointer array))))
array)
(deftype positive-fixnum ()
`(and fixnum (integer 0)))
(defun array-shift (array &key (n 1) (from 0) to (adjust T) (fill NIL f-p) (contents NIL c-p))
"Shifts a subset of array elements in either direction for a specified amount.
Optionally also extends the array and fills empty space with a given element.
N --- The amount to be moved. If positive, things are shifted to the right. If
negative, things are shifted to the left.
FROM --- The left point of the region to move, inclusive.
TO --- The right point of the region to move, exclusive.
ADJUST --- Whether to adjust the fill pointer and the array bounds. The array is only
adjusted if N is positive and the range of TO+N would exceed the ARRAY length,
or if N is negative and TO equals the length of the ARRAY
FILL --- If provided, empty spaces created by the move will be filled with this element.
CONTENTS --- If provided, uses the contents to fill the new space. If |N| is greater than the
length of this sequence, FILL is used to fill the rest of the space if it is
provided. If not, an error is signalled. No matter whether N is negative or
positive, the content is filled in from left to right in the order it is given."
(declare (optimize speed))
(check-type n fixnum)
(check-type from positive-fixnum)
(check-type to (or null positive-fixnum))
(check-type array vector)
(let* ((length (length array))
(to (or to length))
(amount (abs n))
(direction (cond ((< n 0) :left)
((< 0 n) :right)
(T :nowhere)))
(content-length (length contents)))
(declare (type positive-fixnum from to amount content-length)
(type vector array))
(assert (<= from to) () "FROM must be smaller or equal to TO.")
(assert (or f-p (not c-p) (<= amount content-length)) (fill)
"FILL is not provided and CONTENTS is smaller than the amount to shift.")
(case direction
(:right
(when (and adjust (<= length (+ to amount)))
(ensure-array-size array (+ to amount))
(setf length (+ to amount)))
(loop for cursor of-type positive-fixnum
from (1- (min length (+ to amount)))
downto (+ from amount)
do (setf (aref array cursor)
(aref array (the positive-fixnum (- cursor amount)))))
(when c-p
(macrolet ((iterate (iteration)
`(loop for cursor of-type positive-fixnum
from from below (min (+ from amount) to)
for item ,iteration contents
do (setf (aref array cursor) item))))
(etypecase contents
(list (iterate in))
(vector (iterate across)))))
(when f-p
(loop repeat (- amount content-length)
for cursor of-type positive-fixnum
from (+ from content-length) below (min length (+ to amount))
do (setf (aref array cursor) fill))))
(:left
(when (< 0 (- to amount))
(loop for cursor of-type positive-fixnum
from (max 0 (- from amount))
upto (1- (- to amount))
do (setf (aref array cursor)
(aref array (the positive-fixnum (+ cursor amount))))))
(when (and adjust (= to length))
(ensure-array-size array (max from (- to amount)))
(setf length (max from (- to amount))))
(when c-p
(macrolet ((iterate (iteration)
`(loop for cursor of-type positive-fixnum
from (max (- to amount) from) below to
for item ,iteration contents
do (setf (aref array cursor) item))))
(etypecase contents
(list (iterate in))
(vector (iterate across)))))
(when f-p
(loop for cursor of-type positive-fixnum
from (+ content-length (max (- to amount) from)) below to
do (setf (aref array cursor) fill))))))
array)
(defun vector-push-extend-position (element vector position)
"Pushes the element into the specified position and shifts everything
to the right to make space. This is potentially very costly as all
elements after the given position need to be shifted as per ARRAY-SHIFT."
(array-shift vector :n 1 :from position)
(setf (aref vector position) element)
(fill-pointer vector))
(defun vector-push-extend-front (element vector)
"Pushes the element onto the front of the vector and extends if necessary.
This operation is very costly and takes O(n) time as each element needs to
be shifted as per ARRAY-SHIFT.
See VECTOR-PUSH-EXTEND-POSITION"
(vector-push-extend-position element vector 0))
(defun vector-pop-position (vector position)
"Pops the element at the given position of the vector and returns it.
This is potentially very costly as all elements after the given position
need to be shifted back as per ARRAY-SHIFT.
See VECTOR-POP-POSITION*"
(if (= (1- (length vector)) position)
(vector-pop vector)
(prog1 (aref vector position)
(array-shift vector :n -1 :from (1+ position)))))
(defun vector-pop-position* (vector position)
"Pops the element at the given position of the vector and returns it.
This is faster than VECTOR-POP-POSITION, but does not preserve the order of elements
in the vector.
See VECTOR-POP-POSITION"
(decf (fill-pointer vector))
(shiftf (aref vector position) (aref vector (length vector))))
(defun vector-pop-front (vector)
"Pops the first element off the vector and returns it.
This operation is very costly and takes O(n) time as each element needs to
be shifted as per ARRAY-SHIFT.
See VECTOR-POP-FRONT*
See VECTOR-POP-POSITION"
(vector-pop-position vector 0))
(defun vector-pop-front* (vector)
"Pops the first element off the vector and returns it.
This is faster than VECTOR-POP-FRONT, but does not preserve the order of elements
in the vector.
See VECTOR-POP-FRONT
See VECTOR-POP-POSITION"
(vector-pop-position* vector 0))
(defun vector-append (vector sequence &optional position)
"Appends all elements of the sequence at position of the vector and returns it.
This is potentially very costly as all elements after the given position
need to be shifted back as per ARRAY-SHIFT."
(let ((position (or position (length vector))))
(array-shift vector :n (length sequence) :from position)
(macrolet ((iterate (iteration)
`(loop for i from position
for item ,iteration sequence
do (setf (aref vector i) item))))
(etypecase sequence
(list (iterate in))
(vector (iterate across))))
vector))
|
26881
|
#|
This file is a part of Array-Utils
(c) 2014 Shirakumo http://tymoon.eu (<EMAIL>)
Author: <NAME> <<EMAIL>>
|#
(in-package #:cl-user)
(defpackage #:array-utils
(:nicknames #:org.shirakumo.array-utils)
(:use #:cl)
(:export
#:ensure-array-size
#:array-shift
#:vector-push-extend-front
#:vector-push-extend-position
#:vector-pop-front
#:vector-pop-front*
#:vector-pop-position
#:vector-pop-position*
#:vector-append))
(in-package #:org.shirakumo.array-utils)
(defun ensure-array-size (array new-space)
(when (array-has-fill-pointer-p array)
(unless (array-in-bounds-p array new-space)
(adjust-array array new-space))
(incf (fill-pointer array)
(- new-space (fill-pointer array))))
array)
(deftype positive-fixnum ()
`(and fixnum (integer 0)))
(defun array-shift (array &key (n 1) (from 0) to (adjust T) (fill NIL f-p) (contents NIL c-p))
"Shifts a subset of array elements in either direction for a specified amount.
Optionally also extends the array and fills empty space with a given element.
N --- The amount to be moved. If positive, things are shifted to the right. If
negative, things are shifted to the left.
FROM --- The left point of the region to move, inclusive.
TO --- The right point of the region to move, exclusive.
ADJUST --- Whether to adjust the fill pointer and the array bounds. The array is only
adjusted if N is positive and the range of TO+N would exceed the ARRAY length,
or if N is negative and TO equals the length of the ARRAY
FILL --- If provided, empty spaces created by the move will be filled with this element.
CONTENTS --- If provided, uses the contents to fill the new space. If |N| is greater than the
length of this sequence, FILL is used to fill the rest of the space if it is
provided. If not, an error is signalled. No matter whether N is negative or
positive, the content is filled in from left to right in the order it is given."
(declare (optimize speed))
(check-type n fixnum)
(check-type from positive-fixnum)
(check-type to (or null positive-fixnum))
(check-type array vector)
(let* ((length (length array))
(to (or to length))
(amount (abs n))
(direction (cond ((< n 0) :left)
((< 0 n) :right)
(T :nowhere)))
(content-length (length contents)))
(declare (type positive-fixnum from to amount content-length)
(type vector array))
(assert (<= from to) () "FROM must be smaller or equal to TO.")
(assert (or f-p (not c-p) (<= amount content-length)) (fill)
"FILL is not provided and CONTENTS is smaller than the amount to shift.")
(case direction
(:right
(when (and adjust (<= length (+ to amount)))
(ensure-array-size array (+ to amount))
(setf length (+ to amount)))
(loop for cursor of-type positive-fixnum
from (1- (min length (+ to amount)))
downto (+ from amount)
do (setf (aref array cursor)
(aref array (the positive-fixnum (- cursor amount)))))
(when c-p
(macrolet ((iterate (iteration)
`(loop for cursor of-type positive-fixnum
from from below (min (+ from amount) to)
for item ,iteration contents
do (setf (aref array cursor) item))))
(etypecase contents
(list (iterate in))
(vector (iterate across)))))
(when f-p
(loop repeat (- amount content-length)
for cursor of-type positive-fixnum
from (+ from content-length) below (min length (+ to amount))
do (setf (aref array cursor) fill))))
(:left
(when (< 0 (- to amount))
(loop for cursor of-type positive-fixnum
from (max 0 (- from amount))
upto (1- (- to amount))
do (setf (aref array cursor)
(aref array (the positive-fixnum (+ cursor amount))))))
(when (and adjust (= to length))
(ensure-array-size array (max from (- to amount)))
(setf length (max from (- to amount))))
(when c-p
(macrolet ((iterate (iteration)
`(loop for cursor of-type positive-fixnum
from (max (- to amount) from) below to
for item ,iteration contents
do (setf (aref array cursor) item))))
(etypecase contents
(list (iterate in))
(vector (iterate across)))))
(when f-p
(loop for cursor of-type positive-fixnum
from (+ content-length (max (- to amount) from)) below to
do (setf (aref array cursor) fill))))))
array)
(defun vector-push-extend-position (element vector position)
"Pushes the element into the specified position and shifts everything
to the right to make space. This is potentially very costly as all
elements after the given position need to be shifted as per ARRAY-SHIFT."
(array-shift vector :n 1 :from position)
(setf (aref vector position) element)
(fill-pointer vector))
(defun vector-push-extend-front (element vector)
"Pushes the element onto the front of the vector and extends if necessary.
This operation is very costly and takes O(n) time as each element needs to
be shifted as per ARRAY-SHIFT.
See VECTOR-PUSH-EXTEND-POSITION"
(vector-push-extend-position element vector 0))
(defun vector-pop-position (vector position)
"Pops the element at the given position of the vector and returns it.
This is potentially very costly as all elements after the given position
need to be shifted back as per ARRAY-SHIFT.
See VECTOR-POP-POSITION*"
(if (= (1- (length vector)) position)
(vector-pop vector)
(prog1 (aref vector position)
(array-shift vector :n -1 :from (1+ position)))))
(defun vector-pop-position* (vector position)
"Pops the element at the given position of the vector and returns it.
This is faster than VECTOR-POP-POSITION, but does not preserve the order of elements
in the vector.
See VECTOR-POP-POSITION"
(decf (fill-pointer vector))
(shiftf (aref vector position) (aref vector (length vector))))
(defun vector-pop-front (vector)
"Pops the first element off the vector and returns it.
This operation is very costly and takes O(n) time as each element needs to
be shifted as per ARRAY-SHIFT.
See VECTOR-POP-FRONT*
See VECTOR-POP-POSITION"
(vector-pop-position vector 0))
(defun vector-pop-front* (vector)
"Pops the first element off the vector and returns it.
This is faster than VECTOR-POP-FRONT, but does not preserve the order of elements
in the vector.
See VECTOR-POP-FRONT
See VECTOR-POP-POSITION"
(vector-pop-position* vector 0))
(defun vector-append (vector sequence &optional position)
"Appends all elements of the sequence at position of the vector and returns it.
This is potentially very costly as all elements after the given position
need to be shifted back as per ARRAY-SHIFT."
(let ((position (or position (length vector))))
(array-shift vector :n (length sequence) :from position)
(macrolet ((iterate (iteration)
`(loop for i from position
for item ,iteration sequence
do (setf (aref vector i) item))))
(etypecase sequence
(list (iterate in))
(vector (iterate across))))
vector))
| true |
#|
This file is a part of Array-Utils
(c) 2014 Shirakumo http://tymoon.eu (PI:EMAIL:<EMAIL>END_PI)
Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
|#
(in-package #:cl-user)
(defpackage #:array-utils
(:nicknames #:org.shirakumo.array-utils)
(:use #:cl)
(:export
#:ensure-array-size
#:array-shift
#:vector-push-extend-front
#:vector-push-extend-position
#:vector-pop-front
#:vector-pop-front*
#:vector-pop-position
#:vector-pop-position*
#:vector-append))
(in-package #:org.shirakumo.array-utils)
(defun ensure-array-size (array new-space)
(when (array-has-fill-pointer-p array)
(unless (array-in-bounds-p array new-space)
(adjust-array array new-space))
(incf (fill-pointer array)
(- new-space (fill-pointer array))))
array)
(deftype positive-fixnum ()
`(and fixnum (integer 0)))
(defun array-shift (array &key (n 1) (from 0) to (adjust T) (fill NIL f-p) (contents NIL c-p))
"Shifts a subset of array elements in either direction for a specified amount.
Optionally also extends the array and fills empty space with a given element.
N --- The amount to be moved. If positive, things are shifted to the right. If
negative, things are shifted to the left.
FROM --- The left point of the region to move, inclusive.
TO --- The right point of the region to move, exclusive.
ADJUST --- Whether to adjust the fill pointer and the array bounds. The array is only
adjusted if N is positive and the range of TO+N would exceed the ARRAY length,
or if N is negative and TO equals the length of the ARRAY
FILL --- If provided, empty spaces created by the move will be filled with this element.
CONTENTS --- If provided, uses the contents to fill the new space. If |N| is greater than the
length of this sequence, FILL is used to fill the rest of the space if it is
provided. If not, an error is signalled. No matter whether N is negative or
positive, the content is filled in from left to right in the order it is given."
(declare (optimize speed))
(check-type n fixnum)
(check-type from positive-fixnum)
(check-type to (or null positive-fixnum))
(check-type array vector)
(let* ((length (length array))
(to (or to length))
(amount (abs n))
(direction (cond ((< n 0) :left)
((< 0 n) :right)
(T :nowhere)))
(content-length (length contents)))
(declare (type positive-fixnum from to amount content-length)
(type vector array))
(assert (<= from to) () "FROM must be smaller or equal to TO.")
(assert (or f-p (not c-p) (<= amount content-length)) (fill)
"FILL is not provided and CONTENTS is smaller than the amount to shift.")
(case direction
(:right
(when (and adjust (<= length (+ to amount)))
(ensure-array-size array (+ to amount))
(setf length (+ to amount)))
(loop for cursor of-type positive-fixnum
from (1- (min length (+ to amount)))
downto (+ from amount)
do (setf (aref array cursor)
(aref array (the positive-fixnum (- cursor amount)))))
(when c-p
(macrolet ((iterate (iteration)
`(loop for cursor of-type positive-fixnum
from from below (min (+ from amount) to)
for item ,iteration contents
do (setf (aref array cursor) item))))
(etypecase contents
(list (iterate in))
(vector (iterate across)))))
(when f-p
(loop repeat (- amount content-length)
for cursor of-type positive-fixnum
from (+ from content-length) below (min length (+ to amount))
do (setf (aref array cursor) fill))))
(:left
(when (< 0 (- to amount))
(loop for cursor of-type positive-fixnum
from (max 0 (- from amount))
upto (1- (- to amount))
do (setf (aref array cursor)
(aref array (the positive-fixnum (+ cursor amount))))))
(when (and adjust (= to length))
(ensure-array-size array (max from (- to amount)))
(setf length (max from (- to amount))))
(when c-p
(macrolet ((iterate (iteration)
`(loop for cursor of-type positive-fixnum
from (max (- to amount) from) below to
for item ,iteration contents
do (setf (aref array cursor) item))))
(etypecase contents
(list (iterate in))
(vector (iterate across)))))
(when f-p
(loop for cursor of-type positive-fixnum
from (+ content-length (max (- to amount) from)) below to
do (setf (aref array cursor) fill))))))
array)
(defun vector-push-extend-position (element vector position)
"Pushes the element into the specified position and shifts everything
to the right to make space. This is potentially very costly as all
elements after the given position need to be shifted as per ARRAY-SHIFT."
(array-shift vector :n 1 :from position)
(setf (aref vector position) element)
(fill-pointer vector))
(defun vector-push-extend-front (element vector)
"Pushes the element onto the front of the vector and extends if necessary.
This operation is very costly and takes O(n) time as each element needs to
be shifted as per ARRAY-SHIFT.
See VECTOR-PUSH-EXTEND-POSITION"
(vector-push-extend-position element vector 0))
(defun vector-pop-position (vector position)
"Pops the element at the given position of the vector and returns it.
This is potentially very costly as all elements after the given position
need to be shifted back as per ARRAY-SHIFT.
See VECTOR-POP-POSITION*"
(if (= (1- (length vector)) position)
(vector-pop vector)
(prog1 (aref vector position)
(array-shift vector :n -1 :from (1+ position)))))
(defun vector-pop-position* (vector position)
"Pops the element at the given position of the vector and returns it.
This is faster than VECTOR-POP-POSITION, but does not preserve the order of elements
in the vector.
See VECTOR-POP-POSITION"
(decf (fill-pointer vector))
(shiftf (aref vector position) (aref vector (length vector))))
(defun vector-pop-front (vector)
"Pops the first element off the vector and returns it.
This operation is very costly and takes O(n) time as each element needs to
be shifted as per ARRAY-SHIFT.
See VECTOR-POP-FRONT*
See VECTOR-POP-POSITION"
(vector-pop-position vector 0))
(defun vector-pop-front* (vector)
"Pops the first element off the vector and returns it.
This is faster than VECTOR-POP-FRONT, but does not preserve the order of elements
in the vector.
See VECTOR-POP-FRONT
See VECTOR-POP-POSITION"
(vector-pop-position* vector 0))
(defun vector-append (vector sequence &optional position)
"Appends all elements of the sequence at position of the vector and returns it.
This is potentially very costly as all elements after the given position
need to be shifted back as per ARRAY-SHIFT."
(let ((position (or position (length vector))))
(array-shift vector :n (length sequence) :from position)
(macrolet ((iterate (iteration)
`(loop for i from position
for item ,iteration sequence
do (setf (aref vector i) item))))
(etypecase sequence
(list (iterate in))
(vector (iterate across))))
vector))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.