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": ";-*- Mode: Lisp -*-\n;;;; Author: Paul Dietz\n;;;; Created: Thu Aug 21 13:39:56 2003\n;;;; Cont",
"end": 49,
"score": 0.9998576045036316,
"start": 39,
"tag": "NAME",
"value": "Paul Dietz"
}
] |
ansi-tests/round.lsp
|
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD
| 10 |
;-*- Mode: Lisp -*-
;;;; Author: Paul Dietz
;;;; Created: Thu Aug 21 13:39:56 2003
;;;; Contains: Tests of ROUND
(in-package :cl-test)
(compile-and-load "numbers-aux.lsp")
(compile-and-load "round-aux.lsp")
(deftest round.error.1
(signals-error (round) program-error)
t)
(deftest round.error.2
(signals-error (round 1.0 1 nil) program-error)
t)
;;;
(deftest round.1
(round.1-fn)
nil)
(deftest round.2
(round.2-fn)
nil)
(deftest round.3
(round.3-fn 2.0s4)
nil)
(deftest round.4
(round.3-fn 2.0f4)
nil)
(deftest round.5
(round.3-fn 2.0d4)
nil)
(deftest round.6
(round.3-fn 2.0l4)
nil)
(deftest round.7
(round.7-fn)
nil)
(deftest round.8
(round.8-fn)
nil)
(deftest round.9
(round.9-fn)
nil)
(deftest round.10
(loop for x in (remove-if #'zerop *reals*)
for (q r) = (multiple-value-list (round x x))
unless (and (eql q 1)
(zerop r)
(if (rationalp x) (eql r 0)
(eql r (float 0 x))))
collect x)
nil)
(deftest round.11
(loop for x in (remove-if #'zerop *reals*)
for (q r) = (multiple-value-list (round (- x) x))
unless (and (eql q -1)
(zerop r)
(if (rationalp x) (eql r 0)
(eql r (float 0 x))))
collect x)
nil)
(deftest round.12
(let* ((radix (float-radix 1.0s0))
(rad (float radix 1.0s0))
(rrad (/ 0.5s0 rad)))
(loop for i from 1 to 1000
for x = (+ i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r rrad))
collect (list i x q r)))
nil)
(deftest round.13
(let* ((radix (float-radix 1.0s0))
(rad (float radix 1.0s0))
(rrad (/ 0.5s0 rad)))
(loop for i from 1 to 1000
for x = (- i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r (- rrad)))
collect (list i x q r)))
nil)
(deftest round.14
(let* ((radix (float-radix 1.0f0))
(rad (float radix 1.0f0))
(rrad (/ 0.5f0 rad)))
(loop for i from 1 to 1000
for x = (+ i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r rrad))
collect (list i x q r)))
nil)
(deftest round.15
(let* ((radix (float-radix 1.0f0))
(rad (float radix 1.0f0))
(rrad (/ 0.5f0 rad)))
(loop for i from 1 to 1000
for x = (- i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r (- rrad)))
collect (list i x q r)))
nil)
(deftest round.16
(let* ((radix (float-radix 1.0d0))
(rad (float radix 1.0d0))
(rrad (/ 0.5d0 rad)))
(loop for i from 1 to 1000
for x = (+ i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r rrad))
collect (list i x q r)))
nil)
(deftest round.17
(let* ((radix (float-radix 1.0d0))
(rad (float radix 1.0d0))
(rrad (/ 0.5d0 rad)))
(loop for i from 1 to 1000
for x = (- i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r (- rrad)))
collect (list i x q r)))
nil)
(deftest round.18
(let* ((radix (float-radix 1.0l0))
(rad (float radix 1.0l0))
(rrad (/ 0.5l0 rad)))
(loop for i from 1 to 1000
for x = (+ i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r rrad))
collect (list i x q r)))
nil)
(deftest round.19
(let* ((radix (float-radix 1.0l0))
(rad (float radix 1.0l0))
(rrad (/ 0.5l0 rad)))
(loop for i from 1 to 1000
for x = (- i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r (- rrad)))
collect (list i x q r)))
nil)
(deftest round.20
(round 1/2)
0 1/2)
(deftest round.21
(round 3/2)
2 -1/2)
|
92113
|
;-*- Mode: Lisp -*-
;;;; Author: <NAME>
;;;; Created: Thu Aug 21 13:39:56 2003
;;;; Contains: Tests of ROUND
(in-package :cl-test)
(compile-and-load "numbers-aux.lsp")
(compile-and-load "round-aux.lsp")
(deftest round.error.1
(signals-error (round) program-error)
t)
(deftest round.error.2
(signals-error (round 1.0 1 nil) program-error)
t)
;;;
(deftest round.1
(round.1-fn)
nil)
(deftest round.2
(round.2-fn)
nil)
(deftest round.3
(round.3-fn 2.0s4)
nil)
(deftest round.4
(round.3-fn 2.0f4)
nil)
(deftest round.5
(round.3-fn 2.0d4)
nil)
(deftest round.6
(round.3-fn 2.0l4)
nil)
(deftest round.7
(round.7-fn)
nil)
(deftest round.8
(round.8-fn)
nil)
(deftest round.9
(round.9-fn)
nil)
(deftest round.10
(loop for x in (remove-if #'zerop *reals*)
for (q r) = (multiple-value-list (round x x))
unless (and (eql q 1)
(zerop r)
(if (rationalp x) (eql r 0)
(eql r (float 0 x))))
collect x)
nil)
(deftest round.11
(loop for x in (remove-if #'zerop *reals*)
for (q r) = (multiple-value-list (round (- x) x))
unless (and (eql q -1)
(zerop r)
(if (rationalp x) (eql r 0)
(eql r (float 0 x))))
collect x)
nil)
(deftest round.12
(let* ((radix (float-radix 1.0s0))
(rad (float radix 1.0s0))
(rrad (/ 0.5s0 rad)))
(loop for i from 1 to 1000
for x = (+ i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r rrad))
collect (list i x q r)))
nil)
(deftest round.13
(let* ((radix (float-radix 1.0s0))
(rad (float radix 1.0s0))
(rrad (/ 0.5s0 rad)))
(loop for i from 1 to 1000
for x = (- i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r (- rrad)))
collect (list i x q r)))
nil)
(deftest round.14
(let* ((radix (float-radix 1.0f0))
(rad (float radix 1.0f0))
(rrad (/ 0.5f0 rad)))
(loop for i from 1 to 1000
for x = (+ i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r rrad))
collect (list i x q r)))
nil)
(deftest round.15
(let* ((radix (float-radix 1.0f0))
(rad (float radix 1.0f0))
(rrad (/ 0.5f0 rad)))
(loop for i from 1 to 1000
for x = (- i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r (- rrad)))
collect (list i x q r)))
nil)
(deftest round.16
(let* ((radix (float-radix 1.0d0))
(rad (float radix 1.0d0))
(rrad (/ 0.5d0 rad)))
(loop for i from 1 to 1000
for x = (+ i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r rrad))
collect (list i x q r)))
nil)
(deftest round.17
(let* ((radix (float-radix 1.0d0))
(rad (float radix 1.0d0))
(rrad (/ 0.5d0 rad)))
(loop for i from 1 to 1000
for x = (- i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r (- rrad)))
collect (list i x q r)))
nil)
(deftest round.18
(let* ((radix (float-radix 1.0l0))
(rad (float radix 1.0l0))
(rrad (/ 0.5l0 rad)))
(loop for i from 1 to 1000
for x = (+ i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r rrad))
collect (list i x q r)))
nil)
(deftest round.19
(let* ((radix (float-radix 1.0l0))
(rad (float radix 1.0l0))
(rrad (/ 0.5l0 rad)))
(loop for i from 1 to 1000
for x = (- i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r (- rrad)))
collect (list i x q r)))
nil)
(deftest round.20
(round 1/2)
0 1/2)
(deftest round.21
(round 3/2)
2 -1/2)
| true |
;-*- Mode: Lisp -*-
;;;; Author: PI:NAME:<NAME>END_PI
;;;; Created: Thu Aug 21 13:39:56 2003
;;;; Contains: Tests of ROUND
(in-package :cl-test)
(compile-and-load "numbers-aux.lsp")
(compile-and-load "round-aux.lsp")
(deftest round.error.1
(signals-error (round) program-error)
t)
(deftest round.error.2
(signals-error (round 1.0 1 nil) program-error)
t)
;;;
(deftest round.1
(round.1-fn)
nil)
(deftest round.2
(round.2-fn)
nil)
(deftest round.3
(round.3-fn 2.0s4)
nil)
(deftest round.4
(round.3-fn 2.0f4)
nil)
(deftest round.5
(round.3-fn 2.0d4)
nil)
(deftest round.6
(round.3-fn 2.0l4)
nil)
(deftest round.7
(round.7-fn)
nil)
(deftest round.8
(round.8-fn)
nil)
(deftest round.9
(round.9-fn)
nil)
(deftest round.10
(loop for x in (remove-if #'zerop *reals*)
for (q r) = (multiple-value-list (round x x))
unless (and (eql q 1)
(zerop r)
(if (rationalp x) (eql r 0)
(eql r (float 0 x))))
collect x)
nil)
(deftest round.11
(loop for x in (remove-if #'zerop *reals*)
for (q r) = (multiple-value-list (round (- x) x))
unless (and (eql q -1)
(zerop r)
(if (rationalp x) (eql r 0)
(eql r (float 0 x))))
collect x)
nil)
(deftest round.12
(let* ((radix (float-radix 1.0s0))
(rad (float radix 1.0s0))
(rrad (/ 0.5s0 rad)))
(loop for i from 1 to 1000
for x = (+ i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r rrad))
collect (list i x q r)))
nil)
(deftest round.13
(let* ((radix (float-radix 1.0s0))
(rad (float radix 1.0s0))
(rrad (/ 0.5s0 rad)))
(loop for i from 1 to 1000
for x = (- i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r (- rrad)))
collect (list i x q r)))
nil)
(deftest round.14
(let* ((radix (float-radix 1.0f0))
(rad (float radix 1.0f0))
(rrad (/ 0.5f0 rad)))
(loop for i from 1 to 1000
for x = (+ i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r rrad))
collect (list i x q r)))
nil)
(deftest round.15
(let* ((radix (float-radix 1.0f0))
(rad (float radix 1.0f0))
(rrad (/ 0.5f0 rad)))
(loop for i from 1 to 1000
for x = (- i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r (- rrad)))
collect (list i x q r)))
nil)
(deftest round.16
(let* ((radix (float-radix 1.0d0))
(rad (float radix 1.0d0))
(rrad (/ 0.5d0 rad)))
(loop for i from 1 to 1000
for x = (+ i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r rrad))
collect (list i x q r)))
nil)
(deftest round.17
(let* ((radix (float-radix 1.0d0))
(rad (float radix 1.0d0))
(rrad (/ 0.5d0 rad)))
(loop for i from 1 to 1000
for x = (- i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r (- rrad)))
collect (list i x q r)))
nil)
(deftest round.18
(let* ((radix (float-radix 1.0l0))
(rad (float radix 1.0l0))
(rrad (/ 0.5l0 rad)))
(loop for i from 1 to 1000
for x = (+ i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r rrad))
collect (list i x q r)))
nil)
(deftest round.19
(let* ((radix (float-radix 1.0l0))
(rad (float radix 1.0l0))
(rrad (/ 0.5l0 rad)))
(loop for i from 1 to 1000
for x = (- i rrad)
for (q r) = (multiple-value-list (round x))
unless (and (eql q i)
(eql r (- rrad)))
collect (list i x q r)))
nil)
(deftest round.20
(round 1/2)
0 1/2)
(deftest round.21
(round 3/2)
2 -1/2)
|
[
{
"context": ";Suleyman Muhammad\n;1/21/11\n;MY-FOURTH LISP src code\n\n(defun my-four",
"end": 18,
"score": 0.9998688101768494,
"start": 1,
"tag": "NAME",
"value": "Suleyman Muhammad"
}
] |
LISP_2011330/src/allegro-projects/my_defuns/my_fourth.lisp
|
SMan23/Grad-Work_Backup
| 0 |
;Suleyman Muhammad
;1/21/11
;MY-FOURTH LISP src code
(defun my-fourth (lst)
(let ((size (check-len lst)))
(if (null lst) ;IF not list return NIL
nil
(if (< size 4) ;ELSEIF lst < 4 return NIL
(format t "This list is too short")
(car (cdr (cdr (cdr lst)))))))) ;ELSE return fourth element
;TEST CODE:
(my-fourth '(a b)) ; FAIL
(check-len '(a b c d e)) ; Returns the number 5 (list length)
(my-fourth '(a b c d e)) ; Returns 4th element D
|
67519
|
;<NAME>
;1/21/11
;MY-FOURTH LISP src code
(defun my-fourth (lst)
(let ((size (check-len lst)))
(if (null lst) ;IF not list return NIL
nil
(if (< size 4) ;ELSEIF lst < 4 return NIL
(format t "This list is too short")
(car (cdr (cdr (cdr lst)))))))) ;ELSE return fourth element
;TEST CODE:
(my-fourth '(a b)) ; FAIL
(check-len '(a b c d e)) ; Returns the number 5 (list length)
(my-fourth '(a b c d e)) ; Returns 4th element D
| true |
;PI:NAME:<NAME>END_PI
;1/21/11
;MY-FOURTH LISP src code
(defun my-fourth (lst)
(let ((size (check-len lst)))
(if (null lst) ;IF not list return NIL
nil
(if (< size 4) ;ELSEIF lst < 4 return NIL
(format t "This list is too short")
(car (cdr (cdr (cdr lst)))))))) ;ELSE return fourth element
;TEST CODE:
(my-fourth '(a b)) ; FAIL
(check-len '(a b c d e)) ; Returns the number 5 (list length)
(my-fourth '(a b c d e)) ; Returns 4th element D
|
[
{
"context": "ontinue k (value c)))\n\n;; Copyright (c) 2002-2006, Edward Marco Baringer\n;; All rights reserved. \n;; \n;; Redistribution an",
"end": 11529,
"score": 0.9998697638511658,
"start": 11508,
"tag": "NAME",
"value": "Edward Marco Baringer"
},
{
"context": "ith the distribution.\n;;\n;; - Neither the name of Edward Marco Baringer, nor BESE, nor the names\n;; of its contributor",
"end": 12127,
"score": 0.999890148639679,
"start": 12106,
"tag": "NAME",
"value": "Edward Marco Baringer"
}
] |
src/call-cc/handlers.lisp
|
luismbo/arnesi
| 0 |
;; -*- lisp -*-
(in-package :it.bese.arnesi)
;;;; ** Handlres for common-lisp special operators
;;;; Variable References
(defmethod evaluate/cc ((var local-variable-reference) lex-env dyn-env k)
(declare (ignore dyn-env))
(kontinue k (lookup lex-env :let (name var) :error-p t)))
(defmethod evaluate/cc ((var local-lexical-variable-reference) lex-env dyn-env k)
(declare (ignore dyn-env))
(kontinue k (funcall (first (lookup lex-env :lexical-let (name var) :error-p t)))))
(defmethod evaluate/cc ((var free-variable-reference) lex-env dyn-env k)
(declare (ignore lex-env))
(multiple-value-bind (value foundp)
(lookup dyn-env :let (name var))
(if foundp
(kontinue k value)
(kontinue k (symbol-value (name var))))))
;;;; Constants
(defmethod evaluate/cc ((c constant-form) lex-env dyn-env k)
(declare (ignore lex-env dyn-env))
(kontinue k (value c)))
;;;; BLOCK/RETURN-FROM
(defmethod evaluate/cc ((block block-form) lex-env dyn-env k)
(evaluate-progn/cc (body block)
(register lex-env :block (name block) k)
dyn-env k))
(defmethod evaluate/cc ((return return-from-form) lex-env dyn-env k)
(declare (ignore k))
(evaluate/cc (result return)
lex-env dyn-env
(lookup lex-env :block (name (target-block return)) :error-p t)))
;;;; CATCH/THROW
(defmethod evaluate/cc ((catch catch-form) lex-env dyn-env k)
(evaluate/cc (tag catch) lex-env dyn-env
`(catch-tag-k ,catch ,lex-env ,dyn-env ,k)))
(defk catch-tag-k (catch lex-env dyn-env k)
(tag)
(evaluate-progn/cc (body catch) lex-env (register dyn-env :catch tag k) k))
(defmethod evaluate/cc ((throw throw-form) lex-env dyn-env k)
(evaluate/cc (tag throw) lex-env dyn-env
`(throw-tag-k ,throw ,lex-env ,dyn-env ,k)))
(defk throw-tag-k (throw lex-env dyn-env k)
(tag)
(evaluate/cc (value throw) lex-env dyn-env
(lookup dyn-env :catch tag :error-p t)))
;;;; FLET/LABELS
(defmethod evaluate/cc ((flet flet-form) lex-env dyn-env k)
(let ((new-env lex-env))
(dolist* ((name . form) (binds flet))
(setf new-env (register new-env :flet name (make-instance 'closure/cc
:code form
:env lex-env))))
(evaluate-progn/cc (body flet) new-env dyn-env k)))
(defmethod evaluate/cc ((labels labels-form) lex-env dyn-env k)
(let ((closures '()))
(dolist* ((name . form) (binds labels))
(let ((closure (make-instance 'closure/cc :code form)))
(setf lex-env (register lex-env :flet name closure))
(push closure closures)))
(dolist (closure closures)
(setf (env closure) lex-env))
(evaluate-progn/cc (body labels) lex-env dyn-env k)))
;;;; LET/LET*
;; returns a dynamic environment that holds the special variables imported for let
;; these variables are captured from the caller normal lisp code and stored within
;; the continuation. The mixin might be a binding-form-mixin and implicit-progn-with-declare-mixin.
(defun import-specials (mixin dyn-env)
(dolist (declaration (declares mixin))
(let ((name (name declaration)))
(if (and (typep declaration 'special-declaration-form)
(or (not (typep mixin 'binding-form-mixin))
(not (find name (binds mixin) :key 'first)))
(not (lookup dyn-env :let name)))
(setf dyn-env (register dyn-env :let name (symbol-value name))))))
dyn-env)
(defmethod evaluate/cc ((let let-form) lex-env dyn-env k)
(evaluate-let/cc (binds let) nil (body let) lex-env (import-specials let dyn-env) k))
(defk k-for-evaluate-let/cc (var remaining-bindings evaluated-bindings body lex-env dyn-env k)
(value)
(evaluate-let/cc remaining-bindings
(cons (cons var value) evaluated-bindings)
body lex-env dyn-env k))
(defun evaluate-let/cc (remaining-bindings evaluated-bindings body lex-env dyn-env k)
(if remaining-bindings
(destructuring-bind (var . initial-value)
(car remaining-bindings)
(evaluate/cc
initial-value
lex-env dyn-env
`(k-for-evaluate-let/cc
,var
,(cdr remaining-bindings)
,evaluated-bindings
,body
,lex-env ,dyn-env ,k)))
(dolist* ((var . value) evaluated-bindings
(evaluate-progn/cc body lex-env dyn-env k))
(if (special-var-p var (parent (first body)))
(setf dyn-env (register dyn-env :let var value))
(setf lex-env (register lex-env :let var value))))))
(defun special-var-p (var declares-mixin)
(or (find-if (lambda (declaration)
(and (typep declaration 'special-declaration-form)
(eq (name declaration) var)))
(declares declares-mixin))
(boundp var)
;; This is the only portable way to check if a symbol is
;; declared special, without being boundp, i.e. (defvar 'foo).
;; Maybe we should make it optional with a compile-time flag?
#+nil(eval `((lambda ()
(flet ((func ()
(symbol-value ',var)))
(let ((,var t))
(declare (ignorable ,var))
(ignore-errors (func)))))))))
(defmethod evaluate/cc ((let* let*-form) lex-env dyn-env k)
(evaluate-let*/cc (binds let*) (body let*) lex-env (import-specials let* dyn-env) k))
(defk k-for-evaluate-let*/cc (var bindings body lex-env dyn-env k)
(value)
(if (special-var-p var (parent (first body)))
(evaluate-let*/cc bindings body
lex-env
(register dyn-env :let var value)
k)
(evaluate-let*/cc bindings body
(register lex-env :let var value)
dyn-env
k)))
(defun evaluate-let*/cc (bindings body lex-env dyn-env k)
(if bindings
(destructuring-bind (var . initial-value)
(car bindings)
(evaluate/cc initial-value lex-env dyn-env
`(k-for-evaluate-let*/cc ,var ,(cdr bindings) ,body ,lex-env ,dyn-env ,k)))
(evaluate-progn/cc body lex-env dyn-env k)))
;;;; IF
(defk k-for-evaluate-if/cc (then else lex-env dyn-env k)
(value)
(if value
(evaluate/cc then lex-env dyn-env k)
(evaluate/cc else lex-env dyn-env k)))
(defmethod evaluate/cc ((if if-form) lex-env dyn-env k)
(evaluate/cc (consequent if) lex-env dyn-env
`(k-for-evaluate-if/cc ,(then if) ,(else if) ,lex-env ,dyn-env ,k)))
;;;; LOCALLY
(defmethod evaluate/cc ((locally locally-form) lex-env dyn-env k)
(evaluate-progn/cc (body locally) lex-env dyn-env k))
;;;; MACROLET
(defmethod evaluate/cc ((macrolet macrolet-form) lex-env dyn-env k)
;; since the walker already performs macroexpansion there's nothing
;; left to do here.
(evaluate-progn/cc (body macrolet) lex-env dyn-env k))
;;;; multiple-value-call
(defk k-for-m-v-c (remaining-arguments evaluated-arguments lex-env dyn-env k)
(value other-values)
(evaluate-m-v-c
remaining-arguments (append evaluated-arguments (list value) other-values)
lex-env dyn-env k))
(defun evaluate-m-v-c (remaining-arguments evaluated-arguments lex-env dyn-env k)
(if remaining-arguments
(evaluate/cc (car remaining-arguments) lex-env dyn-env
`(k-for-m-v-c ,(cdr remaining-arguments) ,evaluated-arguments ,lex-env ,dyn-env ,k))
(destructuring-bind (function &rest arguments)
evaluated-arguments
(etypecase function
(closure/cc (apply-lambda/cc function arguments dyn-env k))
(function (apply #'kontinue k (multiple-value-list
(multiple-value-call function (values-list arguments)))))))))
(defmethod evaluate/cc ((m-v-c multiple-value-call-form) lex-env dyn-env k)
(evaluate-m-v-c (list* (func m-v-c) (arguments m-v-c)) '() lex-env dyn-env k))
;;;; PROGN
(defmethod evaluate/cc ((progn progn-form) lex-env dyn-env k)
(evaluate-progn/cc (body progn) lex-env dyn-env k))
(defk k-for-evaluate-progn/cc (rest-of-body lex-env dyn-env k)
()
(evaluate-progn/cc rest-of-body lex-env dyn-env k))
(defun evaluate-progn/cc (body lex-env dyn-env k)
(cond
((cdr body)
(evaluate/cc (first body) lex-env dyn-env
`(k-for-evaluate-progn/cc ,(cdr body) ,lex-env ,dyn-env ,k)))
(body
(evaluate/cc (first body) lex-env dyn-env k))
(t
(kontinue k nil))))
;;;; SETQ
(defk k-for-local-setq (var lex-env dyn-env k)
(value)
(setf (lookup lex-env :let var :error-p t) value)
(kontinue k value))
(defk k-for-free-setq (var lex-env dyn-env k)
(value)
(let ((exp (macroexpand var)))
(if (eq var exp)
(setf (symbol-value var) value)
(multiple-value-bind (dummies vals new setter getter)
(get-setf-expansion var)
(funcall
(compile nil
`(lambda ()
(let* (,@(mapcar #'list dummies vals)
(,(car new) ,value))
(prog1
,setter))))))))
(kontinue k value))
(defk k-for-local-lexical-setq (var lex-env dyn-env k)
(value)
(funcall (second (lookup lex-env :lexical-let var :error-p t)) value)
(kontinue k value))
(defmethod evaluate/cc ((setq setq-form) lex-env dyn-env k)
(macrolet ((if-found (&key in-env of-type kontinue-with)
`(multiple-value-bind (value foundp)
(lookup ,in-env ,of-type (var setq))
(declare (ignore value))
(when foundp
(return-from evaluate/cc
(evaluate/cc (value setq) lex-env dyn-env
`(,',kontinue-with ,(var setq) ,lex-env ,dyn-env ,k)))))))
(if-found :in-env lex-env
:of-type :let
:kontinue-with k-for-local-setq)
(if-found :in-env dyn-env
:of-type :let
:kontinue-with k-for-special-setq)
(if-found :in-env lex-env
:of-type :lexical-let
:kontinue-with k-for-local-lexical-setq)
(evaluate/cc (value setq)
lex-env dyn-env
`(k-for-free-setq ,(var setq) ,lex-env ,dyn-env ,k))))
;;;; SYMBOL-MACROLET
(defmethod evaluate/cc ((symbol-macrolet symbol-macrolet-form) lex-env dyn-env k)
;; like macrolet the walker has already done all the work needed for this.
(evaluate-progn/cc (body symbol-macrolet) lex-env dyn-env k))
;;;; TAGBODY/GO
(defk tagbody-k (k)
()
(kontinue k nil))
(defmethod evaluate/cc ((tagbody tagbody-form) lex-env dyn-env k)
(evaluate-progn/cc (body tagbody)
(register lex-env :tag tagbody k) dyn-env
`(tagbody-k ,k)))
(defmethod evaluate/cc ((go-tag go-tag-form) lex-env dyn-env k)
(declare (ignore go-tag lex-env dyn-env))
(kontinue k nil))
(defmethod evaluate/cc ((go go-form) lex-env dyn-env k)
(declare (ignore k))
(evaluate-progn/cc (target-progn go) lex-env dyn-env
(lookup lex-env :tag (enclosing-tagbody go) :error-p t)))
;;;; THE
(defmethod evaluate/cc ((the the-form) lex-env dyn-env k)
(evaluate/cc (value the) lex-env dyn-env k))
;;;; LOAD-TIME-VALUE
(defmethod evaluate/cc ((c load-time-value-form) lex-env dyn-env k)
(declare (ignore lex-env dyn-env))
(kontinue k (value c)))
;; Copyright (c) 2002-2006, Edward Marco Baringer
;; 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.
;;
;; - Neither the name of Edward Marco Baringer, nor BESE, 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
;; 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.
|
29286
|
;; -*- lisp -*-
(in-package :it.bese.arnesi)
;;;; ** Handlres for common-lisp special operators
;;;; Variable References
(defmethod evaluate/cc ((var local-variable-reference) lex-env dyn-env k)
(declare (ignore dyn-env))
(kontinue k (lookup lex-env :let (name var) :error-p t)))
(defmethod evaluate/cc ((var local-lexical-variable-reference) lex-env dyn-env k)
(declare (ignore dyn-env))
(kontinue k (funcall (first (lookup lex-env :lexical-let (name var) :error-p t)))))
(defmethod evaluate/cc ((var free-variable-reference) lex-env dyn-env k)
(declare (ignore lex-env))
(multiple-value-bind (value foundp)
(lookup dyn-env :let (name var))
(if foundp
(kontinue k value)
(kontinue k (symbol-value (name var))))))
;;;; Constants
(defmethod evaluate/cc ((c constant-form) lex-env dyn-env k)
(declare (ignore lex-env dyn-env))
(kontinue k (value c)))
;;;; BLOCK/RETURN-FROM
(defmethod evaluate/cc ((block block-form) lex-env dyn-env k)
(evaluate-progn/cc (body block)
(register lex-env :block (name block) k)
dyn-env k))
(defmethod evaluate/cc ((return return-from-form) lex-env dyn-env k)
(declare (ignore k))
(evaluate/cc (result return)
lex-env dyn-env
(lookup lex-env :block (name (target-block return)) :error-p t)))
;;;; CATCH/THROW
(defmethod evaluate/cc ((catch catch-form) lex-env dyn-env k)
(evaluate/cc (tag catch) lex-env dyn-env
`(catch-tag-k ,catch ,lex-env ,dyn-env ,k)))
(defk catch-tag-k (catch lex-env dyn-env k)
(tag)
(evaluate-progn/cc (body catch) lex-env (register dyn-env :catch tag k) k))
(defmethod evaluate/cc ((throw throw-form) lex-env dyn-env k)
(evaluate/cc (tag throw) lex-env dyn-env
`(throw-tag-k ,throw ,lex-env ,dyn-env ,k)))
(defk throw-tag-k (throw lex-env dyn-env k)
(tag)
(evaluate/cc (value throw) lex-env dyn-env
(lookup dyn-env :catch tag :error-p t)))
;;;; FLET/LABELS
(defmethod evaluate/cc ((flet flet-form) lex-env dyn-env k)
(let ((new-env lex-env))
(dolist* ((name . form) (binds flet))
(setf new-env (register new-env :flet name (make-instance 'closure/cc
:code form
:env lex-env))))
(evaluate-progn/cc (body flet) new-env dyn-env k)))
(defmethod evaluate/cc ((labels labels-form) lex-env dyn-env k)
(let ((closures '()))
(dolist* ((name . form) (binds labels))
(let ((closure (make-instance 'closure/cc :code form)))
(setf lex-env (register lex-env :flet name closure))
(push closure closures)))
(dolist (closure closures)
(setf (env closure) lex-env))
(evaluate-progn/cc (body labels) lex-env dyn-env k)))
;;;; LET/LET*
;; returns a dynamic environment that holds the special variables imported for let
;; these variables are captured from the caller normal lisp code and stored within
;; the continuation. The mixin might be a binding-form-mixin and implicit-progn-with-declare-mixin.
(defun import-specials (mixin dyn-env)
(dolist (declaration (declares mixin))
(let ((name (name declaration)))
(if (and (typep declaration 'special-declaration-form)
(or (not (typep mixin 'binding-form-mixin))
(not (find name (binds mixin) :key 'first)))
(not (lookup dyn-env :let name)))
(setf dyn-env (register dyn-env :let name (symbol-value name))))))
dyn-env)
(defmethod evaluate/cc ((let let-form) lex-env dyn-env k)
(evaluate-let/cc (binds let) nil (body let) lex-env (import-specials let dyn-env) k))
(defk k-for-evaluate-let/cc (var remaining-bindings evaluated-bindings body lex-env dyn-env k)
(value)
(evaluate-let/cc remaining-bindings
(cons (cons var value) evaluated-bindings)
body lex-env dyn-env k))
(defun evaluate-let/cc (remaining-bindings evaluated-bindings body lex-env dyn-env k)
(if remaining-bindings
(destructuring-bind (var . initial-value)
(car remaining-bindings)
(evaluate/cc
initial-value
lex-env dyn-env
`(k-for-evaluate-let/cc
,var
,(cdr remaining-bindings)
,evaluated-bindings
,body
,lex-env ,dyn-env ,k)))
(dolist* ((var . value) evaluated-bindings
(evaluate-progn/cc body lex-env dyn-env k))
(if (special-var-p var (parent (first body)))
(setf dyn-env (register dyn-env :let var value))
(setf lex-env (register lex-env :let var value))))))
(defun special-var-p (var declares-mixin)
(or (find-if (lambda (declaration)
(and (typep declaration 'special-declaration-form)
(eq (name declaration) var)))
(declares declares-mixin))
(boundp var)
;; This is the only portable way to check if a symbol is
;; declared special, without being boundp, i.e. (defvar 'foo).
;; Maybe we should make it optional with a compile-time flag?
#+nil(eval `((lambda ()
(flet ((func ()
(symbol-value ',var)))
(let ((,var t))
(declare (ignorable ,var))
(ignore-errors (func)))))))))
(defmethod evaluate/cc ((let* let*-form) lex-env dyn-env k)
(evaluate-let*/cc (binds let*) (body let*) lex-env (import-specials let* dyn-env) k))
(defk k-for-evaluate-let*/cc (var bindings body lex-env dyn-env k)
(value)
(if (special-var-p var (parent (first body)))
(evaluate-let*/cc bindings body
lex-env
(register dyn-env :let var value)
k)
(evaluate-let*/cc bindings body
(register lex-env :let var value)
dyn-env
k)))
(defun evaluate-let*/cc (bindings body lex-env dyn-env k)
(if bindings
(destructuring-bind (var . initial-value)
(car bindings)
(evaluate/cc initial-value lex-env dyn-env
`(k-for-evaluate-let*/cc ,var ,(cdr bindings) ,body ,lex-env ,dyn-env ,k)))
(evaluate-progn/cc body lex-env dyn-env k)))
;;;; IF
(defk k-for-evaluate-if/cc (then else lex-env dyn-env k)
(value)
(if value
(evaluate/cc then lex-env dyn-env k)
(evaluate/cc else lex-env dyn-env k)))
(defmethod evaluate/cc ((if if-form) lex-env dyn-env k)
(evaluate/cc (consequent if) lex-env dyn-env
`(k-for-evaluate-if/cc ,(then if) ,(else if) ,lex-env ,dyn-env ,k)))
;;;; LOCALLY
(defmethod evaluate/cc ((locally locally-form) lex-env dyn-env k)
(evaluate-progn/cc (body locally) lex-env dyn-env k))
;;;; MACROLET
(defmethod evaluate/cc ((macrolet macrolet-form) lex-env dyn-env k)
;; since the walker already performs macroexpansion there's nothing
;; left to do here.
(evaluate-progn/cc (body macrolet) lex-env dyn-env k))
;;;; multiple-value-call
(defk k-for-m-v-c (remaining-arguments evaluated-arguments lex-env dyn-env k)
(value other-values)
(evaluate-m-v-c
remaining-arguments (append evaluated-arguments (list value) other-values)
lex-env dyn-env k))
(defun evaluate-m-v-c (remaining-arguments evaluated-arguments lex-env dyn-env k)
(if remaining-arguments
(evaluate/cc (car remaining-arguments) lex-env dyn-env
`(k-for-m-v-c ,(cdr remaining-arguments) ,evaluated-arguments ,lex-env ,dyn-env ,k))
(destructuring-bind (function &rest arguments)
evaluated-arguments
(etypecase function
(closure/cc (apply-lambda/cc function arguments dyn-env k))
(function (apply #'kontinue k (multiple-value-list
(multiple-value-call function (values-list arguments)))))))))
(defmethod evaluate/cc ((m-v-c multiple-value-call-form) lex-env dyn-env k)
(evaluate-m-v-c (list* (func m-v-c) (arguments m-v-c)) '() lex-env dyn-env k))
;;;; PROGN
(defmethod evaluate/cc ((progn progn-form) lex-env dyn-env k)
(evaluate-progn/cc (body progn) lex-env dyn-env k))
(defk k-for-evaluate-progn/cc (rest-of-body lex-env dyn-env k)
()
(evaluate-progn/cc rest-of-body lex-env dyn-env k))
(defun evaluate-progn/cc (body lex-env dyn-env k)
(cond
((cdr body)
(evaluate/cc (first body) lex-env dyn-env
`(k-for-evaluate-progn/cc ,(cdr body) ,lex-env ,dyn-env ,k)))
(body
(evaluate/cc (first body) lex-env dyn-env k))
(t
(kontinue k nil))))
;;;; SETQ
(defk k-for-local-setq (var lex-env dyn-env k)
(value)
(setf (lookup lex-env :let var :error-p t) value)
(kontinue k value))
(defk k-for-free-setq (var lex-env dyn-env k)
(value)
(let ((exp (macroexpand var)))
(if (eq var exp)
(setf (symbol-value var) value)
(multiple-value-bind (dummies vals new setter getter)
(get-setf-expansion var)
(funcall
(compile nil
`(lambda ()
(let* (,@(mapcar #'list dummies vals)
(,(car new) ,value))
(prog1
,setter))))))))
(kontinue k value))
(defk k-for-local-lexical-setq (var lex-env dyn-env k)
(value)
(funcall (second (lookup lex-env :lexical-let var :error-p t)) value)
(kontinue k value))
(defmethod evaluate/cc ((setq setq-form) lex-env dyn-env k)
(macrolet ((if-found (&key in-env of-type kontinue-with)
`(multiple-value-bind (value foundp)
(lookup ,in-env ,of-type (var setq))
(declare (ignore value))
(when foundp
(return-from evaluate/cc
(evaluate/cc (value setq) lex-env dyn-env
`(,',kontinue-with ,(var setq) ,lex-env ,dyn-env ,k)))))))
(if-found :in-env lex-env
:of-type :let
:kontinue-with k-for-local-setq)
(if-found :in-env dyn-env
:of-type :let
:kontinue-with k-for-special-setq)
(if-found :in-env lex-env
:of-type :lexical-let
:kontinue-with k-for-local-lexical-setq)
(evaluate/cc (value setq)
lex-env dyn-env
`(k-for-free-setq ,(var setq) ,lex-env ,dyn-env ,k))))
;;;; SYMBOL-MACROLET
(defmethod evaluate/cc ((symbol-macrolet symbol-macrolet-form) lex-env dyn-env k)
;; like macrolet the walker has already done all the work needed for this.
(evaluate-progn/cc (body symbol-macrolet) lex-env dyn-env k))
;;;; TAGBODY/GO
(defk tagbody-k (k)
()
(kontinue k nil))
(defmethod evaluate/cc ((tagbody tagbody-form) lex-env dyn-env k)
(evaluate-progn/cc (body tagbody)
(register lex-env :tag tagbody k) dyn-env
`(tagbody-k ,k)))
(defmethod evaluate/cc ((go-tag go-tag-form) lex-env dyn-env k)
(declare (ignore go-tag lex-env dyn-env))
(kontinue k nil))
(defmethod evaluate/cc ((go go-form) lex-env dyn-env k)
(declare (ignore k))
(evaluate-progn/cc (target-progn go) lex-env dyn-env
(lookup lex-env :tag (enclosing-tagbody go) :error-p t)))
;;;; THE
(defmethod evaluate/cc ((the the-form) lex-env dyn-env k)
(evaluate/cc (value the) lex-env dyn-env k))
;;;; LOAD-TIME-VALUE
(defmethod evaluate/cc ((c load-time-value-form) lex-env dyn-env k)
(declare (ignore lex-env dyn-env))
(kontinue k (value c)))
;; Copyright (c) 2002-2006, <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.
;;
;; - Neither the name of <NAME>, nor BESE, 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
;; 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.
| true |
;; -*- lisp -*-
(in-package :it.bese.arnesi)
;;;; ** Handlres for common-lisp special operators
;;;; Variable References
(defmethod evaluate/cc ((var local-variable-reference) lex-env dyn-env k)
(declare (ignore dyn-env))
(kontinue k (lookup lex-env :let (name var) :error-p t)))
(defmethod evaluate/cc ((var local-lexical-variable-reference) lex-env dyn-env k)
(declare (ignore dyn-env))
(kontinue k (funcall (first (lookup lex-env :lexical-let (name var) :error-p t)))))
(defmethod evaluate/cc ((var free-variable-reference) lex-env dyn-env k)
(declare (ignore lex-env))
(multiple-value-bind (value foundp)
(lookup dyn-env :let (name var))
(if foundp
(kontinue k value)
(kontinue k (symbol-value (name var))))))
;;;; Constants
(defmethod evaluate/cc ((c constant-form) lex-env dyn-env k)
(declare (ignore lex-env dyn-env))
(kontinue k (value c)))
;;;; BLOCK/RETURN-FROM
(defmethod evaluate/cc ((block block-form) lex-env dyn-env k)
(evaluate-progn/cc (body block)
(register lex-env :block (name block) k)
dyn-env k))
(defmethod evaluate/cc ((return return-from-form) lex-env dyn-env k)
(declare (ignore k))
(evaluate/cc (result return)
lex-env dyn-env
(lookup lex-env :block (name (target-block return)) :error-p t)))
;;;; CATCH/THROW
(defmethod evaluate/cc ((catch catch-form) lex-env dyn-env k)
(evaluate/cc (tag catch) lex-env dyn-env
`(catch-tag-k ,catch ,lex-env ,dyn-env ,k)))
(defk catch-tag-k (catch lex-env dyn-env k)
(tag)
(evaluate-progn/cc (body catch) lex-env (register dyn-env :catch tag k) k))
(defmethod evaluate/cc ((throw throw-form) lex-env dyn-env k)
(evaluate/cc (tag throw) lex-env dyn-env
`(throw-tag-k ,throw ,lex-env ,dyn-env ,k)))
(defk throw-tag-k (throw lex-env dyn-env k)
(tag)
(evaluate/cc (value throw) lex-env dyn-env
(lookup dyn-env :catch tag :error-p t)))
;;;; FLET/LABELS
(defmethod evaluate/cc ((flet flet-form) lex-env dyn-env k)
(let ((new-env lex-env))
(dolist* ((name . form) (binds flet))
(setf new-env (register new-env :flet name (make-instance 'closure/cc
:code form
:env lex-env))))
(evaluate-progn/cc (body flet) new-env dyn-env k)))
(defmethod evaluate/cc ((labels labels-form) lex-env dyn-env k)
(let ((closures '()))
(dolist* ((name . form) (binds labels))
(let ((closure (make-instance 'closure/cc :code form)))
(setf lex-env (register lex-env :flet name closure))
(push closure closures)))
(dolist (closure closures)
(setf (env closure) lex-env))
(evaluate-progn/cc (body labels) lex-env dyn-env k)))
;;;; LET/LET*
;; returns a dynamic environment that holds the special variables imported for let
;; these variables are captured from the caller normal lisp code and stored within
;; the continuation. The mixin might be a binding-form-mixin and implicit-progn-with-declare-mixin.
(defun import-specials (mixin dyn-env)
(dolist (declaration (declares mixin))
(let ((name (name declaration)))
(if (and (typep declaration 'special-declaration-form)
(or (not (typep mixin 'binding-form-mixin))
(not (find name (binds mixin) :key 'first)))
(not (lookup dyn-env :let name)))
(setf dyn-env (register dyn-env :let name (symbol-value name))))))
dyn-env)
(defmethod evaluate/cc ((let let-form) lex-env dyn-env k)
(evaluate-let/cc (binds let) nil (body let) lex-env (import-specials let dyn-env) k))
(defk k-for-evaluate-let/cc (var remaining-bindings evaluated-bindings body lex-env dyn-env k)
(value)
(evaluate-let/cc remaining-bindings
(cons (cons var value) evaluated-bindings)
body lex-env dyn-env k))
(defun evaluate-let/cc (remaining-bindings evaluated-bindings body lex-env dyn-env k)
(if remaining-bindings
(destructuring-bind (var . initial-value)
(car remaining-bindings)
(evaluate/cc
initial-value
lex-env dyn-env
`(k-for-evaluate-let/cc
,var
,(cdr remaining-bindings)
,evaluated-bindings
,body
,lex-env ,dyn-env ,k)))
(dolist* ((var . value) evaluated-bindings
(evaluate-progn/cc body lex-env dyn-env k))
(if (special-var-p var (parent (first body)))
(setf dyn-env (register dyn-env :let var value))
(setf lex-env (register lex-env :let var value))))))
(defun special-var-p (var declares-mixin)
(or (find-if (lambda (declaration)
(and (typep declaration 'special-declaration-form)
(eq (name declaration) var)))
(declares declares-mixin))
(boundp var)
;; This is the only portable way to check if a symbol is
;; declared special, without being boundp, i.e. (defvar 'foo).
;; Maybe we should make it optional with a compile-time flag?
#+nil(eval `((lambda ()
(flet ((func ()
(symbol-value ',var)))
(let ((,var t))
(declare (ignorable ,var))
(ignore-errors (func)))))))))
(defmethod evaluate/cc ((let* let*-form) lex-env dyn-env k)
(evaluate-let*/cc (binds let*) (body let*) lex-env (import-specials let* dyn-env) k))
(defk k-for-evaluate-let*/cc (var bindings body lex-env dyn-env k)
(value)
(if (special-var-p var (parent (first body)))
(evaluate-let*/cc bindings body
lex-env
(register dyn-env :let var value)
k)
(evaluate-let*/cc bindings body
(register lex-env :let var value)
dyn-env
k)))
(defun evaluate-let*/cc (bindings body lex-env dyn-env k)
(if bindings
(destructuring-bind (var . initial-value)
(car bindings)
(evaluate/cc initial-value lex-env dyn-env
`(k-for-evaluate-let*/cc ,var ,(cdr bindings) ,body ,lex-env ,dyn-env ,k)))
(evaluate-progn/cc body lex-env dyn-env k)))
;;;; IF
(defk k-for-evaluate-if/cc (then else lex-env dyn-env k)
(value)
(if value
(evaluate/cc then lex-env dyn-env k)
(evaluate/cc else lex-env dyn-env k)))
(defmethod evaluate/cc ((if if-form) lex-env dyn-env k)
(evaluate/cc (consequent if) lex-env dyn-env
`(k-for-evaluate-if/cc ,(then if) ,(else if) ,lex-env ,dyn-env ,k)))
;;;; LOCALLY
(defmethod evaluate/cc ((locally locally-form) lex-env dyn-env k)
(evaluate-progn/cc (body locally) lex-env dyn-env k))
;;;; MACROLET
(defmethod evaluate/cc ((macrolet macrolet-form) lex-env dyn-env k)
;; since the walker already performs macroexpansion there's nothing
;; left to do here.
(evaluate-progn/cc (body macrolet) lex-env dyn-env k))
;;;; multiple-value-call
(defk k-for-m-v-c (remaining-arguments evaluated-arguments lex-env dyn-env k)
(value other-values)
(evaluate-m-v-c
remaining-arguments (append evaluated-arguments (list value) other-values)
lex-env dyn-env k))
(defun evaluate-m-v-c (remaining-arguments evaluated-arguments lex-env dyn-env k)
(if remaining-arguments
(evaluate/cc (car remaining-arguments) lex-env dyn-env
`(k-for-m-v-c ,(cdr remaining-arguments) ,evaluated-arguments ,lex-env ,dyn-env ,k))
(destructuring-bind (function &rest arguments)
evaluated-arguments
(etypecase function
(closure/cc (apply-lambda/cc function arguments dyn-env k))
(function (apply #'kontinue k (multiple-value-list
(multiple-value-call function (values-list arguments)))))))))
(defmethod evaluate/cc ((m-v-c multiple-value-call-form) lex-env dyn-env k)
(evaluate-m-v-c (list* (func m-v-c) (arguments m-v-c)) '() lex-env dyn-env k))
;;;; PROGN
(defmethod evaluate/cc ((progn progn-form) lex-env dyn-env k)
(evaluate-progn/cc (body progn) lex-env dyn-env k))
(defk k-for-evaluate-progn/cc (rest-of-body lex-env dyn-env k)
()
(evaluate-progn/cc rest-of-body lex-env dyn-env k))
(defun evaluate-progn/cc (body lex-env dyn-env k)
(cond
((cdr body)
(evaluate/cc (first body) lex-env dyn-env
`(k-for-evaluate-progn/cc ,(cdr body) ,lex-env ,dyn-env ,k)))
(body
(evaluate/cc (first body) lex-env dyn-env k))
(t
(kontinue k nil))))
;;;; SETQ
(defk k-for-local-setq (var lex-env dyn-env k)
(value)
(setf (lookup lex-env :let var :error-p t) value)
(kontinue k value))
(defk k-for-free-setq (var lex-env dyn-env k)
(value)
(let ((exp (macroexpand var)))
(if (eq var exp)
(setf (symbol-value var) value)
(multiple-value-bind (dummies vals new setter getter)
(get-setf-expansion var)
(funcall
(compile nil
`(lambda ()
(let* (,@(mapcar #'list dummies vals)
(,(car new) ,value))
(prog1
,setter))))))))
(kontinue k value))
(defk k-for-local-lexical-setq (var lex-env dyn-env k)
(value)
(funcall (second (lookup lex-env :lexical-let var :error-p t)) value)
(kontinue k value))
(defmethod evaluate/cc ((setq setq-form) lex-env dyn-env k)
(macrolet ((if-found (&key in-env of-type kontinue-with)
`(multiple-value-bind (value foundp)
(lookup ,in-env ,of-type (var setq))
(declare (ignore value))
(when foundp
(return-from evaluate/cc
(evaluate/cc (value setq) lex-env dyn-env
`(,',kontinue-with ,(var setq) ,lex-env ,dyn-env ,k)))))))
(if-found :in-env lex-env
:of-type :let
:kontinue-with k-for-local-setq)
(if-found :in-env dyn-env
:of-type :let
:kontinue-with k-for-special-setq)
(if-found :in-env lex-env
:of-type :lexical-let
:kontinue-with k-for-local-lexical-setq)
(evaluate/cc (value setq)
lex-env dyn-env
`(k-for-free-setq ,(var setq) ,lex-env ,dyn-env ,k))))
;;;; SYMBOL-MACROLET
(defmethod evaluate/cc ((symbol-macrolet symbol-macrolet-form) lex-env dyn-env k)
;; like macrolet the walker has already done all the work needed for this.
(evaluate-progn/cc (body symbol-macrolet) lex-env dyn-env k))
;;;; TAGBODY/GO
(defk tagbody-k (k)
()
(kontinue k nil))
(defmethod evaluate/cc ((tagbody tagbody-form) lex-env dyn-env k)
(evaluate-progn/cc (body tagbody)
(register lex-env :tag tagbody k) dyn-env
`(tagbody-k ,k)))
(defmethod evaluate/cc ((go-tag go-tag-form) lex-env dyn-env k)
(declare (ignore go-tag lex-env dyn-env))
(kontinue k nil))
(defmethod evaluate/cc ((go go-form) lex-env dyn-env k)
(declare (ignore k))
(evaluate-progn/cc (target-progn go) lex-env dyn-env
(lookup lex-env :tag (enclosing-tagbody go) :error-p t)))
;;;; THE
(defmethod evaluate/cc ((the the-form) lex-env dyn-env k)
(evaluate/cc (value the) lex-env dyn-env k))
;;;; LOAD-TIME-VALUE
(defmethod evaluate/cc ((c load-time-value-form) lex-env dyn-env k)
(declare (ignore lex-env dyn-env))
(kontinue k (value c)))
;; Copyright (c) 2002-2006, 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.
;;
;; - Neither the name of PI:NAME:<NAME>END_PI, nor BESE, 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
;; 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.
|
[
{
"context": "t of Maiden\n (c) 2016 Shirakumo http://tymoon.eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n",
"end": 90,
"score": 0.9999127984046936,
"start": 72,
"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": 115,
"score": 0.9998862743377686,
"start": 101,
"tag": "NAME",
"value": "Nicolas Hafner"
},
{
"context": ".eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(in-package #:org.shirakumo.maiden.agents.ti",
"end": 135,
"score": 0.9999244213104248,
"start": 117,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
agents/time/time.lisp
|
Shirakumo/maiden
| 50 |
#|
This file is a part of Maiden
(c) 2016 Shirakumo http://tymoon.eu ([email protected])
Author: Nicolas Hafner <[email protected]>
|#
(in-package #:org.shirakumo.maiden.agents.time)
(defparameter *timezone-api* "https://maps.googleapis.com/maps/api/timezone/json")
;; (maiden-accounts:define-fields
;; (timezone () "The time zone the account's user is currently in."))
(defun timezone-data (location &optional (time (get-unix-time)) key)
(let* ((key (or key (maiden-storage:with-storage ('time) (maiden-storage:value :api-key))))
(location (if (listp location) location (maiden-location:coordinates location)))
(data (request-as :json *timezone-api* :get `(("sensor" "false")
("timestamp" ,time)
("key" ,(or key ""))
("location" ,(format NIL "~f,~f" (first location) (second location))))))
(status (json-v data "status")))
(cond ((string-equal status "ok")
(list :zone-id (json-v data "timeZoneId")
:zone (json-v data "timeZoneName")
:dst-offset (json-v data "dstOffset")
:offset (json-v data "rawOffset")))
((string-equal status "zero_results")
(values))
((string-equal status "over_query_limit")
(error "Exceeded allowed amount of queries against the Google Maps API."))
((null key)
(error "You have not set the Google Maps API key yet."))
(T
(error "Google Maps failed to perform your request for an unknown reason.")))))
(defun timezone (location)
(let ((data (timezone-data location)))
(values (getf data :zone) (getf data :zone-id))))
(defun time (location)
(let ((data (timezone-data location)))
(+ (get-universal-time)
(getf data :offset)
(getf data :dst-offset))))
(defun user-location (user)
(or (ignore-errors (data-value :timezone user))
(ignore-errors (data-value :location user))
(error "I don't know where ~a is located." user)))
(define-consumer time (agent)
())
(define-command (time timezone-location) (c ev location)
:command "timezone of"
(let* ((data (timezone-data location))
(secs (+ (getf data :offset) (getf data :dst-offset))))
(reply ev "The time zone for ~s is ~a (UTC~@f)"
(getf data :zone) (/ secs 60))))
(define-command (time time-dwim) (c ev &optional signifier)
:command "time"
(cond ((not signifier)
(relay ev 'time-user :user (name (user ev))))
((find-user signifier (client ev))
(relay ev 'time-user :user signifier))
(T
(relay ev 'time-location :location signifier))))
(define-command (time time-location) (c ev &string location)
:command "time in"
(reply ev "The time in ~a is ~a." location (format-absolute-time (time location))))
(define-command (time time-user) (c ev user)
:command "time for"
(reply ev "The time for ~a is ~a." user (format-absolute-time (time (user-location user)))))
(define-command (time time-between) (c ev from to)
:command "time between"
(let* ((data-from (timezone-data from))
(data-to (timezone-data to))
(diff (- (+ (getf data-to :offset) (getf data-to :dst-offset))
(+ (getf data-from :offset) (getf data-from :dst-offset))))
(to-time (format-absolute-time (+ (get-universal-time) (getf data-to :offset) (getf data-to :dst-offset)))))
(if (< (abs diff) 60)
(reply ev "Both are in the same timezone, which is currently at ~a." to-time)
(reply ev "The time in ~a is ~a ~a (~a)."
to (format-relative-time (abs diff)) (if (<= 0 diff) "later" "earlier") to-time))))
(define-command (time time-between-users) (c ev from to)
:command "time between users"
(do-issue (core ev) time-between :from (user-location from) :to (user-location to)))
|
5239
|
#|
This file is a part of Maiden
(c) 2016 Shirakumo http://tymoon.eu (<EMAIL>)
Author: <NAME> <<EMAIL>>
|#
(in-package #:org.shirakumo.maiden.agents.time)
(defparameter *timezone-api* "https://maps.googleapis.com/maps/api/timezone/json")
;; (maiden-accounts:define-fields
;; (timezone () "The time zone the account's user is currently in."))
(defun timezone-data (location &optional (time (get-unix-time)) key)
(let* ((key (or key (maiden-storage:with-storage ('time) (maiden-storage:value :api-key))))
(location (if (listp location) location (maiden-location:coordinates location)))
(data (request-as :json *timezone-api* :get `(("sensor" "false")
("timestamp" ,time)
("key" ,(or key ""))
("location" ,(format NIL "~f,~f" (first location) (second location))))))
(status (json-v data "status")))
(cond ((string-equal status "ok")
(list :zone-id (json-v data "timeZoneId")
:zone (json-v data "timeZoneName")
:dst-offset (json-v data "dstOffset")
:offset (json-v data "rawOffset")))
((string-equal status "zero_results")
(values))
((string-equal status "over_query_limit")
(error "Exceeded allowed amount of queries against the Google Maps API."))
((null key)
(error "You have not set the Google Maps API key yet."))
(T
(error "Google Maps failed to perform your request for an unknown reason.")))))
(defun timezone (location)
(let ((data (timezone-data location)))
(values (getf data :zone) (getf data :zone-id))))
(defun time (location)
(let ((data (timezone-data location)))
(+ (get-universal-time)
(getf data :offset)
(getf data :dst-offset))))
(defun user-location (user)
(or (ignore-errors (data-value :timezone user))
(ignore-errors (data-value :location user))
(error "I don't know where ~a is located." user)))
(define-consumer time (agent)
())
(define-command (time timezone-location) (c ev location)
:command "timezone of"
(let* ((data (timezone-data location))
(secs (+ (getf data :offset) (getf data :dst-offset))))
(reply ev "The time zone for ~s is ~a (UTC~@f)"
(getf data :zone) (/ secs 60))))
(define-command (time time-dwim) (c ev &optional signifier)
:command "time"
(cond ((not signifier)
(relay ev 'time-user :user (name (user ev))))
((find-user signifier (client ev))
(relay ev 'time-user :user signifier))
(T
(relay ev 'time-location :location signifier))))
(define-command (time time-location) (c ev &string location)
:command "time in"
(reply ev "The time in ~a is ~a." location (format-absolute-time (time location))))
(define-command (time time-user) (c ev user)
:command "time for"
(reply ev "The time for ~a is ~a." user (format-absolute-time (time (user-location user)))))
(define-command (time time-between) (c ev from to)
:command "time between"
(let* ((data-from (timezone-data from))
(data-to (timezone-data to))
(diff (- (+ (getf data-to :offset) (getf data-to :dst-offset))
(+ (getf data-from :offset) (getf data-from :dst-offset))))
(to-time (format-absolute-time (+ (get-universal-time) (getf data-to :offset) (getf data-to :dst-offset)))))
(if (< (abs diff) 60)
(reply ev "Both are in the same timezone, which is currently at ~a." to-time)
(reply ev "The time in ~a is ~a ~a (~a)."
to (format-relative-time (abs diff)) (if (<= 0 diff) "later" "earlier") to-time))))
(define-command (time time-between-users) (c ev from to)
:command "time between users"
(do-issue (core ev) time-between :from (user-location from) :to (user-location to)))
| true |
#|
This file is a part of Maiden
(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.maiden.agents.time)
(defparameter *timezone-api* "https://maps.googleapis.com/maps/api/timezone/json")
;; (maiden-accounts:define-fields
;; (timezone () "The time zone the account's user is currently in."))
(defun timezone-data (location &optional (time (get-unix-time)) key)
(let* ((key (or key (maiden-storage:with-storage ('time) (maiden-storage:value :api-key))))
(location (if (listp location) location (maiden-location:coordinates location)))
(data (request-as :json *timezone-api* :get `(("sensor" "false")
("timestamp" ,time)
("key" ,(or key ""))
("location" ,(format NIL "~f,~f" (first location) (second location))))))
(status (json-v data "status")))
(cond ((string-equal status "ok")
(list :zone-id (json-v data "timeZoneId")
:zone (json-v data "timeZoneName")
:dst-offset (json-v data "dstOffset")
:offset (json-v data "rawOffset")))
((string-equal status "zero_results")
(values))
((string-equal status "over_query_limit")
(error "Exceeded allowed amount of queries against the Google Maps API."))
((null key)
(error "You have not set the Google Maps API key yet."))
(T
(error "Google Maps failed to perform your request for an unknown reason.")))))
(defun timezone (location)
(let ((data (timezone-data location)))
(values (getf data :zone) (getf data :zone-id))))
(defun time (location)
(let ((data (timezone-data location)))
(+ (get-universal-time)
(getf data :offset)
(getf data :dst-offset))))
(defun user-location (user)
(or (ignore-errors (data-value :timezone user))
(ignore-errors (data-value :location user))
(error "I don't know where ~a is located." user)))
(define-consumer time (agent)
())
(define-command (time timezone-location) (c ev location)
:command "timezone of"
(let* ((data (timezone-data location))
(secs (+ (getf data :offset) (getf data :dst-offset))))
(reply ev "The time zone for ~s is ~a (UTC~@f)"
(getf data :zone) (/ secs 60))))
(define-command (time time-dwim) (c ev &optional signifier)
:command "time"
(cond ((not signifier)
(relay ev 'time-user :user (name (user ev))))
((find-user signifier (client ev))
(relay ev 'time-user :user signifier))
(T
(relay ev 'time-location :location signifier))))
(define-command (time time-location) (c ev &string location)
:command "time in"
(reply ev "The time in ~a is ~a." location (format-absolute-time (time location))))
(define-command (time time-user) (c ev user)
:command "time for"
(reply ev "The time for ~a is ~a." user (format-absolute-time (time (user-location user)))))
(define-command (time time-between) (c ev from to)
:command "time between"
(let* ((data-from (timezone-data from))
(data-to (timezone-data to))
(diff (- (+ (getf data-to :offset) (getf data-to :dst-offset))
(+ (getf data-from :offset) (getf data-from :dst-offset))))
(to-time (format-absolute-time (+ (get-universal-time) (getf data-to :offset) (getf data-to :dst-offset)))))
(if (< (abs diff) 60)
(reply ev "Both are in the same timezone, which is currently at ~a." to-time)
(reply ev "The time in ~a is ~a ~a (~a)."
to (format-relative-time (abs diff)) (if (<= 0 diff) "later" "earlier") to-time))))
(define-command (time time-between-users) (c ev from to)
:command "time between users"
(do-issue (core ev) time-between :from (user-location from) :to (user-location to)))
|
[
{
"context": "r CL-PREVALENCE\n;;;;\n;;;; Copyright (C) 2003, 2004 Sven Van Caekenberghe, Beta Nine BVBA.\n;;;;\n;;;; You are granted the ri",
"end": 215,
"score": 0.9998742938041687,
"start": 194,
"tag": "NAME",
"value": "Sven Van Caekenberghe"
}
] |
platform/site-lisp/cl-prevalence/src/debug-prevalence.lisp
|
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD
| 10 |
;;;; -*- Mode: LISP -*-
;;;;
;;;; $Id: debug-prevalence.lisp,v 1.3 2006/01/05 14:08:24 scaekenberghe Exp $
;;;;
;;;; Some debugging routines for CL-PREVALENCE
;;;;
;;;; Copyright (C) 2003, 2004 Sven Van Caekenberghe, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(in-package :cl-prevalence)
;; the code for #'s-xml::echo-xml is in "echo.lisp" in S-XML's test code
(defun print-transaction-log (system)
"Echo the XML making up the transaction log of system to t"
(with-open-file (in (get-transaction-log system) :direction :input)
(loop
(let ((transaction (s-xml::echo-xml in *standard-output*)))
(when (null transaction) (return)))))
t)
(defun show-transaction-log (system)
"Print the transaction objects making up the transaction log of system to t"
(with-open-file (in (get-transaction-log system) :direction :input)
(loop
(let ((transaction (deserialize-xml in (get-serialization-state system))))
(if (null transaction)
(return)
(format t "~a~%" transaction)))))
t)
(defun print-snapshot (system)
"Echo the XML making up the snapshot of system to t"
(with-open-file (in (get-snapshot system) :direction :input)
(s-xml::echo-xml in *standard-output*))
t)
(defun transaction-log-tail (system &optional (count 8))
"Return a list of the count last transaction objects of system"
(let (transactions)
(with-open-file (in (get-transaction-log system) :direction :input)
(loop
(let ((transaction (deserialize-xml in (get-serialization-state system))))
(if (null transaction)
(return)
(push transaction transactions)))))
(setf transactions (nreverse transactions))
(nthcdr (max 0 (- (length transactions) count)) transactions)))
;;;; eof
|
64528
|
;;;; -*- Mode: LISP -*-
;;;;
;;;; $Id: debug-prevalence.lisp,v 1.3 2006/01/05 14:08:24 scaekenberghe Exp $
;;;;
;;;; Some debugging routines for CL-PREVALENCE
;;;;
;;;; Copyright (C) 2003, 2004 <NAME>, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(in-package :cl-prevalence)
;; the code for #'s-xml::echo-xml is in "echo.lisp" in S-XML's test code
(defun print-transaction-log (system)
"Echo the XML making up the transaction log of system to t"
(with-open-file (in (get-transaction-log system) :direction :input)
(loop
(let ((transaction (s-xml::echo-xml in *standard-output*)))
(when (null transaction) (return)))))
t)
(defun show-transaction-log (system)
"Print the transaction objects making up the transaction log of system to t"
(with-open-file (in (get-transaction-log system) :direction :input)
(loop
(let ((transaction (deserialize-xml in (get-serialization-state system))))
(if (null transaction)
(return)
(format t "~a~%" transaction)))))
t)
(defun print-snapshot (system)
"Echo the XML making up the snapshot of system to t"
(with-open-file (in (get-snapshot system) :direction :input)
(s-xml::echo-xml in *standard-output*))
t)
(defun transaction-log-tail (system &optional (count 8))
"Return a list of the count last transaction objects of system"
(let (transactions)
(with-open-file (in (get-transaction-log system) :direction :input)
(loop
(let ((transaction (deserialize-xml in (get-serialization-state system))))
(if (null transaction)
(return)
(push transaction transactions)))))
(setf transactions (nreverse transactions))
(nthcdr (max 0 (- (length transactions) count)) transactions)))
;;;; eof
| true |
;;;; -*- Mode: LISP -*-
;;;;
;;;; $Id: debug-prevalence.lisp,v 1.3 2006/01/05 14:08:24 scaekenberghe Exp $
;;;;
;;;; Some debugging routines for CL-PREVALENCE
;;;;
;;;; Copyright (C) 2003, 2004 PI:NAME:<NAME>END_PI, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(in-package :cl-prevalence)
;; the code for #'s-xml::echo-xml is in "echo.lisp" in S-XML's test code
(defun print-transaction-log (system)
"Echo the XML making up the transaction log of system to t"
(with-open-file (in (get-transaction-log system) :direction :input)
(loop
(let ((transaction (s-xml::echo-xml in *standard-output*)))
(when (null transaction) (return)))))
t)
(defun show-transaction-log (system)
"Print the transaction objects making up the transaction log of system to t"
(with-open-file (in (get-transaction-log system) :direction :input)
(loop
(let ((transaction (deserialize-xml in (get-serialization-state system))))
(if (null transaction)
(return)
(format t "~a~%" transaction)))))
t)
(defun print-snapshot (system)
"Echo the XML making up the snapshot of system to t"
(with-open-file (in (get-snapshot system) :direction :input)
(s-xml::echo-xml in *standard-output*))
t)
(defun transaction-log-tail (system &optional (count 8))
"Return a list of the count last transaction objects of system"
(let (transactions)
(with-open-file (in (get-transaction-log system) :direction :input)
(loop
(let ((transaction (deserialize-xml in (get-serialization-state system))))
(if (null transaction)
(return)
(push transaction transactions)))))
(setf transactions (nreverse transactions))
(nthcdr (max 0 (- (length transactions) count)) transactions)))
;;;; eof
|
[
{
"context": "CL\")\n\n(asdf:defsystem :sample-profiler\n :author \"Gail Zacharias <[email protected]>\"\n :license \"Apache2\"\n :descrip",
"end": 139,
"score": 0.999877393245697,
"start": 125,
"tag": "NAME",
"value": "Gail Zacharias"
},
{
"context": "ystem :sample-profiler\n :author \"Gail Zacharias <[email protected]>\"\n :license \"Apache2\"\n :description \"Collect an",
"end": 155,
"score": 0.9999322891235352,
"start": 141,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
sample-profiler.asd
|
Clozure/sample-profiler
| 2 |
;; Copyright (c) 2016 Clozure Associates LLC
#-CCL (error "Only works in CCL")
(asdf:defsystem :sample-profiler
:author "Gail Zacharias <[email protected]>"
:license "Apache2"
:description "Collect and display sample profilling data"
:version "0.0.1"
:serial t
:components ((:file "package")
(:file "profile")))
|
66041
|
;; Copyright (c) 2016 Clozure Associates LLC
#-CCL (error "Only works in CCL")
(asdf:defsystem :sample-profiler
:author "<NAME> <<EMAIL>>"
:license "Apache2"
:description "Collect and display sample profilling data"
:version "0.0.1"
:serial t
:components ((:file "package")
(:file "profile")))
| true |
;; Copyright (c) 2016 Clozure Associates LLC
#-CCL (error "Only works in CCL")
(asdf:defsystem :sample-profiler
:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:license "Apache2"
:description "Collect and display sample profilling data"
:version "0.0.1"
:serial t
:components ((:file "package")
(:file "profile")))
|
[
{
"context": "-plus/src/srfi/srfi-41.lisp\n\n;; Copyright (c) 2014 Takaya OCHIAI <[email protected]>\n;; This software is releas",
"end": 71,
"score": 0.9998814463615417,
"start": 58,
"tag": "NAME",
"value": "Takaya OCHIAI"
},
{
"context": "rfi-41.lisp\n\n;; Copyright (c) 2014 Takaya OCHIAI <[email protected]>\n;; This software is released under the MIT Licen",
"end": 93,
"score": 0.9999306201934814,
"start": 73,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "---------------------------------\n;; Copyright (C) Philip L. Bewig (2007). All Rights Reserved.\n;;\n;; Permission is ",
"end": 293,
"score": 0.9998745918273926,
"start": 278,
"tag": "NAME",
"value": "Philip L. Bewig"
},
{
"context": ")\n\n ; => (3 4 6 12)\n\n\nReferences\n----------\n\n [0] Philip L. Bewig (2007),\n Scheme Request for Implementation 41",
"end": 4079,
"score": 0.9998926520347595,
"start": 4064,
"tag": "NAME",
"value": "Philip L. Bewig"
},
{
"context": "reams.\n http://srfi.schemers.org/srfi-41\n\n [1] Philip L. Bewig (2004),\n Scheme Request for Implementation 40",
"end": 4199,
"score": 0.9998915791511536,
"start": 4184,
"tag": "NAME",
"value": "Philip L. Bewig"
},
{
"context": "i-40\n (srfi-40 is deprecated by srfi-41)\n\n [2] Philip Wadler, Walid Taha and David MacQueen (1998),\n How t",
"end": 4370,
"score": 0.9998884201049805,
"start": 4357,
"tag": "NAME",
"value": "Philip Wadler"
},
{
"context": "-40 is deprecated by srfi-41)\n\n [2] Philip Wadler, Walid Taha and David MacQueen (1998),\n How to add lazine",
"end": 4382,
"score": 0.999891459941864,
"start": 4372,
"tag": "NAME",
"value": "Walid Taha"
},
{
"context": "ed by srfi-41)\n\n [2] Philip Wadler, Walid Taha and David MacQueen (1998),\n How to add laziness to a strict lang",
"end": 4401,
"score": 0.9998825192451477,
"start": 4387,
"tag": "NAME",
"value": "David MacQueen"
},
{
"context": ".edu/~taha/publications/conference/sml98.pdf\n\n [3] Harold Abelson and Gerald Jay Sussman, with Julie Sussman (1996)",
"end": 4568,
"score": 0.999890148639679,
"start": 4554,
"tag": "NAME",
"value": "Harold Abelson"
},
{
"context": "ions/conference/sml98.pdf\n\n [3] Harold Abelson and Gerald Jay Sussman, with Julie Sussman (1996),\n Structure and In",
"end": 4591,
"score": 0.9998917579650879,
"start": 4573,
"tag": "NAME",
"value": "Gerald Jay Sussman"
},
{
"context": "\n\n [3] Harold Abelson and Gerald Jay Sussman, with Julie Sussman (1996),\n Structure and Interpretation of Comp",
"end": 4611,
"score": 0.9998180270195007,
"start": 4598,
"tag": "NAME",
"value": "Julie Sussman"
},
{
"context": "rograms -- 2nd ed,\n Section 3.5 Streams.\n\n [4] Peter Norvig (1992),\n Paradigms of Artificial Intelligence",
"end": 4730,
"score": 0.9996067881584167,
"start": 4718,
"tag": "NAME",
"value": "Peter Norvig"
},
{
"context": ".\n\n [5] g000001,\n srfi-41, https://github.com/g000001/srfi-41\n (scheme style common lisp translatio",
"end": 4917,
"score": 0.9223900437355042,
"start": 4910,
"tag": "USERNAME",
"value": "g000001"
}
] |
src/srfi/srfi-41.lisp
|
tkych/cl-plus
| 1 |
;;;; cl-plus/src/srfi/srfi-41.lisp
;; Copyright (c) 2014 Takaya OCHIAI <[email protected]>
;; This software is released under the MIT License.
;; See cl-plus/LICENSE, for more details.
;;--------------------------------------------------------------------
;; Copyright (C) Philip L. Bewig (2007). All Rights Reserved.
;;
;; 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.
;;--------------------------------------------------------------------
;; The following code is a Common Lisp translation from reference
;; implementation of SRFI-41.
;;====================================================================
;; SRFI-41 for Common Lisp
;;====================================================================
(in-package #:cl-user)
(defpackage #:cl-plus.src.srfi.srfi-41
(:documentation "
SRFI-41 for CL
==============
This is a Common Lisp implementation for \"Scheme Request for
Implementation 41\"[3] (a.k.a., SRFI-41). Roughly speaking, SRFI-41
is a document about streams (i.e., pipe) for Scheme. Since the name
\"stream\" is already used for I/O objects in Common Lisp, we have
introduced \"pipe\" in exchenge for \"stream\".
The pipes in this package are \"even\" style, whereas the pipes in
PAIP[5] (and the streams in SICP[4]) are \"odd\" style. The style
\"even\" and \"odd\" are the prity of the number of constructors
\{delay, cons, nil} in pipe construction. For instance (cf., [1]),
Odd: (cons 1 (delay (cons 2 (delay nil)))) --- 5 conctructors
Even: (delay (cons 1 (delay (cons 2 (delay nil))))) --- 6 conctructors
The practical differences between even and odd are:
1. odd is simple, even is rather complecated (the above example).
2. odd is too eager, even is properly eager (the following example from [2]).
Odd:
----
(ql:quickload :pipes)
(defun count-down1 (start)
(pipes:make-pipe start (count-down1 (1- start))))
(defun cut-off1 (n pipe)
(cond ((zerop n) '())
((null pipe) '())
(t (cons (pipes:pipe-head pipe)
(cut-off1 (1- n)
(pipes:pipe-tail pipe))))))
(handler-case
(cut-off1 4
(pipes:pipe-map (lambda (n) (/ 12 n))
(count-down1 4)))
(error (c) (type-of c)))
; => DIVISION-BY-ZERO
Even:
-----
(ql:quickload :cl-plus)
(use-package :cl+srfi-45)
(defun count-down2 (start)
(lazy
(delay (cons start (count-down2 (1- start))))))
(defun cut-off2 (n pipe)
(cond ((zerop n) '())
((null (force pipe)) '())
(t (cons (car (force pipe))
(cut-off2 (1- n)
(cdr (force pipe)))))))
(defun map2 (fn pipe)
(lazy
(if (null (force pipe))
(delay '())
(delay (cons (funcall fn (car (force pipe)))
(map2 fn (cdr (force pipe))))))))
(cut-off2 4
(map2 (lambda (n) (/ 12 n))
(count-down2 4)))
; => (3 4 6 12)
References
----------
[0] Philip L. Bewig (2007),
Scheme Request for Implementation 41: Streams.
http://srfi.schemers.org/srfi-41
[1] Philip L. Bewig (2004),
Scheme Request for Implementation 40: A Library of Streams.
http://srfi.schemers.org/srfi-40
(srfi-40 is deprecated by srfi-41)
[2] Philip Wadler, Walid Taha and David MacQueen (1998),
How to add laziness to a strict language without even being add.
http://www.cs.rice.edu/~taha/publications/conference/sml98.pdf
[3] Harold Abelson and Gerald Jay Sussman, with Julie Sussman (1996),
Structure and Interpretation of Computer Programs -- 2nd ed,
Section 3.5 Streams.
[4] Peter Norvig (1992),
Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp,
Section 9.3 Delaying Computation.
[5] g000001,
srfi-41, https://github.com/g000001/srfi-41
(scheme style common lisp translation)
")
(:nicknames #:cl+srfi-41)
(:export
;; PRIMITIVE ORIGINAL NAME
#:+empty-pipe+ ; stream-null
#:pipe-cons ; stream-cons
#:pipep ; stream?
#:pipe-null ; stream-null?
#:pipe-cons-p ; stream-pair?
#:pipe-car ; stream-car
#:pipe-cdr ; stream-cdr
#:pipe-lambda ; stream-lambda
;; DERIVED
#:define-pipe ; define-stream
#:list->pipe ; list->stream
#:stream->pipe ; port->stream
#:pipe ; stream
#:pipe->list ; stream->list
#:pipe-append ; stream-append
#:pipe-concat ; stream-concat
#:pipe-constant ; stream-constant
#:pipe-drop ; stream-drop
#:pipe-drop-while ; stream-drop-while
#:pipe-filter ; stream-filter
#:pipe-fold ; stream-fold
#:pipe-for-each ; stream-for-each
#:pipe-from ; stream-from
#:pipe-iterate ; stream-iterate
#:pipe-length ; stream-length
#:pipe-let ; stream-let
#:pipe-map ; stream-map
#:pipe-match ; stream-match
#:pipe-of ; stream-of
#:pipe-range ; stream-range
#:pipe-ref ; stream-ref
#:pipe-reverse ; stream-reverse
#:pipe-scan ; stream-scan
#:pipe-take ; stream-take
#:pipe-take-while ; stream-take-while
#:pipe-unfold ; stream-unfold
#:pipe-unfolds ; stream-unfolds
#:pipe-zip ; stream-zip
)
(:use #:cl)
(:import-from #:alexandria
#:with-gensyms
#:once-only
#:switch)
(:import-from #:cl-plus.src.dev-util
#:append1)
(:import-from #:cl-plus.src.srfi.srfi-45
#:promise
#:promisep
#:lazy
#:eager
#:delay
#:force))
(pushnew :srfi-41 *features*)
(in-package #:cl-plus.src.srfi.srfi-41)
;;--------------------------------------------------------------------
;; Primitive
;;--------------------------------------------------------------------
(defvar +empty-pipe+ (eager 'pipe-nil))
(deftype pipe () 'promise)
(declaim (inline pipep))
(defun pipep (x) (typep x 'promise))
(defun pipe-null (x)
(and (pipep x)
(eq (force x)
(force +empty-pipe+))))
(defstruct (kons (:conc-name nil)
(:constructor kons (kar kdr))
(:predicate konsp)
(:print-function
;; TODO:
;; (p1 . (p2 . (p3 . +empty-pipe+)))
;; -> (p1 p2 p3)
(lambda (self stream depth)
(declare (ignore depth))
(format stream "(~S . ~S)" (kar self) (kdr self)))))
"Immutable cons."
(kar nil :read-only t)
(kdr nil :read-only t))
(defmethod make-load-form ((k kons) &optional env)
(make-load-form-saving-slots k :slot-names '(kar kdr)
:environment env))
(defmacro pipe-cons (object pipe)
`(eager (kons (delay ,object) (lazy ,pipe))))
(defun pipe-cons-p (x)
(and (pipep x)
(konsp (force x))))
(defun pipe-car (pipe)
"STREAM-CAR in srfi-41."
(check-type pipe pipe)
(if (pipe-null pipe)
(error "~S is null pipe." pipe) ; ?! nil or +empty-pipe+
(force (kar (force pipe)))))
(defun pipe-cdr (pipe)
"STREAM-CDR in srfi-41."
(check-type pipe pipe)
(if (pipe-null pipe)
(error "~S is null pipe." pipe) ; ?! nil or +empty-pipe+
(kdr (force pipe))))
(defmacro pipe-lambda (lambda-list &body body)
"STREAM-LAMBDA in srfi-41."
`(lambda ,lambda-list (lazy (progn ,@body))))
;;--------------------------------------------------------------------
;; Derived
;;--------------------------------------------------------------------
(defmacro define-pipe (name lambda-list &body body)
"DEFINE-STREAM in srfi-41."
`(defun ,name ,lambda-list
(lazy (progn ,@body))))
(defun list->pipe (list)
"LIST->STREAM in srfi-41."
(check-type list list)
(labels ((%list->pipe (lst)
(lazy
(if (null lst)
+empty-pipe+
(pipe-cons (car lst)
(%list->pipe (cdr lst)))))))
(%list->pipe list)))
(defun stream->pipe (&optional (stream *standard-input*))
"PORT->STREAM in srfi-41."
(check-type stream (and stream (satisfies input-stream-p)))
(let ((eof (gensym "EOF-")))
(labels ((%stream->pipe ()
(lazy
(let ((char (read-char stream nil eof)))
(if (eq char eof)
+empty-pipe+
(pipe-cons char
(stream->pipe stream)))))))
(%stream->pipe))))
;; (defmacro %pipe (&rest args)
;; "STREAM in srfi-41."
;; (if (null args)
;; '+empty-pipe+
;; `(pipe-cons ,(car args) (%pipe ,@(cdr args)))))
;; (make-lazy-seq '() (%pipe 0 1 2)) => #[[?] ..]
;; (make-lazy-seq '() (pipe 0 1 2)) => #[..]
(defmacro pipe (&rest args)
"STREAM in srfi-41.
NB. result pipe is not eagered."
`(lazy
,(if (null args)
'+empty-pipe+
`(pipe-cons ,(car args) (pipe ,@(cdr args))))))
(defun pipe->list (pipe &optional count)
"PIPE->LIST pipe &optional count => list
STREAM->LIST in srfi-41.
Note:
-----
* The order of arguments is the reverse of stream->list."
(check-type pipe pipe)
(check-type count (or null (integer 0 *)))
(labels ((rec (count pipe)
(if (or (zerop count)
(pipe-null pipe))
'()
(cons (pipe-car pipe)
(rec (1- count) (pipe-cdr pipe))))))
(rec (if count count -1) pipe)))
(defun pipe-append (&rest pipes)
"STREAM-APPEND in srfi-41."
(labels ((%pipe-append (pipes)
(lazy
(cond ((null (cdr pipes)) (car pipes))
((pipe-null (car pipes))
(%pipe-append (cdr pipes)))
(t
(pipe-cons
(pipe-car (car pipes))
(%pipe-append (cons (pipe-cdr (car pipes))
(cdr pipes)))))))))
(cond ((null pipes) +empty-pipe+)
((some (complement #'pipep) pipes)
(error "There is at least one non-pipe object in arguments."))
(t (%pipe-append pipes)))))
(defun pipe-concat (pipe-of-pipes)
"STREAM-CONCAT in srfi-41."
(check-type pipe-of-pipes pipe)
(labels ((%pipe-concat (pipes)
(lazy
(cond ((pipe-null pipes) +empty-pipe+)
((not (pipep (pipe-car pipes)))
(error "non-pipe object in input ~S." pipe-of-pipes))
((pipe-null (pipe-car pipes))
(%pipe-concat (pipe-cdr pipes)))
(t (pipe-cons
(pipe-car (pipe-car pipes))
(%pipe-concat
(pipe-cons (pipe-cdr (pipe-car pipes))
(pipe-cdr pipes)))))))))
(%pipe-concat pipe-of-pipes)))
(defun pipe-constant (&rest objects)
"STREAM-CONSTANT in srfi-41."
(lazy
(cond ((null objects) +empty-pipe+)
((null (cdr objects))
(pipe-cons (car objects)
(pipe-constant (car objects))))
(t (pipe-cons (car objects)
(apply #'pipe-constant
(append1 (cdr objects)
(car objects))))))))
(defun pipe-drop (count pipe)
"STREAM-DROP in srfi-41."
(check-type count (integer 0 *))
(check-type pipe pipe)
(labels ((%pipe-drop (count pipe)
(lazy
(if (or (zerop count)
(pipe-null pipe))
pipe
(%pipe-drop (1- count) (pipe-cdr pipe))))))
(%pipe-drop count pipe)))
(defun pipe-drop-while (predicate pipe)
"STREAM-DROP-WHILE in srfi-41."
(check-type predicate (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-drop-while (pipe)
(lazy
(if (and (pipe-cons-p pipe)
(funcall predicate (pipe-car pipe)))
(%pipe-drop-while (pipe-cdr pipe))
pipe))))
(%pipe-drop-while pipe)))
(defun pipe-filter (predicate pipe)
"STREAM-FILTER in srfi-41."
(check-type predicate (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-filter (pipe)
(lazy
(cond ((pipe-null pipe) +empty-pipe+)
((funcall predicate (pipe-car pipe))
(pipe-cons (pipe-car pipe)
(%pipe-filter (pipe-cdr pipe))))
(t (%pipe-filter (pipe-cdr pipe)))))))
(%pipe-filter pipe)))
(defun pipe-fold (function base pipe)
"STREAM-FOLD in srfi-41."
(check-type function (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-fold (base pipe)
(if (pipe-null pipe)
base
(%pipe-fold (funcall function base (pipe-car pipe))
(pipe-cdr pipe)))))
(%pipe-fold base pipe)))
(defun pipe-for-each (function pipe &rest more-pipes)
"STREAM-FOR-EACH in srfi-41."
(check-type function (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-for-each (pipes)
(when (notany #'pipe-null pipes)
(apply function (mapcar #'pipe-car pipes))
(%pipe-for-each (mapcar #'pipe-cdr pipes)))))
(if (some (complement #'pipep) more-pipes)
(error "There is at least one non-pipe object in MORE-PIPES.")
(%pipe-for-each (cons pipe more-pipes)))))
(defun pipe-from (start &optional (step 1))
"STREAM-FROM in srfi-41."
(check-type start number)
(check-type step number)
(labels ((%pipe-from (start)
(lazy
(pipe-cons start (%pipe-from (+ start step))))))
(%pipe-from start)))
(defun pipe-iterate (successor-fn seed)
"STREAM-ITERATE in srfi-41."
(check-type successor-fn (or symbol function))
(labels ((%pipe-iterate (curr)
(lazy
(pipe-cons curr
(%pipe-iterate (funcall successor-fn curr))))))
(%pipe-iterate seed)))
(defun pipe-length (pipe)
"STREAM-LENGTH in srfi-41."
(check-type pipe pipe)
(labels ((rec (len pipe)
(if (pipe-null pipe)
len
(rec (1+ len) (pipe-cdr pipe)))))
(rec 0 pipe)))
(defun pipe-map (function pipe &rest more-pipes)
"STREAM-MAP in srfi-41."
(check-type function (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-map (pipes)
(lazy
(if (some #'pipe-null pipes)
+empty-pipe+
(pipe-cons (apply function (mapcar #'pipe-car pipes))
(%pipe-map (mapcar #'pipe-cdr pipes)))))))
(if (some (complement #'pipep) more-pipes)
(error "There is at least one non-pipe object in MORE-PIPES.")
(%pipe-map (cons pipe more-pipes)))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun wildp (x)
(and (symbolp x)
(or (string= "_" (symbol-name x))
(eq x t)))))
(defmacro pipe-match-pattern (pipe pattern bindings &body body)
(if (null pattern)
`(and (pipe-null ,pipe)
(let ,bindings
,(when bindings
`(declare (ignorable ,@(mapcar #'car bindings))))
,@body))
(if (consp pattern)
(destructuring-bind (var . rest) pattern
(if (wildp var)
(once-only (pipe)
(with-gensyms (p)
`(and (pipe-cons-p ,pipe)
(let ((,p (pipe-cdr ,pipe)))
(declare (ignorable ,p))
(pipe-match-pattern ,p ,rest ,bindings ,@body)))))
(once-only (pipe)
(with-gensyms (p tmp)
`(and (pipe-cons-p ,pipe)
(let ((,tmp (pipe-car ,pipe))
(,p (pipe-cdr ,pipe)))
(declare (ignorable ,tmp ,p))
(pipe-match-pattern ,p ,rest
,(cons (list var tmp) bindings)
,@body)))))))
(if (wildp pattern)
`(let ,bindings
,(when bindings
`(declare (ignorable ,@(mapcar #'car bindings))))
,@body)
`(let ((,pattern ,pipe)
,@bindings)
,(when bindings
`(declare (ignorable ,@(mapcar #'car bindings))))
,@body)))))
(defmacro pipe-match-test (pipe (pattern &rest args))
(destructuring-bind (exp/fender . exp) args
(if exp
`(pipe-match-pattern ,pipe ,pattern () (and ,exp/fender (list ,@exp)))
`(pipe-match-pattern ,pipe ,pattern () (list ,exp/fender)))))
(defmacro pipe-match (pipe-form &body clauses)
"STREAM-MATCH in srfi-41."
(with-gensyms (pipe match-result pipe-match)
`(block ,pipe-match
(let ((,pipe ,pipe-form))
(check-type ,pipe pipe)
,@(mapcar (lambda (clause)
`(let ((,match-result (pipe-match-test ,pipe ,clause)))
(when ,match-result
(return-from ,pipe-match
(car ,match-result)))))
clauses)
(error "Pattern Failure.")))))
(defmacro pipe-let (tag bindings &body body)
"STREAM-LET in srfi-41."
`(labels ((,tag ,(mapcar #'car bindings)
(lazy (progn ,@body))))
(,tag ,@(mapcar #'cadr bindings))))
(defmacro pipe-of-aux (&rest args)
(case (length args)
(2 (destructuring-bind (expr base) args
`(pipe-cons ,expr ,base)))
(t (destructuring-bind (expr base x . rest) args
(case (length x)
(3 (destructuring-bind (var y pipe/expr) x
(switch ((string-upcase (symbol-name y)) :test #'string=)
("IN"
(with-gensyms (%loop pipe)
`(pipe-let ,%loop ((,pipe ,pipe/expr))
(if (pipe-null ,pipe)
,base
(let ((,var (pipe-car ,pipe)))
(pipe-of-aux ,expr (,%loop (pipe-cdr ,pipe)) ,@rest))))))
("IS"
`(let ((,var ,pipe/expr))
(pipe-of-aux ,expr ,base ,@rest)))
(t
`(if ,x (pipe-of-aux ,expr ,base ,@rest) ,base)))))
(t `(if ,x (pipe-of-aux ,expr ,base ,@rest) ,base)))))))
(defmacro pipe-of (expr &body clauses)
"STREAM-OF in srfi-41."
`(pipe-of-aux ,expr +empty-pipe+ ,@clauses))
(defun pipe-range (start end &optional (step 1))
"STREAM-RANGE in srfi-41."
(check-type start number)
(check-type end number)
(check-type step (or null number))
(let* ((delta (cond (step step)
((< start end) 1)
(t -1)))
(order (if (plusp delta) #'< #'>)))
(labels ((%pipe-range (start)
(lazy
(if (funcall order start end)
(pipe-cons start (%pipe-range (+ start delta)))
+empty-pipe+))))
(%pipe-range start))))
(defun pipe-ref (pipe index)
"STREAM-REF in srfi-41."
(check-type pipe pipe)
(check-type index (integer 0 *))
(labels ((%pipe-ref (pipe i)
(cond
((pipe-null pipe)
(error "Index ~S out of bounds for pipe ~S." index pipe))
((zerop i) (pipe-car pipe))
(t (%pipe-ref (pipe-cdr pipe) (1- i))))))
(%pipe-ref pipe index)))
(defun pipe-reverse (pipe)
"STREAM-REVERSE in srfi-41."
(check-type pipe pipe)
(labels ((%pipe-reverse (pipe rev)
(lazy
(if (pipe-null pipe)
rev
(%pipe-reverse (pipe-cdr pipe)
(pipe-cons (pipe-car pipe) rev))))))
(%pipe-reverse pipe +empty-pipe+)))
(defun pipe-scan (function base pipe)
"STREAM-SCAN in srfi-41."
(check-type function (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-scan (base pipe)
(lazy
(if (pipe-null pipe)
(pipe base)
(pipe-cons base
(%pipe-scan (funcall function
base (pipe-car pipe))
(pipe-cdr pipe)))))))
(%pipe-scan base pipe)))
(defun pipe-take (count pipe)
"STREAM-TAKE in srfi-41."
(check-type count (integer 0 *))
(check-type pipe pipe)
(labels ((%pipe-take (count pipe)
(lazy
(if (or (pipe-null pipe)
(zerop count))
+empty-pipe+
(pipe-cons (pipe-car pipe)
(%pipe-take (1- count)
(pipe-cdr pipe)))))))
(%pipe-take count pipe)))
(defun pipe-take-while (predicate pipe)
"STREAM-TAKE-WHILE in srfi-41."
(check-type predicate (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-take-while (pipe)
(lazy
(cond ((pipe-null pipe) +empty-pipe+)
((funcall predicate (pipe-car pipe))
(pipe-cons (pipe-car pipe)
(%pipe-take-while (pipe-cdr pipe))))
(t +empty-pipe+)))))
(%pipe-take-while pipe)))
(defun pipe-unfold (mapper predicate generator base)
"STREAM-UNFOLD in srfi-41."
(check-type mapper (or symbol function))
(check-type predicate (or symbol function))
(check-type generator (or symbol function))
(labels ((%pipe-unfold (base)
(lazy
(if (funcall predicate base)
(pipe-cons (funcall mapper base)
(%pipe-unfold (funcall generator base)))
+empty-pipe+))))
(%pipe-unfold base)))
(defun pipe-unfolds (generator seed)
"STREAM-UNFOLDS in srfi-41."
(check-type generator (or symbol function))
(labels ((len-values (seed)
(1- (length (multiple-value-list (funcall generator seed)))))
(unfold-result-pipe (seed)
(lazy
(destructuring-bind
(next . results) (multiple-value-list (funcall generator seed))
(pipe-cons results
(unfold-result-pipe next)))))
(result-pipe->output-pipe (result-pipe i)
(lazy
(let ((result (nth (1- i) (pipe-car result-pipe))))
(cond ((consp result)
(pipe-cons (car result)
(result-pipe->output-pipe (pipe-cdr result-pipe)
i)))
;; MEMO:
;; '() and nil are the same in CL.
((eq result :false)
(result-pipe->output-pipe (pipe-cdr result-pipe) i))
((null result)
+empty-pipe+)
(t (error "can't happen."))))))
(result-pipe->output-pipes (result-pipe)
(labels ((rec (i outputs)
(if (zerop i)
(apply #'values outputs)
(rec (1- i) (cons (result-pipe->output-pipe result-pipe i)
outputs)))))
(rec (len-values seed) '()))))
(result-pipe->output-pipes (unfold-result-pipe seed))))
(defun pipe-zip (pipe1 pipe2 &rest more-pipes)
"STREAM-ZIP in srfi-41."
(check-type pipe1 pipe)
(check-type pipe2 pipe)
(when (some (complement #'pipep) more-pipes)
(error "There is at least one non-pipe object in MORE-PIPES."))
(labels ((%pipe-zip (pipes)
(lazy
(if (some #'pipe-null pipes)
+empty-pipe+
(pipe-cons (mapcar #'pipe-car pipes)
(%pipe-zip (mapcar #'pipe-cdr pipes)))))))
(%pipe-zip (list* pipe1 pipe2 more-pipes))))
;;====================================================================
|
71260
|
;;;; cl-plus/src/srfi/srfi-41.lisp
;; Copyright (c) 2014 <NAME> <<EMAIL>>
;; This software is released under the MIT License.
;; See cl-plus/LICENSE, for more details.
;;--------------------------------------------------------------------
;; Copyright (C) <NAME> (2007). All Rights Reserved.
;;
;; 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.
;;--------------------------------------------------------------------
;; The following code is a Common Lisp translation from reference
;; implementation of SRFI-41.
;;====================================================================
;; SRFI-41 for Common Lisp
;;====================================================================
(in-package #:cl-user)
(defpackage #:cl-plus.src.srfi.srfi-41
(:documentation "
SRFI-41 for CL
==============
This is a Common Lisp implementation for \"Scheme Request for
Implementation 41\"[3] (a.k.a., SRFI-41). Roughly speaking, SRFI-41
is a document about streams (i.e., pipe) for Scheme. Since the name
\"stream\" is already used for I/O objects in Common Lisp, we have
introduced \"pipe\" in exchenge for \"stream\".
The pipes in this package are \"even\" style, whereas the pipes in
PAIP[5] (and the streams in SICP[4]) are \"odd\" style. The style
\"even\" and \"odd\" are the prity of the number of constructors
\{delay, cons, nil} in pipe construction. For instance (cf., [1]),
Odd: (cons 1 (delay (cons 2 (delay nil)))) --- 5 conctructors
Even: (delay (cons 1 (delay (cons 2 (delay nil))))) --- 6 conctructors
The practical differences between even and odd are:
1. odd is simple, even is rather complecated (the above example).
2. odd is too eager, even is properly eager (the following example from [2]).
Odd:
----
(ql:quickload :pipes)
(defun count-down1 (start)
(pipes:make-pipe start (count-down1 (1- start))))
(defun cut-off1 (n pipe)
(cond ((zerop n) '())
((null pipe) '())
(t (cons (pipes:pipe-head pipe)
(cut-off1 (1- n)
(pipes:pipe-tail pipe))))))
(handler-case
(cut-off1 4
(pipes:pipe-map (lambda (n) (/ 12 n))
(count-down1 4)))
(error (c) (type-of c)))
; => DIVISION-BY-ZERO
Even:
-----
(ql:quickload :cl-plus)
(use-package :cl+srfi-45)
(defun count-down2 (start)
(lazy
(delay (cons start (count-down2 (1- start))))))
(defun cut-off2 (n pipe)
(cond ((zerop n) '())
((null (force pipe)) '())
(t (cons (car (force pipe))
(cut-off2 (1- n)
(cdr (force pipe)))))))
(defun map2 (fn pipe)
(lazy
(if (null (force pipe))
(delay '())
(delay (cons (funcall fn (car (force pipe)))
(map2 fn (cdr (force pipe))))))))
(cut-off2 4
(map2 (lambda (n) (/ 12 n))
(count-down2 4)))
; => (3 4 6 12)
References
----------
[0] <NAME> (2007),
Scheme Request for Implementation 41: Streams.
http://srfi.schemers.org/srfi-41
[1] <NAME> (2004),
Scheme Request for Implementation 40: A Library of Streams.
http://srfi.schemers.org/srfi-40
(srfi-40 is deprecated by srfi-41)
[2] <NAME>, <NAME> and <NAME> (1998),
How to add laziness to a strict language without even being add.
http://www.cs.rice.edu/~taha/publications/conference/sml98.pdf
[3] <NAME> and <NAME>, with <NAME> (1996),
Structure and Interpretation of Computer Programs -- 2nd ed,
Section 3.5 Streams.
[4] <NAME> (1992),
Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp,
Section 9.3 Delaying Computation.
[5] g000001,
srfi-41, https://github.com/g000001/srfi-41
(scheme style common lisp translation)
")
(:nicknames #:cl+srfi-41)
(:export
;; PRIMITIVE ORIGINAL NAME
#:+empty-pipe+ ; stream-null
#:pipe-cons ; stream-cons
#:pipep ; stream?
#:pipe-null ; stream-null?
#:pipe-cons-p ; stream-pair?
#:pipe-car ; stream-car
#:pipe-cdr ; stream-cdr
#:pipe-lambda ; stream-lambda
;; DERIVED
#:define-pipe ; define-stream
#:list->pipe ; list->stream
#:stream->pipe ; port->stream
#:pipe ; stream
#:pipe->list ; stream->list
#:pipe-append ; stream-append
#:pipe-concat ; stream-concat
#:pipe-constant ; stream-constant
#:pipe-drop ; stream-drop
#:pipe-drop-while ; stream-drop-while
#:pipe-filter ; stream-filter
#:pipe-fold ; stream-fold
#:pipe-for-each ; stream-for-each
#:pipe-from ; stream-from
#:pipe-iterate ; stream-iterate
#:pipe-length ; stream-length
#:pipe-let ; stream-let
#:pipe-map ; stream-map
#:pipe-match ; stream-match
#:pipe-of ; stream-of
#:pipe-range ; stream-range
#:pipe-ref ; stream-ref
#:pipe-reverse ; stream-reverse
#:pipe-scan ; stream-scan
#:pipe-take ; stream-take
#:pipe-take-while ; stream-take-while
#:pipe-unfold ; stream-unfold
#:pipe-unfolds ; stream-unfolds
#:pipe-zip ; stream-zip
)
(:use #:cl)
(:import-from #:alexandria
#:with-gensyms
#:once-only
#:switch)
(:import-from #:cl-plus.src.dev-util
#:append1)
(:import-from #:cl-plus.src.srfi.srfi-45
#:promise
#:promisep
#:lazy
#:eager
#:delay
#:force))
(pushnew :srfi-41 *features*)
(in-package #:cl-plus.src.srfi.srfi-41)
;;--------------------------------------------------------------------
;; Primitive
;;--------------------------------------------------------------------
(defvar +empty-pipe+ (eager 'pipe-nil))
(deftype pipe () 'promise)
(declaim (inline pipep))
(defun pipep (x) (typep x 'promise))
(defun pipe-null (x)
(and (pipep x)
(eq (force x)
(force +empty-pipe+))))
(defstruct (kons (:conc-name nil)
(:constructor kons (kar kdr))
(:predicate konsp)
(:print-function
;; TODO:
;; (p1 . (p2 . (p3 . +empty-pipe+)))
;; -> (p1 p2 p3)
(lambda (self stream depth)
(declare (ignore depth))
(format stream "(~S . ~S)" (kar self) (kdr self)))))
"Immutable cons."
(kar nil :read-only t)
(kdr nil :read-only t))
(defmethod make-load-form ((k kons) &optional env)
(make-load-form-saving-slots k :slot-names '(kar kdr)
:environment env))
(defmacro pipe-cons (object pipe)
`(eager (kons (delay ,object) (lazy ,pipe))))
(defun pipe-cons-p (x)
(and (pipep x)
(konsp (force x))))
(defun pipe-car (pipe)
"STREAM-CAR in srfi-41."
(check-type pipe pipe)
(if (pipe-null pipe)
(error "~S is null pipe." pipe) ; ?! nil or +empty-pipe+
(force (kar (force pipe)))))
(defun pipe-cdr (pipe)
"STREAM-CDR in srfi-41."
(check-type pipe pipe)
(if (pipe-null pipe)
(error "~S is null pipe." pipe) ; ?! nil or +empty-pipe+
(kdr (force pipe))))
(defmacro pipe-lambda (lambda-list &body body)
"STREAM-LAMBDA in srfi-41."
`(lambda ,lambda-list (lazy (progn ,@body))))
;;--------------------------------------------------------------------
;; Derived
;;--------------------------------------------------------------------
(defmacro define-pipe (name lambda-list &body body)
"DEFINE-STREAM in srfi-41."
`(defun ,name ,lambda-list
(lazy (progn ,@body))))
(defun list->pipe (list)
"LIST->STREAM in srfi-41."
(check-type list list)
(labels ((%list->pipe (lst)
(lazy
(if (null lst)
+empty-pipe+
(pipe-cons (car lst)
(%list->pipe (cdr lst)))))))
(%list->pipe list)))
(defun stream->pipe (&optional (stream *standard-input*))
"PORT->STREAM in srfi-41."
(check-type stream (and stream (satisfies input-stream-p)))
(let ((eof (gensym "EOF-")))
(labels ((%stream->pipe ()
(lazy
(let ((char (read-char stream nil eof)))
(if (eq char eof)
+empty-pipe+
(pipe-cons char
(stream->pipe stream)))))))
(%stream->pipe))))
;; (defmacro %pipe (&rest args)
;; "STREAM in srfi-41."
;; (if (null args)
;; '+empty-pipe+
;; `(pipe-cons ,(car args) (%pipe ,@(cdr args)))))
;; (make-lazy-seq '() (%pipe 0 1 2)) => #[[?] ..]
;; (make-lazy-seq '() (pipe 0 1 2)) => #[..]
(defmacro pipe (&rest args)
"STREAM in srfi-41.
NB. result pipe is not eagered."
`(lazy
,(if (null args)
'+empty-pipe+
`(pipe-cons ,(car args) (pipe ,@(cdr args))))))
(defun pipe->list (pipe &optional count)
"PIPE->LIST pipe &optional count => list
STREAM->LIST in srfi-41.
Note:
-----
* The order of arguments is the reverse of stream->list."
(check-type pipe pipe)
(check-type count (or null (integer 0 *)))
(labels ((rec (count pipe)
(if (or (zerop count)
(pipe-null pipe))
'()
(cons (pipe-car pipe)
(rec (1- count) (pipe-cdr pipe))))))
(rec (if count count -1) pipe)))
(defun pipe-append (&rest pipes)
"STREAM-APPEND in srfi-41."
(labels ((%pipe-append (pipes)
(lazy
(cond ((null (cdr pipes)) (car pipes))
((pipe-null (car pipes))
(%pipe-append (cdr pipes)))
(t
(pipe-cons
(pipe-car (car pipes))
(%pipe-append (cons (pipe-cdr (car pipes))
(cdr pipes)))))))))
(cond ((null pipes) +empty-pipe+)
((some (complement #'pipep) pipes)
(error "There is at least one non-pipe object in arguments."))
(t (%pipe-append pipes)))))
(defun pipe-concat (pipe-of-pipes)
"STREAM-CONCAT in srfi-41."
(check-type pipe-of-pipes pipe)
(labels ((%pipe-concat (pipes)
(lazy
(cond ((pipe-null pipes) +empty-pipe+)
((not (pipep (pipe-car pipes)))
(error "non-pipe object in input ~S." pipe-of-pipes))
((pipe-null (pipe-car pipes))
(%pipe-concat (pipe-cdr pipes)))
(t (pipe-cons
(pipe-car (pipe-car pipes))
(%pipe-concat
(pipe-cons (pipe-cdr (pipe-car pipes))
(pipe-cdr pipes)))))))))
(%pipe-concat pipe-of-pipes)))
(defun pipe-constant (&rest objects)
"STREAM-CONSTANT in srfi-41."
(lazy
(cond ((null objects) +empty-pipe+)
((null (cdr objects))
(pipe-cons (car objects)
(pipe-constant (car objects))))
(t (pipe-cons (car objects)
(apply #'pipe-constant
(append1 (cdr objects)
(car objects))))))))
(defun pipe-drop (count pipe)
"STREAM-DROP in srfi-41."
(check-type count (integer 0 *))
(check-type pipe pipe)
(labels ((%pipe-drop (count pipe)
(lazy
(if (or (zerop count)
(pipe-null pipe))
pipe
(%pipe-drop (1- count) (pipe-cdr pipe))))))
(%pipe-drop count pipe)))
(defun pipe-drop-while (predicate pipe)
"STREAM-DROP-WHILE in srfi-41."
(check-type predicate (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-drop-while (pipe)
(lazy
(if (and (pipe-cons-p pipe)
(funcall predicate (pipe-car pipe)))
(%pipe-drop-while (pipe-cdr pipe))
pipe))))
(%pipe-drop-while pipe)))
(defun pipe-filter (predicate pipe)
"STREAM-FILTER in srfi-41."
(check-type predicate (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-filter (pipe)
(lazy
(cond ((pipe-null pipe) +empty-pipe+)
((funcall predicate (pipe-car pipe))
(pipe-cons (pipe-car pipe)
(%pipe-filter (pipe-cdr pipe))))
(t (%pipe-filter (pipe-cdr pipe)))))))
(%pipe-filter pipe)))
(defun pipe-fold (function base pipe)
"STREAM-FOLD in srfi-41."
(check-type function (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-fold (base pipe)
(if (pipe-null pipe)
base
(%pipe-fold (funcall function base (pipe-car pipe))
(pipe-cdr pipe)))))
(%pipe-fold base pipe)))
(defun pipe-for-each (function pipe &rest more-pipes)
"STREAM-FOR-EACH in srfi-41."
(check-type function (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-for-each (pipes)
(when (notany #'pipe-null pipes)
(apply function (mapcar #'pipe-car pipes))
(%pipe-for-each (mapcar #'pipe-cdr pipes)))))
(if (some (complement #'pipep) more-pipes)
(error "There is at least one non-pipe object in MORE-PIPES.")
(%pipe-for-each (cons pipe more-pipes)))))
(defun pipe-from (start &optional (step 1))
"STREAM-FROM in srfi-41."
(check-type start number)
(check-type step number)
(labels ((%pipe-from (start)
(lazy
(pipe-cons start (%pipe-from (+ start step))))))
(%pipe-from start)))
(defun pipe-iterate (successor-fn seed)
"STREAM-ITERATE in srfi-41."
(check-type successor-fn (or symbol function))
(labels ((%pipe-iterate (curr)
(lazy
(pipe-cons curr
(%pipe-iterate (funcall successor-fn curr))))))
(%pipe-iterate seed)))
(defun pipe-length (pipe)
"STREAM-LENGTH in srfi-41."
(check-type pipe pipe)
(labels ((rec (len pipe)
(if (pipe-null pipe)
len
(rec (1+ len) (pipe-cdr pipe)))))
(rec 0 pipe)))
(defun pipe-map (function pipe &rest more-pipes)
"STREAM-MAP in srfi-41."
(check-type function (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-map (pipes)
(lazy
(if (some #'pipe-null pipes)
+empty-pipe+
(pipe-cons (apply function (mapcar #'pipe-car pipes))
(%pipe-map (mapcar #'pipe-cdr pipes)))))))
(if (some (complement #'pipep) more-pipes)
(error "There is at least one non-pipe object in MORE-PIPES.")
(%pipe-map (cons pipe more-pipes)))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun wildp (x)
(and (symbolp x)
(or (string= "_" (symbol-name x))
(eq x t)))))
(defmacro pipe-match-pattern (pipe pattern bindings &body body)
(if (null pattern)
`(and (pipe-null ,pipe)
(let ,bindings
,(when bindings
`(declare (ignorable ,@(mapcar #'car bindings))))
,@body))
(if (consp pattern)
(destructuring-bind (var . rest) pattern
(if (wildp var)
(once-only (pipe)
(with-gensyms (p)
`(and (pipe-cons-p ,pipe)
(let ((,p (pipe-cdr ,pipe)))
(declare (ignorable ,p))
(pipe-match-pattern ,p ,rest ,bindings ,@body)))))
(once-only (pipe)
(with-gensyms (p tmp)
`(and (pipe-cons-p ,pipe)
(let ((,tmp (pipe-car ,pipe))
(,p (pipe-cdr ,pipe)))
(declare (ignorable ,tmp ,p))
(pipe-match-pattern ,p ,rest
,(cons (list var tmp) bindings)
,@body)))))))
(if (wildp pattern)
`(let ,bindings
,(when bindings
`(declare (ignorable ,@(mapcar #'car bindings))))
,@body)
`(let ((,pattern ,pipe)
,@bindings)
,(when bindings
`(declare (ignorable ,@(mapcar #'car bindings))))
,@body)))))
(defmacro pipe-match-test (pipe (pattern &rest args))
(destructuring-bind (exp/fender . exp) args
(if exp
`(pipe-match-pattern ,pipe ,pattern () (and ,exp/fender (list ,@exp)))
`(pipe-match-pattern ,pipe ,pattern () (list ,exp/fender)))))
(defmacro pipe-match (pipe-form &body clauses)
"STREAM-MATCH in srfi-41."
(with-gensyms (pipe match-result pipe-match)
`(block ,pipe-match
(let ((,pipe ,pipe-form))
(check-type ,pipe pipe)
,@(mapcar (lambda (clause)
`(let ((,match-result (pipe-match-test ,pipe ,clause)))
(when ,match-result
(return-from ,pipe-match
(car ,match-result)))))
clauses)
(error "Pattern Failure.")))))
(defmacro pipe-let (tag bindings &body body)
"STREAM-LET in srfi-41."
`(labels ((,tag ,(mapcar #'car bindings)
(lazy (progn ,@body))))
(,tag ,@(mapcar #'cadr bindings))))
(defmacro pipe-of-aux (&rest args)
(case (length args)
(2 (destructuring-bind (expr base) args
`(pipe-cons ,expr ,base)))
(t (destructuring-bind (expr base x . rest) args
(case (length x)
(3 (destructuring-bind (var y pipe/expr) x
(switch ((string-upcase (symbol-name y)) :test #'string=)
("IN"
(with-gensyms (%loop pipe)
`(pipe-let ,%loop ((,pipe ,pipe/expr))
(if (pipe-null ,pipe)
,base
(let ((,var (pipe-car ,pipe)))
(pipe-of-aux ,expr (,%loop (pipe-cdr ,pipe)) ,@rest))))))
("IS"
`(let ((,var ,pipe/expr))
(pipe-of-aux ,expr ,base ,@rest)))
(t
`(if ,x (pipe-of-aux ,expr ,base ,@rest) ,base)))))
(t `(if ,x (pipe-of-aux ,expr ,base ,@rest) ,base)))))))
(defmacro pipe-of (expr &body clauses)
"STREAM-OF in srfi-41."
`(pipe-of-aux ,expr +empty-pipe+ ,@clauses))
(defun pipe-range (start end &optional (step 1))
"STREAM-RANGE in srfi-41."
(check-type start number)
(check-type end number)
(check-type step (or null number))
(let* ((delta (cond (step step)
((< start end) 1)
(t -1)))
(order (if (plusp delta) #'< #'>)))
(labels ((%pipe-range (start)
(lazy
(if (funcall order start end)
(pipe-cons start (%pipe-range (+ start delta)))
+empty-pipe+))))
(%pipe-range start))))
(defun pipe-ref (pipe index)
"STREAM-REF in srfi-41."
(check-type pipe pipe)
(check-type index (integer 0 *))
(labels ((%pipe-ref (pipe i)
(cond
((pipe-null pipe)
(error "Index ~S out of bounds for pipe ~S." index pipe))
((zerop i) (pipe-car pipe))
(t (%pipe-ref (pipe-cdr pipe) (1- i))))))
(%pipe-ref pipe index)))
(defun pipe-reverse (pipe)
"STREAM-REVERSE in srfi-41."
(check-type pipe pipe)
(labels ((%pipe-reverse (pipe rev)
(lazy
(if (pipe-null pipe)
rev
(%pipe-reverse (pipe-cdr pipe)
(pipe-cons (pipe-car pipe) rev))))))
(%pipe-reverse pipe +empty-pipe+)))
(defun pipe-scan (function base pipe)
"STREAM-SCAN in srfi-41."
(check-type function (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-scan (base pipe)
(lazy
(if (pipe-null pipe)
(pipe base)
(pipe-cons base
(%pipe-scan (funcall function
base (pipe-car pipe))
(pipe-cdr pipe)))))))
(%pipe-scan base pipe)))
(defun pipe-take (count pipe)
"STREAM-TAKE in srfi-41."
(check-type count (integer 0 *))
(check-type pipe pipe)
(labels ((%pipe-take (count pipe)
(lazy
(if (or (pipe-null pipe)
(zerop count))
+empty-pipe+
(pipe-cons (pipe-car pipe)
(%pipe-take (1- count)
(pipe-cdr pipe)))))))
(%pipe-take count pipe)))
(defun pipe-take-while (predicate pipe)
"STREAM-TAKE-WHILE in srfi-41."
(check-type predicate (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-take-while (pipe)
(lazy
(cond ((pipe-null pipe) +empty-pipe+)
((funcall predicate (pipe-car pipe))
(pipe-cons (pipe-car pipe)
(%pipe-take-while (pipe-cdr pipe))))
(t +empty-pipe+)))))
(%pipe-take-while pipe)))
(defun pipe-unfold (mapper predicate generator base)
"STREAM-UNFOLD in srfi-41."
(check-type mapper (or symbol function))
(check-type predicate (or symbol function))
(check-type generator (or symbol function))
(labels ((%pipe-unfold (base)
(lazy
(if (funcall predicate base)
(pipe-cons (funcall mapper base)
(%pipe-unfold (funcall generator base)))
+empty-pipe+))))
(%pipe-unfold base)))
(defun pipe-unfolds (generator seed)
"STREAM-UNFOLDS in srfi-41."
(check-type generator (or symbol function))
(labels ((len-values (seed)
(1- (length (multiple-value-list (funcall generator seed)))))
(unfold-result-pipe (seed)
(lazy
(destructuring-bind
(next . results) (multiple-value-list (funcall generator seed))
(pipe-cons results
(unfold-result-pipe next)))))
(result-pipe->output-pipe (result-pipe i)
(lazy
(let ((result (nth (1- i) (pipe-car result-pipe))))
(cond ((consp result)
(pipe-cons (car result)
(result-pipe->output-pipe (pipe-cdr result-pipe)
i)))
;; MEMO:
;; '() and nil are the same in CL.
((eq result :false)
(result-pipe->output-pipe (pipe-cdr result-pipe) i))
((null result)
+empty-pipe+)
(t (error "can't happen."))))))
(result-pipe->output-pipes (result-pipe)
(labels ((rec (i outputs)
(if (zerop i)
(apply #'values outputs)
(rec (1- i) (cons (result-pipe->output-pipe result-pipe i)
outputs)))))
(rec (len-values seed) '()))))
(result-pipe->output-pipes (unfold-result-pipe seed))))
(defun pipe-zip (pipe1 pipe2 &rest more-pipes)
"STREAM-ZIP in srfi-41."
(check-type pipe1 pipe)
(check-type pipe2 pipe)
(when (some (complement #'pipep) more-pipes)
(error "There is at least one non-pipe object in MORE-PIPES."))
(labels ((%pipe-zip (pipes)
(lazy
(if (some #'pipe-null pipes)
+empty-pipe+
(pipe-cons (mapcar #'pipe-car pipes)
(%pipe-zip (mapcar #'pipe-cdr pipes)))))))
(%pipe-zip (list* pipe1 pipe2 more-pipes))))
;;====================================================================
| true |
;;;; cl-plus/src/srfi/srfi-41.lisp
;; Copyright (c) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; This software is released under the MIT License.
;; See cl-plus/LICENSE, for more details.
;;--------------------------------------------------------------------
;; Copyright (C) PI:NAME:<NAME>END_PI (2007). All Rights Reserved.
;;
;; 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.
;;--------------------------------------------------------------------
;; The following code is a Common Lisp translation from reference
;; implementation of SRFI-41.
;;====================================================================
;; SRFI-41 for Common Lisp
;;====================================================================
(in-package #:cl-user)
(defpackage #:cl-plus.src.srfi.srfi-41
(:documentation "
SRFI-41 for CL
==============
This is a Common Lisp implementation for \"Scheme Request for
Implementation 41\"[3] (a.k.a., SRFI-41). Roughly speaking, SRFI-41
is a document about streams (i.e., pipe) for Scheme. Since the name
\"stream\" is already used for I/O objects in Common Lisp, we have
introduced \"pipe\" in exchenge for \"stream\".
The pipes in this package are \"even\" style, whereas the pipes in
PAIP[5] (and the streams in SICP[4]) are \"odd\" style. The style
\"even\" and \"odd\" are the prity of the number of constructors
\{delay, cons, nil} in pipe construction. For instance (cf., [1]),
Odd: (cons 1 (delay (cons 2 (delay nil)))) --- 5 conctructors
Even: (delay (cons 1 (delay (cons 2 (delay nil))))) --- 6 conctructors
The practical differences between even and odd are:
1. odd is simple, even is rather complecated (the above example).
2. odd is too eager, even is properly eager (the following example from [2]).
Odd:
----
(ql:quickload :pipes)
(defun count-down1 (start)
(pipes:make-pipe start (count-down1 (1- start))))
(defun cut-off1 (n pipe)
(cond ((zerop n) '())
((null pipe) '())
(t (cons (pipes:pipe-head pipe)
(cut-off1 (1- n)
(pipes:pipe-tail pipe))))))
(handler-case
(cut-off1 4
(pipes:pipe-map (lambda (n) (/ 12 n))
(count-down1 4)))
(error (c) (type-of c)))
; => DIVISION-BY-ZERO
Even:
-----
(ql:quickload :cl-plus)
(use-package :cl+srfi-45)
(defun count-down2 (start)
(lazy
(delay (cons start (count-down2 (1- start))))))
(defun cut-off2 (n pipe)
(cond ((zerop n) '())
((null (force pipe)) '())
(t (cons (car (force pipe))
(cut-off2 (1- n)
(cdr (force pipe)))))))
(defun map2 (fn pipe)
(lazy
(if (null (force pipe))
(delay '())
(delay (cons (funcall fn (car (force pipe)))
(map2 fn (cdr (force pipe))))))))
(cut-off2 4
(map2 (lambda (n) (/ 12 n))
(count-down2 4)))
; => (3 4 6 12)
References
----------
[0] PI:NAME:<NAME>END_PI (2007),
Scheme Request for Implementation 41: Streams.
http://srfi.schemers.org/srfi-41
[1] PI:NAME:<NAME>END_PI (2004),
Scheme Request for Implementation 40: A Library of Streams.
http://srfi.schemers.org/srfi-40
(srfi-40 is deprecated by srfi-41)
[2] PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI (1998),
How to add laziness to a strict language without even being add.
http://www.cs.rice.edu/~taha/publications/conference/sml98.pdf
[3] PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI, with PI:NAME:<NAME>END_PI (1996),
Structure and Interpretation of Computer Programs -- 2nd ed,
Section 3.5 Streams.
[4] PI:NAME:<NAME>END_PI (1992),
Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp,
Section 9.3 Delaying Computation.
[5] g000001,
srfi-41, https://github.com/g000001/srfi-41
(scheme style common lisp translation)
")
(:nicknames #:cl+srfi-41)
(:export
;; PRIMITIVE ORIGINAL NAME
#:+empty-pipe+ ; stream-null
#:pipe-cons ; stream-cons
#:pipep ; stream?
#:pipe-null ; stream-null?
#:pipe-cons-p ; stream-pair?
#:pipe-car ; stream-car
#:pipe-cdr ; stream-cdr
#:pipe-lambda ; stream-lambda
;; DERIVED
#:define-pipe ; define-stream
#:list->pipe ; list->stream
#:stream->pipe ; port->stream
#:pipe ; stream
#:pipe->list ; stream->list
#:pipe-append ; stream-append
#:pipe-concat ; stream-concat
#:pipe-constant ; stream-constant
#:pipe-drop ; stream-drop
#:pipe-drop-while ; stream-drop-while
#:pipe-filter ; stream-filter
#:pipe-fold ; stream-fold
#:pipe-for-each ; stream-for-each
#:pipe-from ; stream-from
#:pipe-iterate ; stream-iterate
#:pipe-length ; stream-length
#:pipe-let ; stream-let
#:pipe-map ; stream-map
#:pipe-match ; stream-match
#:pipe-of ; stream-of
#:pipe-range ; stream-range
#:pipe-ref ; stream-ref
#:pipe-reverse ; stream-reverse
#:pipe-scan ; stream-scan
#:pipe-take ; stream-take
#:pipe-take-while ; stream-take-while
#:pipe-unfold ; stream-unfold
#:pipe-unfolds ; stream-unfolds
#:pipe-zip ; stream-zip
)
(:use #:cl)
(:import-from #:alexandria
#:with-gensyms
#:once-only
#:switch)
(:import-from #:cl-plus.src.dev-util
#:append1)
(:import-from #:cl-plus.src.srfi.srfi-45
#:promise
#:promisep
#:lazy
#:eager
#:delay
#:force))
(pushnew :srfi-41 *features*)
(in-package #:cl-plus.src.srfi.srfi-41)
;;--------------------------------------------------------------------
;; Primitive
;;--------------------------------------------------------------------
(defvar +empty-pipe+ (eager 'pipe-nil))
(deftype pipe () 'promise)
(declaim (inline pipep))
(defun pipep (x) (typep x 'promise))
(defun pipe-null (x)
(and (pipep x)
(eq (force x)
(force +empty-pipe+))))
(defstruct (kons (:conc-name nil)
(:constructor kons (kar kdr))
(:predicate konsp)
(:print-function
;; TODO:
;; (p1 . (p2 . (p3 . +empty-pipe+)))
;; -> (p1 p2 p3)
(lambda (self stream depth)
(declare (ignore depth))
(format stream "(~S . ~S)" (kar self) (kdr self)))))
"Immutable cons."
(kar nil :read-only t)
(kdr nil :read-only t))
(defmethod make-load-form ((k kons) &optional env)
(make-load-form-saving-slots k :slot-names '(kar kdr)
:environment env))
(defmacro pipe-cons (object pipe)
`(eager (kons (delay ,object) (lazy ,pipe))))
(defun pipe-cons-p (x)
(and (pipep x)
(konsp (force x))))
(defun pipe-car (pipe)
"STREAM-CAR in srfi-41."
(check-type pipe pipe)
(if (pipe-null pipe)
(error "~S is null pipe." pipe) ; ?! nil or +empty-pipe+
(force (kar (force pipe)))))
(defun pipe-cdr (pipe)
"STREAM-CDR in srfi-41."
(check-type pipe pipe)
(if (pipe-null pipe)
(error "~S is null pipe." pipe) ; ?! nil or +empty-pipe+
(kdr (force pipe))))
(defmacro pipe-lambda (lambda-list &body body)
"STREAM-LAMBDA in srfi-41."
`(lambda ,lambda-list (lazy (progn ,@body))))
;;--------------------------------------------------------------------
;; Derived
;;--------------------------------------------------------------------
(defmacro define-pipe (name lambda-list &body body)
"DEFINE-STREAM in srfi-41."
`(defun ,name ,lambda-list
(lazy (progn ,@body))))
(defun list->pipe (list)
"LIST->STREAM in srfi-41."
(check-type list list)
(labels ((%list->pipe (lst)
(lazy
(if (null lst)
+empty-pipe+
(pipe-cons (car lst)
(%list->pipe (cdr lst)))))))
(%list->pipe list)))
(defun stream->pipe (&optional (stream *standard-input*))
"PORT->STREAM in srfi-41."
(check-type stream (and stream (satisfies input-stream-p)))
(let ((eof (gensym "EOF-")))
(labels ((%stream->pipe ()
(lazy
(let ((char (read-char stream nil eof)))
(if (eq char eof)
+empty-pipe+
(pipe-cons char
(stream->pipe stream)))))))
(%stream->pipe))))
;; (defmacro %pipe (&rest args)
;; "STREAM in srfi-41."
;; (if (null args)
;; '+empty-pipe+
;; `(pipe-cons ,(car args) (%pipe ,@(cdr args)))))
;; (make-lazy-seq '() (%pipe 0 1 2)) => #[[?] ..]
;; (make-lazy-seq '() (pipe 0 1 2)) => #[..]
(defmacro pipe (&rest args)
"STREAM in srfi-41.
NB. result pipe is not eagered."
`(lazy
,(if (null args)
'+empty-pipe+
`(pipe-cons ,(car args) (pipe ,@(cdr args))))))
(defun pipe->list (pipe &optional count)
"PIPE->LIST pipe &optional count => list
STREAM->LIST in srfi-41.
Note:
-----
* The order of arguments is the reverse of stream->list."
(check-type pipe pipe)
(check-type count (or null (integer 0 *)))
(labels ((rec (count pipe)
(if (or (zerop count)
(pipe-null pipe))
'()
(cons (pipe-car pipe)
(rec (1- count) (pipe-cdr pipe))))))
(rec (if count count -1) pipe)))
(defun pipe-append (&rest pipes)
"STREAM-APPEND in srfi-41."
(labels ((%pipe-append (pipes)
(lazy
(cond ((null (cdr pipes)) (car pipes))
((pipe-null (car pipes))
(%pipe-append (cdr pipes)))
(t
(pipe-cons
(pipe-car (car pipes))
(%pipe-append (cons (pipe-cdr (car pipes))
(cdr pipes)))))))))
(cond ((null pipes) +empty-pipe+)
((some (complement #'pipep) pipes)
(error "There is at least one non-pipe object in arguments."))
(t (%pipe-append pipes)))))
(defun pipe-concat (pipe-of-pipes)
"STREAM-CONCAT in srfi-41."
(check-type pipe-of-pipes pipe)
(labels ((%pipe-concat (pipes)
(lazy
(cond ((pipe-null pipes) +empty-pipe+)
((not (pipep (pipe-car pipes)))
(error "non-pipe object in input ~S." pipe-of-pipes))
((pipe-null (pipe-car pipes))
(%pipe-concat (pipe-cdr pipes)))
(t (pipe-cons
(pipe-car (pipe-car pipes))
(%pipe-concat
(pipe-cons (pipe-cdr (pipe-car pipes))
(pipe-cdr pipes)))))))))
(%pipe-concat pipe-of-pipes)))
(defun pipe-constant (&rest objects)
"STREAM-CONSTANT in srfi-41."
(lazy
(cond ((null objects) +empty-pipe+)
((null (cdr objects))
(pipe-cons (car objects)
(pipe-constant (car objects))))
(t (pipe-cons (car objects)
(apply #'pipe-constant
(append1 (cdr objects)
(car objects))))))))
(defun pipe-drop (count pipe)
"STREAM-DROP in srfi-41."
(check-type count (integer 0 *))
(check-type pipe pipe)
(labels ((%pipe-drop (count pipe)
(lazy
(if (or (zerop count)
(pipe-null pipe))
pipe
(%pipe-drop (1- count) (pipe-cdr pipe))))))
(%pipe-drop count pipe)))
(defun pipe-drop-while (predicate pipe)
"STREAM-DROP-WHILE in srfi-41."
(check-type predicate (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-drop-while (pipe)
(lazy
(if (and (pipe-cons-p pipe)
(funcall predicate (pipe-car pipe)))
(%pipe-drop-while (pipe-cdr pipe))
pipe))))
(%pipe-drop-while pipe)))
(defun pipe-filter (predicate pipe)
"STREAM-FILTER in srfi-41."
(check-type predicate (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-filter (pipe)
(lazy
(cond ((pipe-null pipe) +empty-pipe+)
((funcall predicate (pipe-car pipe))
(pipe-cons (pipe-car pipe)
(%pipe-filter (pipe-cdr pipe))))
(t (%pipe-filter (pipe-cdr pipe)))))))
(%pipe-filter pipe)))
(defun pipe-fold (function base pipe)
"STREAM-FOLD in srfi-41."
(check-type function (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-fold (base pipe)
(if (pipe-null pipe)
base
(%pipe-fold (funcall function base (pipe-car pipe))
(pipe-cdr pipe)))))
(%pipe-fold base pipe)))
(defun pipe-for-each (function pipe &rest more-pipes)
"STREAM-FOR-EACH in srfi-41."
(check-type function (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-for-each (pipes)
(when (notany #'pipe-null pipes)
(apply function (mapcar #'pipe-car pipes))
(%pipe-for-each (mapcar #'pipe-cdr pipes)))))
(if (some (complement #'pipep) more-pipes)
(error "There is at least one non-pipe object in MORE-PIPES.")
(%pipe-for-each (cons pipe more-pipes)))))
(defun pipe-from (start &optional (step 1))
"STREAM-FROM in srfi-41."
(check-type start number)
(check-type step number)
(labels ((%pipe-from (start)
(lazy
(pipe-cons start (%pipe-from (+ start step))))))
(%pipe-from start)))
(defun pipe-iterate (successor-fn seed)
"STREAM-ITERATE in srfi-41."
(check-type successor-fn (or symbol function))
(labels ((%pipe-iterate (curr)
(lazy
(pipe-cons curr
(%pipe-iterate (funcall successor-fn curr))))))
(%pipe-iterate seed)))
(defun pipe-length (pipe)
"STREAM-LENGTH in srfi-41."
(check-type pipe pipe)
(labels ((rec (len pipe)
(if (pipe-null pipe)
len
(rec (1+ len) (pipe-cdr pipe)))))
(rec 0 pipe)))
(defun pipe-map (function pipe &rest more-pipes)
"STREAM-MAP in srfi-41."
(check-type function (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-map (pipes)
(lazy
(if (some #'pipe-null pipes)
+empty-pipe+
(pipe-cons (apply function (mapcar #'pipe-car pipes))
(%pipe-map (mapcar #'pipe-cdr pipes)))))))
(if (some (complement #'pipep) more-pipes)
(error "There is at least one non-pipe object in MORE-PIPES.")
(%pipe-map (cons pipe more-pipes)))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun wildp (x)
(and (symbolp x)
(or (string= "_" (symbol-name x))
(eq x t)))))
(defmacro pipe-match-pattern (pipe pattern bindings &body body)
(if (null pattern)
`(and (pipe-null ,pipe)
(let ,bindings
,(when bindings
`(declare (ignorable ,@(mapcar #'car bindings))))
,@body))
(if (consp pattern)
(destructuring-bind (var . rest) pattern
(if (wildp var)
(once-only (pipe)
(with-gensyms (p)
`(and (pipe-cons-p ,pipe)
(let ((,p (pipe-cdr ,pipe)))
(declare (ignorable ,p))
(pipe-match-pattern ,p ,rest ,bindings ,@body)))))
(once-only (pipe)
(with-gensyms (p tmp)
`(and (pipe-cons-p ,pipe)
(let ((,tmp (pipe-car ,pipe))
(,p (pipe-cdr ,pipe)))
(declare (ignorable ,tmp ,p))
(pipe-match-pattern ,p ,rest
,(cons (list var tmp) bindings)
,@body)))))))
(if (wildp pattern)
`(let ,bindings
,(when bindings
`(declare (ignorable ,@(mapcar #'car bindings))))
,@body)
`(let ((,pattern ,pipe)
,@bindings)
,(when bindings
`(declare (ignorable ,@(mapcar #'car bindings))))
,@body)))))
(defmacro pipe-match-test (pipe (pattern &rest args))
(destructuring-bind (exp/fender . exp) args
(if exp
`(pipe-match-pattern ,pipe ,pattern () (and ,exp/fender (list ,@exp)))
`(pipe-match-pattern ,pipe ,pattern () (list ,exp/fender)))))
(defmacro pipe-match (pipe-form &body clauses)
"STREAM-MATCH in srfi-41."
(with-gensyms (pipe match-result pipe-match)
`(block ,pipe-match
(let ((,pipe ,pipe-form))
(check-type ,pipe pipe)
,@(mapcar (lambda (clause)
`(let ((,match-result (pipe-match-test ,pipe ,clause)))
(when ,match-result
(return-from ,pipe-match
(car ,match-result)))))
clauses)
(error "Pattern Failure.")))))
(defmacro pipe-let (tag bindings &body body)
"STREAM-LET in srfi-41."
`(labels ((,tag ,(mapcar #'car bindings)
(lazy (progn ,@body))))
(,tag ,@(mapcar #'cadr bindings))))
(defmacro pipe-of-aux (&rest args)
(case (length args)
(2 (destructuring-bind (expr base) args
`(pipe-cons ,expr ,base)))
(t (destructuring-bind (expr base x . rest) args
(case (length x)
(3 (destructuring-bind (var y pipe/expr) x
(switch ((string-upcase (symbol-name y)) :test #'string=)
("IN"
(with-gensyms (%loop pipe)
`(pipe-let ,%loop ((,pipe ,pipe/expr))
(if (pipe-null ,pipe)
,base
(let ((,var (pipe-car ,pipe)))
(pipe-of-aux ,expr (,%loop (pipe-cdr ,pipe)) ,@rest))))))
("IS"
`(let ((,var ,pipe/expr))
(pipe-of-aux ,expr ,base ,@rest)))
(t
`(if ,x (pipe-of-aux ,expr ,base ,@rest) ,base)))))
(t `(if ,x (pipe-of-aux ,expr ,base ,@rest) ,base)))))))
(defmacro pipe-of (expr &body clauses)
"STREAM-OF in srfi-41."
`(pipe-of-aux ,expr +empty-pipe+ ,@clauses))
(defun pipe-range (start end &optional (step 1))
"STREAM-RANGE in srfi-41."
(check-type start number)
(check-type end number)
(check-type step (or null number))
(let* ((delta (cond (step step)
((< start end) 1)
(t -1)))
(order (if (plusp delta) #'< #'>)))
(labels ((%pipe-range (start)
(lazy
(if (funcall order start end)
(pipe-cons start (%pipe-range (+ start delta)))
+empty-pipe+))))
(%pipe-range start))))
(defun pipe-ref (pipe index)
"STREAM-REF in srfi-41."
(check-type pipe pipe)
(check-type index (integer 0 *))
(labels ((%pipe-ref (pipe i)
(cond
((pipe-null pipe)
(error "Index ~S out of bounds for pipe ~S." index pipe))
((zerop i) (pipe-car pipe))
(t (%pipe-ref (pipe-cdr pipe) (1- i))))))
(%pipe-ref pipe index)))
(defun pipe-reverse (pipe)
"STREAM-REVERSE in srfi-41."
(check-type pipe pipe)
(labels ((%pipe-reverse (pipe rev)
(lazy
(if (pipe-null pipe)
rev
(%pipe-reverse (pipe-cdr pipe)
(pipe-cons (pipe-car pipe) rev))))))
(%pipe-reverse pipe +empty-pipe+)))
(defun pipe-scan (function base pipe)
"STREAM-SCAN in srfi-41."
(check-type function (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-scan (base pipe)
(lazy
(if (pipe-null pipe)
(pipe base)
(pipe-cons base
(%pipe-scan (funcall function
base (pipe-car pipe))
(pipe-cdr pipe)))))))
(%pipe-scan base pipe)))
(defun pipe-take (count pipe)
"STREAM-TAKE in srfi-41."
(check-type count (integer 0 *))
(check-type pipe pipe)
(labels ((%pipe-take (count pipe)
(lazy
(if (or (pipe-null pipe)
(zerop count))
+empty-pipe+
(pipe-cons (pipe-car pipe)
(%pipe-take (1- count)
(pipe-cdr pipe)))))))
(%pipe-take count pipe)))
(defun pipe-take-while (predicate pipe)
"STREAM-TAKE-WHILE in srfi-41."
(check-type predicate (or symbol function))
(check-type pipe pipe)
(labels ((%pipe-take-while (pipe)
(lazy
(cond ((pipe-null pipe) +empty-pipe+)
((funcall predicate (pipe-car pipe))
(pipe-cons (pipe-car pipe)
(%pipe-take-while (pipe-cdr pipe))))
(t +empty-pipe+)))))
(%pipe-take-while pipe)))
(defun pipe-unfold (mapper predicate generator base)
"STREAM-UNFOLD in srfi-41."
(check-type mapper (or symbol function))
(check-type predicate (or symbol function))
(check-type generator (or symbol function))
(labels ((%pipe-unfold (base)
(lazy
(if (funcall predicate base)
(pipe-cons (funcall mapper base)
(%pipe-unfold (funcall generator base)))
+empty-pipe+))))
(%pipe-unfold base)))
(defun pipe-unfolds (generator seed)
"STREAM-UNFOLDS in srfi-41."
(check-type generator (or symbol function))
(labels ((len-values (seed)
(1- (length (multiple-value-list (funcall generator seed)))))
(unfold-result-pipe (seed)
(lazy
(destructuring-bind
(next . results) (multiple-value-list (funcall generator seed))
(pipe-cons results
(unfold-result-pipe next)))))
(result-pipe->output-pipe (result-pipe i)
(lazy
(let ((result (nth (1- i) (pipe-car result-pipe))))
(cond ((consp result)
(pipe-cons (car result)
(result-pipe->output-pipe (pipe-cdr result-pipe)
i)))
;; MEMO:
;; '() and nil are the same in CL.
((eq result :false)
(result-pipe->output-pipe (pipe-cdr result-pipe) i))
((null result)
+empty-pipe+)
(t (error "can't happen."))))))
(result-pipe->output-pipes (result-pipe)
(labels ((rec (i outputs)
(if (zerop i)
(apply #'values outputs)
(rec (1- i) (cons (result-pipe->output-pipe result-pipe i)
outputs)))))
(rec (len-values seed) '()))))
(result-pipe->output-pipes (unfold-result-pipe seed))))
(defun pipe-zip (pipe1 pipe2 &rest more-pipes)
"STREAM-ZIP in srfi-41."
(check-type pipe1 pipe)
(check-type pipe2 pipe)
(when (some (complement #'pipep) more-pipes)
(error "There is at least one non-pipe object in MORE-PIPES."))
(labels ((%pipe-zip (pipes)
(lazy
(if (some #'pipe-null pipes)
+empty-pipe+
(pipe-cons (mapcar #'pipe-car pipes)
(%pipe-zip (mapcar #'pipe-cdr pipes)))))))
(%pipe-zip (list* pipe1 pipe2 more-pipes))))
;;====================================================================
|
[
{
"context": ")\n\t (fix x))))\n\n(defthm floor-mod-elim\n ;; [Jared] modified on 2014-07-29 to not forcibly assume ac",
"end": 3126,
"score": 0.7634080648422241,
"start": 3121,
"tag": "NAME",
"value": "Jared"
}
] |
books/arithmetic-2/floor-mod/floor-mod-helper.lisp
|
mayankmanj/acl2
| 305 |
; See the top-level arithmetic-2 LICENSE file for authorship,
; copyright, and license information.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; floor-mod.lisp
;;;
;;; This is a start at a book for reasoning about floor and mod.
;;; Most of what is here came from the IHS books and modified.
;;; I believe that I could do better with some meta-rules, but
;;; I need to do a little more tuning of ACL2's handling of
;;; meta-rules first.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;-----------------------------------------------------------------
;;
;; Definitions
;;
;;-----------------------------------------------------------------
(IN-PACKAGE "ACL2")
(local (include-book "../meta/top"))
(local (include-book "ihs/quotient-remainder-lemmas" :dir :system))
;(defmacro e/d (enable disable)
; `(union-theories ',enable (disable ,@disable)))
(local
(in-theory (disable (:executable-counterpart force))))
(defun fm-y-guard (y)
(cond ((atom y)
`((real/rationalp ,y)
(not (equal ,y 0))))
((endp (cdr y))
`((real/rationalp ,(car y))
(not (equal ,(car y) 0))))
(t
(list* `(real/rationalp ,(car y))
`(not (equal ,(car y) 0))
(fm-y-guard (cdr y))))))
(defun fm-x-guard (x)
(cond ((atom x)
`((real/rationalp ,x)))
((endp (cdr x))
`((real/rationalp ,(car x))))
(t
(cons `(real/rationalp ,(car x))
(fm-x-guard (cdr x))))))
(defmacro fm-guard (x y)
(cons 'and
(append (fm-x-guard x)
(fm-y-guard y))))
(local
(defthm niq-boundsxxx
(implies (and (integerp i)
(<= 0 i)
(integerp j)
(< 0 j))
(and (<= (nonnegative-integer-quotient i j)
(/ i j))
(< (+ (/ i j) -1)
(nonnegative-integer-quotient i j))))
:hints (("Subgoal *1/1''" :in-theory
(enable prefer-positive-exponents-gather-exponents)))
:rule-classes ((:linear
:trigger-terms ((nonnegative-integer-quotient i j))))))
;;-----------------------------------------------------------------
;;
;; Basic definitions and lemmatta
;;
;;-----------------------------------------------------------------
;;(defthm floor-integerpxxx
;; (integerp (floor x y)))
(defthm integerp-modxxx
(implies (and (integerp x)
(integerp y))
(integerp (mod x y)))
:rule-classes :type-prescription)
(defthm rationalp-modxxx
(implies (and (rationalp x)
(rationalp y))
(rationalp (mod x y)))
:rule-classes :type-prescription)
#+:non-standard-analysis
(defthm realp-modxxx
(implies (and (realp x)
(realp y))
(realp (mod x y)))
:rule-classes :type-prescription)
(defthm floor-completionxxx
(implies (or (not (acl2-numberp x))
(not (acl2-numberp y)))
(equal (floor x y)
0)))
(defthm floor-0xxx
(and (equal (floor x 0)
0)
(equal (floor 0 y)
0)))
(defthm mod-completionxxx
(and (implies (not (acl2-numberp x))
(equal (mod x y)
0))
(implies (not (acl2-numberp y))
(equal (mod x y)
(fix x)))))
(defthm mod-0xxx
(and (equal (mod 0 y)
0)
(equal (mod x 0)
(fix x))))
(defthm floor-mod-elim
;; [Jared] modified on 2014-07-29 to not forcibly assume acl2-numberp, to
;; avoid name clash with arithmetic-5.
(implies (acl2-numberp x)
(equal (+ (mod x y) (* y (floor x y))) x))
:hints (("Goal" :in-theory (disable floor)))
:rule-classes ((:rewrite)
(:elim)))
;;-----------------------------------------------------------------
;;
;; alternate, recursive, definitions.
;;
;;-----------------------------------------------------------------
(defun floor* (x y)
(declare (xargs :measure (abs (floor x y))))
(cond ((not (real/rationalp x))
t)
((not (real/rationalp y))
t)
((equal y 0)
t)
((< y 0)
(cond ((< 0 x)
(1- (floor* (+ x y) y)))
((< y x)
t)
(t
(1+ (floor* (- x y) y)))))
(t ;; (< 0 y)
(cond ((< x 0)
(1- (floor* (+ x y) y)))
((< x y)
t)
(t
(1+ (floor* (- x y) y)))))))
(defun mod* (x y)
(declare (xargs :measure (abs (floor x y))))
(cond ((not (real/rationalp x))
t)
((not (real/rationalp y))
t)
((equal y 0)
t)
((< y 0)
(cond ((< 0 x)
(mod* (+ x y) y))
((< y x)
t)
(t
(mod* (- x y) y))))
(t ;; (< 0 y)
(cond ((< x 0)
(mod* (+ x y) y))
((< x y)
t)
(t
(mod* (- x y) y))))))
(defthm ifloor-indxxx
t
:rule-classes ((:induction :pattern (floor x y)
:scheme (floor* x y))))
(defthm imod-indxxx
t
:rule-classes ((:induction :pattern (mod x y)
:scheme (mod* x y))))
;;-----------------------------------------------------------------
;;
;; Simple bounds.
;;
;;-----------------------------------------------------------------
(defthm floor-bounds-1xxx
(implies (fm-guard x y)
(and (< (+ (/ x y) -1)
(floor x y))
(<= (floor x y)
(/ x y))))
:rule-classes ((:generalize)
(:linear :trigger-terms ((floor x y)))
(:forward-chaining :trigger-terms ((floor x y)))))
(defthm floor-bounds-2xxx
(implies (and (fm-guard x y)
(integerp (/ x y)))
(equal (floor x y)
(/ x y)))
:rule-classes ((:generalize)
(:linear :trigger-terms ((floor x y)))
(:forward-chaining :trigger-terms ((floor x y)))))
(defthm floor-bounds-3xxx
(implies (and (fm-guard x y)
(not (integerp (/ x y))))
(< (floor x y)
(/ x y)))
:rule-classes ((:generalize)
(:linear :trigger-terms ((floor x y)))
(:forward-chaining :trigger-terms ((floor x y)))))
(in-theory (disable floor))
(defthm mod-bounds-1xxx
(implies (and (fm-guard x y)
(< 0 y))
(and (<= 0 (mod x y))
(< (mod x y) y)))
:rule-classes ((:generalize)
(:linear)
(:forward-chaining)))
(defthm mod-bounds-2xxx
(implies (and (fm-guard x y)
(< y 0))
(and (<= (mod x y) 0)
(< y (mod x y))))
:rule-classes ((:generalize)
(:linear)
(:forward-chaining)))
(defthm mod-bounds-3xxx
(implies (and (fm-guard x y)
(integerp (/ x y)))
(equal 0 (mod x y)))
:rule-classes ((:generalize)
(:linear)
(:forward-chaining)))
;;-----------------------------------------------------------------
;;
;; Type-prescription and linear rules.
;;
;;-----------------------------------------------------------------
(in-theory (disable floor mod))
(defthm floor-nonnegativexxx
(implies (and (fm-guard x y)
(if (< 0 y)
(<= 0 x)
(<= x 0)))
(<= 0 (floor x y)))
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:type-prescription)))
(defthm floor-nonpositivexxx
(implies (and (fm-guard x y)
(if (< 0 y)
(<= x 0)
(<= 0 x)))
(<= (floor x y) 0))
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:type-prescription)))
(defthm floor-positivexxx
(implies (and (fm-guard x y)
(if (< 0 y)
(<= y x)
(<= x y)))
(< 0 (floor x y)))
:hints (("Subgoal 4.1.2'" :in-theory
(enable prefer-positive-exponents-gather-exponents)))
:otf-flg t
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (< 0 (floor x y))
(if (< 0 y)
(<= y x)
(<= x y)))))))
(defthm floor-negativexxx
(implies (and (fm-guard x y)
(if (< 0 y)
(< x 0)
(< 0 x)))
(< (floor x y) 0))
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (< (floor x y) 0)
(if (< 0 y)
(< x 0)
(< 0 x)))))))
(defthm floor-=-x/yxxx
(implies (and (fm-guard x y)
(integerp (/ x y)))
(equal (floor x y) (/ x y)))
:rule-classes ((:rewrite)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (floor x y) (/ x y))
(integerp (/ x y)))))))
(defthm floor-zeroxxx
(implies (and (fm-guard x y)
(if (< 0 y)
(and (<= 0 x)
(< x y))
(and (<= x 0)
(< y x))))
(equal (floor x y) 0))
:rule-classes ((:rewrite :backchain-limit-lst 1)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (floor x y) 0)
(if (< 0 y)
(and (<= 0 x)
(< x y))
(and (<= x 0)
(< y x))))))))
(defthm floor-onexxx
(implies (and (fm-guard x y)
(if (< 0 y)
(and (<= y x)
(< x (* 2 y)))
(and (<= x y)
(< (* 2 y) x))))
(equal (floor x y) 1))
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (floor x y) 1)
(if (< 0 y)
(and (<= y x)
(< x (* 2 y)))
(and (<= x y)
(< (* 2 y) x))))))))
(defthm floor-minus-onexxx
(implies (and (fm-guard x y)
(if (< 0 y)
(and (< x 0)
(<= (- x) y))
(and (< 0 x)
(<= y (- x)))))
(equal (floor x y) -1))
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (floor x y) -1)
(if (< 0 y)
(and (< x 0)
(<= (- x) y))
(and (< 0 x)
(<= y (- x)))))))))
(defthm mod-nonnegativexxx
(implies (and (fm-guard x y)
(< 0 y))
(<= 0 (mod x y)))
:rule-classes ((:rewrite)
(:type-prescription)))
(defthm mod-nonpositivexxx
(implies (and (fm-guard x y)
(< y 0))
(<= (mod x y) 0))
:rule-classes ((:rewrite)
(:type-prescription)))
(defthm mod-positivexxx
(implies (and (fm-guard x y)
(< 0 y)
(not (integerp (/ x y))))
(< 0 (mod x y)))
:rule-classes ((:rewrite)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (< 0 (mod x y))
(and (< 0 y)
(not (integerp (/ x y)))))))))
(defthm mod-negativexxx
(implies (and (fm-guard x y)
(< y 0)
(not (integerp (/ x y))))
(< (mod x y) 0))
:rule-classes ((:rewrite)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (< (mod x y) 0)
(and (< y 0)
(not (integerp (/ x y)))))))))
(defthm mod-zeroxxx
(implies (and (fm-guard x y)
(integerp (/ x y)))
(equal (mod x y) 0))
:rule-classes ((:rewrite)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (mod x y) 0)
(integerp (/ x y)))))))
(defthm mod-x-y-=-xxxx
(implies (and (fm-guard x y)
(if (< 0 y)
(and (<= 0 x)
(< x y))
(and (<= x 0)
(< y x))))
(equal (mod x y) x))
:rule-classes ((:rewrite :backchain-limit-lst 1)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (mod x y) x)
(if (< 0 y)
(and (<= 0 x)
(< x y))
(and (<= x 0)
(< y x))))))))
(defthm mod-x-y-=-x-+-yxxx
(implies (and (fm-guard x y)
(if (< 0 y)
(and (< x 0)
(<= (- x) y))
(and (< 0 x)
(<= y (- x)))))
(equal (mod x y) (+ x y)))
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (mod x y) (+ x y))
(if (< 0 y)
(and (< x 0)
(<= (- x) y))
(and (< 0 x)
(<= y (- x)))))))))
(defthm mod-x-y-=-x---y ;;; xxxxxx
(implies (and (fm-guard x y)
(if (< 0 y)
(and (<= y x)
(< x (* 2 y)))
(and (<= x y)
(< (* 2 y) x))))
(equal (mod x y) (- x y)))
:hints (("Goal" :in-theory (enable mod))) ;;; New hint.
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (mod x y) (- x y))
(if (< 0 y)
(and (<= y x)
(< x (* 2 y)))
(and (<= x y)
(< (* 2 y) x))))))))
;;-----------------------------------------------------------------
;;
;; ???
;;
;;-----------------------------------------------------------------
(defthm justify-floor-recursionxxx
(and (implies (and (real/rationalp x)
(< 0 x)
(real/rationalp y)
(< 1 y))
(< (floor x y) x))
(implies (and (real/rationalp x)
(< x -1)
(real/rationalp y)
(<= 2 y))
(< x (floor x y)))))
;;-----------------------------------------------------------------
;;
;; Simple reductions
;;
;;-----------------------------------------------------------------
(defthm rewrite-floor-x*y-z-rightxxx
(implies (fm-guard x (y z))
(equal (floor (* x y) z)
(floor x (/ z y)))))
(in-theory (disable rewrite-floor-x*y-z-rightxxx))
(defthm rewrite-mod-x*y-z-rightxxx
(implies (fm-guard x (y z))
(equal (mod (* x y) z)
(* y (mod x (/ z y)))))
:hints (("Goal" :in-theory (enable mod))))
(in-theory (disable rewrite-mod-x*y-z-rightxxx))
(defthm floor-minusxxx
(implies (fm-guard x y)
(equal (floor (- x) y)
(if (integerp (* x (/ y)))
(- (floor x y))
(+ (- (floor x y)) -1)))))
(defthm floor-minus-2xxx
(implies (fm-guard x y)
(equal (floor x (- y))
(if (integerp (* x (/ y)))
(- (floor x y))
(+ (- (floor x y)) -1)))))
(defthm mod-minusxxx
(implies (fm-guard x y)
(equal (mod (- x) y)
(if (integerp (/ x y))
0
(- y (mod x y)))))
:hints (("Goal" :in-theory (enable mod))))
(defthm mod-minus-2xxx
(implies (fm-guard x y)
(equal (mod x (- y))
(if (integerp (/ x y))
0
(- (mod x y) y))))
:hints (("Goal" :in-theory (enable mod))))
; These next two theorems could easily loop.
(defthm floor-plusxxx
(implies (fm-guard (x y) z)
(equal (floor (+ x y) z)
(+ (floor (+ (mod x z) (mod y z)) z)
(+ (floor x z) (floor y z)))))
:hints (("Goal" :use ((:instance floor-+)))))
(in-theory (disable floor-plusxxx))
(defthm mod-plusxxx
(implies (fm-guard (x y) z)
(equal (mod (+ x y) z)
(mod (+ (mod x z) (mod y z)) z)))
:hints (("Goal" :in-theory (enable mod))))
(in-theory (disable mod-plusxxx))
(defthm rewrite-floor-modxxx
(implies (and (equal i (/ y z))
(integerp i)
(fm-guard x (y z)))
(equal (floor (mod x y) z)
(- (floor x z) (* i (floor x y))))))
(defthm rewrite-mod-modxxx
(implies (and (equal i (/ y z))
(integerp i)
(fm-guard x (y z)))
(equal (mod (mod x y) z)
(mod x z))))
;; :hints (("Goal" :in-theory (enable mod-+))))
(defthm mod-+-cancel-0xxx
(implies (and (fm-guard (x y) z))
(equal (equal (mod (+ x y) z) x)
(and (equal (mod y z) 0)
(equal (mod x z) x)))))
;; :hints (("Subgoal 7" :in-theory (enable mod-+))
;; ("Subgoal 6" :in-theory (enable mod-+))
;; ("Subgoal 5" :expand (mod (+ x y) z))))
(defthm floor-cancel-*xxx
(implies (and (fm-guard x y)
(integerp x))
(and (equal (floor (* x y) y)
x)
(equal (floor (* y x) y)
x))))
(defthm floor-cancel-*-2xxx
(implies (and (fm-guard x (y z))
(integerp z))
(equal (floor (* x z) (* y z))
(floor x y))))
(defthm mod-minusxxx
(implies (fm-guard x y)
(equal (mod (- x) y)
(if (integerp (/ x y))
0
(- y (mod x y)))))
:hints (("Goal" :in-theory (enable mod))))
(defthm simplify-mod-*xxx
(implies (fm-guard x (y z))
(equal (mod (* x y) (* y z))
(* y (mod x z))))
:hints (("Goal" :in-theory (enable mod))))
;;-----------------------------------------------------------------
;;
;; Cancellation
;;
;;-----------------------------------------------------------------
(defthm cancel-floor-+xxx
(implies (and (equal i (/ x z))
(integerp i)
(fm-guard (x y) z))
(and (equal (floor (+ x y) z)
(+ i (floor y z)))
(equal (floor (+ y x) z)
(+ i (floor y z))))))
(defthm cancel-floor-+-3xxx
(implies (and (equal i (/ w z))
(integerp i)
(fm-guard (w x y) z))
(equal (floor (+ x y w) z)
(+ i (floor (+ x y) z)))))
(defthm cancel-mod-+xxx
(implies (and (equal i (/ x z))
(integerp i)
(fm-guard (x y) z))
(and (equal (mod (+ x y) z)
(mod y z))
(equal (mod (+ y x) z)
(mod y z))))
:hints (("Goal" :in-theory (enable mod))))
(defthm cancel-mod-+-3xxx
(implies (and (equal i (/ w z))
(integerp i)
(fm-guard (w x y) z))
(equal (mod (+ x y w) z)
(mod (+ x y) z))))
(defthm rewrite-floor-modxxx
(implies (and (equal i (/ y z))
(integerp i)
(fm-guard x (y z)))
(equal (floor (mod x y) z)
(- (floor x z) (* i (floor x y))))))
(defthm rewrite-mod-modxxx
(implies (and (equal i (/ y z))
(integerp i)
(fm-guard x (y z)))
(equal (mod (mod x y) z)
(mod x z))))
(defthm simplify-mod-+-modxxx
(implies (and (equal i (/ y z))
(integerp i)
(fm-guard (w x) (y z)))
(and (equal (mod (+ w (mod x y)) z)
(mod (+ w x) z))
(equal (mod (+ (mod x y) w) z)
(mod (+ w x) z))
(equal (mod (+ w (- (mod x y))) z)
(mod (+ w (- x)) z))
(equal (mod (+ (mod x y) (- w)) z)
(mod (+ x (- w)) z)))))
(defthm mod-+-cancel-0xxx
(implies (and (fm-guard (x y) z))
(equal (equal (mod (+ x y) z) x)
(and (equal (mod y z) 0)
(equal (mod x z) x))))
:hints (("Subgoal 5" :expand (mod (+ x y) z))))
(defthm floor-floor-integerxxx
(implies (and (real/rationalp x)
(integerp i)
(integerp j)
(< 0 i)
(< 0 j))
(equal (floor (floor x i) j)
(floor x (* i j)))))
;;-----------------------------------------------------------------
;;
;; Simple reductions
;;
;;-----------------------------------------------------------------
(defthm mod-twoxxx
(implies (integerp x)
(or (equal (mod x 2) 0)
(equal (mod x 2) 1)))
:rule-classes ((:forward-chaining
:corollary
(implies (integerp x)
(and (<= 0 (mod x 2))
(< (mod x 2) 2)))
:trigger-terms ((mod x 2)))
(:generalize)))
|
64839
|
; See the top-level arithmetic-2 LICENSE file for authorship,
; copyright, and license information.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; floor-mod.lisp
;;;
;;; This is a start at a book for reasoning about floor and mod.
;;; Most of what is here came from the IHS books and modified.
;;; I believe that I could do better with some meta-rules, but
;;; I need to do a little more tuning of ACL2's handling of
;;; meta-rules first.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;-----------------------------------------------------------------
;;
;; Definitions
;;
;;-----------------------------------------------------------------
(IN-PACKAGE "ACL2")
(local (include-book "../meta/top"))
(local (include-book "ihs/quotient-remainder-lemmas" :dir :system))
;(defmacro e/d (enable disable)
; `(union-theories ',enable (disable ,@disable)))
(local
(in-theory (disable (:executable-counterpart force))))
(defun fm-y-guard (y)
(cond ((atom y)
`((real/rationalp ,y)
(not (equal ,y 0))))
((endp (cdr y))
`((real/rationalp ,(car y))
(not (equal ,(car y) 0))))
(t
(list* `(real/rationalp ,(car y))
`(not (equal ,(car y) 0))
(fm-y-guard (cdr y))))))
(defun fm-x-guard (x)
(cond ((atom x)
`((real/rationalp ,x)))
((endp (cdr x))
`((real/rationalp ,(car x))))
(t
(cons `(real/rationalp ,(car x))
(fm-x-guard (cdr x))))))
(defmacro fm-guard (x y)
(cons 'and
(append (fm-x-guard x)
(fm-y-guard y))))
(local
(defthm niq-boundsxxx
(implies (and (integerp i)
(<= 0 i)
(integerp j)
(< 0 j))
(and (<= (nonnegative-integer-quotient i j)
(/ i j))
(< (+ (/ i j) -1)
(nonnegative-integer-quotient i j))))
:hints (("Subgoal *1/1''" :in-theory
(enable prefer-positive-exponents-gather-exponents)))
:rule-classes ((:linear
:trigger-terms ((nonnegative-integer-quotient i j))))))
;;-----------------------------------------------------------------
;;
;; Basic definitions and lemmatta
;;
;;-----------------------------------------------------------------
;;(defthm floor-integerpxxx
;; (integerp (floor x y)))
(defthm integerp-modxxx
(implies (and (integerp x)
(integerp y))
(integerp (mod x y)))
:rule-classes :type-prescription)
(defthm rationalp-modxxx
(implies (and (rationalp x)
(rationalp y))
(rationalp (mod x y)))
:rule-classes :type-prescription)
#+:non-standard-analysis
(defthm realp-modxxx
(implies (and (realp x)
(realp y))
(realp (mod x y)))
:rule-classes :type-prescription)
(defthm floor-completionxxx
(implies (or (not (acl2-numberp x))
(not (acl2-numberp y)))
(equal (floor x y)
0)))
(defthm floor-0xxx
(and (equal (floor x 0)
0)
(equal (floor 0 y)
0)))
(defthm mod-completionxxx
(and (implies (not (acl2-numberp x))
(equal (mod x y)
0))
(implies (not (acl2-numberp y))
(equal (mod x y)
(fix x)))))
(defthm mod-0xxx
(and (equal (mod 0 y)
0)
(equal (mod x 0)
(fix x))))
(defthm floor-mod-elim
;; [<NAME>] modified on 2014-07-29 to not forcibly assume acl2-numberp, to
;; avoid name clash with arithmetic-5.
(implies (acl2-numberp x)
(equal (+ (mod x y) (* y (floor x y))) x))
:hints (("Goal" :in-theory (disable floor)))
:rule-classes ((:rewrite)
(:elim)))
;;-----------------------------------------------------------------
;;
;; alternate, recursive, definitions.
;;
;;-----------------------------------------------------------------
(defun floor* (x y)
(declare (xargs :measure (abs (floor x y))))
(cond ((not (real/rationalp x))
t)
((not (real/rationalp y))
t)
((equal y 0)
t)
((< y 0)
(cond ((< 0 x)
(1- (floor* (+ x y) y)))
((< y x)
t)
(t
(1+ (floor* (- x y) y)))))
(t ;; (< 0 y)
(cond ((< x 0)
(1- (floor* (+ x y) y)))
((< x y)
t)
(t
(1+ (floor* (- x y) y)))))))
(defun mod* (x y)
(declare (xargs :measure (abs (floor x y))))
(cond ((not (real/rationalp x))
t)
((not (real/rationalp y))
t)
((equal y 0)
t)
((< y 0)
(cond ((< 0 x)
(mod* (+ x y) y))
((< y x)
t)
(t
(mod* (- x y) y))))
(t ;; (< 0 y)
(cond ((< x 0)
(mod* (+ x y) y))
((< x y)
t)
(t
(mod* (- x y) y))))))
(defthm ifloor-indxxx
t
:rule-classes ((:induction :pattern (floor x y)
:scheme (floor* x y))))
(defthm imod-indxxx
t
:rule-classes ((:induction :pattern (mod x y)
:scheme (mod* x y))))
;;-----------------------------------------------------------------
;;
;; Simple bounds.
;;
;;-----------------------------------------------------------------
(defthm floor-bounds-1xxx
(implies (fm-guard x y)
(and (< (+ (/ x y) -1)
(floor x y))
(<= (floor x y)
(/ x y))))
:rule-classes ((:generalize)
(:linear :trigger-terms ((floor x y)))
(:forward-chaining :trigger-terms ((floor x y)))))
(defthm floor-bounds-2xxx
(implies (and (fm-guard x y)
(integerp (/ x y)))
(equal (floor x y)
(/ x y)))
:rule-classes ((:generalize)
(:linear :trigger-terms ((floor x y)))
(:forward-chaining :trigger-terms ((floor x y)))))
(defthm floor-bounds-3xxx
(implies (and (fm-guard x y)
(not (integerp (/ x y))))
(< (floor x y)
(/ x y)))
:rule-classes ((:generalize)
(:linear :trigger-terms ((floor x y)))
(:forward-chaining :trigger-terms ((floor x y)))))
(in-theory (disable floor))
(defthm mod-bounds-1xxx
(implies (and (fm-guard x y)
(< 0 y))
(and (<= 0 (mod x y))
(< (mod x y) y)))
:rule-classes ((:generalize)
(:linear)
(:forward-chaining)))
(defthm mod-bounds-2xxx
(implies (and (fm-guard x y)
(< y 0))
(and (<= (mod x y) 0)
(< y (mod x y))))
:rule-classes ((:generalize)
(:linear)
(:forward-chaining)))
(defthm mod-bounds-3xxx
(implies (and (fm-guard x y)
(integerp (/ x y)))
(equal 0 (mod x y)))
:rule-classes ((:generalize)
(:linear)
(:forward-chaining)))
;;-----------------------------------------------------------------
;;
;; Type-prescription and linear rules.
;;
;;-----------------------------------------------------------------
(in-theory (disable floor mod))
(defthm floor-nonnegativexxx
(implies (and (fm-guard x y)
(if (< 0 y)
(<= 0 x)
(<= x 0)))
(<= 0 (floor x y)))
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:type-prescription)))
(defthm floor-nonpositivexxx
(implies (and (fm-guard x y)
(if (< 0 y)
(<= x 0)
(<= 0 x)))
(<= (floor x y) 0))
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:type-prescription)))
(defthm floor-positivexxx
(implies (and (fm-guard x y)
(if (< 0 y)
(<= y x)
(<= x y)))
(< 0 (floor x y)))
:hints (("Subgoal 4.1.2'" :in-theory
(enable prefer-positive-exponents-gather-exponents)))
:otf-flg t
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (< 0 (floor x y))
(if (< 0 y)
(<= y x)
(<= x y)))))))
(defthm floor-negativexxx
(implies (and (fm-guard x y)
(if (< 0 y)
(< x 0)
(< 0 x)))
(< (floor x y) 0))
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (< (floor x y) 0)
(if (< 0 y)
(< x 0)
(< 0 x)))))))
(defthm floor-=-x/yxxx
(implies (and (fm-guard x y)
(integerp (/ x y)))
(equal (floor x y) (/ x y)))
:rule-classes ((:rewrite)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (floor x y) (/ x y))
(integerp (/ x y)))))))
(defthm floor-zeroxxx
(implies (and (fm-guard x y)
(if (< 0 y)
(and (<= 0 x)
(< x y))
(and (<= x 0)
(< y x))))
(equal (floor x y) 0))
:rule-classes ((:rewrite :backchain-limit-lst 1)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (floor x y) 0)
(if (< 0 y)
(and (<= 0 x)
(< x y))
(and (<= x 0)
(< y x))))))))
(defthm floor-onexxx
(implies (and (fm-guard x y)
(if (< 0 y)
(and (<= y x)
(< x (* 2 y)))
(and (<= x y)
(< (* 2 y) x))))
(equal (floor x y) 1))
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (floor x y) 1)
(if (< 0 y)
(and (<= y x)
(< x (* 2 y)))
(and (<= x y)
(< (* 2 y) x))))))))
(defthm floor-minus-onexxx
(implies (and (fm-guard x y)
(if (< 0 y)
(and (< x 0)
(<= (- x) y))
(and (< 0 x)
(<= y (- x)))))
(equal (floor x y) -1))
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (floor x y) -1)
(if (< 0 y)
(and (< x 0)
(<= (- x) y))
(and (< 0 x)
(<= y (- x)))))))))
(defthm mod-nonnegativexxx
(implies (and (fm-guard x y)
(< 0 y))
(<= 0 (mod x y)))
:rule-classes ((:rewrite)
(:type-prescription)))
(defthm mod-nonpositivexxx
(implies (and (fm-guard x y)
(< y 0))
(<= (mod x y) 0))
:rule-classes ((:rewrite)
(:type-prescription)))
(defthm mod-positivexxx
(implies (and (fm-guard x y)
(< 0 y)
(not (integerp (/ x y))))
(< 0 (mod x y)))
:rule-classes ((:rewrite)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (< 0 (mod x y))
(and (< 0 y)
(not (integerp (/ x y)))))))))
(defthm mod-negativexxx
(implies (and (fm-guard x y)
(< y 0)
(not (integerp (/ x y))))
(< (mod x y) 0))
:rule-classes ((:rewrite)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (< (mod x y) 0)
(and (< y 0)
(not (integerp (/ x y)))))))))
(defthm mod-zeroxxx
(implies (and (fm-guard x y)
(integerp (/ x y)))
(equal (mod x y) 0))
:rule-classes ((:rewrite)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (mod x y) 0)
(integerp (/ x y)))))))
(defthm mod-x-y-=-xxxx
(implies (and (fm-guard x y)
(if (< 0 y)
(and (<= 0 x)
(< x y))
(and (<= x 0)
(< y x))))
(equal (mod x y) x))
:rule-classes ((:rewrite :backchain-limit-lst 1)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (mod x y) x)
(if (< 0 y)
(and (<= 0 x)
(< x y))
(and (<= x 0)
(< y x))))))))
(defthm mod-x-y-=-x-+-yxxx
(implies (and (fm-guard x y)
(if (< 0 y)
(and (< x 0)
(<= (- x) y))
(and (< 0 x)
(<= y (- x)))))
(equal (mod x y) (+ x y)))
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (mod x y) (+ x y))
(if (< 0 y)
(and (< x 0)
(<= (- x) y))
(and (< 0 x)
(<= y (- x)))))))))
(defthm mod-x-y-=-x---y ;;; xxxxxx
(implies (and (fm-guard x y)
(if (< 0 y)
(and (<= y x)
(< x (* 2 y)))
(and (<= x y)
(< (* 2 y) x))))
(equal (mod x y) (- x y)))
:hints (("Goal" :in-theory (enable mod))) ;;; New hint.
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (mod x y) (- x y))
(if (< 0 y)
(and (<= y x)
(< x (* 2 y)))
(and (<= x y)
(< (* 2 y) x))))))))
;;-----------------------------------------------------------------
;;
;; ???
;;
;;-----------------------------------------------------------------
(defthm justify-floor-recursionxxx
(and (implies (and (real/rationalp x)
(< 0 x)
(real/rationalp y)
(< 1 y))
(< (floor x y) x))
(implies (and (real/rationalp x)
(< x -1)
(real/rationalp y)
(<= 2 y))
(< x (floor x y)))))
;;-----------------------------------------------------------------
;;
;; Simple reductions
;;
;;-----------------------------------------------------------------
(defthm rewrite-floor-x*y-z-rightxxx
(implies (fm-guard x (y z))
(equal (floor (* x y) z)
(floor x (/ z y)))))
(in-theory (disable rewrite-floor-x*y-z-rightxxx))
(defthm rewrite-mod-x*y-z-rightxxx
(implies (fm-guard x (y z))
(equal (mod (* x y) z)
(* y (mod x (/ z y)))))
:hints (("Goal" :in-theory (enable mod))))
(in-theory (disable rewrite-mod-x*y-z-rightxxx))
(defthm floor-minusxxx
(implies (fm-guard x y)
(equal (floor (- x) y)
(if (integerp (* x (/ y)))
(- (floor x y))
(+ (- (floor x y)) -1)))))
(defthm floor-minus-2xxx
(implies (fm-guard x y)
(equal (floor x (- y))
(if (integerp (* x (/ y)))
(- (floor x y))
(+ (- (floor x y)) -1)))))
(defthm mod-minusxxx
(implies (fm-guard x y)
(equal (mod (- x) y)
(if (integerp (/ x y))
0
(- y (mod x y)))))
:hints (("Goal" :in-theory (enable mod))))
(defthm mod-minus-2xxx
(implies (fm-guard x y)
(equal (mod x (- y))
(if (integerp (/ x y))
0
(- (mod x y) y))))
:hints (("Goal" :in-theory (enable mod))))
; These next two theorems could easily loop.
(defthm floor-plusxxx
(implies (fm-guard (x y) z)
(equal (floor (+ x y) z)
(+ (floor (+ (mod x z) (mod y z)) z)
(+ (floor x z) (floor y z)))))
:hints (("Goal" :use ((:instance floor-+)))))
(in-theory (disable floor-plusxxx))
(defthm mod-plusxxx
(implies (fm-guard (x y) z)
(equal (mod (+ x y) z)
(mod (+ (mod x z) (mod y z)) z)))
:hints (("Goal" :in-theory (enable mod))))
(in-theory (disable mod-plusxxx))
(defthm rewrite-floor-modxxx
(implies (and (equal i (/ y z))
(integerp i)
(fm-guard x (y z)))
(equal (floor (mod x y) z)
(- (floor x z) (* i (floor x y))))))
(defthm rewrite-mod-modxxx
(implies (and (equal i (/ y z))
(integerp i)
(fm-guard x (y z)))
(equal (mod (mod x y) z)
(mod x z))))
;; :hints (("Goal" :in-theory (enable mod-+))))
(defthm mod-+-cancel-0xxx
(implies (and (fm-guard (x y) z))
(equal (equal (mod (+ x y) z) x)
(and (equal (mod y z) 0)
(equal (mod x z) x)))))
;; :hints (("Subgoal 7" :in-theory (enable mod-+))
;; ("Subgoal 6" :in-theory (enable mod-+))
;; ("Subgoal 5" :expand (mod (+ x y) z))))
(defthm floor-cancel-*xxx
(implies (and (fm-guard x y)
(integerp x))
(and (equal (floor (* x y) y)
x)
(equal (floor (* y x) y)
x))))
(defthm floor-cancel-*-2xxx
(implies (and (fm-guard x (y z))
(integerp z))
(equal (floor (* x z) (* y z))
(floor x y))))
(defthm mod-minusxxx
(implies (fm-guard x y)
(equal (mod (- x) y)
(if (integerp (/ x y))
0
(- y (mod x y)))))
:hints (("Goal" :in-theory (enable mod))))
(defthm simplify-mod-*xxx
(implies (fm-guard x (y z))
(equal (mod (* x y) (* y z))
(* y (mod x z))))
:hints (("Goal" :in-theory (enable mod))))
;;-----------------------------------------------------------------
;;
;; Cancellation
;;
;;-----------------------------------------------------------------
(defthm cancel-floor-+xxx
(implies (and (equal i (/ x z))
(integerp i)
(fm-guard (x y) z))
(and (equal (floor (+ x y) z)
(+ i (floor y z)))
(equal (floor (+ y x) z)
(+ i (floor y z))))))
(defthm cancel-floor-+-3xxx
(implies (and (equal i (/ w z))
(integerp i)
(fm-guard (w x y) z))
(equal (floor (+ x y w) z)
(+ i (floor (+ x y) z)))))
(defthm cancel-mod-+xxx
(implies (and (equal i (/ x z))
(integerp i)
(fm-guard (x y) z))
(and (equal (mod (+ x y) z)
(mod y z))
(equal (mod (+ y x) z)
(mod y z))))
:hints (("Goal" :in-theory (enable mod))))
(defthm cancel-mod-+-3xxx
(implies (and (equal i (/ w z))
(integerp i)
(fm-guard (w x y) z))
(equal (mod (+ x y w) z)
(mod (+ x y) z))))
(defthm rewrite-floor-modxxx
(implies (and (equal i (/ y z))
(integerp i)
(fm-guard x (y z)))
(equal (floor (mod x y) z)
(- (floor x z) (* i (floor x y))))))
(defthm rewrite-mod-modxxx
(implies (and (equal i (/ y z))
(integerp i)
(fm-guard x (y z)))
(equal (mod (mod x y) z)
(mod x z))))
(defthm simplify-mod-+-modxxx
(implies (and (equal i (/ y z))
(integerp i)
(fm-guard (w x) (y z)))
(and (equal (mod (+ w (mod x y)) z)
(mod (+ w x) z))
(equal (mod (+ (mod x y) w) z)
(mod (+ w x) z))
(equal (mod (+ w (- (mod x y))) z)
(mod (+ w (- x)) z))
(equal (mod (+ (mod x y) (- w)) z)
(mod (+ x (- w)) z)))))
(defthm mod-+-cancel-0xxx
(implies (and (fm-guard (x y) z))
(equal (equal (mod (+ x y) z) x)
(and (equal (mod y z) 0)
(equal (mod x z) x))))
:hints (("Subgoal 5" :expand (mod (+ x y) z))))
(defthm floor-floor-integerxxx
(implies (and (real/rationalp x)
(integerp i)
(integerp j)
(< 0 i)
(< 0 j))
(equal (floor (floor x i) j)
(floor x (* i j)))))
;;-----------------------------------------------------------------
;;
;; Simple reductions
;;
;;-----------------------------------------------------------------
(defthm mod-twoxxx
(implies (integerp x)
(or (equal (mod x 2) 0)
(equal (mod x 2) 1)))
:rule-classes ((:forward-chaining
:corollary
(implies (integerp x)
(and (<= 0 (mod x 2))
(< (mod x 2) 2)))
:trigger-terms ((mod x 2)))
(:generalize)))
| true |
; See the top-level arithmetic-2 LICENSE file for authorship,
; copyright, and license information.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; floor-mod.lisp
;;;
;;; This is a start at a book for reasoning about floor and mod.
;;; Most of what is here came from the IHS books and modified.
;;; I believe that I could do better with some meta-rules, but
;;; I need to do a little more tuning of ACL2's handling of
;;; meta-rules first.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;-----------------------------------------------------------------
;;
;; Definitions
;;
;;-----------------------------------------------------------------
(IN-PACKAGE "ACL2")
(local (include-book "../meta/top"))
(local (include-book "ihs/quotient-remainder-lemmas" :dir :system))
;(defmacro e/d (enable disable)
; `(union-theories ',enable (disable ,@disable)))
(local
(in-theory (disable (:executable-counterpart force))))
(defun fm-y-guard (y)
(cond ((atom y)
`((real/rationalp ,y)
(not (equal ,y 0))))
((endp (cdr y))
`((real/rationalp ,(car y))
(not (equal ,(car y) 0))))
(t
(list* `(real/rationalp ,(car y))
`(not (equal ,(car y) 0))
(fm-y-guard (cdr y))))))
(defun fm-x-guard (x)
(cond ((atom x)
`((real/rationalp ,x)))
((endp (cdr x))
`((real/rationalp ,(car x))))
(t
(cons `(real/rationalp ,(car x))
(fm-x-guard (cdr x))))))
(defmacro fm-guard (x y)
(cons 'and
(append (fm-x-guard x)
(fm-y-guard y))))
(local
(defthm niq-boundsxxx
(implies (and (integerp i)
(<= 0 i)
(integerp j)
(< 0 j))
(and (<= (nonnegative-integer-quotient i j)
(/ i j))
(< (+ (/ i j) -1)
(nonnegative-integer-quotient i j))))
:hints (("Subgoal *1/1''" :in-theory
(enable prefer-positive-exponents-gather-exponents)))
:rule-classes ((:linear
:trigger-terms ((nonnegative-integer-quotient i j))))))
;;-----------------------------------------------------------------
;;
;; Basic definitions and lemmatta
;;
;;-----------------------------------------------------------------
;;(defthm floor-integerpxxx
;; (integerp (floor x y)))
(defthm integerp-modxxx
(implies (and (integerp x)
(integerp y))
(integerp (mod x y)))
:rule-classes :type-prescription)
(defthm rationalp-modxxx
(implies (and (rationalp x)
(rationalp y))
(rationalp (mod x y)))
:rule-classes :type-prescription)
#+:non-standard-analysis
(defthm realp-modxxx
(implies (and (realp x)
(realp y))
(realp (mod x y)))
:rule-classes :type-prescription)
(defthm floor-completionxxx
(implies (or (not (acl2-numberp x))
(not (acl2-numberp y)))
(equal (floor x y)
0)))
(defthm floor-0xxx
(and (equal (floor x 0)
0)
(equal (floor 0 y)
0)))
(defthm mod-completionxxx
(and (implies (not (acl2-numberp x))
(equal (mod x y)
0))
(implies (not (acl2-numberp y))
(equal (mod x y)
(fix x)))))
(defthm mod-0xxx
(and (equal (mod 0 y)
0)
(equal (mod x 0)
(fix x))))
(defthm floor-mod-elim
;; [PI:NAME:<NAME>END_PI] modified on 2014-07-29 to not forcibly assume acl2-numberp, to
;; avoid name clash with arithmetic-5.
(implies (acl2-numberp x)
(equal (+ (mod x y) (* y (floor x y))) x))
:hints (("Goal" :in-theory (disable floor)))
:rule-classes ((:rewrite)
(:elim)))
;;-----------------------------------------------------------------
;;
;; alternate, recursive, definitions.
;;
;;-----------------------------------------------------------------
(defun floor* (x y)
(declare (xargs :measure (abs (floor x y))))
(cond ((not (real/rationalp x))
t)
((not (real/rationalp y))
t)
((equal y 0)
t)
((< y 0)
(cond ((< 0 x)
(1- (floor* (+ x y) y)))
((< y x)
t)
(t
(1+ (floor* (- x y) y)))))
(t ;; (< 0 y)
(cond ((< x 0)
(1- (floor* (+ x y) y)))
((< x y)
t)
(t
(1+ (floor* (- x y) y)))))))
(defun mod* (x y)
(declare (xargs :measure (abs (floor x y))))
(cond ((not (real/rationalp x))
t)
((not (real/rationalp y))
t)
((equal y 0)
t)
((< y 0)
(cond ((< 0 x)
(mod* (+ x y) y))
((< y x)
t)
(t
(mod* (- x y) y))))
(t ;; (< 0 y)
(cond ((< x 0)
(mod* (+ x y) y))
((< x y)
t)
(t
(mod* (- x y) y))))))
(defthm ifloor-indxxx
t
:rule-classes ((:induction :pattern (floor x y)
:scheme (floor* x y))))
(defthm imod-indxxx
t
:rule-classes ((:induction :pattern (mod x y)
:scheme (mod* x y))))
;;-----------------------------------------------------------------
;;
;; Simple bounds.
;;
;;-----------------------------------------------------------------
(defthm floor-bounds-1xxx
(implies (fm-guard x y)
(and (< (+ (/ x y) -1)
(floor x y))
(<= (floor x y)
(/ x y))))
:rule-classes ((:generalize)
(:linear :trigger-terms ((floor x y)))
(:forward-chaining :trigger-terms ((floor x y)))))
(defthm floor-bounds-2xxx
(implies (and (fm-guard x y)
(integerp (/ x y)))
(equal (floor x y)
(/ x y)))
:rule-classes ((:generalize)
(:linear :trigger-terms ((floor x y)))
(:forward-chaining :trigger-terms ((floor x y)))))
(defthm floor-bounds-3xxx
(implies (and (fm-guard x y)
(not (integerp (/ x y))))
(< (floor x y)
(/ x y)))
:rule-classes ((:generalize)
(:linear :trigger-terms ((floor x y)))
(:forward-chaining :trigger-terms ((floor x y)))))
(in-theory (disable floor))
(defthm mod-bounds-1xxx
(implies (and (fm-guard x y)
(< 0 y))
(and (<= 0 (mod x y))
(< (mod x y) y)))
:rule-classes ((:generalize)
(:linear)
(:forward-chaining)))
(defthm mod-bounds-2xxx
(implies (and (fm-guard x y)
(< y 0))
(and (<= (mod x y) 0)
(< y (mod x y))))
:rule-classes ((:generalize)
(:linear)
(:forward-chaining)))
(defthm mod-bounds-3xxx
(implies (and (fm-guard x y)
(integerp (/ x y)))
(equal 0 (mod x y)))
:rule-classes ((:generalize)
(:linear)
(:forward-chaining)))
;;-----------------------------------------------------------------
;;
;; Type-prescription and linear rules.
;;
;;-----------------------------------------------------------------
(in-theory (disable floor mod))
(defthm floor-nonnegativexxx
(implies (and (fm-guard x y)
(if (< 0 y)
(<= 0 x)
(<= x 0)))
(<= 0 (floor x y)))
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:type-prescription)))
(defthm floor-nonpositivexxx
(implies (and (fm-guard x y)
(if (< 0 y)
(<= x 0)
(<= 0 x)))
(<= (floor x y) 0))
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:type-prescription)))
(defthm floor-positivexxx
(implies (and (fm-guard x y)
(if (< 0 y)
(<= y x)
(<= x y)))
(< 0 (floor x y)))
:hints (("Subgoal 4.1.2'" :in-theory
(enable prefer-positive-exponents-gather-exponents)))
:otf-flg t
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (< 0 (floor x y))
(if (< 0 y)
(<= y x)
(<= x y)))))))
(defthm floor-negativexxx
(implies (and (fm-guard x y)
(if (< 0 y)
(< x 0)
(< 0 x)))
(< (floor x y) 0))
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (< (floor x y) 0)
(if (< 0 y)
(< x 0)
(< 0 x)))))))
(defthm floor-=-x/yxxx
(implies (and (fm-guard x y)
(integerp (/ x y)))
(equal (floor x y) (/ x y)))
:rule-classes ((:rewrite)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (floor x y) (/ x y))
(integerp (/ x y)))))))
(defthm floor-zeroxxx
(implies (and (fm-guard x y)
(if (< 0 y)
(and (<= 0 x)
(< x y))
(and (<= x 0)
(< y x))))
(equal (floor x y) 0))
:rule-classes ((:rewrite :backchain-limit-lst 1)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (floor x y) 0)
(if (< 0 y)
(and (<= 0 x)
(< x y))
(and (<= x 0)
(< y x))))))))
(defthm floor-onexxx
(implies (and (fm-guard x y)
(if (< 0 y)
(and (<= y x)
(< x (* 2 y)))
(and (<= x y)
(< (* 2 y) x))))
(equal (floor x y) 1))
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (floor x y) 1)
(if (< 0 y)
(and (<= y x)
(< x (* 2 y)))
(and (<= x y)
(< (* 2 y) x))))))))
(defthm floor-minus-onexxx
(implies (and (fm-guard x y)
(if (< 0 y)
(and (< x 0)
(<= (- x) y))
(and (< 0 x)
(<= y (- x)))))
(equal (floor x y) -1))
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (floor x y) -1)
(if (< 0 y)
(and (< x 0)
(<= (- x) y))
(and (< 0 x)
(<= y (- x)))))))))
(defthm mod-nonnegativexxx
(implies (and (fm-guard x y)
(< 0 y))
(<= 0 (mod x y)))
:rule-classes ((:rewrite)
(:type-prescription)))
(defthm mod-nonpositivexxx
(implies (and (fm-guard x y)
(< y 0))
(<= (mod x y) 0))
:rule-classes ((:rewrite)
(:type-prescription)))
(defthm mod-positivexxx
(implies (and (fm-guard x y)
(< 0 y)
(not (integerp (/ x y))))
(< 0 (mod x y)))
:rule-classes ((:rewrite)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (< 0 (mod x y))
(and (< 0 y)
(not (integerp (/ x y)))))))))
(defthm mod-negativexxx
(implies (and (fm-guard x y)
(< y 0)
(not (integerp (/ x y))))
(< (mod x y) 0))
:rule-classes ((:rewrite)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (< (mod x y) 0)
(and (< y 0)
(not (integerp (/ x y)))))))))
(defthm mod-zeroxxx
(implies (and (fm-guard x y)
(integerp (/ x y)))
(equal (mod x y) 0))
:rule-classes ((:rewrite)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (mod x y) 0)
(integerp (/ x y)))))))
(defthm mod-x-y-=-xxxx
(implies (and (fm-guard x y)
(if (< 0 y)
(and (<= 0 x)
(< x y))
(and (<= x 0)
(< y x))))
(equal (mod x y) x))
:rule-classes ((:rewrite :backchain-limit-lst 1)
(:type-prescription)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (mod x y) x)
(if (< 0 y)
(and (<= 0 x)
(< x y))
(and (<= x 0)
(< y x))))))))
(defthm mod-x-y-=-x-+-yxxx
(implies (and (fm-guard x y)
(if (< 0 y)
(and (< x 0)
(<= (- x) y))
(and (< 0 x)
(<= y (- x)))))
(equal (mod x y) (+ x y)))
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (mod x y) (+ x y))
(if (< 0 y)
(and (< x 0)
(<= (- x) y))
(and (< 0 x)
(<= y (- x)))))))))
(defthm mod-x-y-=-x---y ;;; xxxxxx
(implies (and (fm-guard x y)
(if (< 0 y)
(and (<= y x)
(< x (* 2 y)))
(and (<= x y)
(< (* 2 y) x))))
(equal (mod x y) (- x y)))
:hints (("Goal" :in-theory (enable mod))) ;;; New hint.
:rule-classes ((:rewrite :backchain-limit-lst 0)
(:rewrite
:corollary
(implies (fm-guard x y)
(equal (equal (mod x y) (- x y))
(if (< 0 y)
(and (<= y x)
(< x (* 2 y)))
(and (<= x y)
(< (* 2 y) x))))))))
;;-----------------------------------------------------------------
;;
;; ???
;;
;;-----------------------------------------------------------------
(defthm justify-floor-recursionxxx
(and (implies (and (real/rationalp x)
(< 0 x)
(real/rationalp y)
(< 1 y))
(< (floor x y) x))
(implies (and (real/rationalp x)
(< x -1)
(real/rationalp y)
(<= 2 y))
(< x (floor x y)))))
;;-----------------------------------------------------------------
;;
;; Simple reductions
;;
;;-----------------------------------------------------------------
(defthm rewrite-floor-x*y-z-rightxxx
(implies (fm-guard x (y z))
(equal (floor (* x y) z)
(floor x (/ z y)))))
(in-theory (disable rewrite-floor-x*y-z-rightxxx))
(defthm rewrite-mod-x*y-z-rightxxx
(implies (fm-guard x (y z))
(equal (mod (* x y) z)
(* y (mod x (/ z y)))))
:hints (("Goal" :in-theory (enable mod))))
(in-theory (disable rewrite-mod-x*y-z-rightxxx))
(defthm floor-minusxxx
(implies (fm-guard x y)
(equal (floor (- x) y)
(if (integerp (* x (/ y)))
(- (floor x y))
(+ (- (floor x y)) -1)))))
(defthm floor-minus-2xxx
(implies (fm-guard x y)
(equal (floor x (- y))
(if (integerp (* x (/ y)))
(- (floor x y))
(+ (- (floor x y)) -1)))))
(defthm mod-minusxxx
(implies (fm-guard x y)
(equal (mod (- x) y)
(if (integerp (/ x y))
0
(- y (mod x y)))))
:hints (("Goal" :in-theory (enable mod))))
(defthm mod-minus-2xxx
(implies (fm-guard x y)
(equal (mod x (- y))
(if (integerp (/ x y))
0
(- (mod x y) y))))
:hints (("Goal" :in-theory (enable mod))))
; These next two theorems could easily loop.
(defthm floor-plusxxx
(implies (fm-guard (x y) z)
(equal (floor (+ x y) z)
(+ (floor (+ (mod x z) (mod y z)) z)
(+ (floor x z) (floor y z)))))
:hints (("Goal" :use ((:instance floor-+)))))
(in-theory (disable floor-plusxxx))
(defthm mod-plusxxx
(implies (fm-guard (x y) z)
(equal (mod (+ x y) z)
(mod (+ (mod x z) (mod y z)) z)))
:hints (("Goal" :in-theory (enable mod))))
(in-theory (disable mod-plusxxx))
(defthm rewrite-floor-modxxx
(implies (and (equal i (/ y z))
(integerp i)
(fm-guard x (y z)))
(equal (floor (mod x y) z)
(- (floor x z) (* i (floor x y))))))
(defthm rewrite-mod-modxxx
(implies (and (equal i (/ y z))
(integerp i)
(fm-guard x (y z)))
(equal (mod (mod x y) z)
(mod x z))))
;; :hints (("Goal" :in-theory (enable mod-+))))
(defthm mod-+-cancel-0xxx
(implies (and (fm-guard (x y) z))
(equal (equal (mod (+ x y) z) x)
(and (equal (mod y z) 0)
(equal (mod x z) x)))))
;; :hints (("Subgoal 7" :in-theory (enable mod-+))
;; ("Subgoal 6" :in-theory (enable mod-+))
;; ("Subgoal 5" :expand (mod (+ x y) z))))
(defthm floor-cancel-*xxx
(implies (and (fm-guard x y)
(integerp x))
(and (equal (floor (* x y) y)
x)
(equal (floor (* y x) y)
x))))
(defthm floor-cancel-*-2xxx
(implies (and (fm-guard x (y z))
(integerp z))
(equal (floor (* x z) (* y z))
(floor x y))))
(defthm mod-minusxxx
(implies (fm-guard x y)
(equal (mod (- x) y)
(if (integerp (/ x y))
0
(- y (mod x y)))))
:hints (("Goal" :in-theory (enable mod))))
(defthm simplify-mod-*xxx
(implies (fm-guard x (y z))
(equal (mod (* x y) (* y z))
(* y (mod x z))))
:hints (("Goal" :in-theory (enable mod))))
;;-----------------------------------------------------------------
;;
;; Cancellation
;;
;;-----------------------------------------------------------------
(defthm cancel-floor-+xxx
(implies (and (equal i (/ x z))
(integerp i)
(fm-guard (x y) z))
(and (equal (floor (+ x y) z)
(+ i (floor y z)))
(equal (floor (+ y x) z)
(+ i (floor y z))))))
(defthm cancel-floor-+-3xxx
(implies (and (equal i (/ w z))
(integerp i)
(fm-guard (w x y) z))
(equal (floor (+ x y w) z)
(+ i (floor (+ x y) z)))))
(defthm cancel-mod-+xxx
(implies (and (equal i (/ x z))
(integerp i)
(fm-guard (x y) z))
(and (equal (mod (+ x y) z)
(mod y z))
(equal (mod (+ y x) z)
(mod y z))))
:hints (("Goal" :in-theory (enable mod))))
(defthm cancel-mod-+-3xxx
(implies (and (equal i (/ w z))
(integerp i)
(fm-guard (w x y) z))
(equal (mod (+ x y w) z)
(mod (+ x y) z))))
(defthm rewrite-floor-modxxx
(implies (and (equal i (/ y z))
(integerp i)
(fm-guard x (y z)))
(equal (floor (mod x y) z)
(- (floor x z) (* i (floor x y))))))
(defthm rewrite-mod-modxxx
(implies (and (equal i (/ y z))
(integerp i)
(fm-guard x (y z)))
(equal (mod (mod x y) z)
(mod x z))))
(defthm simplify-mod-+-modxxx
(implies (and (equal i (/ y z))
(integerp i)
(fm-guard (w x) (y z)))
(and (equal (mod (+ w (mod x y)) z)
(mod (+ w x) z))
(equal (mod (+ (mod x y) w) z)
(mod (+ w x) z))
(equal (mod (+ w (- (mod x y))) z)
(mod (+ w (- x)) z))
(equal (mod (+ (mod x y) (- w)) z)
(mod (+ x (- w)) z)))))
(defthm mod-+-cancel-0xxx
(implies (and (fm-guard (x y) z))
(equal (equal (mod (+ x y) z) x)
(and (equal (mod y z) 0)
(equal (mod x z) x))))
:hints (("Subgoal 5" :expand (mod (+ x y) z))))
(defthm floor-floor-integerxxx
(implies (and (real/rationalp x)
(integerp i)
(integerp j)
(< 0 i)
(< 0 j))
(equal (floor (floor x i) j)
(floor x (* i j)))))
;;-----------------------------------------------------------------
;;
;; Simple reductions
;;
;;-----------------------------------------------------------------
(defthm mod-twoxxx
(implies (integerp x)
(or (equal (mod x 2) 0)
(equal (mod x 2) 1)))
:rule-classes ((:forward-chaining
:corollary
(implies (integerp x)
(and (<= 0 (mod x 2))
(< (mod x 2) 2)))
:trigger-terms ((mod x 2)))
(:generalize)))
|
[
{
"context": "rt of trial\n (c) 2017 Shirakumo http://tymoon.eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n",
"end": 89,
"score": 0.999920129776001,
"start": 71,
"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": 114,
"score": 0.9998968243598938,
"start": 100,
"tag": "NAME",
"value": "Nicolas Hafner"
},
{
"context": ".eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(in-package #:org.shirakumo.fraf.trial)\n\n(de",
"end": 134,
"score": 0.9999265670776367,
"start": 116,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
resources/vertex-array.lisp
|
LinkFly/trial
| 252 |
#|
This file is a part of trial
(c) 2017 Shirakumo http://tymoon.eu ([email protected])
Author: Nicolas Hafner <[email protected]>
|#
(in-package #:org.shirakumo.fraf.trial)
(defclass vertex-array (gl-resource)
((size :initarg :size :initform NIL :accessor size)
(bindings :initarg :bindings :accessor bindings)
(vertex-form :initarg :vertex-form :accessor vertex-form))
(:default-initargs
:bindings (error "BINDINGS required.")
:vertex-form :triangles))
(defmethod print-object ((array vertex-array) stream)
(print-unreadable-object (array stream :type T :identity T)
(format stream "~@[~a~]" (size array))))
(defmethod dependencies ((array vertex-array))
(mapcar #'unlist (bindings array)))
(defun update-array-bindings (array bindings)
(gl:bind-vertex-array (data-pointer array))
(unwind-protect
(loop for binding in bindings
for i from 0
do (destructuring-bind (buffer &key (index i)
(size 3)
(stride 0)
(offset 0)
(normalize NIL)
(instancing 0)
(type))
(enlist binding)
(check-allocated buffer)
(gl:bind-buffer (buffer-type buffer) (gl-name buffer))
(ecase (buffer-type buffer)
(:element-array-buffer
(unless (size array)
(setf (size array) (/ (size buffer) (gl-type-size (element-type buffer)))))
(decf i))
(:array-buffer
(ecase (or type (element-type buffer))
((:half-float :float :fixed)
(gl:vertex-attrib-pointer index size (element-type buffer) normalize stride offset))
((:byte :unsigned-byte :short :unsigned-short :int :unsigned-int)
(gl:vertex-attrib-ipointer index size (element-type buffer) stride offset))
(:double
(%gl:vertex-attrib-lpointer index size (element-type buffer) stride offset)))
(gl:enable-vertex-attrib-array index)
(%gl:vertex-attrib-divisor index instancing)))))
(gl:bind-vertex-array 0)))
(defmethod (setf bindings) :after (bindings (array vertex-array))
(when (allocated-p array)
(update-array-bindings array bindings)))
(defmethod allocate ((array vertex-array))
(let ((vao (gl:gen-vertex-array)))
(with-cleanup-on-failure (progn (gl:delete-vertex-arrays (list vao))
(setf (data-pointer array) NIL))
(setf (data-pointer array) vao)
(update-array-bindings array (bindings array)))))
(defmethod deallocate ((array vertex-array))
(gl:delete-vertex-arrays (list (gl-name array))))
(defmethod unload ((array vertex-array))
(loop for binding in (bindings array)
do (if (listp binding)
(unload (first binding))
(unload binding))))
|
24056
|
#|
This file is a part of trial
(c) 2017 Shirakumo http://tymoon.eu (<EMAIL>)
Author: <NAME> <<EMAIL>>
|#
(in-package #:org.shirakumo.fraf.trial)
(defclass vertex-array (gl-resource)
((size :initarg :size :initform NIL :accessor size)
(bindings :initarg :bindings :accessor bindings)
(vertex-form :initarg :vertex-form :accessor vertex-form))
(:default-initargs
:bindings (error "BINDINGS required.")
:vertex-form :triangles))
(defmethod print-object ((array vertex-array) stream)
(print-unreadable-object (array stream :type T :identity T)
(format stream "~@[~a~]" (size array))))
(defmethod dependencies ((array vertex-array))
(mapcar #'unlist (bindings array)))
(defun update-array-bindings (array bindings)
(gl:bind-vertex-array (data-pointer array))
(unwind-protect
(loop for binding in bindings
for i from 0
do (destructuring-bind (buffer &key (index i)
(size 3)
(stride 0)
(offset 0)
(normalize NIL)
(instancing 0)
(type))
(enlist binding)
(check-allocated buffer)
(gl:bind-buffer (buffer-type buffer) (gl-name buffer))
(ecase (buffer-type buffer)
(:element-array-buffer
(unless (size array)
(setf (size array) (/ (size buffer) (gl-type-size (element-type buffer)))))
(decf i))
(:array-buffer
(ecase (or type (element-type buffer))
((:half-float :float :fixed)
(gl:vertex-attrib-pointer index size (element-type buffer) normalize stride offset))
((:byte :unsigned-byte :short :unsigned-short :int :unsigned-int)
(gl:vertex-attrib-ipointer index size (element-type buffer) stride offset))
(:double
(%gl:vertex-attrib-lpointer index size (element-type buffer) stride offset)))
(gl:enable-vertex-attrib-array index)
(%gl:vertex-attrib-divisor index instancing)))))
(gl:bind-vertex-array 0)))
(defmethod (setf bindings) :after (bindings (array vertex-array))
(when (allocated-p array)
(update-array-bindings array bindings)))
(defmethod allocate ((array vertex-array))
(let ((vao (gl:gen-vertex-array)))
(with-cleanup-on-failure (progn (gl:delete-vertex-arrays (list vao))
(setf (data-pointer array) NIL))
(setf (data-pointer array) vao)
(update-array-bindings array (bindings array)))))
(defmethod deallocate ((array vertex-array))
(gl:delete-vertex-arrays (list (gl-name array))))
(defmethod unload ((array vertex-array))
(loop for binding in (bindings array)
do (if (listp binding)
(unload (first binding))
(unload binding))))
| true |
#|
This file is a part of trial
(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.fraf.trial)
(defclass vertex-array (gl-resource)
((size :initarg :size :initform NIL :accessor size)
(bindings :initarg :bindings :accessor bindings)
(vertex-form :initarg :vertex-form :accessor vertex-form))
(:default-initargs
:bindings (error "BINDINGS required.")
:vertex-form :triangles))
(defmethod print-object ((array vertex-array) stream)
(print-unreadable-object (array stream :type T :identity T)
(format stream "~@[~a~]" (size array))))
(defmethod dependencies ((array vertex-array))
(mapcar #'unlist (bindings array)))
(defun update-array-bindings (array bindings)
(gl:bind-vertex-array (data-pointer array))
(unwind-protect
(loop for binding in bindings
for i from 0
do (destructuring-bind (buffer &key (index i)
(size 3)
(stride 0)
(offset 0)
(normalize NIL)
(instancing 0)
(type))
(enlist binding)
(check-allocated buffer)
(gl:bind-buffer (buffer-type buffer) (gl-name buffer))
(ecase (buffer-type buffer)
(:element-array-buffer
(unless (size array)
(setf (size array) (/ (size buffer) (gl-type-size (element-type buffer)))))
(decf i))
(:array-buffer
(ecase (or type (element-type buffer))
((:half-float :float :fixed)
(gl:vertex-attrib-pointer index size (element-type buffer) normalize stride offset))
((:byte :unsigned-byte :short :unsigned-short :int :unsigned-int)
(gl:vertex-attrib-ipointer index size (element-type buffer) stride offset))
(:double
(%gl:vertex-attrib-lpointer index size (element-type buffer) stride offset)))
(gl:enable-vertex-attrib-array index)
(%gl:vertex-attrib-divisor index instancing)))))
(gl:bind-vertex-array 0)))
(defmethod (setf bindings) :after (bindings (array vertex-array))
(when (allocated-p array)
(update-array-bindings array bindings)))
(defmethod allocate ((array vertex-array))
(let ((vao (gl:gen-vertex-array)))
(with-cleanup-on-failure (progn (gl:delete-vertex-arrays (list vao))
(setf (data-pointer array) NIL))
(setf (data-pointer array) vao)
(update-array-bindings array (bindings array)))))
(defmethod deallocate ((array vertex-array))
(gl:delete-vertex-arrays (list (gl-name array))))
(defmethod unload ((array vertex-array))
(loop for binding in (bindings array)
do (if (listp binding)
(unload (first binding))
(unload binding))))
|
[
{
"context": "face to access environment variables.\"\n :author \"CHIBA Masaomi\"\n :maintainer \"CHIBA Masaomi\"\n :license \"Unlice",
"end": 235,
"score": 0.9998441338539124,
"start": 222,
"tag": "NAME",
"value": "CHIBA Masaomi"
},
{
"context": "iables.\"\n :author \"CHIBA Masaomi\"\n :maintainer \"CHIBA Masaomi\"\n :license \"Unlicense\"\n :serial t\n :depends-on",
"end": 265,
"score": 0.9997870922088623,
"start": 252,
"tag": "NAME",
"value": "CHIBA Masaomi"
},
{
"context": "em :srfi-98))))\n (let ((name \"https://github.com/g000001/srfi-98\")\n (nickname :srfi-98))\n (if (a",
"end": 538,
"score": 0.993280827999115,
"start": 531,
"tag": "USERNAME",
"value": "g000001"
},
{
"context": "face to access environment variables.\"\n :author \"CHIBA Masaomi\"\n :maintainer \"CHIBA Masaomi\"\n :license \"Unlice",
"end": 1031,
"score": 0.9998542666435242,
"start": 1018,
"tag": "NAME",
"value": "CHIBA Masaomi"
},
{
"context": "iables.\"\n :author \"CHIBA Masaomi\"\n :maintainer \"CHIBA Masaomi\"\n :license \"Unlicense\"\n :serial t\n :depends-on",
"end": 1061,
"score": 0.9998321533203125,
"start": 1048,
"tag": "NAME",
"value": "CHIBA Masaomi"
},
{
"context": "n)\n (_ \"https://github.com/g000001/srfi-98#internals\"\n :sr",
"end": 1441,
"score": 0.9670581221580505,
"start": 1434,
"tag": "USERNAME",
"value": "g000001"
}
] |
srfi-98.asd
|
g000001/srfi-98
| 0 |
;;;; srfi-98.asd
(cl:in-package :asdf)
(defsystem :srfi-98
:version "20200108"
:description "SRFI 98: get-environment-variable"
:long-description "SRFI 98: An interface to access environment variables."
:author "CHIBA Masaomi"
:maintainer "CHIBA Masaomi"
:license "Unlicense"
:serial t
:depends-on (#+lispworks :osicat #+sbcl :sb-posix)
:components ((:file "package")
(:file "srfi-98")))
(defmethod perform :after ((o load-op) (c (eql (find-system :srfi-98))))
(let ((name "https://github.com/g000001/srfi-98")
(nickname :srfi-98))
(if (and (find-package nickname)
(not (eq (find-package nickname)
(find-package name))))
(warn "~A: A package with name ~A already exists." name nickname)
(rename-package name name `(,nickname)))))
(defsystem :srfi-98.test
:version "20200108"
:description "SRFI 98: get-environment-variable"
:long-description "SRFI 98: An interface to access environment variables."
:author "CHIBA Masaomi"
:maintainer "CHIBA Masaomi"
:license "Unlicense"
:serial t
:depends-on (:srfi-98 :fiveam)
:components ((:file "test")))
(defmethod perform ((o test-op) (c (eql (find-system :srfi-98.test))))
(or (flet ((_ (pkg sym)
(intern (symbol-name sym) (find-package pkg))))
(let ((result
(funcall (_ :fiveam :run)
(_ "https://github.com/g000001/srfi-98#internals"
:srfi-98))))
(funcall (_ :fiveam :explain!) result)
(funcall (_ :fiveam :results-status) result)))
(error "test-op failed") ))
|
89524
|
;;;; srfi-98.asd
(cl:in-package :asdf)
(defsystem :srfi-98
:version "20200108"
:description "SRFI 98: get-environment-variable"
:long-description "SRFI 98: An interface to access environment variables."
:author "<NAME>"
:maintainer "<NAME>"
:license "Unlicense"
:serial t
:depends-on (#+lispworks :osicat #+sbcl :sb-posix)
:components ((:file "package")
(:file "srfi-98")))
(defmethod perform :after ((o load-op) (c (eql (find-system :srfi-98))))
(let ((name "https://github.com/g000001/srfi-98")
(nickname :srfi-98))
(if (and (find-package nickname)
(not (eq (find-package nickname)
(find-package name))))
(warn "~A: A package with name ~A already exists." name nickname)
(rename-package name name `(,nickname)))))
(defsystem :srfi-98.test
:version "20200108"
:description "SRFI 98: get-environment-variable"
:long-description "SRFI 98: An interface to access environment variables."
:author "<NAME>"
:maintainer "<NAME>"
:license "Unlicense"
:serial t
:depends-on (:srfi-98 :fiveam)
:components ((:file "test")))
(defmethod perform ((o test-op) (c (eql (find-system :srfi-98.test))))
(or (flet ((_ (pkg sym)
(intern (symbol-name sym) (find-package pkg))))
(let ((result
(funcall (_ :fiveam :run)
(_ "https://github.com/g000001/srfi-98#internals"
:srfi-98))))
(funcall (_ :fiveam :explain!) result)
(funcall (_ :fiveam :results-status) result)))
(error "test-op failed") ))
| true |
;;;; srfi-98.asd
(cl:in-package :asdf)
(defsystem :srfi-98
:version "20200108"
:description "SRFI 98: get-environment-variable"
:long-description "SRFI 98: An interface to access environment variables."
:author "PI:NAME:<NAME>END_PI"
:maintainer "PI:NAME:<NAME>END_PI"
:license "Unlicense"
:serial t
:depends-on (#+lispworks :osicat #+sbcl :sb-posix)
:components ((:file "package")
(:file "srfi-98")))
(defmethod perform :after ((o load-op) (c (eql (find-system :srfi-98))))
(let ((name "https://github.com/g000001/srfi-98")
(nickname :srfi-98))
(if (and (find-package nickname)
(not (eq (find-package nickname)
(find-package name))))
(warn "~A: A package with name ~A already exists." name nickname)
(rename-package name name `(,nickname)))))
(defsystem :srfi-98.test
:version "20200108"
:description "SRFI 98: get-environment-variable"
:long-description "SRFI 98: An interface to access environment variables."
:author "PI:NAME:<NAME>END_PI"
:maintainer "PI:NAME:<NAME>END_PI"
:license "Unlicense"
:serial t
:depends-on (:srfi-98 :fiveam)
:components ((:file "test")))
(defmethod perform ((o test-op) (c (eql (find-system :srfi-98.test))))
(or (flet ((_ (pkg sym)
(intern (symbol-name sym) (find-package pkg))))
(let ((result
(funcall (_ :fiveam :run)
(_ "https://github.com/g000001/srfi-98#internals"
:srfi-98))))
(funcall (_ :fiveam :explain!) result)
(funcall (_ :fiveam :results-status) result)))
(error "test-op failed") ))
|
[
{
"context": ";;;\n;;; Copyright (c) 2007 Zachary Beane, All Rights Reserved\n;;;\n;;; Redistribution and u",
"end": 40,
"score": 0.9998437166213989,
"start": 27,
"tag": "NAME",
"value": "Zachary Beane"
}
] |
compress.lisp
|
peoplestom/salza2
| 79 |
;;;
;;; Copyright (c) 2007 Zachary Beane, 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 AUTHOR 'AS IS' AND ANY EXPRESSED
;;; 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 AUTHOR 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 #:salza2)
(defun compress (input chains start end
literal-fun length-fun distance-fun)
(declare (type input-buffer input)
(type chains-buffer chains)
(type input-index start end)
(type function literal-fun length-fun distance-fun)
(optimize speed))
(let ((p start))
(loop
(when (= p end)
(return))
(multiple-value-bind (length distance)
(longest-match p input chains end 4)
(declare (type (integer 0 258) length)
(type (integer 0 32768) distance))
(cond ((zerop length)
(funcall literal-fun (aref input p))
(setf p (logand (+ p 1) #xFFFF)))
(t
(funcall length-fun length)
(funcall distance-fun distance)
(setf p (logand (+ p length) #xFFFF))))))))
|
37591
|
;;;
;;; Copyright (c) 2007 <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 AUTHOR 'AS IS' AND ANY EXPRESSED
;;; 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 AUTHOR 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 #:salza2)
(defun compress (input chains start end
literal-fun length-fun distance-fun)
(declare (type input-buffer input)
(type chains-buffer chains)
(type input-index start end)
(type function literal-fun length-fun distance-fun)
(optimize speed))
(let ((p start))
(loop
(when (= p end)
(return))
(multiple-value-bind (length distance)
(longest-match p input chains end 4)
(declare (type (integer 0 258) length)
(type (integer 0 32768) distance))
(cond ((zerop length)
(funcall literal-fun (aref input p))
(setf p (logand (+ p 1) #xFFFF)))
(t
(funcall length-fun length)
(funcall distance-fun distance)
(setf p (logand (+ p length) #xFFFF))))))))
| true |
;;;
;;; Copyright (c) 2007 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 AUTHOR 'AS IS' AND ANY EXPRESSED
;;; 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 AUTHOR 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 #:salza2)
(defun compress (input chains start end
literal-fun length-fun distance-fun)
(declare (type input-buffer input)
(type chains-buffer chains)
(type input-index start end)
(type function literal-fun length-fun distance-fun)
(optimize speed))
(let ((p start))
(loop
(when (= p end)
(return))
(multiple-value-bind (length distance)
(longest-match p input chains end 4)
(declare (type (integer 0 258) length)
(type (integer 0 32768) distance))
(cond ((zerop length)
(funcall literal-fun (aref input p))
(setf p (logand (+ p 1) #xFFFF)))
(t
(funcall length-fun length)
(funcall distance-fun distance)
(setf p (logand (+ p length) #xFFFF))))))))
|
[
{
"context": "; DEALINGS IN THE SOFTWARE.\n;\n; Original author: Jared Davis <[email protected]>\n\n(in-package \"MILAWA\")\n(inc",
"end": 1356,
"score": 0.9995792508125305,
"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 \"mergesort\"",
"end": 1377,
"score": 0.9999354481697083,
"start": 1358,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/projects/milawa/ACL2/bootstrap/utilities/mergesort-map.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 "mergesort")
(%interactive)
(%autoadmit ordered-mapp)
(%autoprove ordered-mapp-when-not-consp
(%restrict default ordered-mapp (equal x 'x)))
(%autoprove ordered-mapp-when-not-consp-of-cdr
(%restrict default ordered-mapp (equal x 'x)))
(%autoprove ordered-mapp-of-cons
(%restrict default ordered-mapp (equal x '(cons a x))))
(%autoprove booleanp-of-ordered-mapp
(%cdr-induction x))
(%autoprove ordered-mapp-of-cdr-when-ordered-mapp)
(%autoprove lemma-for-uniquep-when-ordered-mapp
(%cdr-induction x))
(%autoprove uniquep-of-domain-when-ordered-mapp
(%cdr-induction x)
(%enable default lemma-for-uniquep-when-ordered-mapp))
(%autoadmit merge-maps)
(%autoprove merge-maps-when-not-consp-left
(%restrict default merge-maps (and (equal x 'x) (equal y 'y))))
(%autoprove merge-maps-when-not-consp-right
(%restrict default merge-maps (and (equal x 'x) (equal y 'y))))
(%autoprove merge-maps-of-cons-and-cons
(%restrict default merge-maps (and (or (equal x '(cons a x))
(equal x '(cons b x)))
(or (equal y '(cons a y))
(equal y '(cons b y))))))
(%autoprove consp-of-merge-maps
(%restrict default merge-maps (and (equal x 'x) (equal y 'y))))
(%autoprove lookup-of-first-of-first)
(%autoprove lookup-when-not-first-of-first)
(%autoprove smaller-than-merge-maps
(%autoinduct merge-maps)
(%restrict default merge-maps (and (equal x 'x) (equal y 'y))))
(%autoprove ordered-mapp-of-merge-maps
(%autoinduct merge-maps x y)
(%restrict default merge-maps (and (equal x 'x) (equal y 'y))))
(%autoprove mapp-of-merge-maps
(%autoinduct merge-maps x y)
(%restrict default merge-maps (and (equal x 'x) (equal y 'y))))
(%autoprove lookup-of-merge-maps
(%autoinduct merge-maps x y)
(%restrict default merge-maps (and (equal x 'x) (equal y 'y)))
(%enable default
lemma-2-for-ordered-list-subsetp-property
lemma-for-uniquep-when-ordered-mapp))
(%autoadmit mergesort-map)
(%autoprove mergesort-map-when-not-consp
(%restrict default mergesort-map (equal x 'x)))
(%autoprove mergesort-map-when-not-consp-of-cdr
(%restrict default mergesort-map (equal x 'x)))
(%autoprove mapp-of-mergesort-map
(%autoinduct mergesort-map)
(%restrict default mergesort-map (equal x 'x)))
(%autoprove ordered-mapp-of-mergesort-map
(%autoinduct mergesort-map)
(%restrict default mergesort-map (equal x 'x)))
(verify-guards mergesort-map)
(%autoprove uniquep-of-domain-of-mergesort-map)
(%autoprove lemma-1-for-lookup-of-mergesort-map
(%use (%instance (%thm halve-list-lookup-property))))
(%autoprove lemma-2-for-lookup-of-mergesort-map
(%use (%instance (%thm halve-list-lookup-property))))
(%autoprove lookup-of-mergesort-map
(%autoinduct mergesort-map)
(%restrict default mergesort-map (equal x 'x))
(%enable default lemma-1-for-lookup-of-mergesort-map
lemma-2-for-lookup-of-mergesort-map))
(%autoprove submapp-of-mergesort-map-and-self-left
(%use (%instance (%thm submapp-badguy-membership-property)
(x (mergesort-map x))
(y x))))
(%autoprove submapp-of-mergesort-map-and-self-right
(%use (%instance (%thm submapp-badguy-membership-property)
(y (mergesort-map x))
(x x))))
(%autoprove submapp-of-mergesort-map-left)
(%autoprove submapp-of-mergesort-map-right)
(%autoadmit ordered-map-submapp)
(%autoprove ordered-map-submapp-when-not-consp-left
(%restrict default ordered-map-submapp (and (equal x 'x) (equal y 'y))))
(%autoprove ordered-map-submapp-when-not-consp-right
(%restrict default ordered-map-submapp (and (equal x 'x) (equal y 'y))))
(%autoprove ordered-map-submapp-of-cons-and-cons
(%restrict default ordered-map-submapp (and (or (equal x '(cons a x))
(equal x '(cons b x)))
(or (equal y '(cons a y))
(equal y '(cons b y))))))
(%autoprove booleanp-of-ordered-map-submapp
(%autoinduct ordered-map-submapp x y))
(%autoprove lemma-1-for-ordered-map-submapp-property)
(%autoprove lemma-2-for-ordered-map-submapp-property
(%enable default submapp))
(%autoprove lemma-3-for-ordered-map-submapp-property
(%disable default equal-of-lookups-when-submapp)
(%use (%instance (%thm equal-of-lookups-when-submapp)
(x x)
(y y)
(a (car (car x))))))
(%autoprove lemma-4-for-ordered-map-submapp-property-aux
(%autoinduct submapp1 dom x y)
(%restrict default submapp1 (equal domain 'dom)))
(%autoprove lemma-4-for-ordered-map-submapp-property
(%enable default
lemma-4-for-ordered-map-submapp-property-aux
lemma-for-uniquep-when-ordered-mapp
submapp))
(%autoprove lemma-5-for-ordered-map-submapp-property
(%disable default lemma-for-uniquep-when-ordered-mapp)
(%use (%instance (%thm lemma-for-uniquep-when-ordered-mapp)
(a (first (first x)))
(x y))))
(%autoprove lemma-6-for-ordered-map-submapp-property
(%disable default equal-of-lookups-when-submapp)
(%use (%instance (%thm equal-of-lookups-when-submapp)
(a (first (first x)))
(x x)
(y y)))
(%auto :strategy (cleanup split urewrite crewrite))
(%restrict default lookup (or (equal x 'x) (equal y 'y))))
(%autoprove lemma-7-for-ordered-map-submapp-property-aux
(%autoinduct submapp1 dom x y)
(%restrict default submapp1 (equal domain 'dom)))
(%autoprove lemma-7-for-ordered-map-submapp-property
(%enable default
submapp
lemma-for-uniquep-when-ordered-mapp)
(%use (%instance (%thm lemma-7-for-ordered-map-submapp-property-aux)
(dom (domain x)))))
(%autoprove ordered-map-submapp-property
(%autoinduct ordered-map-submapp x y)
(%enable default lemma-for-uniquep-when-ordered-mapp
lemma-1-for-ordered-map-submapp-property
lemma-2-for-ordered-map-submapp-property
lemma-3-for-ordered-map-submapp-property
lemma-4-for-ordered-map-submapp-property
lemma-5-for-ordered-map-submapp-property
lemma-6-for-ordered-map-submapp-property
lemma-7-for-ordered-map-submapp-property))
(%autoprove lemma-for-ordered-listp-when-ordered-mapp
(%restrict default << (and (equal x 'a) (equal y 'b))))
(%autoprove ordered-listp-when-ordered-mapp
(%cdr-induction x)
(%enable default lemma-for-ordered-listp-when-ordered-mapp))
(%autoprove ordered-listp-of-mergesort-map)
(%ensure-exactly-these-rules-are-missing "../../../utilities/mergesort")
|
46100
|
; 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 "mergesort")
(%interactive)
(%autoadmit ordered-mapp)
(%autoprove ordered-mapp-when-not-consp
(%restrict default ordered-mapp (equal x 'x)))
(%autoprove ordered-mapp-when-not-consp-of-cdr
(%restrict default ordered-mapp (equal x 'x)))
(%autoprove ordered-mapp-of-cons
(%restrict default ordered-mapp (equal x '(cons a x))))
(%autoprove booleanp-of-ordered-mapp
(%cdr-induction x))
(%autoprove ordered-mapp-of-cdr-when-ordered-mapp)
(%autoprove lemma-for-uniquep-when-ordered-mapp
(%cdr-induction x))
(%autoprove uniquep-of-domain-when-ordered-mapp
(%cdr-induction x)
(%enable default lemma-for-uniquep-when-ordered-mapp))
(%autoadmit merge-maps)
(%autoprove merge-maps-when-not-consp-left
(%restrict default merge-maps (and (equal x 'x) (equal y 'y))))
(%autoprove merge-maps-when-not-consp-right
(%restrict default merge-maps (and (equal x 'x) (equal y 'y))))
(%autoprove merge-maps-of-cons-and-cons
(%restrict default merge-maps (and (or (equal x '(cons a x))
(equal x '(cons b x)))
(or (equal y '(cons a y))
(equal y '(cons b y))))))
(%autoprove consp-of-merge-maps
(%restrict default merge-maps (and (equal x 'x) (equal y 'y))))
(%autoprove lookup-of-first-of-first)
(%autoprove lookup-when-not-first-of-first)
(%autoprove smaller-than-merge-maps
(%autoinduct merge-maps)
(%restrict default merge-maps (and (equal x 'x) (equal y 'y))))
(%autoprove ordered-mapp-of-merge-maps
(%autoinduct merge-maps x y)
(%restrict default merge-maps (and (equal x 'x) (equal y 'y))))
(%autoprove mapp-of-merge-maps
(%autoinduct merge-maps x y)
(%restrict default merge-maps (and (equal x 'x) (equal y 'y))))
(%autoprove lookup-of-merge-maps
(%autoinduct merge-maps x y)
(%restrict default merge-maps (and (equal x 'x) (equal y 'y)))
(%enable default
lemma-2-for-ordered-list-subsetp-property
lemma-for-uniquep-when-ordered-mapp))
(%autoadmit mergesort-map)
(%autoprove mergesort-map-when-not-consp
(%restrict default mergesort-map (equal x 'x)))
(%autoprove mergesort-map-when-not-consp-of-cdr
(%restrict default mergesort-map (equal x 'x)))
(%autoprove mapp-of-mergesort-map
(%autoinduct mergesort-map)
(%restrict default mergesort-map (equal x 'x)))
(%autoprove ordered-mapp-of-mergesort-map
(%autoinduct mergesort-map)
(%restrict default mergesort-map (equal x 'x)))
(verify-guards mergesort-map)
(%autoprove uniquep-of-domain-of-mergesort-map)
(%autoprove lemma-1-for-lookup-of-mergesort-map
(%use (%instance (%thm halve-list-lookup-property))))
(%autoprove lemma-2-for-lookup-of-mergesort-map
(%use (%instance (%thm halve-list-lookup-property))))
(%autoprove lookup-of-mergesort-map
(%autoinduct mergesort-map)
(%restrict default mergesort-map (equal x 'x))
(%enable default lemma-1-for-lookup-of-mergesort-map
lemma-2-for-lookup-of-mergesort-map))
(%autoprove submapp-of-mergesort-map-and-self-left
(%use (%instance (%thm submapp-badguy-membership-property)
(x (mergesort-map x))
(y x))))
(%autoprove submapp-of-mergesort-map-and-self-right
(%use (%instance (%thm submapp-badguy-membership-property)
(y (mergesort-map x))
(x x))))
(%autoprove submapp-of-mergesort-map-left)
(%autoprove submapp-of-mergesort-map-right)
(%autoadmit ordered-map-submapp)
(%autoprove ordered-map-submapp-when-not-consp-left
(%restrict default ordered-map-submapp (and (equal x 'x) (equal y 'y))))
(%autoprove ordered-map-submapp-when-not-consp-right
(%restrict default ordered-map-submapp (and (equal x 'x) (equal y 'y))))
(%autoprove ordered-map-submapp-of-cons-and-cons
(%restrict default ordered-map-submapp (and (or (equal x '(cons a x))
(equal x '(cons b x)))
(or (equal y '(cons a y))
(equal y '(cons b y))))))
(%autoprove booleanp-of-ordered-map-submapp
(%autoinduct ordered-map-submapp x y))
(%autoprove lemma-1-for-ordered-map-submapp-property)
(%autoprove lemma-2-for-ordered-map-submapp-property
(%enable default submapp))
(%autoprove lemma-3-for-ordered-map-submapp-property
(%disable default equal-of-lookups-when-submapp)
(%use (%instance (%thm equal-of-lookups-when-submapp)
(x x)
(y y)
(a (car (car x))))))
(%autoprove lemma-4-for-ordered-map-submapp-property-aux
(%autoinduct submapp1 dom x y)
(%restrict default submapp1 (equal domain 'dom)))
(%autoprove lemma-4-for-ordered-map-submapp-property
(%enable default
lemma-4-for-ordered-map-submapp-property-aux
lemma-for-uniquep-when-ordered-mapp
submapp))
(%autoprove lemma-5-for-ordered-map-submapp-property
(%disable default lemma-for-uniquep-when-ordered-mapp)
(%use (%instance (%thm lemma-for-uniquep-when-ordered-mapp)
(a (first (first x)))
(x y))))
(%autoprove lemma-6-for-ordered-map-submapp-property
(%disable default equal-of-lookups-when-submapp)
(%use (%instance (%thm equal-of-lookups-when-submapp)
(a (first (first x)))
(x x)
(y y)))
(%auto :strategy (cleanup split urewrite crewrite))
(%restrict default lookup (or (equal x 'x) (equal y 'y))))
(%autoprove lemma-7-for-ordered-map-submapp-property-aux
(%autoinduct submapp1 dom x y)
(%restrict default submapp1 (equal domain 'dom)))
(%autoprove lemma-7-for-ordered-map-submapp-property
(%enable default
submapp
lemma-for-uniquep-when-ordered-mapp)
(%use (%instance (%thm lemma-7-for-ordered-map-submapp-property-aux)
(dom (domain x)))))
(%autoprove ordered-map-submapp-property
(%autoinduct ordered-map-submapp x y)
(%enable default lemma-for-uniquep-when-ordered-mapp
lemma-1-for-ordered-map-submapp-property
lemma-2-for-ordered-map-submapp-property
lemma-3-for-ordered-map-submapp-property
lemma-4-for-ordered-map-submapp-property
lemma-5-for-ordered-map-submapp-property
lemma-6-for-ordered-map-submapp-property
lemma-7-for-ordered-map-submapp-property))
(%autoprove lemma-for-ordered-listp-when-ordered-mapp
(%restrict default << (and (equal x 'a) (equal y 'b))))
(%autoprove ordered-listp-when-ordered-mapp
(%cdr-induction x)
(%enable default lemma-for-ordered-listp-when-ordered-mapp))
(%autoprove ordered-listp-of-mergesort-map)
(%ensure-exactly-these-rules-are-missing "../../../utilities/mergesort")
| 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 "mergesort")
(%interactive)
(%autoadmit ordered-mapp)
(%autoprove ordered-mapp-when-not-consp
(%restrict default ordered-mapp (equal x 'x)))
(%autoprove ordered-mapp-when-not-consp-of-cdr
(%restrict default ordered-mapp (equal x 'x)))
(%autoprove ordered-mapp-of-cons
(%restrict default ordered-mapp (equal x '(cons a x))))
(%autoprove booleanp-of-ordered-mapp
(%cdr-induction x))
(%autoprove ordered-mapp-of-cdr-when-ordered-mapp)
(%autoprove lemma-for-uniquep-when-ordered-mapp
(%cdr-induction x))
(%autoprove uniquep-of-domain-when-ordered-mapp
(%cdr-induction x)
(%enable default lemma-for-uniquep-when-ordered-mapp))
(%autoadmit merge-maps)
(%autoprove merge-maps-when-not-consp-left
(%restrict default merge-maps (and (equal x 'x) (equal y 'y))))
(%autoprove merge-maps-when-not-consp-right
(%restrict default merge-maps (and (equal x 'x) (equal y 'y))))
(%autoprove merge-maps-of-cons-and-cons
(%restrict default merge-maps (and (or (equal x '(cons a x))
(equal x '(cons b x)))
(or (equal y '(cons a y))
(equal y '(cons b y))))))
(%autoprove consp-of-merge-maps
(%restrict default merge-maps (and (equal x 'x) (equal y 'y))))
(%autoprove lookup-of-first-of-first)
(%autoprove lookup-when-not-first-of-first)
(%autoprove smaller-than-merge-maps
(%autoinduct merge-maps)
(%restrict default merge-maps (and (equal x 'x) (equal y 'y))))
(%autoprove ordered-mapp-of-merge-maps
(%autoinduct merge-maps x y)
(%restrict default merge-maps (and (equal x 'x) (equal y 'y))))
(%autoprove mapp-of-merge-maps
(%autoinduct merge-maps x y)
(%restrict default merge-maps (and (equal x 'x) (equal y 'y))))
(%autoprove lookup-of-merge-maps
(%autoinduct merge-maps x y)
(%restrict default merge-maps (and (equal x 'x) (equal y 'y)))
(%enable default
lemma-2-for-ordered-list-subsetp-property
lemma-for-uniquep-when-ordered-mapp))
(%autoadmit mergesort-map)
(%autoprove mergesort-map-when-not-consp
(%restrict default mergesort-map (equal x 'x)))
(%autoprove mergesort-map-when-not-consp-of-cdr
(%restrict default mergesort-map (equal x 'x)))
(%autoprove mapp-of-mergesort-map
(%autoinduct mergesort-map)
(%restrict default mergesort-map (equal x 'x)))
(%autoprove ordered-mapp-of-mergesort-map
(%autoinduct mergesort-map)
(%restrict default mergesort-map (equal x 'x)))
(verify-guards mergesort-map)
(%autoprove uniquep-of-domain-of-mergesort-map)
(%autoprove lemma-1-for-lookup-of-mergesort-map
(%use (%instance (%thm halve-list-lookup-property))))
(%autoprove lemma-2-for-lookup-of-mergesort-map
(%use (%instance (%thm halve-list-lookup-property))))
(%autoprove lookup-of-mergesort-map
(%autoinduct mergesort-map)
(%restrict default mergesort-map (equal x 'x))
(%enable default lemma-1-for-lookup-of-mergesort-map
lemma-2-for-lookup-of-mergesort-map))
(%autoprove submapp-of-mergesort-map-and-self-left
(%use (%instance (%thm submapp-badguy-membership-property)
(x (mergesort-map x))
(y x))))
(%autoprove submapp-of-mergesort-map-and-self-right
(%use (%instance (%thm submapp-badguy-membership-property)
(y (mergesort-map x))
(x x))))
(%autoprove submapp-of-mergesort-map-left)
(%autoprove submapp-of-mergesort-map-right)
(%autoadmit ordered-map-submapp)
(%autoprove ordered-map-submapp-when-not-consp-left
(%restrict default ordered-map-submapp (and (equal x 'x) (equal y 'y))))
(%autoprove ordered-map-submapp-when-not-consp-right
(%restrict default ordered-map-submapp (and (equal x 'x) (equal y 'y))))
(%autoprove ordered-map-submapp-of-cons-and-cons
(%restrict default ordered-map-submapp (and (or (equal x '(cons a x))
(equal x '(cons b x)))
(or (equal y '(cons a y))
(equal y '(cons b y))))))
(%autoprove booleanp-of-ordered-map-submapp
(%autoinduct ordered-map-submapp x y))
(%autoprove lemma-1-for-ordered-map-submapp-property)
(%autoprove lemma-2-for-ordered-map-submapp-property
(%enable default submapp))
(%autoprove lemma-3-for-ordered-map-submapp-property
(%disable default equal-of-lookups-when-submapp)
(%use (%instance (%thm equal-of-lookups-when-submapp)
(x x)
(y y)
(a (car (car x))))))
(%autoprove lemma-4-for-ordered-map-submapp-property-aux
(%autoinduct submapp1 dom x y)
(%restrict default submapp1 (equal domain 'dom)))
(%autoprove lemma-4-for-ordered-map-submapp-property
(%enable default
lemma-4-for-ordered-map-submapp-property-aux
lemma-for-uniquep-when-ordered-mapp
submapp))
(%autoprove lemma-5-for-ordered-map-submapp-property
(%disable default lemma-for-uniquep-when-ordered-mapp)
(%use (%instance (%thm lemma-for-uniquep-when-ordered-mapp)
(a (first (first x)))
(x y))))
(%autoprove lemma-6-for-ordered-map-submapp-property
(%disable default equal-of-lookups-when-submapp)
(%use (%instance (%thm equal-of-lookups-when-submapp)
(a (first (first x)))
(x x)
(y y)))
(%auto :strategy (cleanup split urewrite crewrite))
(%restrict default lookup (or (equal x 'x) (equal y 'y))))
(%autoprove lemma-7-for-ordered-map-submapp-property-aux
(%autoinduct submapp1 dom x y)
(%restrict default submapp1 (equal domain 'dom)))
(%autoprove lemma-7-for-ordered-map-submapp-property
(%enable default
submapp
lemma-for-uniquep-when-ordered-mapp)
(%use (%instance (%thm lemma-7-for-ordered-map-submapp-property-aux)
(dom (domain x)))))
(%autoprove ordered-map-submapp-property
(%autoinduct ordered-map-submapp x y)
(%enable default lemma-for-uniquep-when-ordered-mapp
lemma-1-for-ordered-map-submapp-property
lemma-2-for-ordered-map-submapp-property
lemma-3-for-ordered-map-submapp-property
lemma-4-for-ordered-map-submapp-property
lemma-5-for-ordered-map-submapp-property
lemma-6-for-ordered-map-submapp-property
lemma-7-for-ordered-map-submapp-property))
(%autoprove lemma-for-ordered-listp-when-ordered-mapp
(%restrict default << (and (equal x 'a) (equal y 'b))))
(%autoprove ordered-listp-when-ordered-mapp
(%cdr-induction x)
(%enable default lemma-for-ordered-listp-when-ordered-mapp))
(%autoprove ordered-listp-of-mergesort-map)
(%ensure-exactly-these-rules-are-missing "../../../utilities/mergesort")
|
[
{
"context": ";;; (C) Copyright 1990 - 2014 by Wade L. Hennessey. All rights reserved.\n\n;;; -*- Mode:LISP; Synta",
"end": 50,
"score": 0.9998804330825806,
"start": 33,
"tag": "NAME",
"value": "Wade L. Hennessey"
},
{
"context": "elease 6.1 (803). This conversion was\n;;; made by Glenn Burke (one of the original author/maintainers); the\n;;",
"end": 904,
"score": 0.9998965263366699,
"start": 893,
"tag": "NAME",
"value": "Glenn Burke"
},
{
"context": "\"redesigned\".\n;;; Report bugs and propose fixes to [email protected];\n;;; announcements about LOOP will be made to the",
"end": 1814,
"score": 0.9999083876609802,
"start": 1791,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "ts about LOOP will be made to the mailing list\n;;; [email protected]. Mail concerning those lists (such as requests\n;",
"end": 1906,
"score": 0.999906599521637,
"start": 1882,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "-------------------------------------------\n\n;;; [[email protected]] 9-july-87 In define-loop-macro moved\n;;; &enviro",
"end": 3486,
"score": 0.9999274015426636,
"start": 3459,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
src/cl/decls/loop.lisp
|
wadehennessey/wcl
| 73 |
;;; (C) Copyright 1990 - 2014 by Wade L. Hennessey. All rights reserved.
;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:LOOP; Base:10; Lowercase:T -*-
;;; *************************************************************************
;;; ******* Common Lisp ******** LOOP Iteration Macro ***********************
;;; *************************************************************************
;;; ***** (C) COPYRIGHT 1980, 1981 MASSACHUSETTS INSTITUTE OF TECHNOLOGY ****
;;; ********* THIS IS A READ-ONLY FILE! (ALL WRITES RESERVED) ***************
;;; *************************************************************************
;;;; LOOP Iteration Macro
;;; This is the "officially sanctioned" version of LOOP for running in
;;; Common Lisp. It is a conversion of LOOP 829, which is fairly close to
;;; that released with Symbolics Release 6.1 (803). This conversion was
;;; made by Glenn Burke (one of the original author/maintainers); the
;;; work was performed at Palladian Software, in Cambridge MA, April 1986.
;;;
;;; The current version of this file will be maintained at MIT, available
;;; for anonymous FTP on MC.LCS.MIT.EDU from the file "LSB1;CLLOOP >". This
;;; location will no doubt change sometime in the future.
;;;
;;; This file was actually taken from ai.ai.mit.edu:gsb;clloop >
;;;
;;; This file, like the LOOP it is derived from, has unrestricted
;;; distribution -- anyone may take it and use it. But for the sake of
;;; consistency, bug reporting, compatibility, and users' sanity, PLEASE
;;; PLEASE PLEASE don't go overboard with fixes or changes. Remember that
;;; this version is supposed to be compatible with the Maclisp/Zetalisp/NIL
;;; LOOP; it is NOT intended to be "different" or "better" or "redesigned".
;;; Report bugs and propose fixes to [email protected];
;;; announcements about LOOP will be made to the mailing list
;;; [email protected]. Mail concerning those lists (such as requests
;;; to be added) should be sent to the BUG-LOOP-REQUEST and
;;; INFO-LOOP-REQUEST lists respectively. Note the Change History page
;;; below...
;;;
;;; LOOP documentation is still probably available from the MIT Laboratory
;;; for Computer Science publications office:
;;; LCS Publications
;;; 545 Technology Square
;;; Cambridge, MA 02139
;;; It is Technical Memo 169, "LOOP Iteration Macro", and is very old. The
;;; most up-to-date documentation on this version of LOOP is that in the NIL
;;; Reference Manual (TR-311 from LCS Publications); while you wouldn't
;;; want to get that (it costs nearly $15) just for LOOP documentation,
;;; those with access to a NIL manual might photocopy the chapter on LOOP.
;;; That revised documentation can be reissued as a revised technical memo
;;; if there is sufficient demand.
;;;
;;;; Change History
;;; [gsb@palladian] 30-apr-86 00:26 File Created from NIL's LOOP version 829
;;; [gsb@palladian] 30-oct-86 18:23 don't generate (type notype var) decls, special-case notype into T.
;;; (The NOTYPE type keyword needs to be around for compatibility.)
;;; [gsb@palladian] 30-oct-86 18:48 bogus case clause in loop-do-collect. Syntax:common-lisp in file
;;; attribute list, for symbolics gratuitousness.
;;;------------------------------------------------------------------------
;;;------- End of official change history -- note local fixes below -------
;;;------------------------------------------------------------------------
;;; [[email protected]] 9-july-87 In define-loop-macro moved
;;; &environment and its formal to right after &whole to overcome bug
;;; in KCL.
;;;; Macro Environment Setup
; Hack up the stuff for data-types. DATA-TYPE? will always be a macro
; so that it will not require the data-type package at run time if
; all uses of the other routines are conditionalized upon that value.
;;; HEY! ZAPPED: (eval-when (eval compile)
; Crock for DATA-TYPE? derives from DTDCL. We just copy it rather
; than load it in, which requires knowing where it comes from (sigh).
;
(defmacro data-type? (frob)
(let ((foo (gensym)))
`((lambda (,foo)
;; NIL croaks if nil given to GET... No it doesn't any more! But:
;; Every Lisp should (but doesn't) croak if randomness given to GET
;; LISPM croaks (of course) if randomness given to get-pname
(and (symbolp ,foo)
(or (get ,foo ':data-type)
(and (setq ,foo (find-symbol (symbol-name ,foo) 'keyword))
(get ,foo ':data-type)))))
,frob)))
;;; The uses of this macro are retained in the CL version of loop, in case they are
;;; needed in a particular implementation. Originally dating from the use of the
;;; Zetalisp COPYLIST* function, this is used in situations where, were cdr-coding
;;; in use, having cdr-NIL at the end of the list might be suboptimal because the
;;; end of the list will probably be RPLACDed and so cdr-normal should be used instead.
(defmacro loop-copylist* (l)
`(copy-list ,l))
;;;; Random Macros
(defmacro loop-simple-error (unquoted-message &optional (datum nil datump))
`(error ,(if datump "Loop error - ~A: ~A" "LOOP: ~A")
',unquoted-message ,@(and datump (list datum))))
(defmacro loop-warn (unquoted-message &optional (datum nil datump))
(if datump
`(warn ,(concatenate 'string "LOOP: " unquoted-message " -- ~{~S~^ ~}")
,datum)
`(warn ',(concatenate 'string "LOOP: " unquoted-message))))
(defmacro loop-pop-source () '(pop loop-source-code))
(defmacro loop-gentemp (&optional (pref ''loopvar-))
`(gensym (symbol-name ,pref)))
(defvar loop-use-system-destructuring?
nil)
(defvar loop-desetq-temporary)
; Do we want this??? It is, admittedly, useful...
;(defmacro loop-desetq (&rest x)
; (let ((loop-desetq-temporary nil))
; (let ((setq-form (loop-make-desetq x)))
; (if loop-desetq-temporary
; `((lambda (,loop-desetq-temporary) ,setq-form) nil)
; setq-form))))
(defparameter loop-keyword-alist ;clause introducers
'( (named loop-do-named)
(initially loop-do-initially)
(finally loop-do-finally)
(nodeclare loop-nodeclare)
(do loop-do-do)
(doing loop-do-do)
(return loop-do-return)
(collect loop-do-collect list)
(collecting loop-do-collect list)
(append loop-do-collect append)
(appending loop-do-collect append)
(nconc loop-do-collect nconc)
(nconcing loop-do-collect nconc)
(count loop-do-collect count)
(counting loop-do-collect count)
(sum loop-do-collect sum)
(summing loop-do-collect sum)
(maximize loop-do-collect max)
(minimize loop-do-collect min)
(always loop-do-always nil) ;Normal, do always
(never loop-do-always t) ; Negate the test on always.
(thereis loop-do-thereis)
(while loop-do-while nil while) ; Normal, do while
(until loop-do-while t until) ; Negate the test on while
(when loop-do-when nil when) ; Normal, do when
(if loop-do-when nil if) ; synonymous
(unless loop-do-when t unless) ; Negate the test on when
(with loop-do-with)))
(defparameter loop-iteration-keyword-alist
`((for loop-do-for)
(as loop-do-for)
(repeat loop-do-repeat)))
(defparameter loop-for-keyword-alist ;Types of FOR
'( (= loop-for-equals)
(first loop-for-first)
(in loop-list-stepper car)
(on loop-list-stepper nil)
(from loop-for-arithmetic from)
(downfrom loop-for-arithmetic downfrom)
(upfrom loop-for-arithmetic upfrom)
(below loop-for-arithmetic below)
(to loop-for-arithmetic to)
(being loop-for-being)))
(defvar loop-prog-names)
(defvar loop-macro-environment) ;Second arg to macro functions,
;passed to macroexpand.
(defvar loop-path-keyword-alist nil) ; PATH functions
(defvar loop-named-variables) ; see LOOP-NAMED-VARIABLE
(defvar loop-variables) ;Variables local to the loop
(defvar loop-declarations) ; Local dcls for above
(defvar loop-nodeclare) ; but don't declare these
(defvar loop-variable-stack)
(defvar loop-declaration-stack)
(defvar loop-desetq-crocks) ; see loop-make-variable
(defvar loop-desetq-stack) ; and loop-translate-1
(defvar loop-prologue) ;List of forms in reverse order
(defvar loop-wrappers) ;List of wrapping forms, innermost first
(defvar loop-before-loop)
(defvar loop-body) ;..
(defvar loop-after-body) ;.. for FOR steppers
(defvar loop-epilogue) ;..
(defvar loop-after-epilogue) ;So COLLECT's RETURN comes after FINALLY
(defvar loop-conditionals) ;If non-NIL, condition for next form in body
;The above is actually a list of entries of the form
;(cond (condition forms...))
;When it is output, each successive condition will get
;nested inside the previous one, but it is not built up
;that way because you wouldn't be able to tell a WHEN-generated
;COND from a user-generated COND.
;When ELSE is used, each cond can get a second clause
(defvar loop-when-it-variable) ;See LOOP-DO-WHEN
(defvar loop-never-stepped-variable) ; see LOOP-FOR-FIRST
(defvar loop-emitted-body?) ; see LOOP-EMIT-BODY,
; and LOOP-DO-FOR
(defvar loop-iteration-variables) ; LOOP-MAKE-ITERATION-VARIABLE
(defvar loop-iteration-variablep) ; ditto
(defvar loop-collect-cruft) ; for multiple COLLECTs (etc)
(defvar loop-source-code)
(defvar loop-duplicate-code nil) ; see LOOP-OPTIMIZE-DUPLICATED-CODE-ETC
(defmacro define-loop-macro (keyword)
"Makes KEYWORD, which is a LOOP keyword, into a Lisp macro that may
introduce a LOOP form. This facility exists mostly for diehard users of
a predecessor of LOOP. Unconstrained use is not advised, as it tends to
decrease the transportability of the code and needlessly uses up a
function name."
(or (eq keyword 'loop)
(loop-tassoc keyword loop-keyword-alist)
(loop-tassoc keyword loop-iteration-keyword-alist)
(loop-simple-error "not a loop keyword - define-loop-macro" keyword))
`(defmacro ,keyword (&whole whole-form &environment env &rest keywords-and-forms)
;; W can't hack this declare yet...
;; (declare (ignore keywords-and-forms))
(loop-translate whole-form env)))
(define-loop-macro loop)
(defmacro loop-finish ()
"Causes the iteration to terminate \"normally\", the same as implicit
termination by an iteration driving clause, or by use of WHILE or
UNTIL -- the epilogue code (if any) will be run, and any implicitly
collected result will be returned as the value of the LOOP."
'(go end-loop))
(defvar loop-floating-point-types
'(flonum float short-float single-float double-float long-float))
(defvar loop-simplep
'(> < <= >= /= + - 1+ 1- ash equal atom setq prog1 prog2 and or = aref char schar sbit svref))
(defmacro define-loop-path (names &rest cruft)
"(DEFINE-LOOP-PATH NAMES PATH-FUNCTION LIST-OF-ALLOWABLE-PREPOSITIONS
DATUM-1 DATUM-2 ...)
Defines PATH-FUNCTION to be the handler for the path(s) NAMES, which may
be either a symbol or a list of symbols. LIST-OF-ALLOWABLE-PREPOSITIONS
contains a list of prepositions allowed in NAMES. DATUM-i are optional;
they are passed on to PATH-FUNCTION as a list."
(setq names (if (atom names) (list names) names))
(let ((forms (mapcar #'(lambda (name) `(loop-add-path ',name ',cruft))
names)))
`(eval-when (eval load compile) ,@forms)))
(defmacro define-loop-sequence-path (path-name-or-names fetchfun sizefun
&optional sequence-type element-type)
"Defines a sequence iiteration path. PATH-NAME-OR-NAMES is either an
atomic path name or a list of path names. FETCHFUN is a function of
two arguments, the sequence and the index of the item to be fetched.
Indexing is assumed to be zero-origined. SIZEFUN is a function of
one argument, the sequence; it should return the number of elements in
the sequence. SEQUENCE-TYPE is the name of the data-type of the
sequence, and ELEMENT-TYPE is the name of the data-type of the elements
of the sequence."
`(define-loop-path ,path-name-or-names
loop-sequence-elements-path
(of in from downfrom to downto below above by)
,fetchfun ,sizefun ,sequence-type ,element-type))
;;;; Setup stuff
(mapc #'(lambda (x)
(mapc #'(lambda (y)
(setq loop-path-keyword-alist
(cons `(,y loop-sequence-elements-path
(of in from downfrom to downto
below above by)
,@(cdr x))
(delete (loop-tassoc
y loop-path-keyword-alist)
loop-path-keyword-alist
:test #'eq :count 1))))
(car x)))
'( ((element elements) elt length sequence)
;The following should be done by using ELEMENTS and type dcls...
((vector-element
vector-elements
array-element ;; Backwards compatibility -- DRM
array-elements)
aref length vector)
((simple-vector-element simple-vector-elements
simple-general-vector-element simple-general-vector-elements)
svref simple-vector-length simple-vector)
((bits bit bit-vector-element bit-vector-elements)
bit bit-vector-length bit-vector bit)
((simple-bit-vector-element simple-bit-vector-elements)
sbit simple-bit-vector-length simple-bit-vector bit)
((character characters string-element string-elements)
char string-length string string-char)
((simple-string-element simple-string-elements)
schar simple-string-length simple-string string-char)
)
)
|
8779
|
;;; (C) Copyright 1990 - 2014 by <NAME>. All rights reserved.
;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:LOOP; Base:10; Lowercase:T -*-
;;; *************************************************************************
;;; ******* Common Lisp ******** LOOP Iteration Macro ***********************
;;; *************************************************************************
;;; ***** (C) COPYRIGHT 1980, 1981 MASSACHUSETTS INSTITUTE OF TECHNOLOGY ****
;;; ********* THIS IS A READ-ONLY FILE! (ALL WRITES RESERVED) ***************
;;; *************************************************************************
;;;; LOOP Iteration Macro
;;; This is the "officially sanctioned" version of LOOP for running in
;;; Common Lisp. It is a conversion of LOOP 829, which is fairly close to
;;; that released with Symbolics Release 6.1 (803). This conversion was
;;; made by <NAME> (one of the original author/maintainers); the
;;; work was performed at Palladian Software, in Cambridge MA, April 1986.
;;;
;;; The current version of this file will be maintained at MIT, available
;;; for anonymous FTP on MC.LCS.MIT.EDU from the file "LSB1;CLLOOP >". This
;;; location will no doubt change sometime in the future.
;;;
;;; This file was actually taken from ai.ai.mit.edu:gsb;clloop >
;;;
;;; This file, like the LOOP it is derived from, has unrestricted
;;; distribution -- anyone may take it and use it. But for the sake of
;;; consistency, bug reporting, compatibility, and users' sanity, PLEASE
;;; PLEASE PLEASE don't go overboard with fixes or changes. Remember that
;;; this version is supposed to be compatible with the Maclisp/Zetalisp/NIL
;;; LOOP; it is NOT intended to be "different" or "better" or "redesigned".
;;; Report bugs and propose fixes to <EMAIL>;
;;; announcements about LOOP will be made to the mailing list
;;; <EMAIL>. Mail concerning those lists (such as requests
;;; to be added) should be sent to the BUG-LOOP-REQUEST and
;;; INFO-LOOP-REQUEST lists respectively. Note the Change History page
;;; below...
;;;
;;; LOOP documentation is still probably available from the MIT Laboratory
;;; for Computer Science publications office:
;;; LCS Publications
;;; 545 Technology Square
;;; Cambridge, MA 02139
;;; It is Technical Memo 169, "LOOP Iteration Macro", and is very old. The
;;; most up-to-date documentation on this version of LOOP is that in the NIL
;;; Reference Manual (TR-311 from LCS Publications); while you wouldn't
;;; want to get that (it costs nearly $15) just for LOOP documentation,
;;; those with access to a NIL manual might photocopy the chapter on LOOP.
;;; That revised documentation can be reissued as a revised technical memo
;;; if there is sufficient demand.
;;;
;;;; Change History
;;; [gsb@palladian] 30-apr-86 00:26 File Created from NIL's LOOP version 829
;;; [gsb@palladian] 30-oct-86 18:23 don't generate (type notype var) decls, special-case notype into T.
;;; (The NOTYPE type keyword needs to be around for compatibility.)
;;; [gsb@palladian] 30-oct-86 18:48 bogus case clause in loop-do-collect. Syntax:common-lisp in file
;;; attribute list, for symbolics gratuitousness.
;;;------------------------------------------------------------------------
;;;------- End of official change history -- note local fixes below -------
;;;------------------------------------------------------------------------
;;; [<EMAIL>] 9-july-87 In define-loop-macro moved
;;; &environment and its formal to right after &whole to overcome bug
;;; in KCL.
;;;; Macro Environment Setup
; Hack up the stuff for data-types. DATA-TYPE? will always be a macro
; so that it will not require the data-type package at run time if
; all uses of the other routines are conditionalized upon that value.
;;; HEY! ZAPPED: (eval-when (eval compile)
; Crock for DATA-TYPE? derives from DTDCL. We just copy it rather
; than load it in, which requires knowing where it comes from (sigh).
;
(defmacro data-type? (frob)
(let ((foo (gensym)))
`((lambda (,foo)
;; NIL croaks if nil given to GET... No it doesn't any more! But:
;; Every Lisp should (but doesn't) croak if randomness given to GET
;; LISPM croaks (of course) if randomness given to get-pname
(and (symbolp ,foo)
(or (get ,foo ':data-type)
(and (setq ,foo (find-symbol (symbol-name ,foo) 'keyword))
(get ,foo ':data-type)))))
,frob)))
;;; The uses of this macro are retained in the CL version of loop, in case they are
;;; needed in a particular implementation. Originally dating from the use of the
;;; Zetalisp COPYLIST* function, this is used in situations where, were cdr-coding
;;; in use, having cdr-NIL at the end of the list might be suboptimal because the
;;; end of the list will probably be RPLACDed and so cdr-normal should be used instead.
(defmacro loop-copylist* (l)
`(copy-list ,l))
;;;; Random Macros
(defmacro loop-simple-error (unquoted-message &optional (datum nil datump))
`(error ,(if datump "Loop error - ~A: ~A" "LOOP: ~A")
',unquoted-message ,@(and datump (list datum))))
(defmacro loop-warn (unquoted-message &optional (datum nil datump))
(if datump
`(warn ,(concatenate 'string "LOOP: " unquoted-message " -- ~{~S~^ ~}")
,datum)
`(warn ',(concatenate 'string "LOOP: " unquoted-message))))
(defmacro loop-pop-source () '(pop loop-source-code))
(defmacro loop-gentemp (&optional (pref ''loopvar-))
`(gensym (symbol-name ,pref)))
(defvar loop-use-system-destructuring?
nil)
(defvar loop-desetq-temporary)
; Do we want this??? It is, admittedly, useful...
;(defmacro loop-desetq (&rest x)
; (let ((loop-desetq-temporary nil))
; (let ((setq-form (loop-make-desetq x)))
; (if loop-desetq-temporary
; `((lambda (,loop-desetq-temporary) ,setq-form) nil)
; setq-form))))
(defparameter loop-keyword-alist ;clause introducers
'( (named loop-do-named)
(initially loop-do-initially)
(finally loop-do-finally)
(nodeclare loop-nodeclare)
(do loop-do-do)
(doing loop-do-do)
(return loop-do-return)
(collect loop-do-collect list)
(collecting loop-do-collect list)
(append loop-do-collect append)
(appending loop-do-collect append)
(nconc loop-do-collect nconc)
(nconcing loop-do-collect nconc)
(count loop-do-collect count)
(counting loop-do-collect count)
(sum loop-do-collect sum)
(summing loop-do-collect sum)
(maximize loop-do-collect max)
(minimize loop-do-collect min)
(always loop-do-always nil) ;Normal, do always
(never loop-do-always t) ; Negate the test on always.
(thereis loop-do-thereis)
(while loop-do-while nil while) ; Normal, do while
(until loop-do-while t until) ; Negate the test on while
(when loop-do-when nil when) ; Normal, do when
(if loop-do-when nil if) ; synonymous
(unless loop-do-when t unless) ; Negate the test on when
(with loop-do-with)))
(defparameter loop-iteration-keyword-alist
`((for loop-do-for)
(as loop-do-for)
(repeat loop-do-repeat)))
(defparameter loop-for-keyword-alist ;Types of FOR
'( (= loop-for-equals)
(first loop-for-first)
(in loop-list-stepper car)
(on loop-list-stepper nil)
(from loop-for-arithmetic from)
(downfrom loop-for-arithmetic downfrom)
(upfrom loop-for-arithmetic upfrom)
(below loop-for-arithmetic below)
(to loop-for-arithmetic to)
(being loop-for-being)))
(defvar loop-prog-names)
(defvar loop-macro-environment) ;Second arg to macro functions,
;passed to macroexpand.
(defvar loop-path-keyword-alist nil) ; PATH functions
(defvar loop-named-variables) ; see LOOP-NAMED-VARIABLE
(defvar loop-variables) ;Variables local to the loop
(defvar loop-declarations) ; Local dcls for above
(defvar loop-nodeclare) ; but don't declare these
(defvar loop-variable-stack)
(defvar loop-declaration-stack)
(defvar loop-desetq-crocks) ; see loop-make-variable
(defvar loop-desetq-stack) ; and loop-translate-1
(defvar loop-prologue) ;List of forms in reverse order
(defvar loop-wrappers) ;List of wrapping forms, innermost first
(defvar loop-before-loop)
(defvar loop-body) ;..
(defvar loop-after-body) ;.. for FOR steppers
(defvar loop-epilogue) ;..
(defvar loop-after-epilogue) ;So COLLECT's RETURN comes after FINALLY
(defvar loop-conditionals) ;If non-NIL, condition for next form in body
;The above is actually a list of entries of the form
;(cond (condition forms...))
;When it is output, each successive condition will get
;nested inside the previous one, but it is not built up
;that way because you wouldn't be able to tell a WHEN-generated
;COND from a user-generated COND.
;When ELSE is used, each cond can get a second clause
(defvar loop-when-it-variable) ;See LOOP-DO-WHEN
(defvar loop-never-stepped-variable) ; see LOOP-FOR-FIRST
(defvar loop-emitted-body?) ; see LOOP-EMIT-BODY,
; and LOOP-DO-FOR
(defvar loop-iteration-variables) ; LOOP-MAKE-ITERATION-VARIABLE
(defvar loop-iteration-variablep) ; ditto
(defvar loop-collect-cruft) ; for multiple COLLECTs (etc)
(defvar loop-source-code)
(defvar loop-duplicate-code nil) ; see LOOP-OPTIMIZE-DUPLICATED-CODE-ETC
(defmacro define-loop-macro (keyword)
"Makes KEYWORD, which is a LOOP keyword, into a Lisp macro that may
introduce a LOOP form. This facility exists mostly for diehard users of
a predecessor of LOOP. Unconstrained use is not advised, as it tends to
decrease the transportability of the code and needlessly uses up a
function name."
(or (eq keyword 'loop)
(loop-tassoc keyword loop-keyword-alist)
(loop-tassoc keyword loop-iteration-keyword-alist)
(loop-simple-error "not a loop keyword - define-loop-macro" keyword))
`(defmacro ,keyword (&whole whole-form &environment env &rest keywords-and-forms)
;; W can't hack this declare yet...
;; (declare (ignore keywords-and-forms))
(loop-translate whole-form env)))
(define-loop-macro loop)
(defmacro loop-finish ()
"Causes the iteration to terminate \"normally\", the same as implicit
termination by an iteration driving clause, or by use of WHILE or
UNTIL -- the epilogue code (if any) will be run, and any implicitly
collected result will be returned as the value of the LOOP."
'(go end-loop))
(defvar loop-floating-point-types
'(flonum float short-float single-float double-float long-float))
(defvar loop-simplep
'(> < <= >= /= + - 1+ 1- ash equal atom setq prog1 prog2 and or = aref char schar sbit svref))
(defmacro define-loop-path (names &rest cruft)
"(DEFINE-LOOP-PATH NAMES PATH-FUNCTION LIST-OF-ALLOWABLE-PREPOSITIONS
DATUM-1 DATUM-2 ...)
Defines PATH-FUNCTION to be the handler for the path(s) NAMES, which may
be either a symbol or a list of symbols. LIST-OF-ALLOWABLE-PREPOSITIONS
contains a list of prepositions allowed in NAMES. DATUM-i are optional;
they are passed on to PATH-FUNCTION as a list."
(setq names (if (atom names) (list names) names))
(let ((forms (mapcar #'(lambda (name) `(loop-add-path ',name ',cruft))
names)))
`(eval-when (eval load compile) ,@forms)))
(defmacro define-loop-sequence-path (path-name-or-names fetchfun sizefun
&optional sequence-type element-type)
"Defines a sequence iiteration path. PATH-NAME-OR-NAMES is either an
atomic path name or a list of path names. FETCHFUN is a function of
two arguments, the sequence and the index of the item to be fetched.
Indexing is assumed to be zero-origined. SIZEFUN is a function of
one argument, the sequence; it should return the number of elements in
the sequence. SEQUENCE-TYPE is the name of the data-type of the
sequence, and ELEMENT-TYPE is the name of the data-type of the elements
of the sequence."
`(define-loop-path ,path-name-or-names
loop-sequence-elements-path
(of in from downfrom to downto below above by)
,fetchfun ,sizefun ,sequence-type ,element-type))
;;;; Setup stuff
(mapc #'(lambda (x)
(mapc #'(lambda (y)
(setq loop-path-keyword-alist
(cons `(,y loop-sequence-elements-path
(of in from downfrom to downto
below above by)
,@(cdr x))
(delete (loop-tassoc
y loop-path-keyword-alist)
loop-path-keyword-alist
:test #'eq :count 1))))
(car x)))
'( ((element elements) elt length sequence)
;The following should be done by using ELEMENTS and type dcls...
((vector-element
vector-elements
array-element ;; Backwards compatibility -- DRM
array-elements)
aref length vector)
((simple-vector-element simple-vector-elements
simple-general-vector-element simple-general-vector-elements)
svref simple-vector-length simple-vector)
((bits bit bit-vector-element bit-vector-elements)
bit bit-vector-length bit-vector bit)
((simple-bit-vector-element simple-bit-vector-elements)
sbit simple-bit-vector-length simple-bit-vector bit)
((character characters string-element string-elements)
char string-length string string-char)
((simple-string-element simple-string-elements)
schar simple-string-length simple-string string-char)
)
)
| true |
;;; (C) Copyright 1990 - 2014 by PI:NAME:<NAME>END_PI. All rights reserved.
;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:LOOP; Base:10; Lowercase:T -*-
;;; *************************************************************************
;;; ******* Common Lisp ******** LOOP Iteration Macro ***********************
;;; *************************************************************************
;;; ***** (C) COPYRIGHT 1980, 1981 MASSACHUSETTS INSTITUTE OF TECHNOLOGY ****
;;; ********* THIS IS A READ-ONLY FILE! (ALL WRITES RESERVED) ***************
;;; *************************************************************************
;;;; LOOP Iteration Macro
;;; This is the "officially sanctioned" version of LOOP for running in
;;; Common Lisp. It is a conversion of LOOP 829, which is fairly close to
;;; that released with Symbolics Release 6.1 (803). This conversion was
;;; made by PI:NAME:<NAME>END_PI (one of the original author/maintainers); the
;;; work was performed at Palladian Software, in Cambridge MA, April 1986.
;;;
;;; The current version of this file will be maintained at MIT, available
;;; for anonymous FTP on MC.LCS.MIT.EDU from the file "LSB1;CLLOOP >". This
;;; location will no doubt change sometime in the future.
;;;
;;; This file was actually taken from ai.ai.mit.edu:gsb;clloop >
;;;
;;; This file, like the LOOP it is derived from, has unrestricted
;;; distribution -- anyone may take it and use it. But for the sake of
;;; consistency, bug reporting, compatibility, and users' sanity, PLEASE
;;; PLEASE PLEASE don't go overboard with fixes or changes. Remember that
;;; this version is supposed to be compatible with the Maclisp/Zetalisp/NIL
;;; LOOP; it is NOT intended to be "different" or "better" or "redesigned".
;;; Report bugs and propose fixes to PI:EMAIL:<EMAIL>END_PI;
;;; announcements about LOOP will be made to the mailing list
;;; PI:EMAIL:<EMAIL>END_PI. Mail concerning those lists (such as requests
;;; to be added) should be sent to the BUG-LOOP-REQUEST and
;;; INFO-LOOP-REQUEST lists respectively. Note the Change History page
;;; below...
;;;
;;; LOOP documentation is still probably available from the MIT Laboratory
;;; for Computer Science publications office:
;;; LCS Publications
;;; 545 Technology Square
;;; Cambridge, MA 02139
;;; It is Technical Memo 169, "LOOP Iteration Macro", and is very old. The
;;; most up-to-date documentation on this version of LOOP is that in the NIL
;;; Reference Manual (TR-311 from LCS Publications); while you wouldn't
;;; want to get that (it costs nearly $15) just for LOOP documentation,
;;; those with access to a NIL manual might photocopy the chapter on LOOP.
;;; That revised documentation can be reissued as a revised technical memo
;;; if there is sufficient demand.
;;;
;;;; Change History
;;; [gsb@palladian] 30-apr-86 00:26 File Created from NIL's LOOP version 829
;;; [gsb@palladian] 30-oct-86 18:23 don't generate (type notype var) decls, special-case notype into T.
;;; (The NOTYPE type keyword needs to be around for compatibility.)
;;; [gsb@palladian] 30-oct-86 18:48 bogus case clause in loop-do-collect. Syntax:common-lisp in file
;;; attribute list, for symbolics gratuitousness.
;;;------------------------------------------------------------------------
;;;------- End of official change history -- note local fixes below -------
;;;------------------------------------------------------------------------
;;; [PI:EMAIL:<EMAIL>END_PI] 9-july-87 In define-loop-macro moved
;;; &environment and its formal to right after &whole to overcome bug
;;; in KCL.
;;;; Macro Environment Setup
; Hack up the stuff for data-types. DATA-TYPE? will always be a macro
; so that it will not require the data-type package at run time if
; all uses of the other routines are conditionalized upon that value.
;;; HEY! ZAPPED: (eval-when (eval compile)
; Crock for DATA-TYPE? derives from DTDCL. We just copy it rather
; than load it in, which requires knowing where it comes from (sigh).
;
(defmacro data-type? (frob)
(let ((foo (gensym)))
`((lambda (,foo)
;; NIL croaks if nil given to GET... No it doesn't any more! But:
;; Every Lisp should (but doesn't) croak if randomness given to GET
;; LISPM croaks (of course) if randomness given to get-pname
(and (symbolp ,foo)
(or (get ,foo ':data-type)
(and (setq ,foo (find-symbol (symbol-name ,foo) 'keyword))
(get ,foo ':data-type)))))
,frob)))
;;; The uses of this macro are retained in the CL version of loop, in case they are
;;; needed in a particular implementation. Originally dating from the use of the
;;; Zetalisp COPYLIST* function, this is used in situations where, were cdr-coding
;;; in use, having cdr-NIL at the end of the list might be suboptimal because the
;;; end of the list will probably be RPLACDed and so cdr-normal should be used instead.
(defmacro loop-copylist* (l)
`(copy-list ,l))
;;;; Random Macros
(defmacro loop-simple-error (unquoted-message &optional (datum nil datump))
`(error ,(if datump "Loop error - ~A: ~A" "LOOP: ~A")
',unquoted-message ,@(and datump (list datum))))
(defmacro loop-warn (unquoted-message &optional (datum nil datump))
(if datump
`(warn ,(concatenate 'string "LOOP: " unquoted-message " -- ~{~S~^ ~}")
,datum)
`(warn ',(concatenate 'string "LOOP: " unquoted-message))))
(defmacro loop-pop-source () '(pop loop-source-code))
(defmacro loop-gentemp (&optional (pref ''loopvar-))
`(gensym (symbol-name ,pref)))
(defvar loop-use-system-destructuring?
nil)
(defvar loop-desetq-temporary)
; Do we want this??? It is, admittedly, useful...
;(defmacro loop-desetq (&rest x)
; (let ((loop-desetq-temporary nil))
; (let ((setq-form (loop-make-desetq x)))
; (if loop-desetq-temporary
; `((lambda (,loop-desetq-temporary) ,setq-form) nil)
; setq-form))))
(defparameter loop-keyword-alist ;clause introducers
'( (named loop-do-named)
(initially loop-do-initially)
(finally loop-do-finally)
(nodeclare loop-nodeclare)
(do loop-do-do)
(doing loop-do-do)
(return loop-do-return)
(collect loop-do-collect list)
(collecting loop-do-collect list)
(append loop-do-collect append)
(appending loop-do-collect append)
(nconc loop-do-collect nconc)
(nconcing loop-do-collect nconc)
(count loop-do-collect count)
(counting loop-do-collect count)
(sum loop-do-collect sum)
(summing loop-do-collect sum)
(maximize loop-do-collect max)
(minimize loop-do-collect min)
(always loop-do-always nil) ;Normal, do always
(never loop-do-always t) ; Negate the test on always.
(thereis loop-do-thereis)
(while loop-do-while nil while) ; Normal, do while
(until loop-do-while t until) ; Negate the test on while
(when loop-do-when nil when) ; Normal, do when
(if loop-do-when nil if) ; synonymous
(unless loop-do-when t unless) ; Negate the test on when
(with loop-do-with)))
(defparameter loop-iteration-keyword-alist
`((for loop-do-for)
(as loop-do-for)
(repeat loop-do-repeat)))
(defparameter loop-for-keyword-alist ;Types of FOR
'( (= loop-for-equals)
(first loop-for-first)
(in loop-list-stepper car)
(on loop-list-stepper nil)
(from loop-for-arithmetic from)
(downfrom loop-for-arithmetic downfrom)
(upfrom loop-for-arithmetic upfrom)
(below loop-for-arithmetic below)
(to loop-for-arithmetic to)
(being loop-for-being)))
(defvar loop-prog-names)
(defvar loop-macro-environment) ;Second arg to macro functions,
;passed to macroexpand.
(defvar loop-path-keyword-alist nil) ; PATH functions
(defvar loop-named-variables) ; see LOOP-NAMED-VARIABLE
(defvar loop-variables) ;Variables local to the loop
(defvar loop-declarations) ; Local dcls for above
(defvar loop-nodeclare) ; but don't declare these
(defvar loop-variable-stack)
(defvar loop-declaration-stack)
(defvar loop-desetq-crocks) ; see loop-make-variable
(defvar loop-desetq-stack) ; and loop-translate-1
(defvar loop-prologue) ;List of forms in reverse order
(defvar loop-wrappers) ;List of wrapping forms, innermost first
(defvar loop-before-loop)
(defvar loop-body) ;..
(defvar loop-after-body) ;.. for FOR steppers
(defvar loop-epilogue) ;..
(defvar loop-after-epilogue) ;So COLLECT's RETURN comes after FINALLY
(defvar loop-conditionals) ;If non-NIL, condition for next form in body
;The above is actually a list of entries of the form
;(cond (condition forms...))
;When it is output, each successive condition will get
;nested inside the previous one, but it is not built up
;that way because you wouldn't be able to tell a WHEN-generated
;COND from a user-generated COND.
;When ELSE is used, each cond can get a second clause
(defvar loop-when-it-variable) ;See LOOP-DO-WHEN
(defvar loop-never-stepped-variable) ; see LOOP-FOR-FIRST
(defvar loop-emitted-body?) ; see LOOP-EMIT-BODY,
; and LOOP-DO-FOR
(defvar loop-iteration-variables) ; LOOP-MAKE-ITERATION-VARIABLE
(defvar loop-iteration-variablep) ; ditto
(defvar loop-collect-cruft) ; for multiple COLLECTs (etc)
(defvar loop-source-code)
(defvar loop-duplicate-code nil) ; see LOOP-OPTIMIZE-DUPLICATED-CODE-ETC
(defmacro define-loop-macro (keyword)
"Makes KEYWORD, which is a LOOP keyword, into a Lisp macro that may
introduce a LOOP form. This facility exists mostly for diehard users of
a predecessor of LOOP. Unconstrained use is not advised, as it tends to
decrease the transportability of the code and needlessly uses up a
function name."
(or (eq keyword 'loop)
(loop-tassoc keyword loop-keyword-alist)
(loop-tassoc keyword loop-iteration-keyword-alist)
(loop-simple-error "not a loop keyword - define-loop-macro" keyword))
`(defmacro ,keyword (&whole whole-form &environment env &rest keywords-and-forms)
;; W can't hack this declare yet...
;; (declare (ignore keywords-and-forms))
(loop-translate whole-form env)))
(define-loop-macro loop)
(defmacro loop-finish ()
"Causes the iteration to terminate \"normally\", the same as implicit
termination by an iteration driving clause, or by use of WHILE or
UNTIL -- the epilogue code (if any) will be run, and any implicitly
collected result will be returned as the value of the LOOP."
'(go end-loop))
(defvar loop-floating-point-types
'(flonum float short-float single-float double-float long-float))
(defvar loop-simplep
'(> < <= >= /= + - 1+ 1- ash equal atom setq prog1 prog2 and or = aref char schar sbit svref))
(defmacro define-loop-path (names &rest cruft)
"(DEFINE-LOOP-PATH NAMES PATH-FUNCTION LIST-OF-ALLOWABLE-PREPOSITIONS
DATUM-1 DATUM-2 ...)
Defines PATH-FUNCTION to be the handler for the path(s) NAMES, which may
be either a symbol or a list of symbols. LIST-OF-ALLOWABLE-PREPOSITIONS
contains a list of prepositions allowed in NAMES. DATUM-i are optional;
they are passed on to PATH-FUNCTION as a list."
(setq names (if (atom names) (list names) names))
(let ((forms (mapcar #'(lambda (name) `(loop-add-path ',name ',cruft))
names)))
`(eval-when (eval load compile) ,@forms)))
(defmacro define-loop-sequence-path (path-name-or-names fetchfun sizefun
&optional sequence-type element-type)
"Defines a sequence iiteration path. PATH-NAME-OR-NAMES is either an
atomic path name or a list of path names. FETCHFUN is a function of
two arguments, the sequence and the index of the item to be fetched.
Indexing is assumed to be zero-origined. SIZEFUN is a function of
one argument, the sequence; it should return the number of elements in
the sequence. SEQUENCE-TYPE is the name of the data-type of the
sequence, and ELEMENT-TYPE is the name of the data-type of the elements
of the sequence."
`(define-loop-path ,path-name-or-names
loop-sequence-elements-path
(of in from downfrom to downto below above by)
,fetchfun ,sizefun ,sequence-type ,element-type))
;;;; Setup stuff
(mapc #'(lambda (x)
(mapc #'(lambda (y)
(setq loop-path-keyword-alist
(cons `(,y loop-sequence-elements-path
(of in from downfrom to downto
below above by)
,@(cdr x))
(delete (loop-tassoc
y loop-path-keyword-alist)
loop-path-keyword-alist
:test #'eq :count 1))))
(car x)))
'( ((element elements) elt length sequence)
;The following should be done by using ELEMENTS and type dcls...
((vector-element
vector-elements
array-element ;; Backwards compatibility -- DRM
array-elements)
aref length vector)
((simple-vector-element simple-vector-elements
simple-general-vector-element simple-general-vector-elements)
svref simple-vector-length simple-vector)
((bits bit bit-vector-element bit-vector-elements)
bit bit-vector-length bit-vector bit)
((simple-bit-vector-element simple-bit-vector-elements)
sbit simple-bit-vector-length simple-bit-vector bit)
((character characters string-element string-elements)
char string-length string string-char)
((simple-string-element simple-string-elements)
schar simple-string-length simple-string string-char)
)
)
|
[
{
"context": "m to the end of a list\n;\n; Copyright (C) 2008-2011 Eric Smith and Stanford University\n; Copyright (C) 2013-2020",
"end": 87,
"score": 0.9996823072433472,
"start": 77,
"tag": "NAME",
"value": "Eric Smith"
},
{
"context": "ense. See the file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;",
"end": 248,
"score": 0.9996085166931152,
"start": 238,
"tag": "NAME",
"value": "Eric Smith"
},
{
"context": " file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 272,
"score": 0.9999339580535889,
"start": 250,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/kestrel/lists-light/add-to-end.lisp
|
mayankmanj/acl2
| 305 |
; A function to add an item to the end of a list
;
; 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")
;; See also the function rcons in std/lists/rcons.
;maybe this should always be expanded?
(defun add-to-end (item lst)
(declare (xargs :guard (true-listp lst)))
(append lst (list item)))
(defthm true-listp-of-add-to-end
(true-listp (add-to-end a x)))
(defthm len-of-add-to-end
(equal (len (add-to-end a x))
(+ 1 (len x)))
:hints (("Goal" :in-theory (enable add-to-end))))
|
67478
|
; A function to add an item to the end of a list
;
; 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")
;; See also the function rcons in std/lists/rcons.
;maybe this should always be expanded?
(defun add-to-end (item lst)
(declare (xargs :guard (true-listp lst)))
(append lst (list item)))
(defthm true-listp-of-add-to-end
(true-listp (add-to-end a x)))
(defthm len-of-add-to-end
(equal (len (add-to-end a x))
(+ 1 (len x)))
:hints (("Goal" :in-theory (enable add-to-end))))
| true |
; A function to add an item to the end of a list
;
; 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")
;; See also the function rcons in std/lists/rcons.
;maybe this should always be expanded?
(defun add-to-end (item lst)
(declare (xargs :guard (true-listp lst)))
(append lst (list item)))
(defthm true-listp-of-add-to-end
(true-listp (add-to-end a x)))
(defthm len-of-add-to-end
(equal (len (add-to-end a x))
(+ 1 (len x)))
:hints (("Goal" :in-theory (enable add-to-end))))
|
[
{
"context": ";;;; armor-up-test.lisp\n;;;; Author: BreakDS <[email protected]>\n;;;;\n;;;; Description: unit t",
"end": 44,
"score": 0.9996047019958496,
"start": 37,
"tag": "USERNAME",
"value": "BreakDS"
},
{
"context": ";;;; armor-up-test.lisp\n;;;; Author: BreakDS <[email protected]>\n;;;;\n;;;; Description: unit tests for armor-up.l",
"end": 63,
"score": 0.999922513961792,
"start": 46,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
lisp/engine/armor-up-test.lisp
|
breakds/monster-avengers
| 30 |
;;;; armor-up-test.lisp
;;;; Author: BreakDS <[email protected]>
;;;;
;;;; Description: unit tests for armor-up.lisp.
(in-package #:breakds.monster-avengers.armor-up-test)
(defsuite* (test-all :in root-suite
:documentation "unit tests for armor-up."))
(deftest (coding-test
:cases (('(1 1 5) '(10 -10 20))
('(1 3 0) '(-12))))
(hole-sig skill-sig)
(let ((n (length skill-sig)))
(multiple-value-bind (hole-sig-result
skill-sig-result)
(decode-sig-full (encode-sig hole-sig skill-sig) n)
(is (equal hole-sig hole-sig-result))
(is (equal skill-sig skill-sig-result)))))
(deftest decode-skill-sig-at-test ()
(let* ((hole-sig '(1 1 5))
(skill-sig '(10 -10 20))
(key (encode-sig hole-sig skill-sig)))
(is (= (decode-skill-sig-at key 0) 10))
(is (= (decode-skill-sig-at key 1) -10))
(is (= (decode-skill-sig-at key 2) 20))))
(deftest (encoded-+-test
:cases (('(1 1 0) '(10 -10 20) '(0 1 1) '(-5 3 -2) '(1 2 1) '(5 -7 18))
('(5 1 1) '(-12 -14) '(3 0 0) '(2 -5) '(8 1 1) '(-10 -19))))
(hole-sig-a skill-sig-a hole-sig-b skill-sig-b hole-sig-+ skill-sig-+)
(is (= (length skill-sig-a)
(length skill-sig-b)
(length skill-sig-+)))
(let ((n (length skill-sig-a)))
(multiple-value-bind (hole-sig-reuslt skill-sig-result)
(decode-sig-full (encoded-+ (encode-sig hole-sig-a skill-sig-a)
(encode-sig hole-sig-b skill-sig-b))
n)
(is (equal hole-sig-reuslt hole-sig-+))
(is (equal skill-sig-result skill-sig-+)))))
(deftest (encoded-skill-+-test
:cases (('(1 1 0) '(10 -10 20) '(0 1 1) '(-5 3 -2) '(0 0 0) '(5 -7 18))
('(5 1 1) '(-12 -14) '(3 0 0) '(2 -5) '(0 0 0) '(-10 -19))))
(hole-sig-a skill-sig-a hole-sig-b skill-sig-b hole-sig-+ skill-sig-+)
(is (= (length skill-sig-a)
(length skill-sig-b)
(length skill-sig-+)))
(let ((n (length skill-sig-a)))
(multiple-value-bind (hole-sig-reuslt skill-sig-result)
(decode-sig-full (encoded-skill-+ (encode-sig hole-sig-a skill-sig-a)
(encode-sig hole-sig-b skill-sig-b))
n)
(is (equal hole-sig-reuslt hole-sig-+))
(is (equal skill-sig-result skill-sig-+)))))
(deftest (replace-skill-key-at-test
:cases ((0 12)
(3 5)
(4 -6)))
(n value)
(let* ((hole-sig '(1 1 5))
(skill-sig '(10 -10 20))
(key (replace-skill-key-at
(encode-sig hole-sig skill-sig)
n value)))
(is (equal (decode-hole-sig key) hole-sig))
(is (= (decode-skill-sig-at key n) value))))
(deftest (is-satisfied-skill-key-test
:cases (('(1 2 1) t)
('(0 0 0 0) t)
('(-1 2 12) nil)
('(0 0 0 -5) nil)))
(skill-sig expected)
(is (eq (is-satisfied-skill-key (encode-skill-sig skill-sig)
(gen-skill-mask (length skill-sig)))
expected)))
(deftest encode-jewel-if-satisfy-test ()
(let ((piece (make-jewel :id 0
:holes 1
:effects '((1 -1) (2 3) (3 5) (4 -5)))))
(is (null (encode-jewel-if-satisfy piece '(5))))
(is (null (encode-jewel-if-satisfy piece '(1 4))))
(is (null (encode-jewel-if-satisfy piece '(1 5))))
(multiple-value-bind (hole-sig-result
skill-sig-result)
(decode-sig-full (encode-jewel-if-satisfy piece '(3 2 1 5)) 4)
(is (equal hole-sig-result '(0 0 0)))
(is (equal skill-sig-result '(5 3 -1 0))))))
;;; Hash table related macros test
(defun hash-table-equal (hash-table-obj assoc-list)
(and (= (hash-table-count hash-table-obj) (length assoc-list))
(not (loop for item in assoc-list
when (not (equal (cadr item)
(gethash (car item) hash-table-obj)))
return t))))
(defun create-hash-table (assoc-list)
(let ((result (make-hash-table :test #'eq)))
(loop for item in assoc-list
do (setf (gethash (car item) result)
(cadr item)))
result))
(deftest classify-to-map-test ()
(let ((integer-list '((1 2 3)
(7 9)
(6)
(1 5)
(0 0 0 0)))
(integer-vector #((1 2 3)
(7 9)
(6)
(1 5)
(0 0 0 0))))
(is (hash-table-equal (classify-to-map :in integer-list
:key (apply #'+ individual))
'((0 ((0 0 0 0)))
(16 ((7 9)))
(6 ((1 5) (6) (1 2 3))))))
(is (hash-table-equal (classify-to-map :across integer-vector
:key (length individual)
:when (> individual-key 1))
'((2 ((1 5) (7 9)))
(3 ((1 2 3)))
(4 ((0 0 0 0))))))))
(deftest merge-maps-test ()
(let ((small-map (create-hash-table '((3 (1 2 3))
(2 (0 1))
(4 (5)))))
(big-map (create-hash-table '((9 (8))
(7 (4 5 6))))))
(is (hash-table-equal (merge-maps (small-map big-map)
:new-key (+ small-map-key
big-map-key)
:when (> (+ small-map-key
big-map-key)
10)
:new-obj (append small-map-val
big-map-val))
'((12 ((1 2 3 8)))
(11 ((5 4 5 6) (0 1 8)))
(13 ((5 8))))))
(let ((result (make-hash-table :test #'eq)))
(merge-maps (small-map big-map)
:to result
:new-key (+ small-map-key
big-map-key)
:when (> new-key 10)
:new-obj (append small-map-val
big-map-val))
(is (hash-table-equal result
'((12 ((1 2 3 8)))
(11 ((5 4 5 6) (0 1 8)))
(13 ((5 8)))))))))
(defun points-map-equal (p-map-a p-map-b)
(and (= (second p-map-a) (second p-map-b))
(every (lambda (x)
(equal (second x) (getf (first p-map-b) (first x))))
(group (first p-map-a) 2))))
(deftest classify-to-points-map-test ()
(let ((integer-list '((1 2 3)
(7 9)
(6)
(1 5)
(0 0 0 0)))
(integer-vector #((1 2 3)
(7 9)
(6)
(1 5)
(0 0 0 0))))
(is (points-map-equal (classify-to-points-map :in integer-list
:key (apply #'+ individual))
'((0 ((0 0 0 0)) 16 ((7 9)) 6 ((1 5) (6) (1 2 3))) 16)))
(is (points-map-equal (classify-to-points-map :across integer-vector
:key (length individual)
:when (> individual-key 1))
'((2 ((1 5) (7 9))
3 ((1 2 3))
4 ((0 0 0 0))) 4)))))
(deftest merge-points-maps-test ()
(let ((small-map '((3 (1 2 3)
2 (0 1)
4 (5)) 4))
(big-map '((9 (8)
7 (4 5 6)) 9)))
(is (points-map-equal (merge-points-maps (small-map big-map)
:new-key (+ small-map-key
big-map-key)
:when (> (+ small-map-key
big-map-key)
10)
:new-obj (append small-map-val
big-map-val))
'((12 ((1 2 3 8))
11 ((5 4 5 6) (0 1 8))
13 ((5 8))) 13)))
(let ((result (make-points-map)))
(merge-points-maps (small-map big-map)
:to result
:new-key (+ small-map-key
big-map-key)
:when (> new-key 10)
:new-obj (append small-map-val
big-map-val))
(is (points-map-equal result
'((12 ((1 2 3 8))
11 ((5 4 5 6) (0 1 8))
13 ((5 8))) 13))))))
(deftest (jewel-set-*-test
:cases (((list '(2) '(3) nil)
(list '(2) '(3) nil)
(list '(2) '(3) nil '(2 3) '(2 2) '(3 3)))
((list nil) (list nil) (list nil))
((list '(1) '(2) '(3) '(4))
(list '(5) '(6) '(7) '(8))
(list '(:prod ((1) (2) (3) (4)) ((5) (6) (7) (8)))))
((list '(:prod (4) (5)))
(list '(2) '(3) nil)
;; note that result won't contain (:prod (4) (5))
;; since empty (nil) only post-connects empty.
(list '(:prod (:prod (4) (5)) (2))
'(:prod (:prod (4) (5)) (3))))))
(set-a set-b expected)
(let ((*jewel-product-calculation-cut-off* 10))
(is (set-equal (jewel-set-* set-a set-b)
expected))))
(defun keyed-jewel-set-equal (x y)
(and (= (keyed-jewel-set-key x)
(keyed-jewel-set-key y))
(set-equal (keyed-jewel-set-set x)
(keyed-jewel-set-set y))))
(deftest exec-super-jewel-set-expr-test ()
(is (set-equal (exec-super-jewel-set-expr
(+ (list (make-keyed-jewel-set :key 10 :set '((1 2 3)))
(make-keyed-jewel-set :key 7 :set '((8))))
(* (list (make-keyed-jewel-set :key 5 :set '((3) (4)))
(make-keyed-jewel-set :key 10 :set '(nil)))
(list (make-keyed-jewel-set :key 5 :set '((3) (4)))
(make-keyed-jewel-set :key 0 :set '((1) (2)))))))
(list (make-keyed-jewel-set :key 15 :set '((3) (4)))
(make-keyed-jewel-set :key 10 :set '((2) (1) (3 4)
(4 4) (3 3)
(1 2 3)))
(make-keyed-jewel-set :key 7 :set '((8))))
:test #'keyed-jewel-set-equal)))
(defparameter *test-jewels*
(make-array
6
:initial-contents (list (make-jewel
:id 0
:holes 1
:effects '((0 1) (1 -1)))
(make-jewel
:id 1
:holes 1
:effects '((0 -1) (1 1)))
(make-jewel
:id 2
:holes 2
:effects '((0 3) (1 -1)))
(make-jewel
:id 3
:holes 2
:effects '((0 -1) (1 3)))
(make-jewel
:id 4
:holes 3
:effects '((0 5) (1 -1)))
(make-jewel
:id 5
:holes 3
:effects '((2 3))))))
(deftest jewels-encoder-test ()
(let ((*jewels* *test-jewels*))
(let ((encoder (jewels-encoder '(2 1 0))))
(is (equal (decode-skill-sig-full (funcall encoder '(4 3 2)) 3)
'(0 1 7)))
(is (equal (decode-skill-sig-full (funcall encoder '(1 5)) 3)
'(3 1 -1))))))
(deftest (stuff-jewels-test
:cases (('(1 2 2) '(0 1 2) '(1 0 2))
('(0 0 2) '(2 2) '(2 0 0))
('(0 0 2) '(0 2 5) '(0 0 0))
('(2 2 1) '(0 0 0 0 2 3) '(1 0 0))
('(2 2 1) '(0 0 0 0 3 4) '(0 0 0))))
(alignment jewel-list expected)
(let ((*jewels* *test-jewels*))
(is (equal (stuff-jewels alignment jewel-list)
expected)))
(let ((*jewels* *test-jewels*))
(is (equal (stuff-jewels-fast alignment jewel-list)
expected))))
(deftest encode-jewels-test ()
(let ((*jewels* *test-jewels*)
(jewel-list '(1 3 5))
(ids '(1 0)))
(is (equal (decode-skill-sig-full (encode-jewels jewel-list ids) 2)
'(4 -2)))))
(deftest (dfs-jewel-query-test
:cases (('(0 0 0) '((:key (0 0) :set (nil))))
('(1 0 0) '((:key (0 0) :set (nil))
(:key (1 -1) :set ((0)))
(:key (-1 1) :set ((1)))))
('(2 0 0) '((:key (0 0) :set (nil (0 1)))
(:key (1 -1) :set ((0)))
(:key (-1 1) :set ((1)))
(:key (-2 2) :set ((1 1)))
(:key (2 -2) :set ((0 0)))))
('(1 1 0) '((:key (0 0) :set (nil (0 1)))
(:key (1 -1) :set ((0) (0 0 1)))
(:key (-1 1) :set ((1) (0 1 1)))
(:key (3 -3) :set ((0 0 0)))
(:key (-3 3) :set ((1 1 1)))
(:key (2 -2) :set ((0 0)))
(:key (-2 2) :set ((1 1)))
(:key (3 -1) :set ((2)))
(:key (-1 3) :set ((3)))
(:key (4 -2) :set ((0 2)))
(:key (0 2) :set ((0 3)))
(:key (-2 4) :set ((1 3)))
(:key (2 0) :set ((1 2)))))))
(hole-alignment expected)
;; Assuming there are two skills with id 0 (attack) and 1 (defense).
(let ((*jewels* *test-jewels*))
(let ((client (jewel-query-client '((0 2) (1 4)))))
(is (set-equal (dfs-jewel-query '(0 1) hole-alignment)
(loop for item in expected
collect (make-keyed-jewel-set
:key (encode-skill-sig (second item))
:set (fourth item)))
:test #'keyed-jewel-set-equal)))))
(deftest (jewel-query-client-test
:cases (('(0 0 0))
('(1 0 0))
('(2 0 0))
('(7 0 0))
('(0 1 0))
('(0 5 0))
('(1 1 0))
('(1 2 0))
('(3 4 0))
('(0 0 1))
('(0 1 1))
('(2 2 1))
('(1 2 2))))
(hole-alignment)
;; Assuming there are two skills with id 0 (attack) and 1 (defense).
(let ((*jewels* *test-jewels*))
(let* ((required-effects '((0 2) (1 4)))
(client (jewel-query-client required-effects)))
(is (set-equal (funcall client (encode-hole-sig hole-alignment))
(dfs-jewel-query (mapcar #'car required-effects)
hole-alignment)
:test #'keyed-jewel-set-equal)))))
(deftest (targeted-jewel-query-client-test
:cases (('(0 0 0))
('(1 0 0))
('(2 0 0))
('(7 0 0))
('(0 1 0))
('(0 5 0))
('(1 1 0))
('(1 2 0))
('(3 4 0))
('(0 0 1))
('(0 1 1))
('(2 2 1))
('(1 2 2))))
(hole-alignment)
;; Assuming there are two skills with id 0 (attack) and 1 (defense).
(let ((*jewels* *test-jewels*))
(let* ((required-effects '((0 2) (1 4)))
(client (jewel-query-client required-effects 1)))
(is (set-equal (funcall client (encode-hole-sig hole-alignment))
(dfs-jewel-query (mapcar #'car required-effects)
hole-alignment 1)
:test #'keyed-jewel-set-equal)))))
(defparameter *test-armors*
(list (make-armor :id 0 :part-id 0 :effects '((0 3) (2 1)))
(make-armor :id 1 :part-id 0 :effects '((0 3) (2 2)))
(make-armor :id 2 :part-id 0 :effects '((1 2)))
(make-armor :id 3 :part-id 0 :effects '((1 2) (2 3)))
(make-armor :id 4 :part-id 1 :effects '((1 2)))
(make-armor :id 5 :part-id 1 :effects '((1 2) (2 1)))
(make-armor :id 6 :part-id 1 :effects '((0 4)))
(make-armor :id 7 :part-id 1 :effects '((0 4) (2 -2)))
(make-armor :id 8 :part-id 1 :effects '((0 2)))
(make-armor :id 9 :part-id 2 :effects '((0 1) (2 1)))
(make-armor :id 10 :part-id 2 :effects '((0 1) (2 2)))
(make-armor :id 11 :part-id 2 :effects '((0 1)))
(make-armor :id 12 :part-id 2 :effects '((2 3)))
(make-armor :id 13 :part-id 2 :effects '((0 2) (2 -1)))))
(defun armor-equal (x y)
(and (= (armor-id x) (armor-id y))
(= (armor-part-id x) (armor-part-id y))))
(defun armor-forest-equal (x y)
(if (armor-p (car y))
(set-equal x y :test #'armor-equal)
(set-equal x y
:test #'armor-tree-equal)))
(defun armor-tree-equal (x y)
(and (set-equal (armor-tree-left x)
(armor-tree-left y)
:test #'armor-equal)
(armor-forest-equal (armor-tree-right x)
(armor-tree-right y))))
(defun prelim-equal (x y)
(and (= (preliminary-key x) (preliminary-key y))
(set-equal (preliminary-jewel-sets x)
(preliminary-jewel-sets y)
:test #'set-equal)
(armor-forest-equal (preliminary-forest x)
(preliminary-forest y))))
(defun assemble-forest (code-forest)
(cond ((eq (car code-forest) :tree)
(make-armor-tree
:left (loop for code in (second code-forest)
collect (nth code *test-armors*))
:right (assemble-forest (third code-forest))))
((consp (car code-forest))
(loop for sub-tree in code-forest
collect (assemble-forest sub-tree)))
(t (loop for code in code-forest
collect (nth code *test-armors*)))))
(defun ensure-skill-points (forest skill-id skill-points)
(if (armor-p (car forest))
(every #`,(= (points-of-skill x1 skill-id)
skill-points)
forest)
(every (lambda (tree)
(let ((current (points-of-skill
(car (armor-tree-left tree))
skill-id)))
(and (ensure-skill-points
(armor-tree-left tree)
skill-id
current)
(ensure-skill-points
(armor-tree-right tree)
skill-id
(- skill-points current)))))
forest)))
(deftest split-forest-at-skill-test ()
(let ((forest (assemble-forest '((:tree (0 1) ((:tree (4) (9 10))
(:tree (5) (11))))
(:tree (2 3) ((:tree (6 7) (12))
(:tree (8) (13))))))))
(is (ensure-skill-points forest 0 4))
(is (ensure-skill-points forest 1 2))
(let ((result (split-forest-at-skill forest 2 3)))
(is (armor-forest-equal
(getf (car result) 3)
(assemble-forest '((:tree (1) ((:tree (4) (9))
(:tree (5) (11))))
(:tree (0) ((:tree (4) (10))))
(:tree (2) ((:tree (6) (12))))))))
(is (armor-forest-equal
(getf (car result) 4)
(assemble-forest '((:tree (1) ((:tree (4) (10))))
(:tree (3) ((:tree (7) (12))))))))
(is (armor-forest-equal
(getf (car result) 6)
(assemble-forest '((:tree (3) ((:tree (6) (12)))))))))))
(defun mock-max-at-skill-client (target-id)
(let ((store (make-array '(7 400) :element-type 'fixnum :initial-element 0)))
(declare (type (simple-array fixnum (7 400)) store))
(loop for item in *test-armors*
do (setf (aref store (armor-part-id item) (armor-id item))
(the fixnum (points-of-skill item target-id))))
(labels ((client (forest)
(if (armor-p (car forest))
;; case 1: last level
(the fixnum (loop for item in forest
maximize (aref store
(armor-part-id item)
(armor-id item))))
;; case 2 middle levels
(the fixnum
(loop for tree in forest
maximize (+ (the fixnum
(loop for item in (armor-tree-left tree)
maximize (aref store
(armor-part-id item)
(armor-id item))))
(client (armor-tree-right tree))))))))
#'client)))
(deftest extra-skill-split-test ()
(let* ((*jewels* *test-jewels*)
(forest (assemble-forest '((:tree (0 1) ((:tree (4) (9 10))
(:tree (5) (11))))
(:tree (2 3) ((:tree (6 7) (12))
(:tree (8) (13)))))))
(env (make-split-env :hole-query
(jewel-query-client '((0 6) (1 4) (2 7)))
:target-id 2
:encoder (jewels-encoder '(0 1 2))
:target-points 7
:inv-req-key (encode-skill-sig '(-6 -4 -7))
:satisfy-mask (gen-skill-mask 3)
:forest-maximizer (mock-max-at-skill-client 2)
:n 2))
(result (extra-skill-split
(make-preliminary :key (encode-sig '(0 2 1)
'(4 2))
:forest forest
:jewel-sets '((2 3)))
env)))
(is (set-equal result
(list (make-preliminary
:key (encode-sig '(0 2 1) '(4 2 6))
:forest (assemble-forest
'((:tree (3) ((:tree (6) (12))))))
:jewel-sets '((2 3 5)))
(make-preliminary
:key (encode-sig '(0 2 1) '(4 2 4))
:forest (assemble-forest
'((:tree (1) ((:tree (4) (10))))
(:tree (3) ((:tree (7) (12))))))
:jewel-sets '((2 3 5))))
:test #'prelim-equal))))
|
55821
|
;;;; armor-up-test.lisp
;;;; Author: BreakDS <<EMAIL>>
;;;;
;;;; Description: unit tests for armor-up.lisp.
(in-package #:breakds.monster-avengers.armor-up-test)
(defsuite* (test-all :in root-suite
:documentation "unit tests for armor-up."))
(deftest (coding-test
:cases (('(1 1 5) '(10 -10 20))
('(1 3 0) '(-12))))
(hole-sig skill-sig)
(let ((n (length skill-sig)))
(multiple-value-bind (hole-sig-result
skill-sig-result)
(decode-sig-full (encode-sig hole-sig skill-sig) n)
(is (equal hole-sig hole-sig-result))
(is (equal skill-sig skill-sig-result)))))
(deftest decode-skill-sig-at-test ()
(let* ((hole-sig '(1 1 5))
(skill-sig '(10 -10 20))
(key (encode-sig hole-sig skill-sig)))
(is (= (decode-skill-sig-at key 0) 10))
(is (= (decode-skill-sig-at key 1) -10))
(is (= (decode-skill-sig-at key 2) 20))))
(deftest (encoded-+-test
:cases (('(1 1 0) '(10 -10 20) '(0 1 1) '(-5 3 -2) '(1 2 1) '(5 -7 18))
('(5 1 1) '(-12 -14) '(3 0 0) '(2 -5) '(8 1 1) '(-10 -19))))
(hole-sig-a skill-sig-a hole-sig-b skill-sig-b hole-sig-+ skill-sig-+)
(is (= (length skill-sig-a)
(length skill-sig-b)
(length skill-sig-+)))
(let ((n (length skill-sig-a)))
(multiple-value-bind (hole-sig-reuslt skill-sig-result)
(decode-sig-full (encoded-+ (encode-sig hole-sig-a skill-sig-a)
(encode-sig hole-sig-b skill-sig-b))
n)
(is (equal hole-sig-reuslt hole-sig-+))
(is (equal skill-sig-result skill-sig-+)))))
(deftest (encoded-skill-+-test
:cases (('(1 1 0) '(10 -10 20) '(0 1 1) '(-5 3 -2) '(0 0 0) '(5 -7 18))
('(5 1 1) '(-12 -14) '(3 0 0) '(2 -5) '(0 0 0) '(-10 -19))))
(hole-sig-a skill-sig-a hole-sig-b skill-sig-b hole-sig-+ skill-sig-+)
(is (= (length skill-sig-a)
(length skill-sig-b)
(length skill-sig-+)))
(let ((n (length skill-sig-a)))
(multiple-value-bind (hole-sig-reuslt skill-sig-result)
(decode-sig-full (encoded-skill-+ (encode-sig hole-sig-a skill-sig-a)
(encode-sig hole-sig-b skill-sig-b))
n)
(is (equal hole-sig-reuslt hole-sig-+))
(is (equal skill-sig-result skill-sig-+)))))
(deftest (replace-skill-key-at-test
:cases ((0 12)
(3 5)
(4 -6)))
(n value)
(let* ((hole-sig '(1 1 5))
(skill-sig '(10 -10 20))
(key (replace-skill-key-at
(encode-sig hole-sig skill-sig)
n value)))
(is (equal (decode-hole-sig key) hole-sig))
(is (= (decode-skill-sig-at key n) value))))
(deftest (is-satisfied-skill-key-test
:cases (('(1 2 1) t)
('(0 0 0 0) t)
('(-1 2 12) nil)
('(0 0 0 -5) nil)))
(skill-sig expected)
(is (eq (is-satisfied-skill-key (encode-skill-sig skill-sig)
(gen-skill-mask (length skill-sig)))
expected)))
(deftest encode-jewel-if-satisfy-test ()
(let ((piece (make-jewel :id 0
:holes 1
:effects '((1 -1) (2 3) (3 5) (4 -5)))))
(is (null (encode-jewel-if-satisfy piece '(5))))
(is (null (encode-jewel-if-satisfy piece '(1 4))))
(is (null (encode-jewel-if-satisfy piece '(1 5))))
(multiple-value-bind (hole-sig-result
skill-sig-result)
(decode-sig-full (encode-jewel-if-satisfy piece '(3 2 1 5)) 4)
(is (equal hole-sig-result '(0 0 0)))
(is (equal skill-sig-result '(5 3 -1 0))))))
;;; Hash table related macros test
(defun hash-table-equal (hash-table-obj assoc-list)
(and (= (hash-table-count hash-table-obj) (length assoc-list))
(not (loop for item in assoc-list
when (not (equal (cadr item)
(gethash (car item) hash-table-obj)))
return t))))
(defun create-hash-table (assoc-list)
(let ((result (make-hash-table :test #'eq)))
(loop for item in assoc-list
do (setf (gethash (car item) result)
(cadr item)))
result))
(deftest classify-to-map-test ()
(let ((integer-list '((1 2 3)
(7 9)
(6)
(1 5)
(0 0 0 0)))
(integer-vector #((1 2 3)
(7 9)
(6)
(1 5)
(0 0 0 0))))
(is (hash-table-equal (classify-to-map :in integer-list
:key (apply #'+ individual))
'((0 ((0 0 0 0)))
(16 ((7 9)))
(6 ((1 5) (6) (1 2 3))))))
(is (hash-table-equal (classify-to-map :across integer-vector
:key (length individual)
:when (> individual-key 1))
'((2 ((1 5) (7 9)))
(3 ((1 2 3)))
(4 ((0 0 0 0))))))))
(deftest merge-maps-test ()
(let ((small-map (create-hash-table '((3 (1 2 3))
(2 (0 1))
(4 (5)))))
(big-map (create-hash-table '((9 (8))
(7 (4 5 6))))))
(is (hash-table-equal (merge-maps (small-map big-map)
:new-key (+ small-map-key
big-map-key)
:when (> (+ small-map-key
big-map-key)
10)
:new-obj (append small-map-val
big-map-val))
'((12 ((1 2 3 8)))
(11 ((5 4 5 6) (0 1 8)))
(13 ((5 8))))))
(let ((result (make-hash-table :test #'eq)))
(merge-maps (small-map big-map)
:to result
:new-key (+ small-map-key
big-map-key)
:when (> new-key 10)
:new-obj (append small-map-val
big-map-val))
(is (hash-table-equal result
'((12 ((1 2 3 8)))
(11 ((5 4 5 6) (0 1 8)))
(13 ((5 8)))))))))
(defun points-map-equal (p-map-a p-map-b)
(and (= (second p-map-a) (second p-map-b))
(every (lambda (x)
(equal (second x) (getf (first p-map-b) (first x))))
(group (first p-map-a) 2))))
(deftest classify-to-points-map-test ()
(let ((integer-list '((1 2 3)
(7 9)
(6)
(1 5)
(0 0 0 0)))
(integer-vector #((1 2 3)
(7 9)
(6)
(1 5)
(0 0 0 0))))
(is (points-map-equal (classify-to-points-map :in integer-list
:key (apply #'+ individual))
'((0 ((0 0 0 0)) 16 ((7 9)) 6 ((1 5) (6) (1 2 3))) 16)))
(is (points-map-equal (classify-to-points-map :across integer-vector
:key (length individual)
:when (> individual-key 1))
'((2 ((1 5) (7 9))
3 ((1 2 3))
4 ((0 0 0 0))) 4)))))
(deftest merge-points-maps-test ()
(let ((small-map '((3 (1 2 3)
2 (0 1)
4 (5)) 4))
(big-map '((9 (8)
7 (4 5 6)) 9)))
(is (points-map-equal (merge-points-maps (small-map big-map)
:new-key (+ small-map-key
big-map-key)
:when (> (+ small-map-key
big-map-key)
10)
:new-obj (append small-map-val
big-map-val))
'((12 ((1 2 3 8))
11 ((5 4 5 6) (0 1 8))
13 ((5 8))) 13)))
(let ((result (make-points-map)))
(merge-points-maps (small-map big-map)
:to result
:new-key (+ small-map-key
big-map-key)
:when (> new-key 10)
:new-obj (append small-map-val
big-map-val))
(is (points-map-equal result
'((12 ((1 2 3 8))
11 ((5 4 5 6) (0 1 8))
13 ((5 8))) 13))))))
(deftest (jewel-set-*-test
:cases (((list '(2) '(3) nil)
(list '(2) '(3) nil)
(list '(2) '(3) nil '(2 3) '(2 2) '(3 3)))
((list nil) (list nil) (list nil))
((list '(1) '(2) '(3) '(4))
(list '(5) '(6) '(7) '(8))
(list '(:prod ((1) (2) (3) (4)) ((5) (6) (7) (8)))))
((list '(:prod (4) (5)))
(list '(2) '(3) nil)
;; note that result won't contain (:prod (4) (5))
;; since empty (nil) only post-connects empty.
(list '(:prod (:prod (4) (5)) (2))
'(:prod (:prod (4) (5)) (3))))))
(set-a set-b expected)
(let ((*jewel-product-calculation-cut-off* 10))
(is (set-equal (jewel-set-* set-a set-b)
expected))))
(defun keyed-jewel-set-equal (x y)
(and (= (keyed-jewel-set-key x)
(keyed-jewel-set-key y))
(set-equal (keyed-jewel-set-set x)
(keyed-jewel-set-set y))))
(deftest exec-super-jewel-set-expr-test ()
(is (set-equal (exec-super-jewel-set-expr
(+ (list (make-keyed-jewel-set :key 10 :set '((1 2 3)))
(make-keyed-jewel-set :key 7 :set '((8))))
(* (list (make-keyed-jewel-set :key 5 :set '((3) (4)))
(make-keyed-jewel-set :key 10 :set '(nil)))
(list (make-keyed-jewel-set :key 5 :set '((3) (4)))
(make-keyed-jewel-set :key 0 :set '((1) (2)))))))
(list (make-keyed-jewel-set :key 15 :set '((3) (4)))
(make-keyed-jewel-set :key 10 :set '((2) (1) (3 4)
(4 4) (3 3)
(1 2 3)))
(make-keyed-jewel-set :key 7 :set '((8))))
:test #'keyed-jewel-set-equal)))
(defparameter *test-jewels*
(make-array
6
:initial-contents (list (make-jewel
:id 0
:holes 1
:effects '((0 1) (1 -1)))
(make-jewel
:id 1
:holes 1
:effects '((0 -1) (1 1)))
(make-jewel
:id 2
:holes 2
:effects '((0 3) (1 -1)))
(make-jewel
:id 3
:holes 2
:effects '((0 -1) (1 3)))
(make-jewel
:id 4
:holes 3
:effects '((0 5) (1 -1)))
(make-jewel
:id 5
:holes 3
:effects '((2 3))))))
(deftest jewels-encoder-test ()
(let ((*jewels* *test-jewels*))
(let ((encoder (jewels-encoder '(2 1 0))))
(is (equal (decode-skill-sig-full (funcall encoder '(4 3 2)) 3)
'(0 1 7)))
(is (equal (decode-skill-sig-full (funcall encoder '(1 5)) 3)
'(3 1 -1))))))
(deftest (stuff-jewels-test
:cases (('(1 2 2) '(0 1 2) '(1 0 2))
('(0 0 2) '(2 2) '(2 0 0))
('(0 0 2) '(0 2 5) '(0 0 0))
('(2 2 1) '(0 0 0 0 2 3) '(1 0 0))
('(2 2 1) '(0 0 0 0 3 4) '(0 0 0))))
(alignment jewel-list expected)
(let ((*jewels* *test-jewels*))
(is (equal (stuff-jewels alignment jewel-list)
expected)))
(let ((*jewels* *test-jewels*))
(is (equal (stuff-jewels-fast alignment jewel-list)
expected))))
(deftest encode-jewels-test ()
(let ((*jewels* *test-jewels*)
(jewel-list '(1 3 5))
(ids '(1 0)))
(is (equal (decode-skill-sig-full (encode-jewels jewel-list ids) 2)
'(4 -2)))))
(deftest (dfs-jewel-query-test
:cases (('(0 0 0) '((:key (0 0) :set (nil))))
('(1 0 0) '((:key (0 0) :set (nil))
(:key (1 -1) :set ((0)))
(:key (-1 1) :set ((1)))))
('(2 0 0) '((:key (0 0) :set (nil (0 1)))
(:key (1 -1) :set ((0)))
(:key (-1 1) :set ((1)))
(:key (-2 2) :set ((1 1)))
(:key (2 -2) :set ((0 0)))))
('(1 1 0) '((:key (0 0) :set (nil (0 1)))
(:key (1 -1) :set ((0) (0 0 1)))
(:key (-1 1) :set ((1) (0 1 1)))
(:key (3 -3) :set ((0 0 0)))
(:key (-3 3) :set ((1 1 1)))
(:key (2 -2) :set ((0 0)))
(:key (-2 2) :set ((1 1)))
(:key (3 -1) :set ((2)))
(:key (-1 3) :set ((3)))
(:key (4 -2) :set ((0 2)))
(:key (0 2) :set ((0 3)))
(:key (-2 4) :set ((1 3)))
(:key (2 0) :set ((1 2)))))))
(hole-alignment expected)
;; Assuming there are two skills with id 0 (attack) and 1 (defense).
(let ((*jewels* *test-jewels*))
(let ((client (jewel-query-client '((0 2) (1 4)))))
(is (set-equal (dfs-jewel-query '(0 1) hole-alignment)
(loop for item in expected
collect (make-keyed-jewel-set
:key (encode-skill-sig (second item))
:set (fourth item)))
:test #'keyed-jewel-set-equal)))))
(deftest (jewel-query-client-test
:cases (('(0 0 0))
('(1 0 0))
('(2 0 0))
('(7 0 0))
('(0 1 0))
('(0 5 0))
('(1 1 0))
('(1 2 0))
('(3 4 0))
('(0 0 1))
('(0 1 1))
('(2 2 1))
('(1 2 2))))
(hole-alignment)
;; Assuming there are two skills with id 0 (attack) and 1 (defense).
(let ((*jewels* *test-jewels*))
(let* ((required-effects '((0 2) (1 4)))
(client (jewel-query-client required-effects)))
(is (set-equal (funcall client (encode-hole-sig hole-alignment))
(dfs-jewel-query (mapcar #'car required-effects)
hole-alignment)
:test #'keyed-jewel-set-equal)))))
(deftest (targeted-jewel-query-client-test
:cases (('(0 0 0))
('(1 0 0))
('(2 0 0))
('(7 0 0))
('(0 1 0))
('(0 5 0))
('(1 1 0))
('(1 2 0))
('(3 4 0))
('(0 0 1))
('(0 1 1))
('(2 2 1))
('(1 2 2))))
(hole-alignment)
;; Assuming there are two skills with id 0 (attack) and 1 (defense).
(let ((*jewels* *test-jewels*))
(let* ((required-effects '((0 2) (1 4)))
(client (jewel-query-client required-effects 1)))
(is (set-equal (funcall client (encode-hole-sig hole-alignment))
(dfs-jewel-query (mapcar #'car required-effects)
hole-alignment 1)
:test #'keyed-jewel-set-equal)))))
(defparameter *test-armors*
(list (make-armor :id 0 :part-id 0 :effects '((0 3) (2 1)))
(make-armor :id 1 :part-id 0 :effects '((0 3) (2 2)))
(make-armor :id 2 :part-id 0 :effects '((1 2)))
(make-armor :id 3 :part-id 0 :effects '((1 2) (2 3)))
(make-armor :id 4 :part-id 1 :effects '((1 2)))
(make-armor :id 5 :part-id 1 :effects '((1 2) (2 1)))
(make-armor :id 6 :part-id 1 :effects '((0 4)))
(make-armor :id 7 :part-id 1 :effects '((0 4) (2 -2)))
(make-armor :id 8 :part-id 1 :effects '((0 2)))
(make-armor :id 9 :part-id 2 :effects '((0 1) (2 1)))
(make-armor :id 10 :part-id 2 :effects '((0 1) (2 2)))
(make-armor :id 11 :part-id 2 :effects '((0 1)))
(make-armor :id 12 :part-id 2 :effects '((2 3)))
(make-armor :id 13 :part-id 2 :effects '((0 2) (2 -1)))))
(defun armor-equal (x y)
(and (= (armor-id x) (armor-id y))
(= (armor-part-id x) (armor-part-id y))))
(defun armor-forest-equal (x y)
(if (armor-p (car y))
(set-equal x y :test #'armor-equal)
(set-equal x y
:test #'armor-tree-equal)))
(defun armor-tree-equal (x y)
(and (set-equal (armor-tree-left x)
(armor-tree-left y)
:test #'armor-equal)
(armor-forest-equal (armor-tree-right x)
(armor-tree-right y))))
(defun prelim-equal (x y)
(and (= (preliminary-key x) (preliminary-key y))
(set-equal (preliminary-jewel-sets x)
(preliminary-jewel-sets y)
:test #'set-equal)
(armor-forest-equal (preliminary-forest x)
(preliminary-forest y))))
(defun assemble-forest (code-forest)
(cond ((eq (car code-forest) :tree)
(make-armor-tree
:left (loop for code in (second code-forest)
collect (nth code *test-armors*))
:right (assemble-forest (third code-forest))))
((consp (car code-forest))
(loop for sub-tree in code-forest
collect (assemble-forest sub-tree)))
(t (loop for code in code-forest
collect (nth code *test-armors*)))))
(defun ensure-skill-points (forest skill-id skill-points)
(if (armor-p (car forest))
(every #`,(= (points-of-skill x1 skill-id)
skill-points)
forest)
(every (lambda (tree)
(let ((current (points-of-skill
(car (armor-tree-left tree))
skill-id)))
(and (ensure-skill-points
(armor-tree-left tree)
skill-id
current)
(ensure-skill-points
(armor-tree-right tree)
skill-id
(- skill-points current)))))
forest)))
(deftest split-forest-at-skill-test ()
(let ((forest (assemble-forest '((:tree (0 1) ((:tree (4) (9 10))
(:tree (5) (11))))
(:tree (2 3) ((:tree (6 7) (12))
(:tree (8) (13))))))))
(is (ensure-skill-points forest 0 4))
(is (ensure-skill-points forest 1 2))
(let ((result (split-forest-at-skill forest 2 3)))
(is (armor-forest-equal
(getf (car result) 3)
(assemble-forest '((:tree (1) ((:tree (4) (9))
(:tree (5) (11))))
(:tree (0) ((:tree (4) (10))))
(:tree (2) ((:tree (6) (12))))))))
(is (armor-forest-equal
(getf (car result) 4)
(assemble-forest '((:tree (1) ((:tree (4) (10))))
(:tree (3) ((:tree (7) (12))))))))
(is (armor-forest-equal
(getf (car result) 6)
(assemble-forest '((:tree (3) ((:tree (6) (12)))))))))))
(defun mock-max-at-skill-client (target-id)
(let ((store (make-array '(7 400) :element-type 'fixnum :initial-element 0)))
(declare (type (simple-array fixnum (7 400)) store))
(loop for item in *test-armors*
do (setf (aref store (armor-part-id item) (armor-id item))
(the fixnum (points-of-skill item target-id))))
(labels ((client (forest)
(if (armor-p (car forest))
;; case 1: last level
(the fixnum (loop for item in forest
maximize (aref store
(armor-part-id item)
(armor-id item))))
;; case 2 middle levels
(the fixnum
(loop for tree in forest
maximize (+ (the fixnum
(loop for item in (armor-tree-left tree)
maximize (aref store
(armor-part-id item)
(armor-id item))))
(client (armor-tree-right tree))))))))
#'client)))
(deftest extra-skill-split-test ()
(let* ((*jewels* *test-jewels*)
(forest (assemble-forest '((:tree (0 1) ((:tree (4) (9 10))
(:tree (5) (11))))
(:tree (2 3) ((:tree (6 7) (12))
(:tree (8) (13)))))))
(env (make-split-env :hole-query
(jewel-query-client '((0 6) (1 4) (2 7)))
:target-id 2
:encoder (jewels-encoder '(0 1 2))
:target-points 7
:inv-req-key (encode-skill-sig '(-6 -4 -7))
:satisfy-mask (gen-skill-mask 3)
:forest-maximizer (mock-max-at-skill-client 2)
:n 2))
(result (extra-skill-split
(make-preliminary :key (encode-sig '(0 2 1)
'(4 2))
:forest forest
:jewel-sets '((2 3)))
env)))
(is (set-equal result
(list (make-preliminary
:key (encode-sig '(0 2 1) '(4 2 6))
:forest (assemble-forest
'((:tree (3) ((:tree (6) (12))))))
:jewel-sets '((2 3 5)))
(make-preliminary
:key (encode-sig '(0 2 1) '(4 2 4))
:forest (assemble-forest
'((:tree (1) ((:tree (4) (10))))
(:tree (3) ((:tree (7) (12))))))
:jewel-sets '((2 3 5))))
:test #'prelim-equal))))
| true |
;;;; armor-up-test.lisp
;;;; Author: BreakDS <PI:EMAIL:<EMAIL>END_PI>
;;;;
;;;; Description: unit tests for armor-up.lisp.
(in-package #:breakds.monster-avengers.armor-up-test)
(defsuite* (test-all :in root-suite
:documentation "unit tests for armor-up."))
(deftest (coding-test
:cases (('(1 1 5) '(10 -10 20))
('(1 3 0) '(-12))))
(hole-sig skill-sig)
(let ((n (length skill-sig)))
(multiple-value-bind (hole-sig-result
skill-sig-result)
(decode-sig-full (encode-sig hole-sig skill-sig) n)
(is (equal hole-sig hole-sig-result))
(is (equal skill-sig skill-sig-result)))))
(deftest decode-skill-sig-at-test ()
(let* ((hole-sig '(1 1 5))
(skill-sig '(10 -10 20))
(key (encode-sig hole-sig skill-sig)))
(is (= (decode-skill-sig-at key 0) 10))
(is (= (decode-skill-sig-at key 1) -10))
(is (= (decode-skill-sig-at key 2) 20))))
(deftest (encoded-+-test
:cases (('(1 1 0) '(10 -10 20) '(0 1 1) '(-5 3 -2) '(1 2 1) '(5 -7 18))
('(5 1 1) '(-12 -14) '(3 0 0) '(2 -5) '(8 1 1) '(-10 -19))))
(hole-sig-a skill-sig-a hole-sig-b skill-sig-b hole-sig-+ skill-sig-+)
(is (= (length skill-sig-a)
(length skill-sig-b)
(length skill-sig-+)))
(let ((n (length skill-sig-a)))
(multiple-value-bind (hole-sig-reuslt skill-sig-result)
(decode-sig-full (encoded-+ (encode-sig hole-sig-a skill-sig-a)
(encode-sig hole-sig-b skill-sig-b))
n)
(is (equal hole-sig-reuslt hole-sig-+))
(is (equal skill-sig-result skill-sig-+)))))
(deftest (encoded-skill-+-test
:cases (('(1 1 0) '(10 -10 20) '(0 1 1) '(-5 3 -2) '(0 0 0) '(5 -7 18))
('(5 1 1) '(-12 -14) '(3 0 0) '(2 -5) '(0 0 0) '(-10 -19))))
(hole-sig-a skill-sig-a hole-sig-b skill-sig-b hole-sig-+ skill-sig-+)
(is (= (length skill-sig-a)
(length skill-sig-b)
(length skill-sig-+)))
(let ((n (length skill-sig-a)))
(multiple-value-bind (hole-sig-reuslt skill-sig-result)
(decode-sig-full (encoded-skill-+ (encode-sig hole-sig-a skill-sig-a)
(encode-sig hole-sig-b skill-sig-b))
n)
(is (equal hole-sig-reuslt hole-sig-+))
(is (equal skill-sig-result skill-sig-+)))))
(deftest (replace-skill-key-at-test
:cases ((0 12)
(3 5)
(4 -6)))
(n value)
(let* ((hole-sig '(1 1 5))
(skill-sig '(10 -10 20))
(key (replace-skill-key-at
(encode-sig hole-sig skill-sig)
n value)))
(is (equal (decode-hole-sig key) hole-sig))
(is (= (decode-skill-sig-at key n) value))))
(deftest (is-satisfied-skill-key-test
:cases (('(1 2 1) t)
('(0 0 0 0) t)
('(-1 2 12) nil)
('(0 0 0 -5) nil)))
(skill-sig expected)
(is (eq (is-satisfied-skill-key (encode-skill-sig skill-sig)
(gen-skill-mask (length skill-sig)))
expected)))
(deftest encode-jewel-if-satisfy-test ()
(let ((piece (make-jewel :id 0
:holes 1
:effects '((1 -1) (2 3) (3 5) (4 -5)))))
(is (null (encode-jewel-if-satisfy piece '(5))))
(is (null (encode-jewel-if-satisfy piece '(1 4))))
(is (null (encode-jewel-if-satisfy piece '(1 5))))
(multiple-value-bind (hole-sig-result
skill-sig-result)
(decode-sig-full (encode-jewel-if-satisfy piece '(3 2 1 5)) 4)
(is (equal hole-sig-result '(0 0 0)))
(is (equal skill-sig-result '(5 3 -1 0))))))
;;; Hash table related macros test
(defun hash-table-equal (hash-table-obj assoc-list)
(and (= (hash-table-count hash-table-obj) (length assoc-list))
(not (loop for item in assoc-list
when (not (equal (cadr item)
(gethash (car item) hash-table-obj)))
return t))))
(defun create-hash-table (assoc-list)
(let ((result (make-hash-table :test #'eq)))
(loop for item in assoc-list
do (setf (gethash (car item) result)
(cadr item)))
result))
(deftest classify-to-map-test ()
(let ((integer-list '((1 2 3)
(7 9)
(6)
(1 5)
(0 0 0 0)))
(integer-vector #((1 2 3)
(7 9)
(6)
(1 5)
(0 0 0 0))))
(is (hash-table-equal (classify-to-map :in integer-list
:key (apply #'+ individual))
'((0 ((0 0 0 0)))
(16 ((7 9)))
(6 ((1 5) (6) (1 2 3))))))
(is (hash-table-equal (classify-to-map :across integer-vector
:key (length individual)
:when (> individual-key 1))
'((2 ((1 5) (7 9)))
(3 ((1 2 3)))
(4 ((0 0 0 0))))))))
(deftest merge-maps-test ()
(let ((small-map (create-hash-table '((3 (1 2 3))
(2 (0 1))
(4 (5)))))
(big-map (create-hash-table '((9 (8))
(7 (4 5 6))))))
(is (hash-table-equal (merge-maps (small-map big-map)
:new-key (+ small-map-key
big-map-key)
:when (> (+ small-map-key
big-map-key)
10)
:new-obj (append small-map-val
big-map-val))
'((12 ((1 2 3 8)))
(11 ((5 4 5 6) (0 1 8)))
(13 ((5 8))))))
(let ((result (make-hash-table :test #'eq)))
(merge-maps (small-map big-map)
:to result
:new-key (+ small-map-key
big-map-key)
:when (> new-key 10)
:new-obj (append small-map-val
big-map-val))
(is (hash-table-equal result
'((12 ((1 2 3 8)))
(11 ((5 4 5 6) (0 1 8)))
(13 ((5 8)))))))))
(defun points-map-equal (p-map-a p-map-b)
(and (= (second p-map-a) (second p-map-b))
(every (lambda (x)
(equal (second x) (getf (first p-map-b) (first x))))
(group (first p-map-a) 2))))
(deftest classify-to-points-map-test ()
(let ((integer-list '((1 2 3)
(7 9)
(6)
(1 5)
(0 0 0 0)))
(integer-vector #((1 2 3)
(7 9)
(6)
(1 5)
(0 0 0 0))))
(is (points-map-equal (classify-to-points-map :in integer-list
:key (apply #'+ individual))
'((0 ((0 0 0 0)) 16 ((7 9)) 6 ((1 5) (6) (1 2 3))) 16)))
(is (points-map-equal (classify-to-points-map :across integer-vector
:key (length individual)
:when (> individual-key 1))
'((2 ((1 5) (7 9))
3 ((1 2 3))
4 ((0 0 0 0))) 4)))))
(deftest merge-points-maps-test ()
(let ((small-map '((3 (1 2 3)
2 (0 1)
4 (5)) 4))
(big-map '((9 (8)
7 (4 5 6)) 9)))
(is (points-map-equal (merge-points-maps (small-map big-map)
:new-key (+ small-map-key
big-map-key)
:when (> (+ small-map-key
big-map-key)
10)
:new-obj (append small-map-val
big-map-val))
'((12 ((1 2 3 8))
11 ((5 4 5 6) (0 1 8))
13 ((5 8))) 13)))
(let ((result (make-points-map)))
(merge-points-maps (small-map big-map)
:to result
:new-key (+ small-map-key
big-map-key)
:when (> new-key 10)
:new-obj (append small-map-val
big-map-val))
(is (points-map-equal result
'((12 ((1 2 3 8))
11 ((5 4 5 6) (0 1 8))
13 ((5 8))) 13))))))
(deftest (jewel-set-*-test
:cases (((list '(2) '(3) nil)
(list '(2) '(3) nil)
(list '(2) '(3) nil '(2 3) '(2 2) '(3 3)))
((list nil) (list nil) (list nil))
((list '(1) '(2) '(3) '(4))
(list '(5) '(6) '(7) '(8))
(list '(:prod ((1) (2) (3) (4)) ((5) (6) (7) (8)))))
((list '(:prod (4) (5)))
(list '(2) '(3) nil)
;; note that result won't contain (:prod (4) (5))
;; since empty (nil) only post-connects empty.
(list '(:prod (:prod (4) (5)) (2))
'(:prod (:prod (4) (5)) (3))))))
(set-a set-b expected)
(let ((*jewel-product-calculation-cut-off* 10))
(is (set-equal (jewel-set-* set-a set-b)
expected))))
(defun keyed-jewel-set-equal (x y)
(and (= (keyed-jewel-set-key x)
(keyed-jewel-set-key y))
(set-equal (keyed-jewel-set-set x)
(keyed-jewel-set-set y))))
(deftest exec-super-jewel-set-expr-test ()
(is (set-equal (exec-super-jewel-set-expr
(+ (list (make-keyed-jewel-set :key 10 :set '((1 2 3)))
(make-keyed-jewel-set :key 7 :set '((8))))
(* (list (make-keyed-jewel-set :key 5 :set '((3) (4)))
(make-keyed-jewel-set :key 10 :set '(nil)))
(list (make-keyed-jewel-set :key 5 :set '((3) (4)))
(make-keyed-jewel-set :key 0 :set '((1) (2)))))))
(list (make-keyed-jewel-set :key 15 :set '((3) (4)))
(make-keyed-jewel-set :key 10 :set '((2) (1) (3 4)
(4 4) (3 3)
(1 2 3)))
(make-keyed-jewel-set :key 7 :set '((8))))
:test #'keyed-jewel-set-equal)))
(defparameter *test-jewels*
(make-array
6
:initial-contents (list (make-jewel
:id 0
:holes 1
:effects '((0 1) (1 -1)))
(make-jewel
:id 1
:holes 1
:effects '((0 -1) (1 1)))
(make-jewel
:id 2
:holes 2
:effects '((0 3) (1 -1)))
(make-jewel
:id 3
:holes 2
:effects '((0 -1) (1 3)))
(make-jewel
:id 4
:holes 3
:effects '((0 5) (1 -1)))
(make-jewel
:id 5
:holes 3
:effects '((2 3))))))
(deftest jewels-encoder-test ()
(let ((*jewels* *test-jewels*))
(let ((encoder (jewels-encoder '(2 1 0))))
(is (equal (decode-skill-sig-full (funcall encoder '(4 3 2)) 3)
'(0 1 7)))
(is (equal (decode-skill-sig-full (funcall encoder '(1 5)) 3)
'(3 1 -1))))))
(deftest (stuff-jewels-test
:cases (('(1 2 2) '(0 1 2) '(1 0 2))
('(0 0 2) '(2 2) '(2 0 0))
('(0 0 2) '(0 2 5) '(0 0 0))
('(2 2 1) '(0 0 0 0 2 3) '(1 0 0))
('(2 2 1) '(0 0 0 0 3 4) '(0 0 0))))
(alignment jewel-list expected)
(let ((*jewels* *test-jewels*))
(is (equal (stuff-jewels alignment jewel-list)
expected)))
(let ((*jewels* *test-jewels*))
(is (equal (stuff-jewels-fast alignment jewel-list)
expected))))
(deftest encode-jewels-test ()
(let ((*jewels* *test-jewels*)
(jewel-list '(1 3 5))
(ids '(1 0)))
(is (equal (decode-skill-sig-full (encode-jewels jewel-list ids) 2)
'(4 -2)))))
(deftest (dfs-jewel-query-test
:cases (('(0 0 0) '((:key (0 0) :set (nil))))
('(1 0 0) '((:key (0 0) :set (nil))
(:key (1 -1) :set ((0)))
(:key (-1 1) :set ((1)))))
('(2 0 0) '((:key (0 0) :set (nil (0 1)))
(:key (1 -1) :set ((0)))
(:key (-1 1) :set ((1)))
(:key (-2 2) :set ((1 1)))
(:key (2 -2) :set ((0 0)))))
('(1 1 0) '((:key (0 0) :set (nil (0 1)))
(:key (1 -1) :set ((0) (0 0 1)))
(:key (-1 1) :set ((1) (0 1 1)))
(:key (3 -3) :set ((0 0 0)))
(:key (-3 3) :set ((1 1 1)))
(:key (2 -2) :set ((0 0)))
(:key (-2 2) :set ((1 1)))
(:key (3 -1) :set ((2)))
(:key (-1 3) :set ((3)))
(:key (4 -2) :set ((0 2)))
(:key (0 2) :set ((0 3)))
(:key (-2 4) :set ((1 3)))
(:key (2 0) :set ((1 2)))))))
(hole-alignment expected)
;; Assuming there are two skills with id 0 (attack) and 1 (defense).
(let ((*jewels* *test-jewels*))
(let ((client (jewel-query-client '((0 2) (1 4)))))
(is (set-equal (dfs-jewel-query '(0 1) hole-alignment)
(loop for item in expected
collect (make-keyed-jewel-set
:key (encode-skill-sig (second item))
:set (fourth item)))
:test #'keyed-jewel-set-equal)))))
(deftest (jewel-query-client-test
:cases (('(0 0 0))
('(1 0 0))
('(2 0 0))
('(7 0 0))
('(0 1 0))
('(0 5 0))
('(1 1 0))
('(1 2 0))
('(3 4 0))
('(0 0 1))
('(0 1 1))
('(2 2 1))
('(1 2 2))))
(hole-alignment)
;; Assuming there are two skills with id 0 (attack) and 1 (defense).
(let ((*jewels* *test-jewels*))
(let* ((required-effects '((0 2) (1 4)))
(client (jewel-query-client required-effects)))
(is (set-equal (funcall client (encode-hole-sig hole-alignment))
(dfs-jewel-query (mapcar #'car required-effects)
hole-alignment)
:test #'keyed-jewel-set-equal)))))
(deftest (targeted-jewel-query-client-test
:cases (('(0 0 0))
('(1 0 0))
('(2 0 0))
('(7 0 0))
('(0 1 0))
('(0 5 0))
('(1 1 0))
('(1 2 0))
('(3 4 0))
('(0 0 1))
('(0 1 1))
('(2 2 1))
('(1 2 2))))
(hole-alignment)
;; Assuming there are two skills with id 0 (attack) and 1 (defense).
(let ((*jewels* *test-jewels*))
(let* ((required-effects '((0 2) (1 4)))
(client (jewel-query-client required-effects 1)))
(is (set-equal (funcall client (encode-hole-sig hole-alignment))
(dfs-jewel-query (mapcar #'car required-effects)
hole-alignment 1)
:test #'keyed-jewel-set-equal)))))
(defparameter *test-armors*
(list (make-armor :id 0 :part-id 0 :effects '((0 3) (2 1)))
(make-armor :id 1 :part-id 0 :effects '((0 3) (2 2)))
(make-armor :id 2 :part-id 0 :effects '((1 2)))
(make-armor :id 3 :part-id 0 :effects '((1 2) (2 3)))
(make-armor :id 4 :part-id 1 :effects '((1 2)))
(make-armor :id 5 :part-id 1 :effects '((1 2) (2 1)))
(make-armor :id 6 :part-id 1 :effects '((0 4)))
(make-armor :id 7 :part-id 1 :effects '((0 4) (2 -2)))
(make-armor :id 8 :part-id 1 :effects '((0 2)))
(make-armor :id 9 :part-id 2 :effects '((0 1) (2 1)))
(make-armor :id 10 :part-id 2 :effects '((0 1) (2 2)))
(make-armor :id 11 :part-id 2 :effects '((0 1)))
(make-armor :id 12 :part-id 2 :effects '((2 3)))
(make-armor :id 13 :part-id 2 :effects '((0 2) (2 -1)))))
(defun armor-equal (x y)
(and (= (armor-id x) (armor-id y))
(= (armor-part-id x) (armor-part-id y))))
(defun armor-forest-equal (x y)
(if (armor-p (car y))
(set-equal x y :test #'armor-equal)
(set-equal x y
:test #'armor-tree-equal)))
(defun armor-tree-equal (x y)
(and (set-equal (armor-tree-left x)
(armor-tree-left y)
:test #'armor-equal)
(armor-forest-equal (armor-tree-right x)
(armor-tree-right y))))
(defun prelim-equal (x y)
(and (= (preliminary-key x) (preliminary-key y))
(set-equal (preliminary-jewel-sets x)
(preliminary-jewel-sets y)
:test #'set-equal)
(armor-forest-equal (preliminary-forest x)
(preliminary-forest y))))
(defun assemble-forest (code-forest)
(cond ((eq (car code-forest) :tree)
(make-armor-tree
:left (loop for code in (second code-forest)
collect (nth code *test-armors*))
:right (assemble-forest (third code-forest))))
((consp (car code-forest))
(loop for sub-tree in code-forest
collect (assemble-forest sub-tree)))
(t (loop for code in code-forest
collect (nth code *test-armors*)))))
(defun ensure-skill-points (forest skill-id skill-points)
(if (armor-p (car forest))
(every #`,(= (points-of-skill x1 skill-id)
skill-points)
forest)
(every (lambda (tree)
(let ((current (points-of-skill
(car (armor-tree-left tree))
skill-id)))
(and (ensure-skill-points
(armor-tree-left tree)
skill-id
current)
(ensure-skill-points
(armor-tree-right tree)
skill-id
(- skill-points current)))))
forest)))
(deftest split-forest-at-skill-test ()
(let ((forest (assemble-forest '((:tree (0 1) ((:tree (4) (9 10))
(:tree (5) (11))))
(:tree (2 3) ((:tree (6 7) (12))
(:tree (8) (13))))))))
(is (ensure-skill-points forest 0 4))
(is (ensure-skill-points forest 1 2))
(let ((result (split-forest-at-skill forest 2 3)))
(is (armor-forest-equal
(getf (car result) 3)
(assemble-forest '((:tree (1) ((:tree (4) (9))
(:tree (5) (11))))
(:tree (0) ((:tree (4) (10))))
(:tree (2) ((:tree (6) (12))))))))
(is (armor-forest-equal
(getf (car result) 4)
(assemble-forest '((:tree (1) ((:tree (4) (10))))
(:tree (3) ((:tree (7) (12))))))))
(is (armor-forest-equal
(getf (car result) 6)
(assemble-forest '((:tree (3) ((:tree (6) (12)))))))))))
(defun mock-max-at-skill-client (target-id)
(let ((store (make-array '(7 400) :element-type 'fixnum :initial-element 0)))
(declare (type (simple-array fixnum (7 400)) store))
(loop for item in *test-armors*
do (setf (aref store (armor-part-id item) (armor-id item))
(the fixnum (points-of-skill item target-id))))
(labels ((client (forest)
(if (armor-p (car forest))
;; case 1: last level
(the fixnum (loop for item in forest
maximize (aref store
(armor-part-id item)
(armor-id item))))
;; case 2 middle levels
(the fixnum
(loop for tree in forest
maximize (+ (the fixnum
(loop for item in (armor-tree-left tree)
maximize (aref store
(armor-part-id item)
(armor-id item))))
(client (armor-tree-right tree))))))))
#'client)))
(deftest extra-skill-split-test ()
(let* ((*jewels* *test-jewels*)
(forest (assemble-forest '((:tree (0 1) ((:tree (4) (9 10))
(:tree (5) (11))))
(:tree (2 3) ((:tree (6 7) (12))
(:tree (8) (13)))))))
(env (make-split-env :hole-query
(jewel-query-client '((0 6) (1 4) (2 7)))
:target-id 2
:encoder (jewels-encoder '(0 1 2))
:target-points 7
:inv-req-key (encode-skill-sig '(-6 -4 -7))
:satisfy-mask (gen-skill-mask 3)
:forest-maximizer (mock-max-at-skill-client 2)
:n 2))
(result (extra-skill-split
(make-preliminary :key (encode-sig '(0 2 1)
'(4 2))
:forest forest
:jewel-sets '((2 3)))
env)))
(is (set-equal result
(list (make-preliminary
:key (encode-sig '(0 2 1) '(4 2 6))
:forest (assemble-forest
'((:tree (3) ((:tree (6) (12))))))
:jewel-sets '((2 3 5)))
(make-preliminary
:key (encode-sig '(0 2 1) '(4 2 4))
:forest (assemble-forest
'((:tree (1) ((:tree (4) (10))))
(:tree (3) ((:tree (7) (12))))))
:jewel-sets '((2 3 5))))
:test #'prelim-equal))))
|
[
{
"context": ";;;;\n;;;\n;; @file tst-nleq.lisp\n;; @author Mitch Richling <https://www.mitchr.me>\n;; @brief Unit tests.",
"end": 306,
"score": 0.9998886585235596,
"start": 292,
"tag": "NAME",
"value": "Mitch Richling"
},
{
"context": "\n;; Copyright (c) 1997,1998,2004,2013,2014,,2015, Mitchell Jay Richling <https://www.mitchr.me> All rights reserved.\n;;\n;",
"end": 514,
"score": 0.99989253282547,
"start": 493,
"tag": "NAME",
"value": "Mitchell Jay Richling"
}
] |
tst-nleq.lisp
|
richmit/mjrcalc
| 17 |
;; -*- Mode:Lisp; Syntax:ANSI-Common-LISP; Coding:us-ascii-unix; fill-column:158 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;; @file tst-nleq.lisp
;; @author Mitch Richling <https://www.mitchr.me>
;; @brief Unit tests.@EOL
;; @std Common Lisp
;; @see use-nleq.lisp
;; @copyright
;; @parblock
;; Copyright (c) 1997,1998,2004,2013,2014,,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
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defpackage :MJR_NLEQ-TESTS (:USE :COMMON-LISP :LISP-UNIT :MJR_NLEQ :MJR_EPS))
(in-package :MJR_NLEQ-TESTS)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun f1 (x) (values (+ (* 1 x x x x x) (* -4 x x x x) (* -5 x x x) (* 20 x x) (* 4 x) -16) ; -1 1 -2 2 4
(+ (* 5 x x x x) (* -16 x x x) (* -15 x x) (* 40 x) 4)
(+ (* 20 x x x) (* -48 x x) (* -30 x) 40)
(+ (* 60 x x) (* -96 x) -30)))
(defvar f1s "x^5-4*x^4-5*x^3+20*x^2+4*x-16")
(defun f2 (x) (values (sin x) ; 0
(cos x)
(- (sin x))))
(defvar f2s "sin(x)")
(defun f3 (x) (values x ; 0
1
0))
(defvar f3s "x")
(defun f4 (x) (values (* 3 x) ; 0
3
0))
(defvar f4s "3*x")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-test mjr_nleq_root-bsect
(assert-equalp (values 0 0 nil) (mjr_nleq_root-bsect #'f3 -1 1))
(assert-equalp (values 0 0 nil) (mjr_nleq_root-bsect #'f3 -1 1 :use-false-position 't))
(assert-equalp (values 0 0 nil) (mjr_nleq_root-bsect #'f4 -1 2 :use-false-position 't))
(assert-equalp (values 0 0 nil) (mjr_nleq_root-bsect f3s -1 1))
(assert-equalp (values 0 0 nil) (mjr_nleq_root-bsect f3s -1 1 :use-false-position 't))
(assert-equalp (values 0 0 nil) (mjr_nleq_root-bsect f4s -1 2 :use-false-position 't))
;; Close to a good answer..
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect #'f2 -1.0 0.5))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect #'f3 -1.0 1.5))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect #'f1 -10.0 -1.5 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect #'f1 -1.5 -0.5 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect #'f1 -1.5 -10 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect #'f1 -0.5 -1.5 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect f2s -1.0 0.5))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect f3s -1.0 1.5))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect f1s -10.0 -1.5 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect f1s -1.5 -0.5 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect f1s -1.5 -10 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect f1s -0.5 -1.5 :xeps 1e-10))
;; Now do it with :use-false-position..
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect #'f2 -1.0 0.5 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect #'f3 -1.0 1.5 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect #'f1 -10.0 -1.5 :xeps 1e-10 :use-false-position 't :yeps 0 :max-itr 3000)) ; Pathological case for false position
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect #'f1 -1.5 -0.5 :xeps 1e-10 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect #'f1 -1.5 -10 :xeps 1e-10 :use-false-position 't :yeps 0 :max-itr 3000)) ; Pathological case for false position
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect #'f1 -0.5 -1.5 :xeps 1e-10 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect f2s -1.0 0.5 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect f3s -1.0 1.5 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect f1s -10.0 -1.5 :xeps 1e-10 :use-false-position 't :yeps 0 :max-itr 3000)) ; Pathological case for false position
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect f1s -1.5 -0.5 :xeps 1e-10 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect f1s -1.5 -10 :xeps 1e-10 :use-false-position 't :yeps 0 :max-itr 3000)) ; Pathological case for false position
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect f1s -0.5 -1.5 :xeps 1e-10 :use-false-position 't))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-test mjr_nleq_root-newton
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-newton #'f2 1.1))
(assert-equality (mjr_eps_make-fixed= .001) 1 (mjr_nleq_root-newton #'f1 1.1))
(assert-equality (mjr_eps_make-fixed= .001) 2 (mjr_nleq_root-newton #'f1 2.1))
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-newton #'f1 -1.1))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-newton f2s 1.1))
(assert-equality (mjr_eps_make-fixed= .001) 1 (mjr_nleq_root-newton f1s 1.1))
(assert-equality (mjr_eps_make-fixed= .001) 2 (mjr_nleq_root-newton f1s 2.1))
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-newton f1s -1.1))
(assert-equality (mjr_eps_make-fixed= .01) pi (mjr_nleq_root-newton "log(x)*sin(x)" 3.5e0))
(assert-equality (mjr_eps_make-fixed= .01) pi (mjr_nleq_root-newton "sin(x)*sin(x)" 3.5e0))
(assert-equality (mjr_eps_make-fixed= .01) pi (mjr_nleq_root-newton "x^2*sin(x)" 3.5e0))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-test mjr_nleq_root-laguerre
(assert-equality (mjr_eps_make-fixed= .0001) 0 (mjr_nleq_root-laguerre #'f2 10 1.1))
(assert-equality (mjr_eps_make-fixed= .0001) 1 (mjr_nleq_root-laguerre #'f1 5 1.1))
(assert-equality (mjr_eps_make-fixed= .0001) 2 (mjr_nleq_root-laguerre #'f1 5 2.1))
(assert-equality (mjr_eps_make-fixed= .0001) -1 (mjr_nleq_root-laguerre #'f1 5 -1.1))
(assert-equality (mjr_eps_make-fixed= .0001) 0 (mjr_nleq_root-laguerre f2s 10 1.1))
(assert-equality (mjr_eps_make-fixed= .0001) 1 (mjr_nleq_root-laguerre f1s 5 1.1))
(assert-equality (mjr_eps_make-fixed= .0001) 2 (mjr_nleq_root-laguerre f1s 5 2.1))
(assert-equality (mjr_eps_make-fixed= .0001) -1 (mjr_nleq_root-laguerre f1s 5 -1.1))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-test mjr_nleq_fixed-point-itr
(assert-equality (mjr_eps_make-fixed= .001) 1.1140665 (mjr_nleq_fixed-point-itr (lambda (x) (/ (sin x))) 1))
(assert-equality (mjr_eps_make-fixed= .001) 1.1140665 (mjr_nleq_fixed-point-itr "1/sin(x)" 1))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(run-tests)
|
83515
|
;; -*- Mode:Lisp; Syntax:ANSI-Common-LISP; Coding:us-ascii-unix; fill-column:158 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;; @file tst-nleq.lisp
;; @author <NAME> <https://www.mitchr.me>
;; @brief Unit tests.@EOL
;; @std Common Lisp
;; @see use-nleq.lisp
;; @copyright
;; @parblock
;; Copyright (c) 1997,1998,2004,2013,2014,,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
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defpackage :MJR_NLEQ-TESTS (:USE :COMMON-LISP :LISP-UNIT :MJR_NLEQ :MJR_EPS))
(in-package :MJR_NLEQ-TESTS)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun f1 (x) (values (+ (* 1 x x x x x) (* -4 x x x x) (* -5 x x x) (* 20 x x) (* 4 x) -16) ; -1 1 -2 2 4
(+ (* 5 x x x x) (* -16 x x x) (* -15 x x) (* 40 x) 4)
(+ (* 20 x x x) (* -48 x x) (* -30 x) 40)
(+ (* 60 x x) (* -96 x) -30)))
(defvar f1s "x^5-4*x^4-5*x^3+20*x^2+4*x-16")
(defun f2 (x) (values (sin x) ; 0
(cos x)
(- (sin x))))
(defvar f2s "sin(x)")
(defun f3 (x) (values x ; 0
1
0))
(defvar f3s "x")
(defun f4 (x) (values (* 3 x) ; 0
3
0))
(defvar f4s "3*x")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-test mjr_nleq_root-bsect
(assert-equalp (values 0 0 nil) (mjr_nleq_root-bsect #'f3 -1 1))
(assert-equalp (values 0 0 nil) (mjr_nleq_root-bsect #'f3 -1 1 :use-false-position 't))
(assert-equalp (values 0 0 nil) (mjr_nleq_root-bsect #'f4 -1 2 :use-false-position 't))
(assert-equalp (values 0 0 nil) (mjr_nleq_root-bsect f3s -1 1))
(assert-equalp (values 0 0 nil) (mjr_nleq_root-bsect f3s -1 1 :use-false-position 't))
(assert-equalp (values 0 0 nil) (mjr_nleq_root-bsect f4s -1 2 :use-false-position 't))
;; Close to a good answer..
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect #'f2 -1.0 0.5))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect #'f3 -1.0 1.5))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect #'f1 -10.0 -1.5 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect #'f1 -1.5 -0.5 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect #'f1 -1.5 -10 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect #'f1 -0.5 -1.5 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect f2s -1.0 0.5))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect f3s -1.0 1.5))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect f1s -10.0 -1.5 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect f1s -1.5 -0.5 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect f1s -1.5 -10 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect f1s -0.5 -1.5 :xeps 1e-10))
;; Now do it with :use-false-position..
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect #'f2 -1.0 0.5 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect #'f3 -1.0 1.5 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect #'f1 -10.0 -1.5 :xeps 1e-10 :use-false-position 't :yeps 0 :max-itr 3000)) ; Pathological case for false position
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect #'f1 -1.5 -0.5 :xeps 1e-10 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect #'f1 -1.5 -10 :xeps 1e-10 :use-false-position 't :yeps 0 :max-itr 3000)) ; Pathological case for false position
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect #'f1 -0.5 -1.5 :xeps 1e-10 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect f2s -1.0 0.5 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect f3s -1.0 1.5 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect f1s -10.0 -1.5 :xeps 1e-10 :use-false-position 't :yeps 0 :max-itr 3000)) ; Pathological case for false position
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect f1s -1.5 -0.5 :xeps 1e-10 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect f1s -1.5 -10 :xeps 1e-10 :use-false-position 't :yeps 0 :max-itr 3000)) ; Pathological case for false position
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect f1s -0.5 -1.5 :xeps 1e-10 :use-false-position 't))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-test mjr_nleq_root-newton
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-newton #'f2 1.1))
(assert-equality (mjr_eps_make-fixed= .001) 1 (mjr_nleq_root-newton #'f1 1.1))
(assert-equality (mjr_eps_make-fixed= .001) 2 (mjr_nleq_root-newton #'f1 2.1))
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-newton #'f1 -1.1))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-newton f2s 1.1))
(assert-equality (mjr_eps_make-fixed= .001) 1 (mjr_nleq_root-newton f1s 1.1))
(assert-equality (mjr_eps_make-fixed= .001) 2 (mjr_nleq_root-newton f1s 2.1))
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-newton f1s -1.1))
(assert-equality (mjr_eps_make-fixed= .01) pi (mjr_nleq_root-newton "log(x)*sin(x)" 3.5e0))
(assert-equality (mjr_eps_make-fixed= .01) pi (mjr_nleq_root-newton "sin(x)*sin(x)" 3.5e0))
(assert-equality (mjr_eps_make-fixed= .01) pi (mjr_nleq_root-newton "x^2*sin(x)" 3.5e0))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-test mjr_nleq_root-laguerre
(assert-equality (mjr_eps_make-fixed= .0001) 0 (mjr_nleq_root-laguerre #'f2 10 1.1))
(assert-equality (mjr_eps_make-fixed= .0001) 1 (mjr_nleq_root-laguerre #'f1 5 1.1))
(assert-equality (mjr_eps_make-fixed= .0001) 2 (mjr_nleq_root-laguerre #'f1 5 2.1))
(assert-equality (mjr_eps_make-fixed= .0001) -1 (mjr_nleq_root-laguerre #'f1 5 -1.1))
(assert-equality (mjr_eps_make-fixed= .0001) 0 (mjr_nleq_root-laguerre f2s 10 1.1))
(assert-equality (mjr_eps_make-fixed= .0001) 1 (mjr_nleq_root-laguerre f1s 5 1.1))
(assert-equality (mjr_eps_make-fixed= .0001) 2 (mjr_nleq_root-laguerre f1s 5 2.1))
(assert-equality (mjr_eps_make-fixed= .0001) -1 (mjr_nleq_root-laguerre f1s 5 -1.1))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-test mjr_nleq_fixed-point-itr
(assert-equality (mjr_eps_make-fixed= .001) 1.1140665 (mjr_nleq_fixed-point-itr (lambda (x) (/ (sin x))) 1))
(assert-equality (mjr_eps_make-fixed= .001) 1.1140665 (mjr_nleq_fixed-point-itr "1/sin(x)" 1))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(run-tests)
| true |
;; -*- Mode:Lisp; Syntax:ANSI-Common-LISP; Coding:us-ascii-unix; fill-column:158 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;; @file tst-nleq.lisp
;; @author PI:NAME:<NAME>END_PI <https://www.mitchr.me>
;; @brief Unit tests.@EOL
;; @std Common Lisp
;; @see use-nleq.lisp
;; @copyright
;; @parblock
;; Copyright (c) 1997,1998,2004,2013,2014,,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
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defpackage :MJR_NLEQ-TESTS (:USE :COMMON-LISP :LISP-UNIT :MJR_NLEQ :MJR_EPS))
(in-package :MJR_NLEQ-TESTS)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun f1 (x) (values (+ (* 1 x x x x x) (* -4 x x x x) (* -5 x x x) (* 20 x x) (* 4 x) -16) ; -1 1 -2 2 4
(+ (* 5 x x x x) (* -16 x x x) (* -15 x x) (* 40 x) 4)
(+ (* 20 x x x) (* -48 x x) (* -30 x) 40)
(+ (* 60 x x) (* -96 x) -30)))
(defvar f1s "x^5-4*x^4-5*x^3+20*x^2+4*x-16")
(defun f2 (x) (values (sin x) ; 0
(cos x)
(- (sin x))))
(defvar f2s "sin(x)")
(defun f3 (x) (values x ; 0
1
0))
(defvar f3s "x")
(defun f4 (x) (values (* 3 x) ; 0
3
0))
(defvar f4s "3*x")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-test mjr_nleq_root-bsect
(assert-equalp (values 0 0 nil) (mjr_nleq_root-bsect #'f3 -1 1))
(assert-equalp (values 0 0 nil) (mjr_nleq_root-bsect #'f3 -1 1 :use-false-position 't))
(assert-equalp (values 0 0 nil) (mjr_nleq_root-bsect #'f4 -1 2 :use-false-position 't))
(assert-equalp (values 0 0 nil) (mjr_nleq_root-bsect f3s -1 1))
(assert-equalp (values 0 0 nil) (mjr_nleq_root-bsect f3s -1 1 :use-false-position 't))
(assert-equalp (values 0 0 nil) (mjr_nleq_root-bsect f4s -1 2 :use-false-position 't))
;; Close to a good answer..
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect #'f2 -1.0 0.5))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect #'f3 -1.0 1.5))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect #'f1 -10.0 -1.5 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect #'f1 -1.5 -0.5 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect #'f1 -1.5 -10 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect #'f1 -0.5 -1.5 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect f2s -1.0 0.5))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect f3s -1.0 1.5))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect f1s -10.0 -1.5 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect f1s -1.5 -0.5 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect f1s -1.5 -10 :xeps 1e-10))
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect f1s -0.5 -1.5 :xeps 1e-10))
;; Now do it with :use-false-position..
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect #'f2 -1.0 0.5 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect #'f3 -1.0 1.5 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect #'f1 -10.0 -1.5 :xeps 1e-10 :use-false-position 't :yeps 0 :max-itr 3000)) ; Pathological case for false position
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect #'f1 -1.5 -0.5 :xeps 1e-10 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect #'f1 -1.5 -10 :xeps 1e-10 :use-false-position 't :yeps 0 :max-itr 3000)) ; Pathological case for false position
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect #'f1 -0.5 -1.5 :xeps 1e-10 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect f2s -1.0 0.5 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-bsect f3s -1.0 1.5 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect f1s -10.0 -1.5 :xeps 1e-10 :use-false-position 't :yeps 0 :max-itr 3000)) ; Pathological case for false position
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect f1s -1.5 -0.5 :xeps 1e-10 :use-false-position 't))
(assert-equality (mjr_eps_make-fixed= .001) -2 (mjr_nleq_root-bsect f1s -1.5 -10 :xeps 1e-10 :use-false-position 't :yeps 0 :max-itr 3000)) ; Pathological case for false position
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-bsect f1s -0.5 -1.5 :xeps 1e-10 :use-false-position 't))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-test mjr_nleq_root-newton
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-newton #'f2 1.1))
(assert-equality (mjr_eps_make-fixed= .001) 1 (mjr_nleq_root-newton #'f1 1.1))
(assert-equality (mjr_eps_make-fixed= .001) 2 (mjr_nleq_root-newton #'f1 2.1))
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-newton #'f1 -1.1))
(assert-equality (mjr_eps_make-fixed= .001) 0 (mjr_nleq_root-newton f2s 1.1))
(assert-equality (mjr_eps_make-fixed= .001) 1 (mjr_nleq_root-newton f1s 1.1))
(assert-equality (mjr_eps_make-fixed= .001) 2 (mjr_nleq_root-newton f1s 2.1))
(assert-equality (mjr_eps_make-fixed= .001) -1 (mjr_nleq_root-newton f1s -1.1))
(assert-equality (mjr_eps_make-fixed= .01) pi (mjr_nleq_root-newton "log(x)*sin(x)" 3.5e0))
(assert-equality (mjr_eps_make-fixed= .01) pi (mjr_nleq_root-newton "sin(x)*sin(x)" 3.5e0))
(assert-equality (mjr_eps_make-fixed= .01) pi (mjr_nleq_root-newton "x^2*sin(x)" 3.5e0))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-test mjr_nleq_root-laguerre
(assert-equality (mjr_eps_make-fixed= .0001) 0 (mjr_nleq_root-laguerre #'f2 10 1.1))
(assert-equality (mjr_eps_make-fixed= .0001) 1 (mjr_nleq_root-laguerre #'f1 5 1.1))
(assert-equality (mjr_eps_make-fixed= .0001) 2 (mjr_nleq_root-laguerre #'f1 5 2.1))
(assert-equality (mjr_eps_make-fixed= .0001) -1 (mjr_nleq_root-laguerre #'f1 5 -1.1))
(assert-equality (mjr_eps_make-fixed= .0001) 0 (mjr_nleq_root-laguerre f2s 10 1.1))
(assert-equality (mjr_eps_make-fixed= .0001) 1 (mjr_nleq_root-laguerre f1s 5 1.1))
(assert-equality (mjr_eps_make-fixed= .0001) 2 (mjr_nleq_root-laguerre f1s 5 2.1))
(assert-equality (mjr_eps_make-fixed= .0001) -1 (mjr_nleq_root-laguerre f1s 5 -1.1))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-test mjr_nleq_fixed-point-itr
(assert-equality (mjr_eps_make-fixed= .001) 1.1140665 (mjr_nleq_fixed-point-itr (lambda (x) (/ (sin x))) 1))
(assert-equality (mjr_eps_make-fixed= .001) 1.1140665 (mjr_nleq_fixed-point-itr "1/sin(x)" 1))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(run-tests)
|
[
{
"context": "; DEALINGS IN THE SOFTWARE.\n;\n; Original author: Jared Davis <[email protected]>\n\n(in-package \"VL\")\n(include-",
"end": 1390,
"score": 0.9996490478515625,
"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 \"base\")\n(includ",
"end": 1410,
"score": 0.9999331831932068,
"start": 1392,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/centaur/vl/loader/parser/tests/imports.lisp
|
mayankmanj/acl2
| 305 |
; 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 "base")
(include-book "../imports")
(define vl-pretty-import ((x vl-import-p))
(list 'import
(vl-import->pkg x)
(vl-import->part x)
(vl-pretty-atts (vl-import->atts x))))
(defprojection vl-pretty-imports ((x vl-importlist-p))
(vl-pretty-import x))
(encapsulate nil
(local (in-theory (enable vl-is-token?
vl-lookahead-is-token?
)))
(defparser-top vl-parse-package-import-declaration
:guard (and (vl-lookahead-is-token? :vl-kwd-import tokens)
(vl-lookahead-is-token? :vl-idtoken (cdr tokens))
(vl-atts-p atts))))
(defmacro test-import (&key input expect (successp 't) atts)
`(assert! (b* ((tokens (make-test-tokens ,input))
(pstate (make-vl-parsestate :warnings nil))
(config *vl-default-loadconfig*)
((mv erp val ?tokens (vl-parsestate pstate))
(vl-parse-package-import-declaration-top ,atts))
((when erp)
(cw "ERP is ~x0.~%" erp)
(not ,successp)))
(cw "VAL is ~x0.~%" val)
(debuggable-and ,successp
(equal (vl-pretty-imports val) ,expect)
(not pstate.warnings)))))
(test-import :input "import foo::*;"
:expect '((import "foo" :vl-import* nil)))
(test-import :input "import foo :: bar;"
:expect '((import "foo" "bar" nil)))
(test-import :input "import foo::baz;"
:expect '((import "foo" "baz" nil)))
(test-import :input "import \\foo-bar ::baz;"
:expect '((import "foo-bar" "baz" nil)))
(test-import :input "import \\foo-bar ::\\baz-beep ;"
:expect '((import "foo-bar" "baz-beep" nil)))
(test-import :input "import foo::*, foo::bar;"
:expect '((import "foo" :vl-import* nil)
(import "foo" "bar" nil)))
(test-import :input "import foo::bar, foo::baz;"
:expect '((import "foo" "bar" nil)
(import "foo" "baz" nil)))
(test-import :input "import foo::*, foo::bar;"
:atts (list (cons "myatt" (vl-idexpr "myval")))
:expect '((import "foo" :vl-import* (("myatt" <- (id "myval"))))
(import "foo" "bar" (("myatt" <- (id "myval"))))))
;; These are now ruled out by our guard due to adding DPI stuff.
;; (test-import :input "import" ;; sanity check early eof
;; :successp nil)
;; (test-import :input "import ;" ;; need at least one item
;; :successp nil)
(test-import :input "import foo::*" ;; missing semicolon
:successp nil)
(test-import :input "import foo, bar;" ;; missing :: stuff
:successp nil)
(test-import :input "import \\foo-bar ::\\baz-beep; " ;; missing space after baz-beep
:successp nil)
(test-import :input "import foo::*, foo::bar" ;; no semicolon
:successp nil)
(test-import :input "import foo::*, foo::bar, " ;; no item
:successp nil)
(test-import :input "import foo::*, foo::bar, foo:: ;" ;; no name
:successp nil)
(test-import :input "import foo::*, foo::bar, foo ;" ;; no name
:successp nil)
(test-import :input "import foo::*, foo::bar, foo"
:successp nil)
|
1566
|
; 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 "base")
(include-book "../imports")
(define vl-pretty-import ((x vl-import-p))
(list 'import
(vl-import->pkg x)
(vl-import->part x)
(vl-pretty-atts (vl-import->atts x))))
(defprojection vl-pretty-imports ((x vl-importlist-p))
(vl-pretty-import x))
(encapsulate nil
(local (in-theory (enable vl-is-token?
vl-lookahead-is-token?
)))
(defparser-top vl-parse-package-import-declaration
:guard (and (vl-lookahead-is-token? :vl-kwd-import tokens)
(vl-lookahead-is-token? :vl-idtoken (cdr tokens))
(vl-atts-p atts))))
(defmacro test-import (&key input expect (successp 't) atts)
`(assert! (b* ((tokens (make-test-tokens ,input))
(pstate (make-vl-parsestate :warnings nil))
(config *vl-default-loadconfig*)
((mv erp val ?tokens (vl-parsestate pstate))
(vl-parse-package-import-declaration-top ,atts))
((when erp)
(cw "ERP is ~x0.~%" erp)
(not ,successp)))
(cw "VAL is ~x0.~%" val)
(debuggable-and ,successp
(equal (vl-pretty-imports val) ,expect)
(not pstate.warnings)))))
(test-import :input "import foo::*;"
:expect '((import "foo" :vl-import* nil)))
(test-import :input "import foo :: bar;"
:expect '((import "foo" "bar" nil)))
(test-import :input "import foo::baz;"
:expect '((import "foo" "baz" nil)))
(test-import :input "import \\foo-bar ::baz;"
:expect '((import "foo-bar" "baz" nil)))
(test-import :input "import \\foo-bar ::\\baz-beep ;"
:expect '((import "foo-bar" "baz-beep" nil)))
(test-import :input "import foo::*, foo::bar;"
:expect '((import "foo" :vl-import* nil)
(import "foo" "bar" nil)))
(test-import :input "import foo::bar, foo::baz;"
:expect '((import "foo" "bar" nil)
(import "foo" "baz" nil)))
(test-import :input "import foo::*, foo::bar;"
:atts (list (cons "myatt" (vl-idexpr "myval")))
:expect '((import "foo" :vl-import* (("myatt" <- (id "myval"))))
(import "foo" "bar" (("myatt" <- (id "myval"))))))
;; These are now ruled out by our guard due to adding DPI stuff.
;; (test-import :input "import" ;; sanity check early eof
;; :successp nil)
;; (test-import :input "import ;" ;; need at least one item
;; :successp nil)
(test-import :input "import foo::*" ;; missing semicolon
:successp nil)
(test-import :input "import foo, bar;" ;; missing :: stuff
:successp nil)
(test-import :input "import \\foo-bar ::\\baz-beep; " ;; missing space after baz-beep
:successp nil)
(test-import :input "import foo::*, foo::bar" ;; no semicolon
:successp nil)
(test-import :input "import foo::*, foo::bar, " ;; no item
:successp nil)
(test-import :input "import foo::*, foo::bar, foo:: ;" ;; no name
:successp nil)
(test-import :input "import foo::*, foo::bar, foo ;" ;; no name
:successp nil)
(test-import :input "import foo::*, foo::bar, foo"
:successp nil)
| 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 "base")
(include-book "../imports")
(define vl-pretty-import ((x vl-import-p))
(list 'import
(vl-import->pkg x)
(vl-import->part x)
(vl-pretty-atts (vl-import->atts x))))
(defprojection vl-pretty-imports ((x vl-importlist-p))
(vl-pretty-import x))
(encapsulate nil
(local (in-theory (enable vl-is-token?
vl-lookahead-is-token?
)))
(defparser-top vl-parse-package-import-declaration
:guard (and (vl-lookahead-is-token? :vl-kwd-import tokens)
(vl-lookahead-is-token? :vl-idtoken (cdr tokens))
(vl-atts-p atts))))
(defmacro test-import (&key input expect (successp 't) atts)
`(assert! (b* ((tokens (make-test-tokens ,input))
(pstate (make-vl-parsestate :warnings nil))
(config *vl-default-loadconfig*)
((mv erp val ?tokens (vl-parsestate pstate))
(vl-parse-package-import-declaration-top ,atts))
((when erp)
(cw "ERP is ~x0.~%" erp)
(not ,successp)))
(cw "VAL is ~x0.~%" val)
(debuggable-and ,successp
(equal (vl-pretty-imports val) ,expect)
(not pstate.warnings)))))
(test-import :input "import foo::*;"
:expect '((import "foo" :vl-import* nil)))
(test-import :input "import foo :: bar;"
:expect '((import "foo" "bar" nil)))
(test-import :input "import foo::baz;"
:expect '((import "foo" "baz" nil)))
(test-import :input "import \\foo-bar ::baz;"
:expect '((import "foo-bar" "baz" nil)))
(test-import :input "import \\foo-bar ::\\baz-beep ;"
:expect '((import "foo-bar" "baz-beep" nil)))
(test-import :input "import foo::*, foo::bar;"
:expect '((import "foo" :vl-import* nil)
(import "foo" "bar" nil)))
(test-import :input "import foo::bar, foo::baz;"
:expect '((import "foo" "bar" nil)
(import "foo" "baz" nil)))
(test-import :input "import foo::*, foo::bar;"
:atts (list (cons "myatt" (vl-idexpr "myval")))
:expect '((import "foo" :vl-import* (("myatt" <- (id "myval"))))
(import "foo" "bar" (("myatt" <- (id "myval"))))))
;; These are now ruled out by our guard due to adding DPI stuff.
;; (test-import :input "import" ;; sanity check early eof
;; :successp nil)
;; (test-import :input "import ;" ;; need at least one item
;; :successp nil)
(test-import :input "import foo::*" ;; missing semicolon
:successp nil)
(test-import :input "import foo, bar;" ;; missing :: stuff
:successp nil)
(test-import :input "import \\foo-bar ::\\baz-beep; " ;; missing space after baz-beep
:successp nil)
(test-import :input "import foo::*, foo::bar" ;; no semicolon
:successp nil)
(test-import :input "import foo::*, foo::bar, " ;; no item
:successp nil)
(test-import :input "import foo::*, foo::bar, foo:: ;" ;; no name
:successp nil)
(test-import :input "import foo::*, foo::bar, foo ;" ;; no name
:successp nil)
(test-import :input "import foo::*, foo::bar, foo"
:successp nil)
|
[
{
"context": ";-*- Mode: Lisp -*-\n;;;; Author: Paul Dietz\n;;;; Created: Thu Oct 10 22:39:25 2002\n;;;; Cont",
"end": 49,
"score": 0.9998606443405151,
"start": 39,
"tag": "NAME",
"value": "Paul Dietz"
}
] |
programs/ansi-test/data-and-control-flow/call-arguments-limit.lsp
|
TeamSPoon/wam_common_lisp_devel_workspace
| 8 |
;-*- Mode: Lisp -*-
;;;; Author: Paul Dietz
;;;; Created: Thu Oct 10 22:39:25 2002
;;;; Contains: Tests for CALL-ARGUMENTS-LIMIT
(deftest call-arguments-limit.1
(notnot-mv (constantp 'call-arguments-limit))
t)
(deftest call-arguments-limit.2
(notnot-mv (typep call-arguments-limit 'integer))
t)
(deftest call-arguments-limit.3
(< call-arguments-limit 50)
nil)
(deftest call-arguments-limit.4
(let* ((m (min 65536 (1- call-arguments-limit)))
(args (make-list m :initial-element 'a)))
(equalt (apply #'list args) args))
t)
(deftest call-arguments-limit.5
(< call-arguments-limit lambda-parameters-limit)
nil)
|
22785
|
;-*- Mode: Lisp -*-
;;;; Author: <NAME>
;;;; Created: Thu Oct 10 22:39:25 2002
;;;; Contains: Tests for CALL-ARGUMENTS-LIMIT
(deftest call-arguments-limit.1
(notnot-mv (constantp 'call-arguments-limit))
t)
(deftest call-arguments-limit.2
(notnot-mv (typep call-arguments-limit 'integer))
t)
(deftest call-arguments-limit.3
(< call-arguments-limit 50)
nil)
(deftest call-arguments-limit.4
(let* ((m (min 65536 (1- call-arguments-limit)))
(args (make-list m :initial-element 'a)))
(equalt (apply #'list args) args))
t)
(deftest call-arguments-limit.5
(< call-arguments-limit lambda-parameters-limit)
nil)
| true |
;-*- Mode: Lisp -*-
;;;; Author: PI:NAME:<NAME>END_PI
;;;; Created: Thu Oct 10 22:39:25 2002
;;;; Contains: Tests for CALL-ARGUMENTS-LIMIT
(deftest call-arguments-limit.1
(notnot-mv (constantp 'call-arguments-limit))
t)
(deftest call-arguments-limit.2
(notnot-mv (typep call-arguments-limit 'integer))
t)
(deftest call-arguments-limit.3
(< call-arguments-limit 50)
nil)
(deftest call-arguments-limit.4
(let* ((m (min 65536 (1- call-arguments-limit)))
(args (make-list m :initial-element 'a)))
(equalt (apply #'list args) args))
t)
(deftest call-arguments-limit.5
(< call-arguments-limit lambda-parameters-limit)
nil)
|
[
{
"context": "function remove-equal.\n;\n; Copyright (C) 2008-2011 Eric Smith and Stanford University\n; Copyright (C) 2013-2019",
"end": 101,
"score": 0.9996703267097473,
"start": 91,
"tag": "NAME",
"value": "Eric Smith"
},
{
"context": "ense. See the file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;",
"end": 262,
"score": 0.9996606111526489,
"start": 252,
"tag": "NAME",
"value": "Eric Smith"
},
{
"context": " file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 286,
"score": 0.9999339580535889,
"start": 264,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/kestrel/lists-light/remove-equal.lisp
|
nzt/acl2
| 1 |
; A lightweight book about the built-in function remove-equal.
;
; Copyright (C) 2008-2011 Eric Smith and Stanford University
; Copyright (C) 2013-2019 Kestrel Institute
;
; License: A 3-clause BSD license. See the file books/3BSD-mod.txt.
;
; Author: Eric Smith ([email protected])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(in-theory (disable remove-equal))
;; A simple/abbreviation rule.
(defthm remove-equal-of-nil
(equal (remove-equal x nil)
nil)
:hints (("Goal" :in-theory (enable remove-equal))))
(defthmd remove-equal-when-not-consp
(implies (not (consp l))
(equal (remove-equal x l)
nil))
:hints (("Goal" :in-theory (enable remove-equal))))
(defthm remove-equal-when-not-consp-cheap
(implies (not (consp l))
(equal (remove-equal x l)
nil))
:rule-classes ((:rewrite :backchain-limit-lst (0)))
:hints (("Goal" :in-theory (enable remove-equal))))
(defthm remove-equal-of-cons
(equal (remove-equal x (cons y l))
(if (equal x y)
(remove-equal x l)
(cons y (remove-equal x l))))
:hints (("Goal" :in-theory (enable remove-equal))))
(defthm remove-equal-of-cons-same
(equal (remove-equal x (cons x l))
(remove-equal x l))
:hints (("Goal" :in-theory (enable remove-equal))))
(defthm remove-equal-of-car-same
(equal (remove-equal (car l) l)
(remove-equal (car l) (cdr l)))
:hints (("Goal" :in-theory (enable remove-equal))))
(defthm len-of-remove-equal-linear
(<= (len (remove-equal x l))
(len l))
:rule-classes ((:linear :trigger-terms ((len (remove-equal x l)))))
:hints (("Goal" :in-theory (enable remove-equal))))
;; ACL2 puts in a loop-stopper.
(defthm remove-equal-of-remove-equal
(equal (remove-equal x (remove-equal y l))
(remove-equal y (remove-equal x l)))
:hints (("Goal" :in-theory (enable remove-equal))))
(defthm not-member-equal-of-remove-equal
(implies (not (member-equal x l))
(not (member-equal x (remove-equal y l)))))
(defthm member-equal-of-remove-equal-irrel-iff
(implies (not (equal x y))
(iff (member-equal x (remove-equal y l))
(member-equal x l))))
|
51007
|
; A lightweight book about the built-in function remove-equal.
;
; Copyright (C) 2008-2011 <NAME> and Stanford University
; Copyright (C) 2013-2019 Kestrel Institute
;
; License: A 3-clause BSD license. See the file books/3BSD-mod.txt.
;
; Author: <NAME> (<EMAIL>)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(in-theory (disable remove-equal))
;; A simple/abbreviation rule.
(defthm remove-equal-of-nil
(equal (remove-equal x nil)
nil)
:hints (("Goal" :in-theory (enable remove-equal))))
(defthmd remove-equal-when-not-consp
(implies (not (consp l))
(equal (remove-equal x l)
nil))
:hints (("Goal" :in-theory (enable remove-equal))))
(defthm remove-equal-when-not-consp-cheap
(implies (not (consp l))
(equal (remove-equal x l)
nil))
:rule-classes ((:rewrite :backchain-limit-lst (0)))
:hints (("Goal" :in-theory (enable remove-equal))))
(defthm remove-equal-of-cons
(equal (remove-equal x (cons y l))
(if (equal x y)
(remove-equal x l)
(cons y (remove-equal x l))))
:hints (("Goal" :in-theory (enable remove-equal))))
(defthm remove-equal-of-cons-same
(equal (remove-equal x (cons x l))
(remove-equal x l))
:hints (("Goal" :in-theory (enable remove-equal))))
(defthm remove-equal-of-car-same
(equal (remove-equal (car l) l)
(remove-equal (car l) (cdr l)))
:hints (("Goal" :in-theory (enable remove-equal))))
(defthm len-of-remove-equal-linear
(<= (len (remove-equal x l))
(len l))
:rule-classes ((:linear :trigger-terms ((len (remove-equal x l)))))
:hints (("Goal" :in-theory (enable remove-equal))))
;; ACL2 puts in a loop-stopper.
(defthm remove-equal-of-remove-equal
(equal (remove-equal x (remove-equal y l))
(remove-equal y (remove-equal x l)))
:hints (("Goal" :in-theory (enable remove-equal))))
(defthm not-member-equal-of-remove-equal
(implies (not (member-equal x l))
(not (member-equal x (remove-equal y l)))))
(defthm member-equal-of-remove-equal-irrel-iff
(implies (not (equal x y))
(iff (member-equal x (remove-equal y l))
(member-equal x l))))
| true |
; A lightweight book about the built-in function remove-equal.
;
; Copyright (C) 2008-2011 PI:NAME:<NAME>END_PI and Stanford University
; Copyright (C) 2013-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")
(in-theory (disable remove-equal))
;; A simple/abbreviation rule.
(defthm remove-equal-of-nil
(equal (remove-equal x nil)
nil)
:hints (("Goal" :in-theory (enable remove-equal))))
(defthmd remove-equal-when-not-consp
(implies (not (consp l))
(equal (remove-equal x l)
nil))
:hints (("Goal" :in-theory (enable remove-equal))))
(defthm remove-equal-when-not-consp-cheap
(implies (not (consp l))
(equal (remove-equal x l)
nil))
:rule-classes ((:rewrite :backchain-limit-lst (0)))
:hints (("Goal" :in-theory (enable remove-equal))))
(defthm remove-equal-of-cons
(equal (remove-equal x (cons y l))
(if (equal x y)
(remove-equal x l)
(cons y (remove-equal x l))))
:hints (("Goal" :in-theory (enable remove-equal))))
(defthm remove-equal-of-cons-same
(equal (remove-equal x (cons x l))
(remove-equal x l))
:hints (("Goal" :in-theory (enable remove-equal))))
(defthm remove-equal-of-car-same
(equal (remove-equal (car l) l)
(remove-equal (car l) (cdr l)))
:hints (("Goal" :in-theory (enable remove-equal))))
(defthm len-of-remove-equal-linear
(<= (len (remove-equal x l))
(len l))
:rule-classes ((:linear :trigger-terms ((len (remove-equal x l)))))
:hints (("Goal" :in-theory (enable remove-equal))))
;; ACL2 puts in a loop-stopper.
(defthm remove-equal-of-remove-equal
(equal (remove-equal x (remove-equal y l))
(remove-equal y (remove-equal x l)))
:hints (("Goal" :in-theory (enable remove-equal))))
(defthm not-member-equal-of-remove-equal
(implies (not (member-equal x l))
(not (member-equal x (remove-equal y l)))))
(defthm member-equal-of-remove-equal-irrel-iff
(implies (not (equal x y))
(iff (member-equal x (remove-equal y l))
(member-equal x l))))
|
[
{
"context": "-Common-Lisp -*-\n;;;\n;;; Copyright (c) 2002 - 2010 Douglas R. Miles. All rights reserved.\n;;;\n;;; @module COGBOT-INI",
"end": 123,
"score": 0.999877393245697,
"start": 107,
"tag": "NAME",
"value": "Douglas R. Miles"
},
{
"context": "GBOT-INIT\n;;; @features :COGBOT-NL\n;;;\n;;; @author dmiles\n;;; @owner dmiles\n;;;\n;;; @created 2010/01/10\n;;;",
"end": 222,
"score": 0.9992491006851196,
"start": 216,
"tag": "USERNAME",
"value": "dmiles"
},
{
"context": "tures :COGBOT-NL\n;;;\n;;; @author dmiles\n;;; @owner dmiles\n;;;\n;;; @created 2010/01/10\n;;;;;;;;;;;;;;;;;;;;;",
"end": 240,
"score": 0.9988381862640381,
"start": 234,
"tag": "USERNAME",
"value": "dmiles"
}
] |
pack/logicmoo_nlu/prolog/e2c/cogbot-init.lisp
|
logicmoo/old_logicmoo_workspace
| 1 |
;;;{{{DOC
;;; -*- Mode: LISP; Package: CYC; Syntax: ANSI-Common-Lisp -*-
;;;
;;; Copyright (c) 2002 - 2010 Douglas R. Miles. All rights reserved.
;;;
;;; @module COGBOT-INIT
;;; @features :COGBOT-NL
;;;
;;; @author dmiles
;;; @owner dmiles
;;;
;;; @created 2010/01/10
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; tools & utilities for Cogbot/NLParsing
;;
;; !!!!!!!!!!!!!!!
;; IMPORTANT NOTES:
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; External interface:
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Depends on interface:
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;}}}EDOC
(in-package "CYC")
;; (load "e2c/cogbot-init.lisp")
;; DMiles likes to watch
(define FORCE-PRINT (string) (print string) (force-output))
(force-print ";; start loading e2c/cogbot-init.lisp")
(csetq *silent-progress?* NIL) ;this adds some printouts
(csetq *dump-verbose* T) ;this adds some printouts
#|
(csetq *recan-verbose?* T)
(csetq *tm-load-verbose?* T)
(csetq *sunit-verbose* T)
(csetq *sme-lexwiz-verbose?* T)
(csetq *verbose-print-pph-phrases?* T)
(csetq *it-failing-verbose* T)
(csetq *it-verbose* T)
(csetq *psp-verbose?* T)
(csetq *quote-char* #\")
(csetq *TASK-PROCESSOR-VERBOSITY* 1) ;;9
(csetq *SBHL-TRACE-LEVEL* 1) ;; 9
(csetq *ALLOW-EXTERNAL-INFERENCE* nil)
(csetq *EVALUATABLE-BACKCHAIN-ENABLED* t)
(csetq *ALLOW-FORWARD-SKOLEMIZATION* t)
(csetq *UNBOUND-RULE-BACKCHAIN-ENABLED* t)
(csetq *SUSPEND-SBHL-TYPE-CHECKING?* t)
(csetq *REPORT-DEFAULT-METHOD-CALLS?* t)
(csetq *EVAL-IN-API-TRACED-FNS* '(T EVAL))
(csetq *EVAL-IN-API-LEVEL* -1)
(csetq *DEFAULT-TRANSFORMATION-MAX* 10000) ;; normal 1000
(csetq *DEFAULT-RECURSION-LIMIT* 10000) ;; normal 1000
(csetq *ALLOW-EXPANDED-RULES-AS-OWL-EXPORT-CANDIDATES?* t)
(csetq *ALLOW-BACKWARD-GAFS* t)
(csetq *HL-FAILURE-BACKCHAINING* t)
(csetq *PERFORM-EQUALS-UNIFICATION* t)
(csetq *READ-REQUIRE-CONSTANT-EXISTS* t)
(csetq *PERFORM-UNIFICATION-OCCURS-CHECK* t)
(csetq *READ-REQUIRE-CONSTANT-EXISTS* T )
(csetq *SUSPEND-SBHL-TYPE-CHECKING?* T )
(csetq *EVALUATABLE-BACKCHAIN-ENABLED* nil )
(csetq *ALLOW-FORWARD-SKOLEMIZATION* nil )
(csetq *UNBOUND-RULE-BACKCHAIN-ENABLED* nil )
(csetq *REPORT-DEFAULT-METHOD-CALLS?* nil )
(csetq *ALLOW-EXPANDED-RULES-AS-OWL-EXPORT-CANDIDATES?* nil )
(csetq *ALLOW-BACKWARD-GAFS* nil )
(csetq *HL-FAILURE-BACKCHAINING* nil )
(csetq *PERFORM-EQUALS-UNIFICATION* nil )
|#
(define foc (string) (ret (find-or-create-constant string)))
;; makes it more like common lisp .. (but leaks functions)
;; (defmacro lambda (args &rest body) (ret `#'(define ,(gensym "LAMBDA") ,args ,@body)))
(in-package :SUBLISP)
#+Allegro
(defmacro sl:define (name arglist &body body &environment env)
(let ((*top-level-environment* env))
(must (valid-function-definition-symbol name) "~S ~S is not written in valid SubL." 'sl:define name)
;; (must (valid-define-arglist arglist) "~S arglist inappropriate --- ~S." name arglist)
(must (valid-function-body name body) "~S body is not written in valid SubL." name)
(unless (tree-member 'sl:ret body)
(warn "~%Function ~S will not return a value." name))
(multiple-value-bind (body declarations doc-string)
(ex::strip-declarations-and-doc-string body)
`(progn
(when *translator-loaded*
(funcall *translator-arglist-change-callback* ',name ',arglist))
(defun ,name ,arglist
,@(when declarations
`((declare ,@declarations)))
,@(when doc-string (list doc-string))
(macrolet ((sl:ret (value)
`(return-from ,',name ,value)))
,@(when sl::*call-profiling-enabled?*
`((sl::possibly-note-function-entry ',name)))
,@body
nil))))))
(in-package :CYC)
(define cbnl-assert (sent &rest flags)
(csetq flags (flatten (cons flags *VocabularyMt*)))
(clet ((mt (car (member-if #'MT? flags)))
(cmd `(fast-assert-int ,(list 'quote sent) ,mt ,(fif (member :default flags) :default :monotonic) ,(fif (member :BACKWARD flags) :backward :forward))))
(clet ((res (eval cmd)))
(punless res
(format t "~&~s~& ;; HL ERROR: ~s~&" cmd (HL-EXPLANATION-OF-WHY-NOT-WFF sent Mt))
(format t "~&;; EL ERROR: ~s~&~&" (WHY-NOT-WFF sent Mt))
(force-output)
(ret (values nil (WHY-NOT-WFF sent Mt))))
(clet ((as (find-assertion-cycl sent mt)))
(cyc-assert `(#$myReviewer ,as ,*COGBOTUSER*) #$BookkeepingMt)
(ret (values as res))))))
(define cbnl-retract (sent &rest mts)
(clet (askable template)
(csetq mts (member-if #'mt? (flatten (cons mts (list *SMT*)))))
(csetq sent (fif (equal (car sent) #$ist) sent (list #$ist '?Mt sent)))
(csetq askable (fif (equal (car sent) #$ist) sent (list #$ist '?Mt sent)))
(force-print `(ask-template ',sent ',askable ,*SMT*))
(csetq mts (ask-template sent askable *SMT*))
(print (length mts))
(cdolist (sent mts) (ke-unassert-now (third sent)(second sent)))
(ret mts)))
(csetq *SMT* #$EverythingPSC)
(define sentence-ids (sent &rest mts)
(clet (result askable template)
(csetq mts (member-if #'mt? (flatten (cons mts (list *SMT*)))))
(csetq sent (fif (equal (car sent) #$ist) sent (list #$ist '?Mt sent)))
(csetq askable (fif (equal (car sent) #$ist) sent (list #$ist '?Mt sent)))
;;(force-print `(ask-template ',sent ',askable ,*SMT*))
(csetq mts (ask-template sent askable *SMT*))
(cdolist (sent mts)
(clet ((call `(find-gaf ',(third sent) ',(canonicalize-hlmt (second sent))))(inm (force-print call))(gaf (eval call)))
(pwhen gaf (cpushnew (assertion-id gaf ) result))))
(ret result)))
'(sentence-ids '(#$isa ?CITY #$USCity))
(define sentence-clauses (sent &rest mts)
(clet (result askable template)
(csetq mts (member-if #'mt? (flatten (cons mts (list *SMT*)))))
(csetq sent (fif (equal (car sent) #$ist) sent (list #$ist '?Mt sent)))
(csetq askable (fif (equal (car sent) #$ist) sent (list #$ist '?Mt sent)))
;;(force-print `(ask-template ',sent ',askable ,*SMT*))
(csetq mts (ask-template sent askable *SMT* )) ;;4 nil nil 3000
(ret mts)))
'(sentence-clauses '(#$isa ?CITY #$USCity))
(set-the-cyclist "CycAdministrator")
(force-print ";; done loading e2c/cogbot-init.lisp")
(in-package :CYC)
|
24277
|
;;;{{{DOC
;;; -*- Mode: LISP; Package: CYC; Syntax: ANSI-Common-Lisp -*-
;;;
;;; Copyright (c) 2002 - 2010 <NAME>. All rights reserved.
;;;
;;; @module COGBOT-INIT
;;; @features :COGBOT-NL
;;;
;;; @author dmiles
;;; @owner dmiles
;;;
;;; @created 2010/01/10
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; tools & utilities for Cogbot/NLParsing
;;
;; !!!!!!!!!!!!!!!
;; IMPORTANT NOTES:
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; External interface:
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Depends on interface:
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;}}}EDOC
(in-package "CYC")
;; (load "e2c/cogbot-init.lisp")
;; DMiles likes to watch
(define FORCE-PRINT (string) (print string) (force-output))
(force-print ";; start loading e2c/cogbot-init.lisp")
(csetq *silent-progress?* NIL) ;this adds some printouts
(csetq *dump-verbose* T) ;this adds some printouts
#|
(csetq *recan-verbose?* T)
(csetq *tm-load-verbose?* T)
(csetq *sunit-verbose* T)
(csetq *sme-lexwiz-verbose?* T)
(csetq *verbose-print-pph-phrases?* T)
(csetq *it-failing-verbose* T)
(csetq *it-verbose* T)
(csetq *psp-verbose?* T)
(csetq *quote-char* #\")
(csetq *TASK-PROCESSOR-VERBOSITY* 1) ;;9
(csetq *SBHL-TRACE-LEVEL* 1) ;; 9
(csetq *ALLOW-EXTERNAL-INFERENCE* nil)
(csetq *EVALUATABLE-BACKCHAIN-ENABLED* t)
(csetq *ALLOW-FORWARD-SKOLEMIZATION* t)
(csetq *UNBOUND-RULE-BACKCHAIN-ENABLED* t)
(csetq *SUSPEND-SBHL-TYPE-CHECKING?* t)
(csetq *REPORT-DEFAULT-METHOD-CALLS?* t)
(csetq *EVAL-IN-API-TRACED-FNS* '(T EVAL))
(csetq *EVAL-IN-API-LEVEL* -1)
(csetq *DEFAULT-TRANSFORMATION-MAX* 10000) ;; normal 1000
(csetq *DEFAULT-RECURSION-LIMIT* 10000) ;; normal 1000
(csetq *ALLOW-EXPANDED-RULES-AS-OWL-EXPORT-CANDIDATES?* t)
(csetq *ALLOW-BACKWARD-GAFS* t)
(csetq *HL-FAILURE-BACKCHAINING* t)
(csetq *PERFORM-EQUALS-UNIFICATION* t)
(csetq *READ-REQUIRE-CONSTANT-EXISTS* t)
(csetq *PERFORM-UNIFICATION-OCCURS-CHECK* t)
(csetq *READ-REQUIRE-CONSTANT-EXISTS* T )
(csetq *SUSPEND-SBHL-TYPE-CHECKING?* T )
(csetq *EVALUATABLE-BACKCHAIN-ENABLED* nil )
(csetq *ALLOW-FORWARD-SKOLEMIZATION* nil )
(csetq *UNBOUND-RULE-BACKCHAIN-ENABLED* nil )
(csetq *REPORT-DEFAULT-METHOD-CALLS?* nil )
(csetq *ALLOW-EXPANDED-RULES-AS-OWL-EXPORT-CANDIDATES?* nil )
(csetq *ALLOW-BACKWARD-GAFS* nil )
(csetq *HL-FAILURE-BACKCHAINING* nil )
(csetq *PERFORM-EQUALS-UNIFICATION* nil )
|#
(define foc (string) (ret (find-or-create-constant string)))
;; makes it more like common lisp .. (but leaks functions)
;; (defmacro lambda (args &rest body) (ret `#'(define ,(gensym "LAMBDA") ,args ,@body)))
(in-package :SUBLISP)
#+Allegro
(defmacro sl:define (name arglist &body body &environment env)
(let ((*top-level-environment* env))
(must (valid-function-definition-symbol name) "~S ~S is not written in valid SubL." 'sl:define name)
;; (must (valid-define-arglist arglist) "~S arglist inappropriate --- ~S." name arglist)
(must (valid-function-body name body) "~S body is not written in valid SubL." name)
(unless (tree-member 'sl:ret body)
(warn "~%Function ~S will not return a value." name))
(multiple-value-bind (body declarations doc-string)
(ex::strip-declarations-and-doc-string body)
`(progn
(when *translator-loaded*
(funcall *translator-arglist-change-callback* ',name ',arglist))
(defun ,name ,arglist
,@(when declarations
`((declare ,@declarations)))
,@(when doc-string (list doc-string))
(macrolet ((sl:ret (value)
`(return-from ,',name ,value)))
,@(when sl::*call-profiling-enabled?*
`((sl::possibly-note-function-entry ',name)))
,@body
nil))))))
(in-package :CYC)
(define cbnl-assert (sent &rest flags)
(csetq flags (flatten (cons flags *VocabularyMt*)))
(clet ((mt (car (member-if #'MT? flags)))
(cmd `(fast-assert-int ,(list 'quote sent) ,mt ,(fif (member :default flags) :default :monotonic) ,(fif (member :BACKWARD flags) :backward :forward))))
(clet ((res (eval cmd)))
(punless res
(format t "~&~s~& ;; HL ERROR: ~s~&" cmd (HL-EXPLANATION-OF-WHY-NOT-WFF sent Mt))
(format t "~&;; EL ERROR: ~s~&~&" (WHY-NOT-WFF sent Mt))
(force-output)
(ret (values nil (WHY-NOT-WFF sent Mt))))
(clet ((as (find-assertion-cycl sent mt)))
(cyc-assert `(#$myReviewer ,as ,*COGBOTUSER*) #$BookkeepingMt)
(ret (values as res))))))
(define cbnl-retract (sent &rest mts)
(clet (askable template)
(csetq mts (member-if #'mt? (flatten (cons mts (list *SMT*)))))
(csetq sent (fif (equal (car sent) #$ist) sent (list #$ist '?Mt sent)))
(csetq askable (fif (equal (car sent) #$ist) sent (list #$ist '?Mt sent)))
(force-print `(ask-template ',sent ',askable ,*SMT*))
(csetq mts (ask-template sent askable *SMT*))
(print (length mts))
(cdolist (sent mts) (ke-unassert-now (third sent)(second sent)))
(ret mts)))
(csetq *SMT* #$EverythingPSC)
(define sentence-ids (sent &rest mts)
(clet (result askable template)
(csetq mts (member-if #'mt? (flatten (cons mts (list *SMT*)))))
(csetq sent (fif (equal (car sent) #$ist) sent (list #$ist '?Mt sent)))
(csetq askable (fif (equal (car sent) #$ist) sent (list #$ist '?Mt sent)))
;;(force-print `(ask-template ',sent ',askable ,*SMT*))
(csetq mts (ask-template sent askable *SMT*))
(cdolist (sent mts)
(clet ((call `(find-gaf ',(third sent) ',(canonicalize-hlmt (second sent))))(inm (force-print call))(gaf (eval call)))
(pwhen gaf (cpushnew (assertion-id gaf ) result))))
(ret result)))
'(sentence-ids '(#$isa ?CITY #$USCity))
(define sentence-clauses (sent &rest mts)
(clet (result askable template)
(csetq mts (member-if #'mt? (flatten (cons mts (list *SMT*)))))
(csetq sent (fif (equal (car sent) #$ist) sent (list #$ist '?Mt sent)))
(csetq askable (fif (equal (car sent) #$ist) sent (list #$ist '?Mt sent)))
;;(force-print `(ask-template ',sent ',askable ,*SMT*))
(csetq mts (ask-template sent askable *SMT* )) ;;4 nil nil 3000
(ret mts)))
'(sentence-clauses '(#$isa ?CITY #$USCity))
(set-the-cyclist "CycAdministrator")
(force-print ";; done loading e2c/cogbot-init.lisp")
(in-package :CYC)
| true |
;;;{{{DOC
;;; -*- Mode: LISP; Package: CYC; Syntax: ANSI-Common-Lisp -*-
;;;
;;; Copyright (c) 2002 - 2010 PI:NAME:<NAME>END_PI. All rights reserved.
;;;
;;; @module COGBOT-INIT
;;; @features :COGBOT-NL
;;;
;;; @author dmiles
;;; @owner dmiles
;;;
;;; @created 2010/01/10
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; tools & utilities for Cogbot/NLParsing
;;
;; !!!!!!!!!!!!!!!
;; IMPORTANT NOTES:
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; External interface:
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Depends on interface:
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;}}}EDOC
(in-package "CYC")
;; (load "e2c/cogbot-init.lisp")
;; DMiles likes to watch
(define FORCE-PRINT (string) (print string) (force-output))
(force-print ";; start loading e2c/cogbot-init.lisp")
(csetq *silent-progress?* NIL) ;this adds some printouts
(csetq *dump-verbose* T) ;this adds some printouts
#|
(csetq *recan-verbose?* T)
(csetq *tm-load-verbose?* T)
(csetq *sunit-verbose* T)
(csetq *sme-lexwiz-verbose?* T)
(csetq *verbose-print-pph-phrases?* T)
(csetq *it-failing-verbose* T)
(csetq *it-verbose* T)
(csetq *psp-verbose?* T)
(csetq *quote-char* #\")
(csetq *TASK-PROCESSOR-VERBOSITY* 1) ;;9
(csetq *SBHL-TRACE-LEVEL* 1) ;; 9
(csetq *ALLOW-EXTERNAL-INFERENCE* nil)
(csetq *EVALUATABLE-BACKCHAIN-ENABLED* t)
(csetq *ALLOW-FORWARD-SKOLEMIZATION* t)
(csetq *UNBOUND-RULE-BACKCHAIN-ENABLED* t)
(csetq *SUSPEND-SBHL-TYPE-CHECKING?* t)
(csetq *REPORT-DEFAULT-METHOD-CALLS?* t)
(csetq *EVAL-IN-API-TRACED-FNS* '(T EVAL))
(csetq *EVAL-IN-API-LEVEL* -1)
(csetq *DEFAULT-TRANSFORMATION-MAX* 10000) ;; normal 1000
(csetq *DEFAULT-RECURSION-LIMIT* 10000) ;; normal 1000
(csetq *ALLOW-EXPANDED-RULES-AS-OWL-EXPORT-CANDIDATES?* t)
(csetq *ALLOW-BACKWARD-GAFS* t)
(csetq *HL-FAILURE-BACKCHAINING* t)
(csetq *PERFORM-EQUALS-UNIFICATION* t)
(csetq *READ-REQUIRE-CONSTANT-EXISTS* t)
(csetq *PERFORM-UNIFICATION-OCCURS-CHECK* t)
(csetq *READ-REQUIRE-CONSTANT-EXISTS* T )
(csetq *SUSPEND-SBHL-TYPE-CHECKING?* T )
(csetq *EVALUATABLE-BACKCHAIN-ENABLED* nil )
(csetq *ALLOW-FORWARD-SKOLEMIZATION* nil )
(csetq *UNBOUND-RULE-BACKCHAIN-ENABLED* nil )
(csetq *REPORT-DEFAULT-METHOD-CALLS?* nil )
(csetq *ALLOW-EXPANDED-RULES-AS-OWL-EXPORT-CANDIDATES?* nil )
(csetq *ALLOW-BACKWARD-GAFS* nil )
(csetq *HL-FAILURE-BACKCHAINING* nil )
(csetq *PERFORM-EQUALS-UNIFICATION* nil )
|#
(define foc (string) (ret (find-or-create-constant string)))
;; makes it more like common lisp .. (but leaks functions)
;; (defmacro lambda (args &rest body) (ret `#'(define ,(gensym "LAMBDA") ,args ,@body)))
(in-package :SUBLISP)
#+Allegro
(defmacro sl:define (name arglist &body body &environment env)
(let ((*top-level-environment* env))
(must (valid-function-definition-symbol name) "~S ~S is not written in valid SubL." 'sl:define name)
;; (must (valid-define-arglist arglist) "~S arglist inappropriate --- ~S." name arglist)
(must (valid-function-body name body) "~S body is not written in valid SubL." name)
(unless (tree-member 'sl:ret body)
(warn "~%Function ~S will not return a value." name))
(multiple-value-bind (body declarations doc-string)
(ex::strip-declarations-and-doc-string body)
`(progn
(when *translator-loaded*
(funcall *translator-arglist-change-callback* ',name ',arglist))
(defun ,name ,arglist
,@(when declarations
`((declare ,@declarations)))
,@(when doc-string (list doc-string))
(macrolet ((sl:ret (value)
`(return-from ,',name ,value)))
,@(when sl::*call-profiling-enabled?*
`((sl::possibly-note-function-entry ',name)))
,@body
nil))))))
(in-package :CYC)
(define cbnl-assert (sent &rest flags)
(csetq flags (flatten (cons flags *VocabularyMt*)))
(clet ((mt (car (member-if #'MT? flags)))
(cmd `(fast-assert-int ,(list 'quote sent) ,mt ,(fif (member :default flags) :default :monotonic) ,(fif (member :BACKWARD flags) :backward :forward))))
(clet ((res (eval cmd)))
(punless res
(format t "~&~s~& ;; HL ERROR: ~s~&" cmd (HL-EXPLANATION-OF-WHY-NOT-WFF sent Mt))
(format t "~&;; EL ERROR: ~s~&~&" (WHY-NOT-WFF sent Mt))
(force-output)
(ret (values nil (WHY-NOT-WFF sent Mt))))
(clet ((as (find-assertion-cycl sent mt)))
(cyc-assert `(#$myReviewer ,as ,*COGBOTUSER*) #$BookkeepingMt)
(ret (values as res))))))
(define cbnl-retract (sent &rest mts)
(clet (askable template)
(csetq mts (member-if #'mt? (flatten (cons mts (list *SMT*)))))
(csetq sent (fif (equal (car sent) #$ist) sent (list #$ist '?Mt sent)))
(csetq askable (fif (equal (car sent) #$ist) sent (list #$ist '?Mt sent)))
(force-print `(ask-template ',sent ',askable ,*SMT*))
(csetq mts (ask-template sent askable *SMT*))
(print (length mts))
(cdolist (sent mts) (ke-unassert-now (third sent)(second sent)))
(ret mts)))
(csetq *SMT* #$EverythingPSC)
(define sentence-ids (sent &rest mts)
(clet (result askable template)
(csetq mts (member-if #'mt? (flatten (cons mts (list *SMT*)))))
(csetq sent (fif (equal (car sent) #$ist) sent (list #$ist '?Mt sent)))
(csetq askable (fif (equal (car sent) #$ist) sent (list #$ist '?Mt sent)))
;;(force-print `(ask-template ',sent ',askable ,*SMT*))
(csetq mts (ask-template sent askable *SMT*))
(cdolist (sent mts)
(clet ((call `(find-gaf ',(third sent) ',(canonicalize-hlmt (second sent))))(inm (force-print call))(gaf (eval call)))
(pwhen gaf (cpushnew (assertion-id gaf ) result))))
(ret result)))
'(sentence-ids '(#$isa ?CITY #$USCity))
(define sentence-clauses (sent &rest mts)
(clet (result askable template)
(csetq mts (member-if #'mt? (flatten (cons mts (list *SMT*)))))
(csetq sent (fif (equal (car sent) #$ist) sent (list #$ist '?Mt sent)))
(csetq askable (fif (equal (car sent) #$ist) sent (list #$ist '?Mt sent)))
;;(force-print `(ask-template ',sent ',askable ,*SMT*))
(csetq mts (ask-template sent askable *SMT* )) ;;4 nil nil 3000
(ret mts)))
'(sentence-clauses '(#$isa ?CITY #$USCity))
(set-the-cyclist "CycAdministrator")
(force-print ";; done loading e2c/cogbot-init.lisp")
(in-package :CYC)
|
[
{
"context": "ense. See the file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;",
"end": 213,
"score": 0.9997639656066895,
"start": 203,
"tag": "NAME",
"value": "Eric Smith"
},
{
"context": " file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 237,
"score": 0.9999304413795471,
"start": 215,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/kestrel/alists-light/alists-equiv-on.lisp
|
KestrelInstitute/acl2
| 0 |
; A predicate that checks whether two alists agree on a given list of keys
;
; Copyright (C) 2021-2022 Kestrel Institute
;
; License: A 3-clause BSD license. See the file books/3BSD-mod.txt.
;
; Author: Eric Smith ([email protected])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(local (include-book "kestrel/alists-light/assoc-equal" :dir :system))
(local (include-book "kestrel/alists-light/pairlis-dollar" :dir :system))
(local (include-book "kestrel/lists-light/set-difference-equal" :dir :system))
;; Checks whether ALIST1 and ALIST2 are equivalent wrt the KEYS. For these
;; purposes, not having a binding for a key is equivalent to binding it to nil.
(defun alists-equiv-on (keys alist1 alist2)
(if (endp keys)
t
(let ((key (first keys)))
(and (equal (cdr (assoc-equal key alist1)) ; ok if bound to nil in one alist and not bound in the other
(cdr (assoc-equal key alist2)))
(alists-equiv-on (rest keys) alist1 alist2)))))
(defthm alists-equiv-on-of-union-equal
(equal (alists-equiv-on (union-equal keys1 keys2) alist1 alist2)
(and (alists-equiv-on keys1 alist1 alist2)
(alists-equiv-on keys2 alist1 alist2))))
(defthm alists-equiv-on-of-cons-and-cons-same
(implies (alists-equiv-on keys alist1 alist2)
(alists-equiv-on keys
(cons pair alist1)
(cons pair alist2))))
(defthm alists-equiv-on-of-cons-and-cons-same-2
(implies (alists-equiv-on (remove-equal (car pair) keys) alist1 alist2)
(alists-equiv-on keys
(cons pair alist1)
(cons pair alist2))))
(defthm equal-of-cdr-of-assoc-equal-and-cdr-of-assoc-equal-when-alists-equiv-on
(implies (and (alists-equiv-on keys alist1 alist2)
(member-equal key keys))
(equal (equal (cdr (assoc-equal key alist1))
(cdr (assoc-equal key alist2)))
t)))
(local
(defun cdr-remove-caar-induct (x y)
(if (endp x)
(list x y)
(cdr-remove-caar-induct (cdr x) (remove-equal (caar x) y)))))
(defthm alists-equiv-on-of-append-and-append-same
(implies (and (alists-equiv-on (set-difference-equal keys (strip-cars alist1))
alist2
alist3)
(alistp alist1)
; (no-duplicatesp-equal (strip-cars alist1)) ;drop?
)
(alists-equiv-on keys
(append alist1 alist2)
(append alist1 alist3)))
:hints (("subgoal *1/2" :cases ((equal (car keys) (caar alist1))))
("Goal" :expand ((STRIP-CARS ALIST1)
(ALISTS-EQUIV-ON KEYS (APPEND ALIST1 ALIST2)
(APPEND ALIST1 ALIST3)))
:induct (cdr-remove-caar-induct ALIST1 keys)
:do-not '(generalize eliminate-destructors)
:in-theory (enable append
))))
|
92546
|
; A predicate that checks whether two alists agree on a given list of keys
;
; Copyright (C) 2021-2022 Kestrel Institute
;
; License: A 3-clause BSD license. See the file books/3BSD-mod.txt.
;
; Author: <NAME> (<EMAIL>)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(local (include-book "kestrel/alists-light/assoc-equal" :dir :system))
(local (include-book "kestrel/alists-light/pairlis-dollar" :dir :system))
(local (include-book "kestrel/lists-light/set-difference-equal" :dir :system))
;; Checks whether ALIST1 and ALIST2 are equivalent wrt the KEYS. For these
;; purposes, not having a binding for a key is equivalent to binding it to nil.
(defun alists-equiv-on (keys alist1 alist2)
(if (endp keys)
t
(let ((key (first keys)))
(and (equal (cdr (assoc-equal key alist1)) ; ok if bound to nil in one alist and not bound in the other
(cdr (assoc-equal key alist2)))
(alists-equiv-on (rest keys) alist1 alist2)))))
(defthm alists-equiv-on-of-union-equal
(equal (alists-equiv-on (union-equal keys1 keys2) alist1 alist2)
(and (alists-equiv-on keys1 alist1 alist2)
(alists-equiv-on keys2 alist1 alist2))))
(defthm alists-equiv-on-of-cons-and-cons-same
(implies (alists-equiv-on keys alist1 alist2)
(alists-equiv-on keys
(cons pair alist1)
(cons pair alist2))))
(defthm alists-equiv-on-of-cons-and-cons-same-2
(implies (alists-equiv-on (remove-equal (car pair) keys) alist1 alist2)
(alists-equiv-on keys
(cons pair alist1)
(cons pair alist2))))
(defthm equal-of-cdr-of-assoc-equal-and-cdr-of-assoc-equal-when-alists-equiv-on
(implies (and (alists-equiv-on keys alist1 alist2)
(member-equal key keys))
(equal (equal (cdr (assoc-equal key alist1))
(cdr (assoc-equal key alist2)))
t)))
(local
(defun cdr-remove-caar-induct (x y)
(if (endp x)
(list x y)
(cdr-remove-caar-induct (cdr x) (remove-equal (caar x) y)))))
(defthm alists-equiv-on-of-append-and-append-same
(implies (and (alists-equiv-on (set-difference-equal keys (strip-cars alist1))
alist2
alist3)
(alistp alist1)
; (no-duplicatesp-equal (strip-cars alist1)) ;drop?
)
(alists-equiv-on keys
(append alist1 alist2)
(append alist1 alist3)))
:hints (("subgoal *1/2" :cases ((equal (car keys) (caar alist1))))
("Goal" :expand ((STRIP-CARS ALIST1)
(ALISTS-EQUIV-ON KEYS (APPEND ALIST1 ALIST2)
(APPEND ALIST1 ALIST3)))
:induct (cdr-remove-caar-induct ALIST1 keys)
:do-not '(generalize eliminate-destructors)
:in-theory (enable append
))))
| true |
; A predicate that checks whether two alists agree on a given list of keys
;
; Copyright (C) 2021-2022 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")
(local (include-book "kestrel/alists-light/assoc-equal" :dir :system))
(local (include-book "kestrel/alists-light/pairlis-dollar" :dir :system))
(local (include-book "kestrel/lists-light/set-difference-equal" :dir :system))
;; Checks whether ALIST1 and ALIST2 are equivalent wrt the KEYS. For these
;; purposes, not having a binding for a key is equivalent to binding it to nil.
(defun alists-equiv-on (keys alist1 alist2)
(if (endp keys)
t
(let ((key (first keys)))
(and (equal (cdr (assoc-equal key alist1)) ; ok if bound to nil in one alist and not bound in the other
(cdr (assoc-equal key alist2)))
(alists-equiv-on (rest keys) alist1 alist2)))))
(defthm alists-equiv-on-of-union-equal
(equal (alists-equiv-on (union-equal keys1 keys2) alist1 alist2)
(and (alists-equiv-on keys1 alist1 alist2)
(alists-equiv-on keys2 alist1 alist2))))
(defthm alists-equiv-on-of-cons-and-cons-same
(implies (alists-equiv-on keys alist1 alist2)
(alists-equiv-on keys
(cons pair alist1)
(cons pair alist2))))
(defthm alists-equiv-on-of-cons-and-cons-same-2
(implies (alists-equiv-on (remove-equal (car pair) keys) alist1 alist2)
(alists-equiv-on keys
(cons pair alist1)
(cons pair alist2))))
(defthm equal-of-cdr-of-assoc-equal-and-cdr-of-assoc-equal-when-alists-equiv-on
(implies (and (alists-equiv-on keys alist1 alist2)
(member-equal key keys))
(equal (equal (cdr (assoc-equal key alist1))
(cdr (assoc-equal key alist2)))
t)))
(local
(defun cdr-remove-caar-induct (x y)
(if (endp x)
(list x y)
(cdr-remove-caar-induct (cdr x) (remove-equal (caar x) y)))))
(defthm alists-equiv-on-of-append-and-append-same
(implies (and (alists-equiv-on (set-difference-equal keys (strip-cars alist1))
alist2
alist3)
(alistp alist1)
; (no-duplicatesp-equal (strip-cars alist1)) ;drop?
)
(alists-equiv-on keys
(append alist1 alist2)
(append alist1 alist3)))
:hints (("subgoal *1/2" :cases ((equal (car keys) (caar alist1))))
("Goal" :expand ((STRIP-CARS ALIST1)
(ALISTS-EQUIV-ON KEYS (APPEND ALIST1 ALIST2)
(APPEND ALIST1 ALIST3)))
:induct (cdr-remove-caar-induct ALIST1 keys)
:do-not '(generalize eliminate-destructors)
:in-theory (enable append
))))
|
[
{
"context": ";; Copyright 2017 Bradley Jensen\n;;\n;; Licensed under the Apache License, Version ",
"end": 32,
"score": 0.9998485445976257,
"start": 18,
"tag": "NAME",
"value": "Bradley Jensen"
}
] |
core/parser.lisp
|
diasbruno/shcl
| 0 |
;; Copyright 2017 Bradley Jensen
;;
;; 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.
(defpackage :shcl/core/parser
(:use
:common-lisp :alexandria :shcl/core/lexer :shcl/core/utility
:shcl/core/iterator)
(:import-from :shcl/core/advice #:define-advisable)
(:import-from :closer-mop)
(:shadowing-import-from :alexandria #:when-let #:when-let*)
(:export #:define-parser #:syntax-iterator #:make-internal-parse-error #:abort-parse
#:syntax-tree-parts #:syntax-tree))
(in-package :shcl/core/parser)
(optimization-settings)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun take-while (predicate list)
(let (result)
(loop :while (and list (funcall predicate (car list)))
:do (progn
(push (car list) result)
(setf list (cdr list))))
(values (nreverse result) list)))
(defun grammar-option-form-p (form)
(and (consp form)
(keywordp (car form))))
(defun grammar-lookup-option (option-name options)
(second (find option-name options :key #'car :test #'eq)))
(defun left-recursion-p (nonterminals)
(let ((graph (make-hash-table)))
(dolist (nonterm nonterminals)
(destructuring-bind (name &rest productions) nonterm
(dolist (production productions)
(push (if (consp production)
(car production)
production)
(gethash name graph)))))
(labels ((examine (where &optional (stack (list where)))
(let ((children (gethash where graph)))
(dolist (child children)
(when (member child stack)
(return-from left-recursion-p (nreverse (cons child stack))))
(examine child (cons child stack))))))
(dolist (sym (hash-table-keys graph))
(examine sym))
nil))))
(defclass syntax-tree ()
((raw-matches
:initform #()
:reader syntax-tree-parts)))
(defmethod make-load-form ((sy syntax-tree) &optional environment)
(let ((slots (mapcar 'closer-mop:slot-definition-name (closer-mop:class-slots (class-of sy)))))
(make-load-form-saving-slots sy :slot-names slots :environment environment)))
(defmethod print-object ((st syntax-tree) stream)
(print-unreadable-object (st stream :type t :identity nil)
(format stream "~A" (slot-value st 'raw-matches))))
(define-condition abort-parse (error)
((message
:initarg :message
:type string
:initform "<No reason>"
:accessor parse-error-message)
(expected
:initarg :expected-tokens
:type list
:initform nil
:accessor parse-error-expected-tokens))
(:report (lambda (c s)
(format s "Parse error (~A)"
(parse-error-message c))
(let ((expected (parse-error-expected-tokens c)))
(when expected
(format s ", expected tokens ~A" expected))))))
(defstruct internal-parse-error
message
expected-tokens
fatal)
(defmacro define-parser-part (&whole whole name (iter-sym) &body body)
(multiple-value-bind (real-body declarations doc-string)
(parse-body body :documentation t :whole whole)
`(define-advisable ,name (,iter-sym)
,@(when doc-string (list doc-string))
,@declarations
(labels
((no-parse (message &rest expected-tokens)
(return-from ,name
(values nil (make-internal-parse-error
:message message
:expected-tokens expected-tokens
:fatal nil))))
(abort-parse (message &rest expected-tokens)
(return-from ,name
(values nil (make-internal-parse-error
:message message
:expected-tokens expected-tokens
:fatal t))))
(emit (object)
(return-from ,name
(values object nil))))
(declare (inline no-parse abort-parse emit)
(dynamic-extent #'no-parse #'abort-parse #'emit)
(ignorable #'no-parse #'abort-parse #'emit))
(progn ,@real-body)
(error "Explicit emit is required")))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun parser-part-name (thing)
(symbol-nconc-intern nil "PARSE-" thing)))
(defmacro define-nonterminal (nonterminal-name &body productions)
(let (the-body
hit-epsilon
(slots (make-hash-table)))
(macrolet
((send-to (where &body rest)
`(progn
,@(loop :for form :in rest :collect
`(push ,form ,where)))))
(dolist (production productions)
(cond
(hit-epsilon
(error "Epsilon must be the last production"))
((eq nil production)
(send-to the-body `(emit nil))
(setf hit-epsilon t))
((symbolp production)
(send-to the-body
`(let ((ahead (fork-lookahead-iterator iter)))
(multiple-value-bind (value error) (,(parser-part-name production) ahead)
(when (or value (and error (internal-parse-error-fatal error)))
(move-lookahead-to iter ahead)
(return-from ,(parser-part-name nonterminal-name)
(values value error)))))))
((consp production)
(dolist (thing production)
(unless (keywordp thing)
(setf (gethash (if (consp thing) (first thing) thing) slots) t)))
(let (let-body
strict)
(dolist (thing production)
(block next
(when (eq :strict thing)
(setf strict t)
(return-from next))
(unless (consp thing)
(setf thing (list thing thing)))
(send-to let-body
`(multiple-value-bind (value error) (,(parser-part-name (second thing)) ahead)
,(if strict
`(when error
(setf (internal-parse-error-fatal error) t)
(move-lookahead-to iter ahead)
(return-from ,(parser-part-name nonterminal-name)
(values value error)))
`(when error
(return-from next-production)))
(setf (slot-value instance ',(car thing)) value)
(vector-push-extend value matches)))))
(send-to the-body
`(block next-production
(let ((instance (make-instance ',nonterminal-name))
(matches (make-extensible-vector))
(ahead (fork-lookahead-iterator iter)))
,@(nreverse let-body)
(setf (slot-value instance 'raw-matches) matches)
(move-lookahead-to iter ahead)
(return-from ,(parser-part-name nonterminal-name)
(values instance nil))))))))))
`(progn
,@(unless (zerop (hash-table-size slots))
`((defclass ,nonterminal-name (syntax-tree)
(,@(hash-table-keys slots)))))
(define-parser-part ,(parser-part-name nonterminal-name) (iter)
,@(nreverse the-body)
(no-parse "Nonterminal failed to match" ',nonterminal-name))
',nonterminal-name)))
(defmacro define-terminal (name type)
`(define-parser-part ,(parser-part-name name) (iter)
(multiple-value-bind (value more) (peek-lookahead-iterator iter)
(unless more
(no-parse "unexpected EOF" ',name))
(unless (typep value ',type)
(no-parse "Token mismatch" ',name)))
(emit (next iter))))
(defmacro define-parser (name &body body)
(let (result-forms)
(macrolet ((send (form) `(push ,form result-forms))
(send-to (place form) `(push ,form ,place)))
(multiple-value-bind (options nonterminals) (take-while #'grammar-option-form-p body)
(let ((start-symbol (grammar-lookup-option :start-symbol options))
(terminals (grammar-lookup-option :terminals options))
(eof-symbol (grammar-lookup-option :eof-symbol options)))
(unless (and start-symbol terminals)
(error "Start symbol and terminals are required"))
(when (left-recursion-p nonterminals)
(error "Grammar has left recursion ~A" (left-recursion-p nonterminals)))
;; Easiest stuff first. The root node
(send `(define-parser-part ,(parser-part-name name) (iter)
(return-from ,(parser-part-name name) (,(parser-part-name start-symbol) iter))))
;; Now parsers for the terminals
(dolist (term terminals)
(send `(define-terminal ,term ,term)))
(when eof-symbol
(send `(define-parser-part ,(parser-part-name eof-symbol) (iter)
(multiple-value-bind (value more) (peek-lookahead-iterator iter)
(declare (ignore value))
(when more
(no-parse "expected EOF" ',eof-symbol))
(emit ',eof-symbol)))))
;; Now the nonterminals
(dolist (nonterm nonterminals)
(send `(define-nonterminal ,(first nonterm)
,@(rest nonterm)))))))
`(progn ,@(nreverse result-forms))))
(defun syntax-iterator (parser-function token-iterator)
(make-iterator ()
(let ((methods (closer-mop:generic-function-methods parser-function)))
(dolist (m methods)
(check-type m shcl/core/advice::advice-method)))
(multiple-value-bind (value error) (funcall parser-function token-iterator)
(when error
(error 'abort-parse :message (internal-parse-error-message error)
:expected-tokens (internal-parse-error-expected-tokens error)))
(unless value
(stop))
(emit value))))
|
408
|
;; Copyright 2017 <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.
(defpackage :shcl/core/parser
(:use
:common-lisp :alexandria :shcl/core/lexer :shcl/core/utility
:shcl/core/iterator)
(:import-from :shcl/core/advice #:define-advisable)
(:import-from :closer-mop)
(:shadowing-import-from :alexandria #:when-let #:when-let*)
(:export #:define-parser #:syntax-iterator #:make-internal-parse-error #:abort-parse
#:syntax-tree-parts #:syntax-tree))
(in-package :shcl/core/parser)
(optimization-settings)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun take-while (predicate list)
(let (result)
(loop :while (and list (funcall predicate (car list)))
:do (progn
(push (car list) result)
(setf list (cdr list))))
(values (nreverse result) list)))
(defun grammar-option-form-p (form)
(and (consp form)
(keywordp (car form))))
(defun grammar-lookup-option (option-name options)
(second (find option-name options :key #'car :test #'eq)))
(defun left-recursion-p (nonterminals)
(let ((graph (make-hash-table)))
(dolist (nonterm nonterminals)
(destructuring-bind (name &rest productions) nonterm
(dolist (production productions)
(push (if (consp production)
(car production)
production)
(gethash name graph)))))
(labels ((examine (where &optional (stack (list where)))
(let ((children (gethash where graph)))
(dolist (child children)
(when (member child stack)
(return-from left-recursion-p (nreverse (cons child stack))))
(examine child (cons child stack))))))
(dolist (sym (hash-table-keys graph))
(examine sym))
nil))))
(defclass syntax-tree ()
((raw-matches
:initform #()
:reader syntax-tree-parts)))
(defmethod make-load-form ((sy syntax-tree) &optional environment)
(let ((slots (mapcar 'closer-mop:slot-definition-name (closer-mop:class-slots (class-of sy)))))
(make-load-form-saving-slots sy :slot-names slots :environment environment)))
(defmethod print-object ((st syntax-tree) stream)
(print-unreadable-object (st stream :type t :identity nil)
(format stream "~A" (slot-value st 'raw-matches))))
(define-condition abort-parse (error)
((message
:initarg :message
:type string
:initform "<No reason>"
:accessor parse-error-message)
(expected
:initarg :expected-tokens
:type list
:initform nil
:accessor parse-error-expected-tokens))
(:report (lambda (c s)
(format s "Parse error (~A)"
(parse-error-message c))
(let ((expected (parse-error-expected-tokens c)))
(when expected
(format s ", expected tokens ~A" expected))))))
(defstruct internal-parse-error
message
expected-tokens
fatal)
(defmacro define-parser-part (&whole whole name (iter-sym) &body body)
(multiple-value-bind (real-body declarations doc-string)
(parse-body body :documentation t :whole whole)
`(define-advisable ,name (,iter-sym)
,@(when doc-string (list doc-string))
,@declarations
(labels
((no-parse (message &rest expected-tokens)
(return-from ,name
(values nil (make-internal-parse-error
:message message
:expected-tokens expected-tokens
:fatal nil))))
(abort-parse (message &rest expected-tokens)
(return-from ,name
(values nil (make-internal-parse-error
:message message
:expected-tokens expected-tokens
:fatal t))))
(emit (object)
(return-from ,name
(values object nil))))
(declare (inline no-parse abort-parse emit)
(dynamic-extent #'no-parse #'abort-parse #'emit)
(ignorable #'no-parse #'abort-parse #'emit))
(progn ,@real-body)
(error "Explicit emit is required")))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun parser-part-name (thing)
(symbol-nconc-intern nil "PARSE-" thing)))
(defmacro define-nonterminal (nonterminal-name &body productions)
(let (the-body
hit-epsilon
(slots (make-hash-table)))
(macrolet
((send-to (where &body rest)
`(progn
,@(loop :for form :in rest :collect
`(push ,form ,where)))))
(dolist (production productions)
(cond
(hit-epsilon
(error "Epsilon must be the last production"))
((eq nil production)
(send-to the-body `(emit nil))
(setf hit-epsilon t))
((symbolp production)
(send-to the-body
`(let ((ahead (fork-lookahead-iterator iter)))
(multiple-value-bind (value error) (,(parser-part-name production) ahead)
(when (or value (and error (internal-parse-error-fatal error)))
(move-lookahead-to iter ahead)
(return-from ,(parser-part-name nonterminal-name)
(values value error)))))))
((consp production)
(dolist (thing production)
(unless (keywordp thing)
(setf (gethash (if (consp thing) (first thing) thing) slots) t)))
(let (let-body
strict)
(dolist (thing production)
(block next
(when (eq :strict thing)
(setf strict t)
(return-from next))
(unless (consp thing)
(setf thing (list thing thing)))
(send-to let-body
`(multiple-value-bind (value error) (,(parser-part-name (second thing)) ahead)
,(if strict
`(when error
(setf (internal-parse-error-fatal error) t)
(move-lookahead-to iter ahead)
(return-from ,(parser-part-name nonterminal-name)
(values value error)))
`(when error
(return-from next-production)))
(setf (slot-value instance ',(car thing)) value)
(vector-push-extend value matches)))))
(send-to the-body
`(block next-production
(let ((instance (make-instance ',nonterminal-name))
(matches (make-extensible-vector))
(ahead (fork-lookahead-iterator iter)))
,@(nreverse let-body)
(setf (slot-value instance 'raw-matches) matches)
(move-lookahead-to iter ahead)
(return-from ,(parser-part-name nonterminal-name)
(values instance nil))))))))))
`(progn
,@(unless (zerop (hash-table-size slots))
`((defclass ,nonterminal-name (syntax-tree)
(,@(hash-table-keys slots)))))
(define-parser-part ,(parser-part-name nonterminal-name) (iter)
,@(nreverse the-body)
(no-parse "Nonterminal failed to match" ',nonterminal-name))
',nonterminal-name)))
(defmacro define-terminal (name type)
`(define-parser-part ,(parser-part-name name) (iter)
(multiple-value-bind (value more) (peek-lookahead-iterator iter)
(unless more
(no-parse "unexpected EOF" ',name))
(unless (typep value ',type)
(no-parse "Token mismatch" ',name)))
(emit (next iter))))
(defmacro define-parser (name &body body)
(let (result-forms)
(macrolet ((send (form) `(push ,form result-forms))
(send-to (place form) `(push ,form ,place)))
(multiple-value-bind (options nonterminals) (take-while #'grammar-option-form-p body)
(let ((start-symbol (grammar-lookup-option :start-symbol options))
(terminals (grammar-lookup-option :terminals options))
(eof-symbol (grammar-lookup-option :eof-symbol options)))
(unless (and start-symbol terminals)
(error "Start symbol and terminals are required"))
(when (left-recursion-p nonterminals)
(error "Grammar has left recursion ~A" (left-recursion-p nonterminals)))
;; Easiest stuff first. The root node
(send `(define-parser-part ,(parser-part-name name) (iter)
(return-from ,(parser-part-name name) (,(parser-part-name start-symbol) iter))))
;; Now parsers for the terminals
(dolist (term terminals)
(send `(define-terminal ,term ,term)))
(when eof-symbol
(send `(define-parser-part ,(parser-part-name eof-symbol) (iter)
(multiple-value-bind (value more) (peek-lookahead-iterator iter)
(declare (ignore value))
(when more
(no-parse "expected EOF" ',eof-symbol))
(emit ',eof-symbol)))))
;; Now the nonterminals
(dolist (nonterm nonterminals)
(send `(define-nonterminal ,(first nonterm)
,@(rest nonterm)))))))
`(progn ,@(nreverse result-forms))))
(defun syntax-iterator (parser-function token-iterator)
(make-iterator ()
(let ((methods (closer-mop:generic-function-methods parser-function)))
(dolist (m methods)
(check-type m shcl/core/advice::advice-method)))
(multiple-value-bind (value error) (funcall parser-function token-iterator)
(when error
(error 'abort-parse :message (internal-parse-error-message error)
:expected-tokens (internal-parse-error-expected-tokens error)))
(unless value
(stop))
(emit value))))
| true |
;; Copyright 2017 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.
(defpackage :shcl/core/parser
(:use
:common-lisp :alexandria :shcl/core/lexer :shcl/core/utility
:shcl/core/iterator)
(:import-from :shcl/core/advice #:define-advisable)
(:import-from :closer-mop)
(:shadowing-import-from :alexandria #:when-let #:when-let*)
(:export #:define-parser #:syntax-iterator #:make-internal-parse-error #:abort-parse
#:syntax-tree-parts #:syntax-tree))
(in-package :shcl/core/parser)
(optimization-settings)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun take-while (predicate list)
(let (result)
(loop :while (and list (funcall predicate (car list)))
:do (progn
(push (car list) result)
(setf list (cdr list))))
(values (nreverse result) list)))
(defun grammar-option-form-p (form)
(and (consp form)
(keywordp (car form))))
(defun grammar-lookup-option (option-name options)
(second (find option-name options :key #'car :test #'eq)))
(defun left-recursion-p (nonterminals)
(let ((graph (make-hash-table)))
(dolist (nonterm nonterminals)
(destructuring-bind (name &rest productions) nonterm
(dolist (production productions)
(push (if (consp production)
(car production)
production)
(gethash name graph)))))
(labels ((examine (where &optional (stack (list where)))
(let ((children (gethash where graph)))
(dolist (child children)
(when (member child stack)
(return-from left-recursion-p (nreverse (cons child stack))))
(examine child (cons child stack))))))
(dolist (sym (hash-table-keys graph))
(examine sym))
nil))))
(defclass syntax-tree ()
((raw-matches
:initform #()
:reader syntax-tree-parts)))
(defmethod make-load-form ((sy syntax-tree) &optional environment)
(let ((slots (mapcar 'closer-mop:slot-definition-name (closer-mop:class-slots (class-of sy)))))
(make-load-form-saving-slots sy :slot-names slots :environment environment)))
(defmethod print-object ((st syntax-tree) stream)
(print-unreadable-object (st stream :type t :identity nil)
(format stream "~A" (slot-value st 'raw-matches))))
(define-condition abort-parse (error)
((message
:initarg :message
:type string
:initform "<No reason>"
:accessor parse-error-message)
(expected
:initarg :expected-tokens
:type list
:initform nil
:accessor parse-error-expected-tokens))
(:report (lambda (c s)
(format s "Parse error (~A)"
(parse-error-message c))
(let ((expected (parse-error-expected-tokens c)))
(when expected
(format s ", expected tokens ~A" expected))))))
(defstruct internal-parse-error
message
expected-tokens
fatal)
(defmacro define-parser-part (&whole whole name (iter-sym) &body body)
(multiple-value-bind (real-body declarations doc-string)
(parse-body body :documentation t :whole whole)
`(define-advisable ,name (,iter-sym)
,@(when doc-string (list doc-string))
,@declarations
(labels
((no-parse (message &rest expected-tokens)
(return-from ,name
(values nil (make-internal-parse-error
:message message
:expected-tokens expected-tokens
:fatal nil))))
(abort-parse (message &rest expected-tokens)
(return-from ,name
(values nil (make-internal-parse-error
:message message
:expected-tokens expected-tokens
:fatal t))))
(emit (object)
(return-from ,name
(values object nil))))
(declare (inline no-parse abort-parse emit)
(dynamic-extent #'no-parse #'abort-parse #'emit)
(ignorable #'no-parse #'abort-parse #'emit))
(progn ,@real-body)
(error "Explicit emit is required")))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun parser-part-name (thing)
(symbol-nconc-intern nil "PARSE-" thing)))
(defmacro define-nonterminal (nonterminal-name &body productions)
(let (the-body
hit-epsilon
(slots (make-hash-table)))
(macrolet
((send-to (where &body rest)
`(progn
,@(loop :for form :in rest :collect
`(push ,form ,where)))))
(dolist (production productions)
(cond
(hit-epsilon
(error "Epsilon must be the last production"))
((eq nil production)
(send-to the-body `(emit nil))
(setf hit-epsilon t))
((symbolp production)
(send-to the-body
`(let ((ahead (fork-lookahead-iterator iter)))
(multiple-value-bind (value error) (,(parser-part-name production) ahead)
(when (or value (and error (internal-parse-error-fatal error)))
(move-lookahead-to iter ahead)
(return-from ,(parser-part-name nonterminal-name)
(values value error)))))))
((consp production)
(dolist (thing production)
(unless (keywordp thing)
(setf (gethash (if (consp thing) (first thing) thing) slots) t)))
(let (let-body
strict)
(dolist (thing production)
(block next
(when (eq :strict thing)
(setf strict t)
(return-from next))
(unless (consp thing)
(setf thing (list thing thing)))
(send-to let-body
`(multiple-value-bind (value error) (,(parser-part-name (second thing)) ahead)
,(if strict
`(when error
(setf (internal-parse-error-fatal error) t)
(move-lookahead-to iter ahead)
(return-from ,(parser-part-name nonterminal-name)
(values value error)))
`(when error
(return-from next-production)))
(setf (slot-value instance ',(car thing)) value)
(vector-push-extend value matches)))))
(send-to the-body
`(block next-production
(let ((instance (make-instance ',nonterminal-name))
(matches (make-extensible-vector))
(ahead (fork-lookahead-iterator iter)))
,@(nreverse let-body)
(setf (slot-value instance 'raw-matches) matches)
(move-lookahead-to iter ahead)
(return-from ,(parser-part-name nonterminal-name)
(values instance nil))))))))))
`(progn
,@(unless (zerop (hash-table-size slots))
`((defclass ,nonterminal-name (syntax-tree)
(,@(hash-table-keys slots)))))
(define-parser-part ,(parser-part-name nonterminal-name) (iter)
,@(nreverse the-body)
(no-parse "Nonterminal failed to match" ',nonterminal-name))
',nonterminal-name)))
(defmacro define-terminal (name type)
`(define-parser-part ,(parser-part-name name) (iter)
(multiple-value-bind (value more) (peek-lookahead-iterator iter)
(unless more
(no-parse "unexpected EOF" ',name))
(unless (typep value ',type)
(no-parse "Token mismatch" ',name)))
(emit (next iter))))
(defmacro define-parser (name &body body)
(let (result-forms)
(macrolet ((send (form) `(push ,form result-forms))
(send-to (place form) `(push ,form ,place)))
(multiple-value-bind (options nonterminals) (take-while #'grammar-option-form-p body)
(let ((start-symbol (grammar-lookup-option :start-symbol options))
(terminals (grammar-lookup-option :terminals options))
(eof-symbol (grammar-lookup-option :eof-symbol options)))
(unless (and start-symbol terminals)
(error "Start symbol and terminals are required"))
(when (left-recursion-p nonterminals)
(error "Grammar has left recursion ~A" (left-recursion-p nonterminals)))
;; Easiest stuff first. The root node
(send `(define-parser-part ,(parser-part-name name) (iter)
(return-from ,(parser-part-name name) (,(parser-part-name start-symbol) iter))))
;; Now parsers for the terminals
(dolist (term terminals)
(send `(define-terminal ,term ,term)))
(when eof-symbol
(send `(define-parser-part ,(parser-part-name eof-symbol) (iter)
(multiple-value-bind (value more) (peek-lookahead-iterator iter)
(declare (ignore value))
(when more
(no-parse "expected EOF" ',eof-symbol))
(emit ',eof-symbol)))))
;; Now the nonterminals
(dolist (nonterm nonterminals)
(send `(define-nonterminal ,(first nonterm)
,@(rest nonterm)))))))
`(progn ,@(nreverse result-forms))))
(defun syntax-iterator (parser-function token-iterator)
(make-iterator ()
(let ((methods (closer-mop:generic-function-methods parser-function)))
(dolist (m methods)
(check-type m shcl/core/advice::advice-method)))
(multiple-value-bind (value error) (funcall parser-function token-iterator)
(when error
(error 'abort-parse :message (internal-parse-error-message error)
:expected-tokens (internal-parse-error-expected-tokens error)))
(unless value
(stop))
(emit value))))
|
[
{
"context": "t-tabs-mode: nil -*-\n\n;;; Copyright (C) 2010-2011, Dmitry Ignatiev <[email protected]>\n\n;;; Permission is hereby ",
"end": 92,
"score": 0.9998824000358582,
"start": 77,
"tag": "NAME",
"value": "Dmitry Ignatiev"
},
{
"context": "*-\n\n;;; Copyright (C) 2010-2011, Dmitry Ignatiev <[email protected]>\n\n;;; Permission is hereby granted, free of charg",
"end": 114,
"score": 0.9999329447746277,
"start": 94,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
system/guid.lisp
|
Lovesan/doors
| 13 |
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;; Copyright (C) 2010-2011, Dmitry Ignatiev <[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
(in-package #:doors)
(declaim (inline guid guidp make-guid guid-dw guid-w1 guid-w2
guid-b1 guid-b2 guid-b3 guid-b4
guid-b5 guid-b6 guid-b7 guid-b8
%guid-reader %guid-writer %guid-cleaner))
(define-struct
(guid
(:constructor guid (dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8))
(:constructor make-guid)
(:predicate guidp)
(:cleaner %guid-cleaner)
(:reader %guid-reader)
(:writer %guid-writer)
(:print-object (lambda (object stream)
(print-unreadable-object (object stream :type t)
(with-accessors
((dw guid-dw) (w1 guid-w1) (w2 guid-w2)
(b1 guid-b1) (b2 guid-b2) (b3 guid-b3) (b4 guid-b4)
(b5 guid-b5) (b6 guid-b6) (b7 guid-b7) (b8 guid-b8))
object
(format
stream
"{~8,'0X-~{~4,'0X-~}~{~2,'0X~}-~{~2,'0X~}}"
dw
(list w1 w2)
(list b1 b2)
(list b3 b4 b5 b6 b7 b8))))
object)))
(dw uint32)
(w1 uint16)
(w2 uint16)
(b1 uint8)
(b2 uint8)
(b3 uint8)
(b4 uint8)
(b5 uint8)
(b6 uint8)
(b7 uint8)
(b8 uint8))
(defmacro with-guid-accessors ((dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8)
guid
&body body)
`(with-accessors ((,dw guid-dw) (,w1 guid-w1) (,w2 guid-w2)
(,b1 guid-b1) (,b2 guid-b2) (,b3 guid-b3) (,b4 guid-b4)
(,b5 guid-b5) (,b6 guid-b6) (,b7 guid-b7) (,b8 guid-b8))
(the guid ,guid)
,@body))
(defun %guid-reader (p o)
(declare (type pointer p))
(let ((out (or o (guid 0 0 0 0 0 0 0 0 0 0 0))))
(declare (type guid out))
(with-guid-accessors
(dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8) out
(setf dw (deref p 'dword (offsetof 'guid 'dw))
w1 (deref p 'word (offsetof 'guid 'w1))
w2 (deref p 'word (offsetof 'guid 'w2))
b1 (deref p 'byte (offsetof 'guid 'b1))
b2 (deref p 'byte (offsetof 'guid 'b2))
b3 (deref p 'byte (offsetof 'guid 'b3))
b4 (deref p 'byte (offsetof 'guid 'b4))
b5 (deref p 'byte (offsetof 'guid 'b5))
b6 (deref p 'byte (offsetof 'guid 'b6))
b7 (deref p 'byte (offsetof 'guid 'b7))
b8 (deref p 'byte (offsetof 'guid 'b8)))
out)))
(defun %guid-writer (v p)
(declare (type pointer p) (type guid v))
(with-guid-accessors
(dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8) v
(setf (deref p 'dword (offsetof 'guid 'dw)) dw
(deref p 'word (offsetof 'guid 'w1)) w1
(deref p 'word (offsetof 'guid 'w2)) w2
(deref p 'byte (offsetof 'guid 'b1)) b1
(deref p 'byte (offsetof 'guid 'b2)) b2
(deref p 'byte (offsetof 'guid 'b3)) b3
(deref p 'byte (offsetof 'guid 'b4)) b4
(deref p 'byte (offsetof 'guid 'b5)) b5
(deref p 'byte (offsetof 'guid 'b6)) b6
(deref p 'byte (offsetof 'guid 'b7)) b7
(deref p 'byte (offsetof 'guid 'b8)) b8)
v))
(defun %guid-cleaner (p v)
(declare (ignore p v))
nil)
(declaim (inline guid-equal))
(defun guid-equal (guid1 guid2)
(declare (type guid guid1 guid2))
(with-accessors
((dw-1 guid-dw) (w1-1 guid-w1) (w2-1 guid-w2)
(b1-1 guid-b1) (b2-1 guid-b2) (b3-1 guid-b3) (b4-1 guid-b4)
(b5-1 guid-b5) (b6-1 guid-b6) (b7-1 guid-b7) (b8-1 guid-b8))
guid1
(with-accessors
((dw-2 guid-dw) (w1-2 guid-w1) (w2-2 guid-w2)
(b1-2 guid-b1) (b2-2 guid-b2) (b3-2 guid-b3) (b4-2 guid-b4)
(b5-2 guid-b5) (b6-2 guid-b6) (b7-2 guid-b7) (b8-2 guid-b8))
guid2
(and (= dw-1 dw-2) (= w1-1 w1-2) (= w2-1 w2-2)
(= b1-1 b1-2) (= b2-1 b2-2) (= b3-1 b3-2) (= b4-1 b4-2)
(= b5-1 b5-2) (= b6-1 b6-2) (= b7-1 b7-2) (= b8-1 b8-2)))))
(defalias uuid () 'guid)
(deftype uuid () 'guid)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmethod make-load-form ((object guid) &optional env)
(declare (ignore env))
(with-guid-accessors (dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8)
object
`(load-time-value
(guid ,dw ,w1 ,w2 ,b1 ,b2 ,b3 ,b4 ,b5 ,b6 ,b7 ,b8)
t))))
(defmacro %define-guid (name dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8)
(check-type name symbol)
(check-type dw dword)
(check-type w1 word)
(check-type w2 word)
(check-type b1 ubyte)
(check-type b2 ubyte)
(check-type b3 ubyte)
(check-type b4 ubyte)
(check-type b5 ubyte)
(check-type b6 ubyte)
(check-type b7 ubyte)
(check-type b8 ubyte)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(define-constant ,name (load-time-value
(guid ,dw ,w1 ,w2 ,b1 ,b2 ,b3 ,b4 ,b5 ,b6 ,b7 ,b8)
t)
:test #'equalp)
',name))
(defmacro define-guid (name &rest values)
(check-type name symbol)
(cond
((stringp (first values))
(assert (null (rest values)) (values))
(with-guid-accessors
(dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8)
(external-function-call
"IIDFromString"
((:stdcall ole32)
(hresult rv guid)
((& wstring))
((& guid :out) guid :aux))
(car values))
`(%define-guid ,name ,dw ,w1 ,w2 ,b1 ,b2 ,b3 ,b4 ,b5 ,b6 ,b7 ,b8)))
(T (assert (= 11 (length values)) (values))
`(%define-guid ,name ,@values))))
(define-guid uuid-null 0 0 0 0 0 0 0 0 0 0 0)
(defgeneric uuid-of (class)
(:method (class)
(error 'windows-error :code error-invalid-arg))
(:method ((class symbol))
(uuid-of (find-class class)))
(:method ((class null))
uuid-null))
(define-compiler-macro uuid-of (&whole form class)
(if (constantp class)
(uuid-of (eval class))
form))
(define-condition invalid-guid-format (windows-error)
((%string :accessor invalid-guid-format-string
:initform ""
:initarg :string))
(:report (lambda (c s)
(pprint-logical-block (s nil)
(format s "~s is an invalid representation of GUID."
(invalid-guid-format-string c))
(pprint-newline :mandatory s)
(write-string
"String must be of form \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\""
s)
(pprint-newline :mandatory s))
c))
(:documentation
"Signalled when GUID-FROM-STRING function recieves string of invalid format."))
(defun string-from-guid (guid)
(declare (type guid guid))
"Converts a GUID structure to its string representation."
(external-function-call
"StringFromGUID2"
((:stdcall ole32)
(int rv buffer)
((& guid) guid :aux guid)
((& wstring :out) buffer :aux (make-string 38))
(int cch :aux 39))))
(defun guid-from-string (string)
(declare (type string string))
"Converts a string representation of GUID into GUID structure."
(external-function-call
"IIDFromString"
((:stdcall ole32)
(dword rv (if (zerop rv)
guid
(error 'invalid-guid-format
:string string)))
((& wstring) string :aux string)
((& guid :out) guid :aux))))
(define-external-function
("CoCreateGuid" create-guid)
(:stdcall ole32)
(hresult rv guid)
"Creates a GUID, a unique 128-bit integer used for CLSIDs and interface identifiers. "
(guid (& guid :out) :aux))
|
11949
|
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;; Copyright (C) 2010-2011, <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
(in-package #:doors)
(declaim (inline guid guidp make-guid guid-dw guid-w1 guid-w2
guid-b1 guid-b2 guid-b3 guid-b4
guid-b5 guid-b6 guid-b7 guid-b8
%guid-reader %guid-writer %guid-cleaner))
(define-struct
(guid
(:constructor guid (dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8))
(:constructor make-guid)
(:predicate guidp)
(:cleaner %guid-cleaner)
(:reader %guid-reader)
(:writer %guid-writer)
(:print-object (lambda (object stream)
(print-unreadable-object (object stream :type t)
(with-accessors
((dw guid-dw) (w1 guid-w1) (w2 guid-w2)
(b1 guid-b1) (b2 guid-b2) (b3 guid-b3) (b4 guid-b4)
(b5 guid-b5) (b6 guid-b6) (b7 guid-b7) (b8 guid-b8))
object
(format
stream
"{~8,'0X-~{~4,'0X-~}~{~2,'0X~}-~{~2,'0X~}}"
dw
(list w1 w2)
(list b1 b2)
(list b3 b4 b5 b6 b7 b8))))
object)))
(dw uint32)
(w1 uint16)
(w2 uint16)
(b1 uint8)
(b2 uint8)
(b3 uint8)
(b4 uint8)
(b5 uint8)
(b6 uint8)
(b7 uint8)
(b8 uint8))
(defmacro with-guid-accessors ((dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8)
guid
&body body)
`(with-accessors ((,dw guid-dw) (,w1 guid-w1) (,w2 guid-w2)
(,b1 guid-b1) (,b2 guid-b2) (,b3 guid-b3) (,b4 guid-b4)
(,b5 guid-b5) (,b6 guid-b6) (,b7 guid-b7) (,b8 guid-b8))
(the guid ,guid)
,@body))
(defun %guid-reader (p o)
(declare (type pointer p))
(let ((out (or o (guid 0 0 0 0 0 0 0 0 0 0 0))))
(declare (type guid out))
(with-guid-accessors
(dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8) out
(setf dw (deref p 'dword (offsetof 'guid 'dw))
w1 (deref p 'word (offsetof 'guid 'w1))
w2 (deref p 'word (offsetof 'guid 'w2))
b1 (deref p 'byte (offsetof 'guid 'b1))
b2 (deref p 'byte (offsetof 'guid 'b2))
b3 (deref p 'byte (offsetof 'guid 'b3))
b4 (deref p 'byte (offsetof 'guid 'b4))
b5 (deref p 'byte (offsetof 'guid 'b5))
b6 (deref p 'byte (offsetof 'guid 'b6))
b7 (deref p 'byte (offsetof 'guid 'b7))
b8 (deref p 'byte (offsetof 'guid 'b8)))
out)))
(defun %guid-writer (v p)
(declare (type pointer p) (type guid v))
(with-guid-accessors
(dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8) v
(setf (deref p 'dword (offsetof 'guid 'dw)) dw
(deref p 'word (offsetof 'guid 'w1)) w1
(deref p 'word (offsetof 'guid 'w2)) w2
(deref p 'byte (offsetof 'guid 'b1)) b1
(deref p 'byte (offsetof 'guid 'b2)) b2
(deref p 'byte (offsetof 'guid 'b3)) b3
(deref p 'byte (offsetof 'guid 'b4)) b4
(deref p 'byte (offsetof 'guid 'b5)) b5
(deref p 'byte (offsetof 'guid 'b6)) b6
(deref p 'byte (offsetof 'guid 'b7)) b7
(deref p 'byte (offsetof 'guid 'b8)) b8)
v))
(defun %guid-cleaner (p v)
(declare (ignore p v))
nil)
(declaim (inline guid-equal))
(defun guid-equal (guid1 guid2)
(declare (type guid guid1 guid2))
(with-accessors
((dw-1 guid-dw) (w1-1 guid-w1) (w2-1 guid-w2)
(b1-1 guid-b1) (b2-1 guid-b2) (b3-1 guid-b3) (b4-1 guid-b4)
(b5-1 guid-b5) (b6-1 guid-b6) (b7-1 guid-b7) (b8-1 guid-b8))
guid1
(with-accessors
((dw-2 guid-dw) (w1-2 guid-w1) (w2-2 guid-w2)
(b1-2 guid-b1) (b2-2 guid-b2) (b3-2 guid-b3) (b4-2 guid-b4)
(b5-2 guid-b5) (b6-2 guid-b6) (b7-2 guid-b7) (b8-2 guid-b8))
guid2
(and (= dw-1 dw-2) (= w1-1 w1-2) (= w2-1 w2-2)
(= b1-1 b1-2) (= b2-1 b2-2) (= b3-1 b3-2) (= b4-1 b4-2)
(= b5-1 b5-2) (= b6-1 b6-2) (= b7-1 b7-2) (= b8-1 b8-2)))))
(defalias uuid () 'guid)
(deftype uuid () 'guid)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmethod make-load-form ((object guid) &optional env)
(declare (ignore env))
(with-guid-accessors (dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8)
object
`(load-time-value
(guid ,dw ,w1 ,w2 ,b1 ,b2 ,b3 ,b4 ,b5 ,b6 ,b7 ,b8)
t))))
(defmacro %define-guid (name dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8)
(check-type name symbol)
(check-type dw dword)
(check-type w1 word)
(check-type w2 word)
(check-type b1 ubyte)
(check-type b2 ubyte)
(check-type b3 ubyte)
(check-type b4 ubyte)
(check-type b5 ubyte)
(check-type b6 ubyte)
(check-type b7 ubyte)
(check-type b8 ubyte)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(define-constant ,name (load-time-value
(guid ,dw ,w1 ,w2 ,b1 ,b2 ,b3 ,b4 ,b5 ,b6 ,b7 ,b8)
t)
:test #'equalp)
',name))
(defmacro define-guid (name &rest values)
(check-type name symbol)
(cond
((stringp (first values))
(assert (null (rest values)) (values))
(with-guid-accessors
(dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8)
(external-function-call
"IIDFromString"
((:stdcall ole32)
(hresult rv guid)
((& wstring))
((& guid :out) guid :aux))
(car values))
`(%define-guid ,name ,dw ,w1 ,w2 ,b1 ,b2 ,b3 ,b4 ,b5 ,b6 ,b7 ,b8)))
(T (assert (= 11 (length values)) (values))
`(%define-guid ,name ,@values))))
(define-guid uuid-null 0 0 0 0 0 0 0 0 0 0 0)
(defgeneric uuid-of (class)
(:method (class)
(error 'windows-error :code error-invalid-arg))
(:method ((class symbol))
(uuid-of (find-class class)))
(:method ((class null))
uuid-null))
(define-compiler-macro uuid-of (&whole form class)
(if (constantp class)
(uuid-of (eval class))
form))
(define-condition invalid-guid-format (windows-error)
((%string :accessor invalid-guid-format-string
:initform ""
:initarg :string))
(:report (lambda (c s)
(pprint-logical-block (s nil)
(format s "~s is an invalid representation of GUID."
(invalid-guid-format-string c))
(pprint-newline :mandatory s)
(write-string
"String must be of form \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\""
s)
(pprint-newline :mandatory s))
c))
(:documentation
"Signalled when GUID-FROM-STRING function recieves string of invalid format."))
(defun string-from-guid (guid)
(declare (type guid guid))
"Converts a GUID structure to its string representation."
(external-function-call
"StringFromGUID2"
((:stdcall ole32)
(int rv buffer)
((& guid) guid :aux guid)
((& wstring :out) buffer :aux (make-string 38))
(int cch :aux 39))))
(defun guid-from-string (string)
(declare (type string string))
"Converts a string representation of GUID into GUID structure."
(external-function-call
"IIDFromString"
((:stdcall ole32)
(dword rv (if (zerop rv)
guid
(error 'invalid-guid-format
:string string)))
((& wstring) string :aux string)
((& guid :out) guid :aux))))
(define-external-function
("CoCreateGuid" create-guid)
(:stdcall ole32)
(hresult rv guid)
"Creates a GUID, a unique 128-bit integer used for CLSIDs and interface identifiers. "
(guid (& guid :out) :aux))
| true |
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;; Copyright (C) 2010-2011, 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
(in-package #:doors)
(declaim (inline guid guidp make-guid guid-dw guid-w1 guid-w2
guid-b1 guid-b2 guid-b3 guid-b4
guid-b5 guid-b6 guid-b7 guid-b8
%guid-reader %guid-writer %guid-cleaner))
(define-struct
(guid
(:constructor guid (dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8))
(:constructor make-guid)
(:predicate guidp)
(:cleaner %guid-cleaner)
(:reader %guid-reader)
(:writer %guid-writer)
(:print-object (lambda (object stream)
(print-unreadable-object (object stream :type t)
(with-accessors
((dw guid-dw) (w1 guid-w1) (w2 guid-w2)
(b1 guid-b1) (b2 guid-b2) (b3 guid-b3) (b4 guid-b4)
(b5 guid-b5) (b6 guid-b6) (b7 guid-b7) (b8 guid-b8))
object
(format
stream
"{~8,'0X-~{~4,'0X-~}~{~2,'0X~}-~{~2,'0X~}}"
dw
(list w1 w2)
(list b1 b2)
(list b3 b4 b5 b6 b7 b8))))
object)))
(dw uint32)
(w1 uint16)
(w2 uint16)
(b1 uint8)
(b2 uint8)
(b3 uint8)
(b4 uint8)
(b5 uint8)
(b6 uint8)
(b7 uint8)
(b8 uint8))
(defmacro with-guid-accessors ((dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8)
guid
&body body)
`(with-accessors ((,dw guid-dw) (,w1 guid-w1) (,w2 guid-w2)
(,b1 guid-b1) (,b2 guid-b2) (,b3 guid-b3) (,b4 guid-b4)
(,b5 guid-b5) (,b6 guid-b6) (,b7 guid-b7) (,b8 guid-b8))
(the guid ,guid)
,@body))
(defun %guid-reader (p o)
(declare (type pointer p))
(let ((out (or o (guid 0 0 0 0 0 0 0 0 0 0 0))))
(declare (type guid out))
(with-guid-accessors
(dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8) out
(setf dw (deref p 'dword (offsetof 'guid 'dw))
w1 (deref p 'word (offsetof 'guid 'w1))
w2 (deref p 'word (offsetof 'guid 'w2))
b1 (deref p 'byte (offsetof 'guid 'b1))
b2 (deref p 'byte (offsetof 'guid 'b2))
b3 (deref p 'byte (offsetof 'guid 'b3))
b4 (deref p 'byte (offsetof 'guid 'b4))
b5 (deref p 'byte (offsetof 'guid 'b5))
b6 (deref p 'byte (offsetof 'guid 'b6))
b7 (deref p 'byte (offsetof 'guid 'b7))
b8 (deref p 'byte (offsetof 'guid 'b8)))
out)))
(defun %guid-writer (v p)
(declare (type pointer p) (type guid v))
(with-guid-accessors
(dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8) v
(setf (deref p 'dword (offsetof 'guid 'dw)) dw
(deref p 'word (offsetof 'guid 'w1)) w1
(deref p 'word (offsetof 'guid 'w2)) w2
(deref p 'byte (offsetof 'guid 'b1)) b1
(deref p 'byte (offsetof 'guid 'b2)) b2
(deref p 'byte (offsetof 'guid 'b3)) b3
(deref p 'byte (offsetof 'guid 'b4)) b4
(deref p 'byte (offsetof 'guid 'b5)) b5
(deref p 'byte (offsetof 'guid 'b6)) b6
(deref p 'byte (offsetof 'guid 'b7)) b7
(deref p 'byte (offsetof 'guid 'b8)) b8)
v))
(defun %guid-cleaner (p v)
(declare (ignore p v))
nil)
(declaim (inline guid-equal))
(defun guid-equal (guid1 guid2)
(declare (type guid guid1 guid2))
(with-accessors
((dw-1 guid-dw) (w1-1 guid-w1) (w2-1 guid-w2)
(b1-1 guid-b1) (b2-1 guid-b2) (b3-1 guid-b3) (b4-1 guid-b4)
(b5-1 guid-b5) (b6-1 guid-b6) (b7-1 guid-b7) (b8-1 guid-b8))
guid1
(with-accessors
((dw-2 guid-dw) (w1-2 guid-w1) (w2-2 guid-w2)
(b1-2 guid-b1) (b2-2 guid-b2) (b3-2 guid-b3) (b4-2 guid-b4)
(b5-2 guid-b5) (b6-2 guid-b6) (b7-2 guid-b7) (b8-2 guid-b8))
guid2
(and (= dw-1 dw-2) (= w1-1 w1-2) (= w2-1 w2-2)
(= b1-1 b1-2) (= b2-1 b2-2) (= b3-1 b3-2) (= b4-1 b4-2)
(= b5-1 b5-2) (= b6-1 b6-2) (= b7-1 b7-2) (= b8-1 b8-2)))))
(defalias uuid () 'guid)
(deftype uuid () 'guid)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defmethod make-load-form ((object guid) &optional env)
(declare (ignore env))
(with-guid-accessors (dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8)
object
`(load-time-value
(guid ,dw ,w1 ,w2 ,b1 ,b2 ,b3 ,b4 ,b5 ,b6 ,b7 ,b8)
t))))
(defmacro %define-guid (name dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8)
(check-type name symbol)
(check-type dw dword)
(check-type w1 word)
(check-type w2 word)
(check-type b1 ubyte)
(check-type b2 ubyte)
(check-type b3 ubyte)
(check-type b4 ubyte)
(check-type b5 ubyte)
(check-type b6 ubyte)
(check-type b7 ubyte)
(check-type b8 ubyte)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(define-constant ,name (load-time-value
(guid ,dw ,w1 ,w2 ,b1 ,b2 ,b3 ,b4 ,b5 ,b6 ,b7 ,b8)
t)
:test #'equalp)
',name))
(defmacro define-guid (name &rest values)
(check-type name symbol)
(cond
((stringp (first values))
(assert (null (rest values)) (values))
(with-guid-accessors
(dw w1 w2 b1 b2 b3 b4 b5 b6 b7 b8)
(external-function-call
"IIDFromString"
((:stdcall ole32)
(hresult rv guid)
((& wstring))
((& guid :out) guid :aux))
(car values))
`(%define-guid ,name ,dw ,w1 ,w2 ,b1 ,b2 ,b3 ,b4 ,b5 ,b6 ,b7 ,b8)))
(T (assert (= 11 (length values)) (values))
`(%define-guid ,name ,@values))))
(define-guid uuid-null 0 0 0 0 0 0 0 0 0 0 0)
(defgeneric uuid-of (class)
(:method (class)
(error 'windows-error :code error-invalid-arg))
(:method ((class symbol))
(uuid-of (find-class class)))
(:method ((class null))
uuid-null))
(define-compiler-macro uuid-of (&whole form class)
(if (constantp class)
(uuid-of (eval class))
form))
(define-condition invalid-guid-format (windows-error)
((%string :accessor invalid-guid-format-string
:initform ""
:initarg :string))
(:report (lambda (c s)
(pprint-logical-block (s nil)
(format s "~s is an invalid representation of GUID."
(invalid-guid-format-string c))
(pprint-newline :mandatory s)
(write-string
"String must be of form \"{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}\""
s)
(pprint-newline :mandatory s))
c))
(:documentation
"Signalled when GUID-FROM-STRING function recieves string of invalid format."))
(defun string-from-guid (guid)
(declare (type guid guid))
"Converts a GUID structure to its string representation."
(external-function-call
"StringFromGUID2"
((:stdcall ole32)
(int rv buffer)
((& guid) guid :aux guid)
((& wstring :out) buffer :aux (make-string 38))
(int cch :aux 39))))
(defun guid-from-string (string)
(declare (type string string))
"Converts a string representation of GUID into GUID structure."
(external-function-call
"IIDFromString"
((:stdcall ole32)
(dword rv (if (zerop rv)
guid
(error 'invalid-guid-format
:string string)))
((& wstring) string :aux string)
((& guid :out) guid :aux))))
(define-external-function
("CoCreateGuid" create-guid)
(:stdcall ole32)
(hresult rv guid)
"Creates a GUID, a unique 128-bit integer used for CLSIDs and interface identifiers. "
(guid (& guid :out) :aux))
|
[
{
"context": "part of ld36\n(c) 2016 Shirakumo http://tymoon.eu ([email protected])\nAuthor: Nicolas Hafner <[email protected]>, Jan",
"end": 86,
"score": 0.9999024271965027,
"start": 68,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "kumo http://tymoon.eu ([email protected])\nAuthor: Nicolas Hafner <[email protected]>, Janne Pakarinen <gingerales",
"end": 110,
"score": 0.9998905658721924,
"start": 96,
"tag": "NAME",
"value": "Nicolas Hafner"
},
{
"context": "n.eu ([email protected])\nAuthor: Nicolas Hafner <[email protected]>, Janne Pakarinen <[email protected]>\n|#\n\n(in",
"end": 130,
"score": 0.9999155402183533,
"start": 112,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "n.eu)\nAuthor: Nicolas Hafner <[email protected]>, Janne Pakarinen <[email protected]>\n|#\n\n(in-package #:org.shi",
"end": 148,
"score": 0.9998959898948669,
"start": 133,
"tag": "NAME",
"value": "Janne Pakarinen"
},
{
"context": "las Hafner <[email protected]>, Janne Pakarinen <[email protected]>\n|#\n\n(in-package #:org.shirakumo.fraf.ld36)\n(in-r",
"end": 171,
"score": 0.9999276399612427,
"start": 150,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
critter.lisp
|
Shirakumo/ld36
| 1 |
#|
This file is a part of ld36
(c) 2016 Shirakumo http://tymoon.eu ([email protected])
Author: Nicolas Hafner <[email protected]>, Janne Pakarinen <[email protected]>
|#
(in-package #:org.shirakumo.fraf.ld36)
(in-readtable :qtools)
(define-subject critter (sprite-subject collidable flipping pivoted-entity pass-through)
((behavior :initform :idle :accessor behavior)
(previous-location :initform NIL :accessor previous-location)
(last-moved :initform 0 :accessor last-moved)
(target :initform NIL :accessor target))
(:default-initargs
:location (vec 0 0 0)
:hitbox (vec 40 20 20)
:bounds (vec 40 20 20)
:pivot (vec -20 0 10)))
(defmethod initialize-instance :after ((critter critter) &key pivot bounds)
(when (and bounds (not pivot))
(setf (pivot critter) (vec (- (/ (vx (bounds critter)) 2)) 0
(- (/ (vz (bounds critter)) 2)))))
(nv- (location critter) 1))
(defmethod paint ((critter critter) target)
(with-pushed-matrix
(gl:translate 0 0 (- (vz (pivot critter))))
(call-next-method)))
(defmethod interact ((critter critter) player))
(define-handler (critter tick) (ev)
(when (running (scene (window :main)))
(with-slots (behavior last-moved target previous-location location velocity facing) critter
(case behavior
(:idle
(when (< (random 6000) (incf last-moved))
(let* ((avoid-direction (when previous-location (normalize (v- location previous-location))))
(relative-target (random-target 100 300 :avoid avoid-direction)))
(setf target (v+ location relative-target)
behavior :moving))))
(:moving
(let ((relative-target (v- target location)))
(setf velocity
(v* (vec 5 0 5) (normalize relative-target)))
(cond ((< (distance velocity) (distance relative-target))
(nv+ location velocity)
(setf facing (if (< (vx velocity) 0) :left :right)))
(T
(setf location target)))
(when (v= location target)
(setf behavior :idle
previous-location location))))))))
(defun random-target (min max &key avoid)
(let ((x (* (if (< 0 (random 2)) 1 -1) (+ min (random (- max min)))))
(z (* (if (< 0 (random 2)) 1 -1) (+ min (random (- max min))))))
(when (and avoid (v< 0 avoid))
;; 66% chance to turn away from a direction being avoided if earlier random chance pointed that way
(when (and (< 0 (* (vx avoid) x)) (< 0 (random 3)))
(setf x (- x)))
(when (and (< 0 (* (vz avoid) z)) (< 0 (random 3)))
(setf z (- z))))
;; So that diagonal isn't a longer movement distance
(cap-distance (vec x 0 z) max)))
(defun cap-distance (vec max)
(let* ((distance (distance vec))
(capper (/ max distance)))
(vec (floor (* (vx vec) capper)) 0 (floor (* (vz vec) capper)))))
(defun distance (vec)
;; This is a faster way to calculate an approximate distance than (sqrt (* x x) (* y y)).
;; Another option would be (* (/ 1 (sqrt 2)) (+ x y)) but that's only better for when x roughly equals y.
;; Using this instead of (vlength) because there might be a bunch of critters going around.
;; TODO: (sqrt 2) and (sqrt 0.5) should be cached into parameter
;; NOTE: This is only the 2D space distance!!!
(* (/ (1+ (sqrt (- 4 (* 2 (sqrt 2))))) 2)
(max (abs (vx vec))
(abs (vz vec))
(* (sqrt 0.5) (+ (abs (vx vec)) (abs (vz vec)))))))
(defun normalize (vec)
(v/ vec (distance vec)))
(define-asset texture mouse-idle (:ld36)
:file "mouse-idle.png")
(define-asset texture mouse-walking (:ld36)
:file "mouse-walking.png")
(define-subject mouse (critter)
((home :initform NIL :accessor home)
(time-alive :initform 0 :accessor time-alive)
(go-home-at :initform (+ 500 (random 1000)) :accessor go-home-at))
(:default-initargs
:animations '((idle 2.0 1 :texture (:ld36 mouse-idle) :next idle)
(walk 0.7 2 :texture (:ld36 mouse-walking) :next idle))))
(defmethod initialize-instance :after ((mouse mouse) &key home)
;; TODO: spawn a home hole if home is NIL
(setf (home mouse) home))
(defmethod interact ((mouse mouse) player)
(leave mouse (scene (window :main)))
(enter (make-instance 'dead-mouse) (inventory player)))
(defmethod leave :after ((mouse mouse) (scene scene))
(when (running scene)
(incf (gone (home mouse)))))
(define-handler (mouse mouse-tick tick) (ev)
(when (running (scene (window :main)))
(with-slots (time-alive behavior home target go-home-at) mouse
(incf time-alive)
(cond ((and target (v= target (location home)) (v= (location mouse) (location home)))
(leave mouse (scene (window :main))))
((or (<= go-home-at time-alive) (= 0 (random (- go-home-at time-alive))))
(setf target (location home)
behavior :moving)))
(case behavior
(:moving
(setf (animation mouse) 'walk))
(:idle
(setf (animation mouse) 'idle))))))
|
1525
|
#|
This file is a part of ld36
(c) 2016 Shirakumo http://tymoon.eu (<EMAIL>)
Author: <NAME> <<EMAIL>>, <NAME> <<EMAIL>>
|#
(in-package #:org.shirakumo.fraf.ld36)
(in-readtable :qtools)
(define-subject critter (sprite-subject collidable flipping pivoted-entity pass-through)
((behavior :initform :idle :accessor behavior)
(previous-location :initform NIL :accessor previous-location)
(last-moved :initform 0 :accessor last-moved)
(target :initform NIL :accessor target))
(:default-initargs
:location (vec 0 0 0)
:hitbox (vec 40 20 20)
:bounds (vec 40 20 20)
:pivot (vec -20 0 10)))
(defmethod initialize-instance :after ((critter critter) &key pivot bounds)
(when (and bounds (not pivot))
(setf (pivot critter) (vec (- (/ (vx (bounds critter)) 2)) 0
(- (/ (vz (bounds critter)) 2)))))
(nv- (location critter) 1))
(defmethod paint ((critter critter) target)
(with-pushed-matrix
(gl:translate 0 0 (- (vz (pivot critter))))
(call-next-method)))
(defmethod interact ((critter critter) player))
(define-handler (critter tick) (ev)
(when (running (scene (window :main)))
(with-slots (behavior last-moved target previous-location location velocity facing) critter
(case behavior
(:idle
(when (< (random 6000) (incf last-moved))
(let* ((avoid-direction (when previous-location (normalize (v- location previous-location))))
(relative-target (random-target 100 300 :avoid avoid-direction)))
(setf target (v+ location relative-target)
behavior :moving))))
(:moving
(let ((relative-target (v- target location)))
(setf velocity
(v* (vec 5 0 5) (normalize relative-target)))
(cond ((< (distance velocity) (distance relative-target))
(nv+ location velocity)
(setf facing (if (< (vx velocity) 0) :left :right)))
(T
(setf location target)))
(when (v= location target)
(setf behavior :idle
previous-location location))))))))
(defun random-target (min max &key avoid)
(let ((x (* (if (< 0 (random 2)) 1 -1) (+ min (random (- max min)))))
(z (* (if (< 0 (random 2)) 1 -1) (+ min (random (- max min))))))
(when (and avoid (v< 0 avoid))
;; 66% chance to turn away from a direction being avoided if earlier random chance pointed that way
(when (and (< 0 (* (vx avoid) x)) (< 0 (random 3)))
(setf x (- x)))
(when (and (< 0 (* (vz avoid) z)) (< 0 (random 3)))
(setf z (- z))))
;; So that diagonal isn't a longer movement distance
(cap-distance (vec x 0 z) max)))
(defun cap-distance (vec max)
(let* ((distance (distance vec))
(capper (/ max distance)))
(vec (floor (* (vx vec) capper)) 0 (floor (* (vz vec) capper)))))
(defun distance (vec)
;; This is a faster way to calculate an approximate distance than (sqrt (* x x) (* y y)).
;; Another option would be (* (/ 1 (sqrt 2)) (+ x y)) but that's only better for when x roughly equals y.
;; Using this instead of (vlength) because there might be a bunch of critters going around.
;; TODO: (sqrt 2) and (sqrt 0.5) should be cached into parameter
;; NOTE: This is only the 2D space distance!!!
(* (/ (1+ (sqrt (- 4 (* 2 (sqrt 2))))) 2)
(max (abs (vx vec))
(abs (vz vec))
(* (sqrt 0.5) (+ (abs (vx vec)) (abs (vz vec)))))))
(defun normalize (vec)
(v/ vec (distance vec)))
(define-asset texture mouse-idle (:ld36)
:file "mouse-idle.png")
(define-asset texture mouse-walking (:ld36)
:file "mouse-walking.png")
(define-subject mouse (critter)
((home :initform NIL :accessor home)
(time-alive :initform 0 :accessor time-alive)
(go-home-at :initform (+ 500 (random 1000)) :accessor go-home-at))
(:default-initargs
:animations '((idle 2.0 1 :texture (:ld36 mouse-idle) :next idle)
(walk 0.7 2 :texture (:ld36 mouse-walking) :next idle))))
(defmethod initialize-instance :after ((mouse mouse) &key home)
;; TODO: spawn a home hole if home is NIL
(setf (home mouse) home))
(defmethod interact ((mouse mouse) player)
(leave mouse (scene (window :main)))
(enter (make-instance 'dead-mouse) (inventory player)))
(defmethod leave :after ((mouse mouse) (scene scene))
(when (running scene)
(incf (gone (home mouse)))))
(define-handler (mouse mouse-tick tick) (ev)
(when (running (scene (window :main)))
(with-slots (time-alive behavior home target go-home-at) mouse
(incf time-alive)
(cond ((and target (v= target (location home)) (v= (location mouse) (location home)))
(leave mouse (scene (window :main))))
((or (<= go-home-at time-alive) (= 0 (random (- go-home-at time-alive))))
(setf target (location home)
behavior :moving)))
(case behavior
(:moving
(setf (animation mouse) 'walk))
(:idle
(setf (animation mouse) 'idle))))))
| true |
#|
This file is a part of ld36
(c) 2016 Shirakumo http://tymoon.eu (PI:EMAIL:<EMAIL>END_PI)
Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
|#
(in-package #:org.shirakumo.fraf.ld36)
(in-readtable :qtools)
(define-subject critter (sprite-subject collidable flipping pivoted-entity pass-through)
((behavior :initform :idle :accessor behavior)
(previous-location :initform NIL :accessor previous-location)
(last-moved :initform 0 :accessor last-moved)
(target :initform NIL :accessor target))
(:default-initargs
:location (vec 0 0 0)
:hitbox (vec 40 20 20)
:bounds (vec 40 20 20)
:pivot (vec -20 0 10)))
(defmethod initialize-instance :after ((critter critter) &key pivot bounds)
(when (and bounds (not pivot))
(setf (pivot critter) (vec (- (/ (vx (bounds critter)) 2)) 0
(- (/ (vz (bounds critter)) 2)))))
(nv- (location critter) 1))
(defmethod paint ((critter critter) target)
(with-pushed-matrix
(gl:translate 0 0 (- (vz (pivot critter))))
(call-next-method)))
(defmethod interact ((critter critter) player))
(define-handler (critter tick) (ev)
(when (running (scene (window :main)))
(with-slots (behavior last-moved target previous-location location velocity facing) critter
(case behavior
(:idle
(when (< (random 6000) (incf last-moved))
(let* ((avoid-direction (when previous-location (normalize (v- location previous-location))))
(relative-target (random-target 100 300 :avoid avoid-direction)))
(setf target (v+ location relative-target)
behavior :moving))))
(:moving
(let ((relative-target (v- target location)))
(setf velocity
(v* (vec 5 0 5) (normalize relative-target)))
(cond ((< (distance velocity) (distance relative-target))
(nv+ location velocity)
(setf facing (if (< (vx velocity) 0) :left :right)))
(T
(setf location target)))
(when (v= location target)
(setf behavior :idle
previous-location location))))))))
(defun random-target (min max &key avoid)
(let ((x (* (if (< 0 (random 2)) 1 -1) (+ min (random (- max min)))))
(z (* (if (< 0 (random 2)) 1 -1) (+ min (random (- max min))))))
(when (and avoid (v< 0 avoid))
;; 66% chance to turn away from a direction being avoided if earlier random chance pointed that way
(when (and (< 0 (* (vx avoid) x)) (< 0 (random 3)))
(setf x (- x)))
(when (and (< 0 (* (vz avoid) z)) (< 0 (random 3)))
(setf z (- z))))
;; So that diagonal isn't a longer movement distance
(cap-distance (vec x 0 z) max)))
(defun cap-distance (vec max)
(let* ((distance (distance vec))
(capper (/ max distance)))
(vec (floor (* (vx vec) capper)) 0 (floor (* (vz vec) capper)))))
(defun distance (vec)
;; This is a faster way to calculate an approximate distance than (sqrt (* x x) (* y y)).
;; Another option would be (* (/ 1 (sqrt 2)) (+ x y)) but that's only better for when x roughly equals y.
;; Using this instead of (vlength) because there might be a bunch of critters going around.
;; TODO: (sqrt 2) and (sqrt 0.5) should be cached into parameter
;; NOTE: This is only the 2D space distance!!!
(* (/ (1+ (sqrt (- 4 (* 2 (sqrt 2))))) 2)
(max (abs (vx vec))
(abs (vz vec))
(* (sqrt 0.5) (+ (abs (vx vec)) (abs (vz vec)))))))
(defun normalize (vec)
(v/ vec (distance vec)))
(define-asset texture mouse-idle (:ld36)
:file "mouse-idle.png")
(define-asset texture mouse-walking (:ld36)
:file "mouse-walking.png")
(define-subject mouse (critter)
((home :initform NIL :accessor home)
(time-alive :initform 0 :accessor time-alive)
(go-home-at :initform (+ 500 (random 1000)) :accessor go-home-at))
(:default-initargs
:animations '((idle 2.0 1 :texture (:ld36 mouse-idle) :next idle)
(walk 0.7 2 :texture (:ld36 mouse-walking) :next idle))))
(defmethod initialize-instance :after ((mouse mouse) &key home)
;; TODO: spawn a home hole if home is NIL
(setf (home mouse) home))
(defmethod interact ((mouse mouse) player)
(leave mouse (scene (window :main)))
(enter (make-instance 'dead-mouse) (inventory player)))
(defmethod leave :after ((mouse mouse) (scene scene))
(when (running scene)
(incf (gone (home mouse)))))
(define-handler (mouse mouse-tick tick) (ev)
(when (running (scene (window :main)))
(with-slots (time-alive behavior home target go-home-at) mouse
(incf time-alive)
(cond ((and target (v= target (location home)) (v= (location mouse) (location home)))
(leave mouse (scene (window :main))))
((or (<= go-home-at time-alive) (= 0 (random (- go-home-at time-alive))))
(setf target (location home)
behavior :moving)))
(case behavior
(:moving
(setf (animation mouse) 'walk))
(:idle
(setf (animation mouse) 'idle))))))
|
[
{
"context": "ying node translations\n;\n; Copyright (C) 2008-2011 Eric Smith and Stanford University\n; Copyright (C) 2013-2020",
"end": 95,
"score": 0.9996753931045532,
"start": 85,
"tag": "NAME",
"value": "Eric Smith"
},
{
"context": "ense. See the file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;",
"end": 306,
"score": 0.9996504187583923,
"start": 296,
"tag": "NAME",
"value": "Eric Smith"
},
{
"context": " file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 330,
"score": 0.9999290108680725,
"start": 308,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/kestrel/axe/rebuild-nodes.lisp
|
ayazhafiz/acl2
| 0 |
; Tools to rebuild DAGs while applying node translations
;
; 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 "worklist-array")
(include-book "dag-arrays")
(include-book "translation-array")
(include-book "dag-array-builders")
(include-book "def-dag-builder-theorems")
(include-book "sortedp-less-than-or-equal")
(include-book "all-less-than-or-equal-all")
(include-book "less-than-or-equal-all")
(local (include-book "merge-sort-less-than-rules"))
(local (include-book "kestrel/typed-lists-light/nat-listp" :dir :system))
(local (include-book "kestrel/lists-light/last" :dir :system))
(local (include-book "kestrel/lists-light/append" :dir :system))
(local (include-book "kestrel/lists-light/subsetp-equal" :dir :system))
(local (include-book "kestrel/utilities/equal-of-booleans" :dir :system))
(local (include-book "kestrel/arithmetic-light/plus" :dir :system))
(local
(defthm integerp-of-if
(equal (integerp (if x y z))
(if x
(integerp y)
(integerp z)))))
(local
(defthm acl2-numberp-when-integerp
(implies (integerp x)
(acl2-numberp x))))
;dup
(defthmd natp-of-+-of-1-alt
(implies (integerp x)
(equal (natp (+ 1 x))
(<= -1 x))))
(defthm <=-of-0-and-car-of-last-when-all-natp
(implies (and (all-natp x)
(consp x))
(<= 0 (car (last x))))
:hints (("Goal" :in-theory (enable last))))
(defthm <-of--1-and-car-of-last-when-all-natp
(implies (and (all-natp x)
(consp x))
(< -1 (car (last x))))
:hints (("Goal" :in-theory (enable last))))
(defthm <-of-car-of-last-and--1-when-all-natp
(implies (and (all-natp x)
(consp x))
(not (< (car (last x)) -1)))
:hints (("Goal" :in-theory (enable last))))
(encapsulate ()
(local (include-book "kestrel/lists-light/memberp" :dir :system))
;move
(defcong perm iff (member-equal x y) 2
:hints (("Goal" :in-theory (enable member-equal perm)))))
;move
(defcong perm equal (subsetp-equal x y) 2
:hints (("Goal" :in-theory (enable subsetp-equal))))
(defthm subsetp-equal-of-merge-sort-<
(equal (subsetp-equal x (merge-sort-< x))
(subsetp-equal x x)))
;disble?
(defthm natp-of-car-when-nat-listp-type
(implies (and (nat-listp x)
(consp x))
(natp (car x)))
:rule-classes :type-prescription)
(defthm integerp-of-car-of-last-when-all-natp
(implies (and (all-natp x)
(consp x))
(integerp (car (last x))))
:hints (("Goal" :in-theory (enable last))))
(defthm nat-listp-when-all-natp
(implies (all-natp x)
(equal (nat-listp x)
(true-listp x)))
:hints (("Goal" :in-theory (enable nat-listp all-natp))))
(defthmd <-of-car-when-all-<
(implies (and (all-< items x)
(consp items))
(< (car items) x))
:hints (("Goal" :in-theory (enable all-<))))
(defthm <-of-car-when-all-<-cheap
(implies (and (all-< items x)
(consp items))
(< (car items) x))
:rule-classes ((:rewrite :backchain-limit-lst (0 nil)))
:hints (("Goal" :in-theory (enable all-<))))
(defthm all-<-of-+-of-1
(implies (and (syntaxp (not (quotep y)))
(all-integerp x)
(integerp y))
(equal (all-< x (+ 1 y))
(all-<= x y)))
:hints (("Goal" :in-theory (enable all-<= all-<))))
(defthm all-<=-of-car-of-last-when-sortedp-<=-2
(implies (and (sortedp-<= x)
(subsetp-equal y x))
(all-<= y (car (last x))))
:hints (("Goal" :in-theory (enable ALL-<=
SUBSETP-EQUAL
sortedp-<=))))
;;move to rational-lists.lisp
(defthm all-<=-of-maxelem
(all-<= lst (maxelem lst))
:hints (("Goal" :in-theory (enable all-<=))))
(defthmd dargp-of-car-when-all-natp
(implies (all-natp x)
(equal (dargp (car x))
(consp x))))
(defthm all-<=-all-of-get-unexamined-nodenum-args
(implies (and (all-<=-all (keep-atoms args) worklist)
(all-<=-all acc worklist))
(all-<=-all (get-unexamined-nodenum-args args worklist-array acc) worklist))
:hints (("Goal" :in-theory (enable get-unexamined-nodenum-args keep-atoms))))
(defthm all-<=-of-keep-atoms
(implies (and (all-dargp-less-than args (+ 1 nodenum))
(natp nodenum))
(all-<= (keep-atoms args) nodenum))
:hints (("Goal" :in-theory (enable all-dargp-less-than keep-atoms))))
(defthm all-<=-of-keep-atoms-of-dargs
(implies (and (pseudo-dag-arrayp 'dag-array dag-array dag-len)
(consp (AREF1 'DAG-ARRAY DAG-ARRAY NODENUM))
(NOT (EQUAL 'QUOTE (CAR (AREF1 'DAG-ARRAY DAG-ARRAY NODENUM))))
(natp nodenum)
(< nodenum dag-len))
(all-<= (keep-atoms (dargs (aref1 'dag-array dag-array nodenum)))
nodenum))
:hints (("Goal" :use (:instance all-<=-of-keep-atoms (args (dargs (aref1 'dag-array dag-array nodenum))))
:in-theory (disable all-<=-of-keep-atoms))))
(defthm ALL-<=-ALL-when-ALL-<=-ALL-of-cdr-arg2
(implies (and (ALL-<=-ALL x (cdr y))
)
(equal (ALL-<=-ALL x y)
(or (not (consp y))
(all-<= x (car y)))))
:hints (("Goal" :in-theory (enable ALL-<=-ALL))))
(defthm all-<=-all-of-keep-atoms-of-dargs
(implies (and (pseudo-dag-arrayp 'dag-array dag-array dag-len)
(consp (AREF1 'DAG-ARRAY DAG-ARRAY NODENUM))
(NOT (EQUAL 'QUOTE (CAR (AREF1 'DAG-ARRAY DAG-ARRAY NODENUM))))
(natp nodenum)
(< nodenum dag-len)
(<=-all nodenum nodenums)
)
(all-<=-all (keep-atoms (dargs (aref1 'dag-array dag-array nodenum)))
nodenums))
:hints (("goal" :in-theory (enable <=-all)
:induct (<=-all nodenum nodenums))
("subgoal *1/2"
:use (:instance all-<=-of-keep-atoms-of-dargs)
:in-theory (e/d (<=-all)
(ALL-<-OF-KEEP-ATOMS
all-<=-of-keep-atoms-of-dargs
all-<=-of-keep-atoms
all-<-of-keep-atoms-of-dargs-when-bounded-dag-exprp
;;all-dargp-less-than-of-args-when-bounded-dag-exprp
)))))
;; Rebuilds all the nodes in WORKLIST, and their supporters, while performing the substitution indicated by TRANSLATION-ARRAY.
;; Returns (mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist).
;; This doesn't change any existing nodes in the dag (just builds new ones).
;; TODO: this could compute ground terms - but the caller would need to check for quoteps in the result
;; TODO: We could stop once we hit a node smaller than any node which is changed in the translation-array? track the smallest node with a pending change. no smaller node needs to be changed?
(defund rebuild-nodes-aux (worklist ;should be sorted
translation-array ;maps each nodenum to nil (unhandled) or a nodenum (maybe the nodenum itself) [or a quotep - no, not currently]
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
worklist-array)
(declare (xargs :guard (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(sortedp-<= worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len)
(array1p 'worklist-array worklist-array) ;maps nodes to :examined or nil
(= (alen1 'worklist-array worklist-array)
(alen1 'translation-array translation-array)))
;; For the measure, we first check whether the number of
;; examined nodes goes up. If not, we check that the length
;; of the worklist goes down.
:measure (make-ord 1 (+ 1 (- (nfix (alen1 'worklist-array worklist-array))
(num-examined-nodes (+ -1 (alen1 'worklist-array worklist-array))
'worklist-array worklist-array)))
(len worklist))
:verify-guards nil ; done below
))
(if (or (endp worklist)
(not (and (mbt (array1p 'worklist-array worklist-array))
(mbt (all-natp worklist))
(mbt (all-< worklist (alen1 'worklist-array worklist-array))))))
(mv (erp-nil) translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(let ((nodenum (first worklist)))
(if (aref1 'translation-array translation-array nodenum)
;;This nodenum is being replaced, so we don't need to build any new
;;nodes (and it is already bound in translation-array):
(rebuild-nodes-aux (rest worklist) translation-array
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
;; We mark the node as "examined" so it doesn't get added again:
(aset1 'worklist-array worklist-array nodenum :examined))
(let ((expr (aref1 'dag-array dag-array nodenum)))
(if (atom expr)
;;it's a variable, so no nodes need to be rebuilt:
(rebuild-nodes-aux (rest worklist)
(aset1 'translation-array translation-array nodenum nodenum)
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
;; We mark the node as "examined" so it doesn't get added again:
(aset1 'worklist-array worklist-array nodenum :examined))
(if (fquotep expr)
;;it's a constant, so no nodes need to be rebuilt:
(rebuild-nodes-aux (rest worklist)
(aset1 'translation-array translation-array nodenum
nodenum ;todo: i'd like to say expr here, but that could cause translation-array to map nodes to things other than nodenums (which the callers would need to handle -- e.g., if a literal maps to a quotep)
)
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
;; We mark the node as "examined" so it doesn't get added again:
(aset1 'worklist-array worklist-array nodenum :examined))
;;it's a function call:
(let ((res (aref1 'worklist-array worklist-array nodenum)))
(if (eq res :examined)
;; The node has been examined, and since we are back to handling
;; it again, we know that its children have already been examined
;; and processed. So now we can process this node:
(b* (((mv erp new-args changep)
(translate-args-with-changep (dargs expr) translation-array))
((when erp) (mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)))
(if changep
;; TODO: It would be nice to evaluate ground terms here,
;; but that could cause translation-array to map nodes to
;; things other than nodenums (which the callers would
;; need to handle -- e.g., if a literal maps to a quotep).
(mv-let (erp new-nodenum dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(add-function-call-expr-to-dag-array (ffn-symb expr) new-args dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(if erp
(mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(rebuild-nodes-aux (rest worklist)
(aset1 'translation-array translation-array nodenum new-nodenum)
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
worklist-array)))
;; No change, so the node maps to itself:
(rebuild-nodes-aux (rest worklist)
(aset1 'translation-array translation-array nodenum nodenum)
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
worklist-array)))
;; We expand the node. This node's children have not
;; necessarily been processed, but if they've been examined,
;; they've been fully processed.
(let* ((unexamined-args (get-unexamined-nodenum-args (dargs expr) worklist-array nil))
;; TODO: Optimze the case where unexamined-args is nil?
(sorted-unexamined-args (merge-sort-< unexamined-args)))
(rebuild-nodes-aux (append sorted-unexamined-args worklist)
translation-array
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
(aset1 'worklist-array worklist-array nodenum :examined))))))))))))
;dup
(defthm all-<=-when-all-<
(implies (all-< x bound)
(all-<= x bound))
:hints (("Goal" :in-theory (enable all-< all-<=))))
(verify-guards rebuild-nodes-aux :hints (("Goal" :in-theory (e/d (<-of-car-when-all-< dargp-of-car-when-all-natp
all-<=-when-all-<)
(dargp
dargp-less-than
SORTEDP-<=)))))
(def-dag-builder-theorems
(rebuild-nodes-aux worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist worklist-array)
(mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
:hyps ((nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
;;(all-< (strip-cdrs dag-constant-alist) dag-len)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len)
))
(defthm array1p-of-mv-nth-1-of-rebuild-nodes-aux
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))
(array1p 'translation-array (mv-nth 1 (rebuild-nodes-aux worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist worklist-array))))
:hints (("Goal" :in-theory (enable rebuild-nodes-aux))))
(defthm alen1-of-mv-nth-1-of-rebuild-nodes-aux
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))
(equal (alen1 'translation-array (mv-nth 1 (rebuild-nodes-aux worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist worklist-array)))
(alen1 'translation-array translation-array)))
:hints (("Goal" :in-theory (enable rebuild-nodes-aux))))
(defthm translation-arrayp-aux-of-mv-nth-1-of-rebuild-nodes-aux
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len)
(array1p 'worklist-array worklist-array) ;maps nodes to :examined or nil
(= (alen1 'worklist-array worklist-array)
(alen1 'translation-array translation-array)))
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array))
(mv-nth '1 (rebuild-nodes-aux worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist worklist-array))))
:hints (("Goal" :in-theory (e/d (rebuild-nodes-aux) (dargp)))))
(defthm bounded-translation-arrayp-aux-of-mv-nth-1-of-rebuild-nodes-aux
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len)
(array1p 'worklist-array worklist-array) ;maps nodes to :examined or nil
(= (alen1 'worklist-array worklist-array)
(alen1 'translation-array translation-array)))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array))
(mv-nth 1 (rebuild-nodes-aux worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist worklist-array))
(mv-nth 3 (rebuild-nodes-aux worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist worklist-array))))
:hints (("Goal" :in-theory (e/d (rebuild-nodes-aux) (dargp)))))
;; Returns (mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist).
(defund rebuild-nodes (worklist ;should be sorted
translation-array ;maps each nodenum to nil (unhandled) or a nodenum (maybe the nodenum itself) [or a quotep - no, not currently]
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(declare (xargs :guard (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(sortedp-<= worklist)
(consp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))))
(rebuild-nodes-aux worklist
translation-array
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
(make-empty-array 'worklist-array (alen1 'translation-array translation-array))))
(def-dag-builder-theorems
(rebuild-nodes worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
:recursivep nil
:hyps ((nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
;;(all-< (strip-cdrs dag-constant-alist) dag-len)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len)
))
(defthm array1p-of-mv-nth-1-of-rebuild-nodes
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))
(array1p 'translation-array (mv-nth 1 (rebuild-nodes worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))))
:hints (("Goal" :in-theory (enable rebuild-nodes))))
(defthm alen1-of-mv-nth-1-of-rebuild-nodes
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))
(equal (alen1 'translation-array (mv-nth 1 (rebuild-nodes worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)))
(alen1 'translation-array translation-array)))
:hints (("Goal" :in-theory (enable rebuild-nodes))))
(defthm translation-arrayp-aux-of-mv-nth-1-of-rebuild-nodes
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(equal n (+ -1 (alen1 'translation-array translation-array))) ;done as hyp to allow better matching
(nat-listp worklist)
(consp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))
(translation-arrayp-aux n
(mv-nth 1 (rebuild-nodes worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))))
:hints (("Goal" :in-theory (enable rebuild-nodes))))
(defthm bounded-translation-arrayp-aux-of-mv-nth-1-of-rebuild-nodes
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(equal n (+ -1 (alen1 'translation-array translation-array))) ;done as hyp to allow better matching
(nat-listp worklist)
(consp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))
(bounded-translation-arrayp-aux n
(mv-nth 1 (rebuild-nodes worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))
(mv-nth 3 (rebuild-nodes worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))))
:hints (("Goal" :in-theory (enable rebuild-nodes))))
;; Returns (mv erp literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist).
;smashes 'translation-array (and 'tag-array ?)
;ffixme can the literal-nodenums returned ever contain a quotep?
;this could compute ground terms - but the caller would need to check for quoteps in the result
;doesn't change any existing nodes in the dag (just builds new ones)
;; TODO: Consider making a version of this for prover depth 0 which rebuilds
;; the array from scratch (since we can change existing nodes when at depth 0).
(defund rebuild-literals-with-substitution (literal-nodenums
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
nodenum-to-replace
new-nodenum ;fixme allow this to be a quotep?
)
(declare (xargs :guard (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp literal-nodenums)
(all-< literal-nodenums dag-len)
(natp nodenum-to-replace)
(< nodenum-to-replace dag-len)
(natp new-nodenum)
(< new-nodenum dag-len))
:guard-hints (("Goal" :in-theory (e/d (all-integerp-when-all-natp all-rationalp-when-all-natp)
(myquotep dargp dargp-less-than))))))
(b* (((when (not (consp literal-nodenums))) ;must check since we take the max below
(mv (erp-nil) ;or perhaps this is an error. can it happen?
literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))
(sorted-literal-nodenums (merge-sort-< literal-nodenums)) ;; todo: somehow avoid doing this sorting over and over? keep the list sorted?
(max-literal-nodenum (car (last sorted-literal-nodenums)))
((when (< max-literal-nodenum nodenum-to-replace)) ;; may only happen when substituting for a var that doesn't appear in any other literal
;;No change, since nodenum-to-replace does not appear in any literal:
(mv (erp-nil)
literal-nodenums ;; the original literal-nodenums (so that the order is the same)
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))
(translation-array (make-empty-array 'translation-array (+ 1 max-literal-nodenum)))
;; ensure that nodenum-to-replace gets replaced with new-nodenum:
(translation-array (aset1 'translation-array translation-array nodenum-to-replace new-nodenum))
((mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(rebuild-nodes sorted-literal-nodenums ;; initial worklist
translation-array
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))
((when erp) (mv erp literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))
((mv changed-literal-nodenums
unchanged-literal-nodenums)
(translate-nodes literal-nodenums ;; could use sorted-literal-nodenums instead
translation-array
;; Initialize accumulator to include all uneffected nodes
nil nil)))
(mv (erp-nil)
;; We put the changed nodes first, in the hope that we will use them to
;; substitute next, creating a slightly larger term, and so on. The
;; unchanged-literal-nodenums here got reversed wrt the input, so if
;; we had a bad ordering last time, we may have a good ordering this
;; time:
(append changed-literal-nodenums unchanged-literal-nodenums)
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)))
(defthm len-of-mv-nth-1-of-rebuild-literals-with-substitution
(implies (not (mv-nth 0 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum)))
(equal (len (mv-nth 1 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum)))
(len literal-nodenums)))
:hints (("Goal" :in-theory (enable rebuild-literals-with-substitution))))
(local (in-theory (enable all-integerp-when-all-natp
natp-of-+-of-1-alt))) ;for the call of def-dag-builder-theorems just below
(def-dag-builder-theorems
(rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum)
(mv erp literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
:recursivep nil
:hyps ((nat-listp literal-nodenums)
(all-< literal-nodenums dag-len)
(natp nodenum-to-replace)
(< nodenum-to-replace dag-len)
(natp new-nodenum)
(< new-nodenum dag-len)))
;gen?
(defthm nat-listp-of-mv-nth-1-of-rebuild-literals-with-substitution
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp literal-nodenums)
(all-< literal-nodenums dag-len)
(natp nodenum-to-replace)
(nat-listp acc)
(natp new-nodenum)
(< new-nodenum dag-len)
;; (not (mv-nth 0 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum)))
)
(nat-listp (mv-nth 1 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum))))
:hints (("Goal" :in-theory (e/d (rebuild-literals-with-substitution reverse-becomes-reverse-list) (;REVERSE-REMOVAL
natp)))))
(defthm true-listp-of-mv-nth-1-of-rebuild-literals-with-substitution
(implies (true-listp literal-nodenums)
(true-listp (mv-nth 1 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum))))
:hints (("Goal" :in-theory (e/d (rebuild-literals-with-substitution reverse-becomes-reverse-list) (;REVERSE-REMOVAL
natp)))))
(defthm all-<-of-mv-nth-1-of-rebuild-literals-with-substitution
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp literal-nodenums)
(all-< literal-nodenums dag-len)
(natp nodenum-to-replace)
(< nodenum-to-replace dag-len)
(nat-listp acc)
(natp new-nodenum)
(< new-nodenum dag-len)
;; (not (mv-nth 0 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum)))
(all-< acc dag-len)
)
(all-< (mv-nth 1 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum))
(mv-nth 3 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum))))
:hints (("Goal" :in-theory (e/d (rebuild-literals-with-substitution reverse-becomes-reverse-list) (;REVERSE-REMOVAL
natp)))))
|
55004
|
; Tools to rebuild DAGs while applying node translations
;
; 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 "worklist-array")
(include-book "dag-arrays")
(include-book "translation-array")
(include-book "dag-array-builders")
(include-book "def-dag-builder-theorems")
(include-book "sortedp-less-than-or-equal")
(include-book "all-less-than-or-equal-all")
(include-book "less-than-or-equal-all")
(local (include-book "merge-sort-less-than-rules"))
(local (include-book "kestrel/typed-lists-light/nat-listp" :dir :system))
(local (include-book "kestrel/lists-light/last" :dir :system))
(local (include-book "kestrel/lists-light/append" :dir :system))
(local (include-book "kestrel/lists-light/subsetp-equal" :dir :system))
(local (include-book "kestrel/utilities/equal-of-booleans" :dir :system))
(local (include-book "kestrel/arithmetic-light/plus" :dir :system))
(local
(defthm integerp-of-if
(equal (integerp (if x y z))
(if x
(integerp y)
(integerp z)))))
(local
(defthm acl2-numberp-when-integerp
(implies (integerp x)
(acl2-numberp x))))
;dup
(defthmd natp-of-+-of-1-alt
(implies (integerp x)
(equal (natp (+ 1 x))
(<= -1 x))))
(defthm <=-of-0-and-car-of-last-when-all-natp
(implies (and (all-natp x)
(consp x))
(<= 0 (car (last x))))
:hints (("Goal" :in-theory (enable last))))
(defthm <-of--1-and-car-of-last-when-all-natp
(implies (and (all-natp x)
(consp x))
(< -1 (car (last x))))
:hints (("Goal" :in-theory (enable last))))
(defthm <-of-car-of-last-and--1-when-all-natp
(implies (and (all-natp x)
(consp x))
(not (< (car (last x)) -1)))
:hints (("Goal" :in-theory (enable last))))
(encapsulate ()
(local (include-book "kestrel/lists-light/memberp" :dir :system))
;move
(defcong perm iff (member-equal x y) 2
:hints (("Goal" :in-theory (enable member-equal perm)))))
;move
(defcong perm equal (subsetp-equal x y) 2
:hints (("Goal" :in-theory (enable subsetp-equal))))
(defthm subsetp-equal-of-merge-sort-<
(equal (subsetp-equal x (merge-sort-< x))
(subsetp-equal x x)))
;disble?
(defthm natp-of-car-when-nat-listp-type
(implies (and (nat-listp x)
(consp x))
(natp (car x)))
:rule-classes :type-prescription)
(defthm integerp-of-car-of-last-when-all-natp
(implies (and (all-natp x)
(consp x))
(integerp (car (last x))))
:hints (("Goal" :in-theory (enable last))))
(defthm nat-listp-when-all-natp
(implies (all-natp x)
(equal (nat-listp x)
(true-listp x)))
:hints (("Goal" :in-theory (enable nat-listp all-natp))))
(defthmd <-of-car-when-all-<
(implies (and (all-< items x)
(consp items))
(< (car items) x))
:hints (("Goal" :in-theory (enable all-<))))
(defthm <-of-car-when-all-<-cheap
(implies (and (all-< items x)
(consp items))
(< (car items) x))
:rule-classes ((:rewrite :backchain-limit-lst (0 nil)))
:hints (("Goal" :in-theory (enable all-<))))
(defthm all-<-of-+-of-1
(implies (and (syntaxp (not (quotep y)))
(all-integerp x)
(integerp y))
(equal (all-< x (+ 1 y))
(all-<= x y)))
:hints (("Goal" :in-theory (enable all-<= all-<))))
(defthm all-<=-of-car-of-last-when-sortedp-<=-2
(implies (and (sortedp-<= x)
(subsetp-equal y x))
(all-<= y (car (last x))))
:hints (("Goal" :in-theory (enable ALL-<=
SUBSETP-EQUAL
sortedp-<=))))
;;move to rational-lists.lisp
(defthm all-<=-of-maxelem
(all-<= lst (maxelem lst))
:hints (("Goal" :in-theory (enable all-<=))))
(defthmd dargp-of-car-when-all-natp
(implies (all-natp x)
(equal (dargp (car x))
(consp x))))
(defthm all-<=-all-of-get-unexamined-nodenum-args
(implies (and (all-<=-all (keep-atoms args) worklist)
(all-<=-all acc worklist))
(all-<=-all (get-unexamined-nodenum-args args worklist-array acc) worklist))
:hints (("Goal" :in-theory (enable get-unexamined-nodenum-args keep-atoms))))
(defthm all-<=-of-keep-atoms
(implies (and (all-dargp-less-than args (+ 1 nodenum))
(natp nodenum))
(all-<= (keep-atoms args) nodenum))
:hints (("Goal" :in-theory (enable all-dargp-less-than keep-atoms))))
(defthm all-<=-of-keep-atoms-of-dargs
(implies (and (pseudo-dag-arrayp 'dag-array dag-array dag-len)
(consp (AREF1 'DAG-ARRAY DAG-ARRAY NODENUM))
(NOT (EQUAL 'QUOTE (CAR (AREF1 'DAG-ARRAY DAG-ARRAY NODENUM))))
(natp nodenum)
(< nodenum dag-len))
(all-<= (keep-atoms (dargs (aref1 'dag-array dag-array nodenum)))
nodenum))
:hints (("Goal" :use (:instance all-<=-of-keep-atoms (args (dargs (aref1 'dag-array dag-array nodenum))))
:in-theory (disable all-<=-of-keep-atoms))))
(defthm ALL-<=-ALL-when-ALL-<=-ALL-of-cdr-arg2
(implies (and (ALL-<=-ALL x (cdr y))
)
(equal (ALL-<=-ALL x y)
(or (not (consp y))
(all-<= x (car y)))))
:hints (("Goal" :in-theory (enable ALL-<=-ALL))))
(defthm all-<=-all-of-keep-atoms-of-dargs
(implies (and (pseudo-dag-arrayp 'dag-array dag-array dag-len)
(consp (AREF1 'DAG-ARRAY DAG-ARRAY NODENUM))
(NOT (EQUAL 'QUOTE (CAR (AREF1 'DAG-ARRAY DAG-ARRAY NODENUM))))
(natp nodenum)
(< nodenum dag-len)
(<=-all nodenum nodenums)
)
(all-<=-all (keep-atoms (dargs (aref1 'dag-array dag-array nodenum)))
nodenums))
:hints (("goal" :in-theory (enable <=-all)
:induct (<=-all nodenum nodenums))
("subgoal *1/2"
:use (:instance all-<=-of-keep-atoms-of-dargs)
:in-theory (e/d (<=-all)
(ALL-<-OF-KEEP-ATOMS
all-<=-of-keep-atoms-of-dargs
all-<=-of-keep-atoms
all-<-of-keep-atoms-of-dargs-when-bounded-dag-exprp
;;all-dargp-less-than-of-args-when-bounded-dag-exprp
)))))
;; Rebuilds all the nodes in WORKLIST, and their supporters, while performing the substitution indicated by TRANSLATION-ARRAY.
;; Returns (mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist).
;; This doesn't change any existing nodes in the dag (just builds new ones).
;; TODO: this could compute ground terms - but the caller would need to check for quoteps in the result
;; TODO: We could stop once we hit a node smaller than any node which is changed in the translation-array? track the smallest node with a pending change. no smaller node needs to be changed?
(defund rebuild-nodes-aux (worklist ;should be sorted
translation-array ;maps each nodenum to nil (unhandled) or a nodenum (maybe the nodenum itself) [or a quotep - no, not currently]
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
worklist-array)
(declare (xargs :guard (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(sortedp-<= worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len)
(array1p 'worklist-array worklist-array) ;maps nodes to :examined or nil
(= (alen1 'worklist-array worklist-array)
(alen1 'translation-array translation-array)))
;; For the measure, we first check whether the number of
;; examined nodes goes up. If not, we check that the length
;; of the worklist goes down.
:measure (make-ord 1 (+ 1 (- (nfix (alen1 'worklist-array worklist-array))
(num-examined-nodes (+ -1 (alen1 'worklist-array worklist-array))
'worklist-array worklist-array)))
(len worklist))
:verify-guards nil ; done below
))
(if (or (endp worklist)
(not (and (mbt (array1p 'worklist-array worklist-array))
(mbt (all-natp worklist))
(mbt (all-< worklist (alen1 'worklist-array worklist-array))))))
(mv (erp-nil) translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(let ((nodenum (first worklist)))
(if (aref1 'translation-array translation-array nodenum)
;;This nodenum is being replaced, so we don't need to build any new
;;nodes (and it is already bound in translation-array):
(rebuild-nodes-aux (rest worklist) translation-array
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
;; We mark the node as "examined" so it doesn't get added again:
(aset1 'worklist-array worklist-array nodenum :examined))
(let ((expr (aref1 'dag-array dag-array nodenum)))
(if (atom expr)
;;it's a variable, so no nodes need to be rebuilt:
(rebuild-nodes-aux (rest worklist)
(aset1 'translation-array translation-array nodenum nodenum)
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
;; We mark the node as "examined" so it doesn't get added again:
(aset1 'worklist-array worklist-array nodenum :examined))
(if (fquotep expr)
;;it's a constant, so no nodes need to be rebuilt:
(rebuild-nodes-aux (rest worklist)
(aset1 'translation-array translation-array nodenum
nodenum ;todo: i'd like to say expr here, but that could cause translation-array to map nodes to things other than nodenums (which the callers would need to handle -- e.g., if a literal maps to a quotep)
)
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
;; We mark the node as "examined" so it doesn't get added again:
(aset1 'worklist-array worklist-array nodenum :examined))
;;it's a function call:
(let ((res (aref1 'worklist-array worklist-array nodenum)))
(if (eq res :examined)
;; The node has been examined, and since we are back to handling
;; it again, we know that its children have already been examined
;; and processed. So now we can process this node:
(b* (((mv erp new-args changep)
(translate-args-with-changep (dargs expr) translation-array))
((when erp) (mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)))
(if changep
;; TODO: It would be nice to evaluate ground terms here,
;; but that could cause translation-array to map nodes to
;; things other than nodenums (which the callers would
;; need to handle -- e.g., if a literal maps to a quotep).
(mv-let (erp new-nodenum dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(add-function-call-expr-to-dag-array (ffn-symb expr) new-args dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(if erp
(mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(rebuild-nodes-aux (rest worklist)
(aset1 'translation-array translation-array nodenum new-nodenum)
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
worklist-array)))
;; No change, so the node maps to itself:
(rebuild-nodes-aux (rest worklist)
(aset1 'translation-array translation-array nodenum nodenum)
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
worklist-array)))
;; We expand the node. This node's children have not
;; necessarily been processed, but if they've been examined,
;; they've been fully processed.
(let* ((unexamined-args (get-unexamined-nodenum-args (dargs expr) worklist-array nil))
;; TODO: Optimze the case where unexamined-args is nil?
(sorted-unexamined-args (merge-sort-< unexamined-args)))
(rebuild-nodes-aux (append sorted-unexamined-args worklist)
translation-array
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
(aset1 'worklist-array worklist-array nodenum :examined))))))))))))
;dup
(defthm all-<=-when-all-<
(implies (all-< x bound)
(all-<= x bound))
:hints (("Goal" :in-theory (enable all-< all-<=))))
(verify-guards rebuild-nodes-aux :hints (("Goal" :in-theory (e/d (<-of-car-when-all-< dargp-of-car-when-all-natp
all-<=-when-all-<)
(dargp
dargp-less-than
SORTEDP-<=)))))
(def-dag-builder-theorems
(rebuild-nodes-aux worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist worklist-array)
(mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
:hyps ((nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
;;(all-< (strip-cdrs dag-constant-alist) dag-len)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len)
))
(defthm array1p-of-mv-nth-1-of-rebuild-nodes-aux
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))
(array1p 'translation-array (mv-nth 1 (rebuild-nodes-aux worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist worklist-array))))
:hints (("Goal" :in-theory (enable rebuild-nodes-aux))))
(defthm alen1-of-mv-nth-1-of-rebuild-nodes-aux
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))
(equal (alen1 'translation-array (mv-nth 1 (rebuild-nodes-aux worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist worklist-array)))
(alen1 'translation-array translation-array)))
:hints (("Goal" :in-theory (enable rebuild-nodes-aux))))
(defthm translation-arrayp-aux-of-mv-nth-1-of-rebuild-nodes-aux
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len)
(array1p 'worklist-array worklist-array) ;maps nodes to :examined or nil
(= (alen1 'worklist-array worklist-array)
(alen1 'translation-array translation-array)))
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array))
(mv-nth '1 (rebuild-nodes-aux worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist worklist-array))))
:hints (("Goal" :in-theory (e/d (rebuild-nodes-aux) (dargp)))))
(defthm bounded-translation-arrayp-aux-of-mv-nth-1-of-rebuild-nodes-aux
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len)
(array1p 'worklist-array worklist-array) ;maps nodes to :examined or nil
(= (alen1 'worklist-array worklist-array)
(alen1 'translation-array translation-array)))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array))
(mv-nth 1 (rebuild-nodes-aux worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist worklist-array))
(mv-nth 3 (rebuild-nodes-aux worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist worklist-array))))
:hints (("Goal" :in-theory (e/d (rebuild-nodes-aux) (dargp)))))
;; Returns (mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist).
(defund rebuild-nodes (worklist ;should be sorted
translation-array ;maps each nodenum to nil (unhandled) or a nodenum (maybe the nodenum itself) [or a quotep - no, not currently]
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(declare (xargs :guard (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(sortedp-<= worklist)
(consp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))))
(rebuild-nodes-aux worklist
translation-array
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
(make-empty-array 'worklist-array (alen1 'translation-array translation-array))))
(def-dag-builder-theorems
(rebuild-nodes worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
:recursivep nil
:hyps ((nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
;;(all-< (strip-cdrs dag-constant-alist) dag-len)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len)
))
(defthm array1p-of-mv-nth-1-of-rebuild-nodes
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))
(array1p 'translation-array (mv-nth 1 (rebuild-nodes worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))))
:hints (("Goal" :in-theory (enable rebuild-nodes))))
(defthm alen1-of-mv-nth-1-of-rebuild-nodes
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))
(equal (alen1 'translation-array (mv-nth 1 (rebuild-nodes worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)))
(alen1 'translation-array translation-array)))
:hints (("Goal" :in-theory (enable rebuild-nodes))))
(defthm translation-arrayp-aux-of-mv-nth-1-of-rebuild-nodes
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(equal n (+ -1 (alen1 'translation-array translation-array))) ;done as hyp to allow better matching
(nat-listp worklist)
(consp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))
(translation-arrayp-aux n
(mv-nth 1 (rebuild-nodes worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))))
:hints (("Goal" :in-theory (enable rebuild-nodes))))
(defthm bounded-translation-arrayp-aux-of-mv-nth-1-of-rebuild-nodes
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(equal n (+ -1 (alen1 'translation-array translation-array))) ;done as hyp to allow better matching
(nat-listp worklist)
(consp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))
(bounded-translation-arrayp-aux n
(mv-nth 1 (rebuild-nodes worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))
(mv-nth 3 (rebuild-nodes worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))))
:hints (("Goal" :in-theory (enable rebuild-nodes))))
;; Returns (mv erp literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist).
;smashes 'translation-array (and 'tag-array ?)
;ffixme can the literal-nodenums returned ever contain a quotep?
;this could compute ground terms - but the caller would need to check for quoteps in the result
;doesn't change any existing nodes in the dag (just builds new ones)
;; TODO: Consider making a version of this for prover depth 0 which rebuilds
;; the array from scratch (since we can change existing nodes when at depth 0).
(defund rebuild-literals-with-substitution (literal-nodenums
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
nodenum-to-replace
new-nodenum ;fixme allow this to be a quotep?
)
(declare (xargs :guard (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp literal-nodenums)
(all-< literal-nodenums dag-len)
(natp nodenum-to-replace)
(< nodenum-to-replace dag-len)
(natp new-nodenum)
(< new-nodenum dag-len))
:guard-hints (("Goal" :in-theory (e/d (all-integerp-when-all-natp all-rationalp-when-all-natp)
(myquotep dargp dargp-less-than))))))
(b* (((when (not (consp literal-nodenums))) ;must check since we take the max below
(mv (erp-nil) ;or perhaps this is an error. can it happen?
literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))
(sorted-literal-nodenums (merge-sort-< literal-nodenums)) ;; todo: somehow avoid doing this sorting over and over? keep the list sorted?
(max-literal-nodenum (car (last sorted-literal-nodenums)))
((when (< max-literal-nodenum nodenum-to-replace)) ;; may only happen when substituting for a var that doesn't appear in any other literal
;;No change, since nodenum-to-replace does not appear in any literal:
(mv (erp-nil)
literal-nodenums ;; the original literal-nodenums (so that the order is the same)
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))
(translation-array (make-empty-array 'translation-array (+ 1 max-literal-nodenum)))
;; ensure that nodenum-to-replace gets replaced with new-nodenum:
(translation-array (aset1 'translation-array translation-array nodenum-to-replace new-nodenum))
((mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(rebuild-nodes sorted-literal-nodenums ;; initial worklist
translation-array
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))
((when erp) (mv erp literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))
((mv changed-literal-nodenums
unchanged-literal-nodenums)
(translate-nodes literal-nodenums ;; could use sorted-literal-nodenums instead
translation-array
;; Initialize accumulator to include all uneffected nodes
nil nil)))
(mv (erp-nil)
;; We put the changed nodes first, in the hope that we will use them to
;; substitute next, creating a slightly larger term, and so on. The
;; unchanged-literal-nodenums here got reversed wrt the input, so if
;; we had a bad ordering last time, we may have a good ordering this
;; time:
(append changed-literal-nodenums unchanged-literal-nodenums)
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)))
(defthm len-of-mv-nth-1-of-rebuild-literals-with-substitution
(implies (not (mv-nth 0 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum)))
(equal (len (mv-nth 1 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum)))
(len literal-nodenums)))
:hints (("Goal" :in-theory (enable rebuild-literals-with-substitution))))
(local (in-theory (enable all-integerp-when-all-natp
natp-of-+-of-1-alt))) ;for the call of def-dag-builder-theorems just below
(def-dag-builder-theorems
(rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum)
(mv erp literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
:recursivep nil
:hyps ((nat-listp literal-nodenums)
(all-< literal-nodenums dag-len)
(natp nodenum-to-replace)
(< nodenum-to-replace dag-len)
(natp new-nodenum)
(< new-nodenum dag-len)))
;gen?
(defthm nat-listp-of-mv-nth-1-of-rebuild-literals-with-substitution
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp literal-nodenums)
(all-< literal-nodenums dag-len)
(natp nodenum-to-replace)
(nat-listp acc)
(natp new-nodenum)
(< new-nodenum dag-len)
;; (not (mv-nth 0 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum)))
)
(nat-listp (mv-nth 1 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum))))
:hints (("Goal" :in-theory (e/d (rebuild-literals-with-substitution reverse-becomes-reverse-list) (;REVERSE-REMOVAL
natp)))))
(defthm true-listp-of-mv-nth-1-of-rebuild-literals-with-substitution
(implies (true-listp literal-nodenums)
(true-listp (mv-nth 1 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum))))
:hints (("Goal" :in-theory (e/d (rebuild-literals-with-substitution reverse-becomes-reverse-list) (;REVERSE-REMOVAL
natp)))))
(defthm all-<-of-mv-nth-1-of-rebuild-literals-with-substitution
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp literal-nodenums)
(all-< literal-nodenums dag-len)
(natp nodenum-to-replace)
(< nodenum-to-replace dag-len)
(nat-listp acc)
(natp new-nodenum)
(< new-nodenum dag-len)
;; (not (mv-nth 0 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum)))
(all-< acc dag-len)
)
(all-< (mv-nth 1 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum))
(mv-nth 3 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum))))
:hints (("Goal" :in-theory (e/d (rebuild-literals-with-substitution reverse-becomes-reverse-list) (;REVERSE-REMOVAL
natp)))))
| true |
; Tools to rebuild DAGs while applying node translations
;
; 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 "worklist-array")
(include-book "dag-arrays")
(include-book "translation-array")
(include-book "dag-array-builders")
(include-book "def-dag-builder-theorems")
(include-book "sortedp-less-than-or-equal")
(include-book "all-less-than-or-equal-all")
(include-book "less-than-or-equal-all")
(local (include-book "merge-sort-less-than-rules"))
(local (include-book "kestrel/typed-lists-light/nat-listp" :dir :system))
(local (include-book "kestrel/lists-light/last" :dir :system))
(local (include-book "kestrel/lists-light/append" :dir :system))
(local (include-book "kestrel/lists-light/subsetp-equal" :dir :system))
(local (include-book "kestrel/utilities/equal-of-booleans" :dir :system))
(local (include-book "kestrel/arithmetic-light/plus" :dir :system))
(local
(defthm integerp-of-if
(equal (integerp (if x y z))
(if x
(integerp y)
(integerp z)))))
(local
(defthm acl2-numberp-when-integerp
(implies (integerp x)
(acl2-numberp x))))
;dup
(defthmd natp-of-+-of-1-alt
(implies (integerp x)
(equal (natp (+ 1 x))
(<= -1 x))))
(defthm <=-of-0-and-car-of-last-when-all-natp
(implies (and (all-natp x)
(consp x))
(<= 0 (car (last x))))
:hints (("Goal" :in-theory (enable last))))
(defthm <-of--1-and-car-of-last-when-all-natp
(implies (and (all-natp x)
(consp x))
(< -1 (car (last x))))
:hints (("Goal" :in-theory (enable last))))
(defthm <-of-car-of-last-and--1-when-all-natp
(implies (and (all-natp x)
(consp x))
(not (< (car (last x)) -1)))
:hints (("Goal" :in-theory (enable last))))
(encapsulate ()
(local (include-book "kestrel/lists-light/memberp" :dir :system))
;move
(defcong perm iff (member-equal x y) 2
:hints (("Goal" :in-theory (enable member-equal perm)))))
;move
(defcong perm equal (subsetp-equal x y) 2
:hints (("Goal" :in-theory (enable subsetp-equal))))
(defthm subsetp-equal-of-merge-sort-<
(equal (subsetp-equal x (merge-sort-< x))
(subsetp-equal x x)))
;disble?
(defthm natp-of-car-when-nat-listp-type
(implies (and (nat-listp x)
(consp x))
(natp (car x)))
:rule-classes :type-prescription)
(defthm integerp-of-car-of-last-when-all-natp
(implies (and (all-natp x)
(consp x))
(integerp (car (last x))))
:hints (("Goal" :in-theory (enable last))))
(defthm nat-listp-when-all-natp
(implies (all-natp x)
(equal (nat-listp x)
(true-listp x)))
:hints (("Goal" :in-theory (enable nat-listp all-natp))))
(defthmd <-of-car-when-all-<
(implies (and (all-< items x)
(consp items))
(< (car items) x))
:hints (("Goal" :in-theory (enable all-<))))
(defthm <-of-car-when-all-<-cheap
(implies (and (all-< items x)
(consp items))
(< (car items) x))
:rule-classes ((:rewrite :backchain-limit-lst (0 nil)))
:hints (("Goal" :in-theory (enable all-<))))
(defthm all-<-of-+-of-1
(implies (and (syntaxp (not (quotep y)))
(all-integerp x)
(integerp y))
(equal (all-< x (+ 1 y))
(all-<= x y)))
:hints (("Goal" :in-theory (enable all-<= all-<))))
(defthm all-<=-of-car-of-last-when-sortedp-<=-2
(implies (and (sortedp-<= x)
(subsetp-equal y x))
(all-<= y (car (last x))))
:hints (("Goal" :in-theory (enable ALL-<=
SUBSETP-EQUAL
sortedp-<=))))
;;move to rational-lists.lisp
(defthm all-<=-of-maxelem
(all-<= lst (maxelem lst))
:hints (("Goal" :in-theory (enable all-<=))))
(defthmd dargp-of-car-when-all-natp
(implies (all-natp x)
(equal (dargp (car x))
(consp x))))
(defthm all-<=-all-of-get-unexamined-nodenum-args
(implies (and (all-<=-all (keep-atoms args) worklist)
(all-<=-all acc worklist))
(all-<=-all (get-unexamined-nodenum-args args worklist-array acc) worklist))
:hints (("Goal" :in-theory (enable get-unexamined-nodenum-args keep-atoms))))
(defthm all-<=-of-keep-atoms
(implies (and (all-dargp-less-than args (+ 1 nodenum))
(natp nodenum))
(all-<= (keep-atoms args) nodenum))
:hints (("Goal" :in-theory (enable all-dargp-less-than keep-atoms))))
(defthm all-<=-of-keep-atoms-of-dargs
(implies (and (pseudo-dag-arrayp 'dag-array dag-array dag-len)
(consp (AREF1 'DAG-ARRAY DAG-ARRAY NODENUM))
(NOT (EQUAL 'QUOTE (CAR (AREF1 'DAG-ARRAY DAG-ARRAY NODENUM))))
(natp nodenum)
(< nodenum dag-len))
(all-<= (keep-atoms (dargs (aref1 'dag-array dag-array nodenum)))
nodenum))
:hints (("Goal" :use (:instance all-<=-of-keep-atoms (args (dargs (aref1 'dag-array dag-array nodenum))))
:in-theory (disable all-<=-of-keep-atoms))))
(defthm ALL-<=-ALL-when-ALL-<=-ALL-of-cdr-arg2
(implies (and (ALL-<=-ALL x (cdr y))
)
(equal (ALL-<=-ALL x y)
(or (not (consp y))
(all-<= x (car y)))))
:hints (("Goal" :in-theory (enable ALL-<=-ALL))))
(defthm all-<=-all-of-keep-atoms-of-dargs
(implies (and (pseudo-dag-arrayp 'dag-array dag-array dag-len)
(consp (AREF1 'DAG-ARRAY DAG-ARRAY NODENUM))
(NOT (EQUAL 'QUOTE (CAR (AREF1 'DAG-ARRAY DAG-ARRAY NODENUM))))
(natp nodenum)
(< nodenum dag-len)
(<=-all nodenum nodenums)
)
(all-<=-all (keep-atoms (dargs (aref1 'dag-array dag-array nodenum)))
nodenums))
:hints (("goal" :in-theory (enable <=-all)
:induct (<=-all nodenum nodenums))
("subgoal *1/2"
:use (:instance all-<=-of-keep-atoms-of-dargs)
:in-theory (e/d (<=-all)
(ALL-<-OF-KEEP-ATOMS
all-<=-of-keep-atoms-of-dargs
all-<=-of-keep-atoms
all-<-of-keep-atoms-of-dargs-when-bounded-dag-exprp
;;all-dargp-less-than-of-args-when-bounded-dag-exprp
)))))
;; Rebuilds all the nodes in WORKLIST, and their supporters, while performing the substitution indicated by TRANSLATION-ARRAY.
;; Returns (mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist).
;; This doesn't change any existing nodes in the dag (just builds new ones).
;; TODO: this could compute ground terms - but the caller would need to check for quoteps in the result
;; TODO: We could stop once we hit a node smaller than any node which is changed in the translation-array? track the smallest node with a pending change. no smaller node needs to be changed?
(defund rebuild-nodes-aux (worklist ;should be sorted
translation-array ;maps each nodenum to nil (unhandled) or a nodenum (maybe the nodenum itself) [or a quotep - no, not currently]
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
worklist-array)
(declare (xargs :guard (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(sortedp-<= worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len)
(array1p 'worklist-array worklist-array) ;maps nodes to :examined or nil
(= (alen1 'worklist-array worklist-array)
(alen1 'translation-array translation-array)))
;; For the measure, we first check whether the number of
;; examined nodes goes up. If not, we check that the length
;; of the worklist goes down.
:measure (make-ord 1 (+ 1 (- (nfix (alen1 'worklist-array worklist-array))
(num-examined-nodes (+ -1 (alen1 'worklist-array worklist-array))
'worklist-array worklist-array)))
(len worklist))
:verify-guards nil ; done below
))
(if (or (endp worklist)
(not (and (mbt (array1p 'worklist-array worklist-array))
(mbt (all-natp worklist))
(mbt (all-< worklist (alen1 'worklist-array worklist-array))))))
(mv (erp-nil) translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(let ((nodenum (first worklist)))
(if (aref1 'translation-array translation-array nodenum)
;;This nodenum is being replaced, so we don't need to build any new
;;nodes (and it is already bound in translation-array):
(rebuild-nodes-aux (rest worklist) translation-array
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
;; We mark the node as "examined" so it doesn't get added again:
(aset1 'worklist-array worklist-array nodenum :examined))
(let ((expr (aref1 'dag-array dag-array nodenum)))
(if (atom expr)
;;it's a variable, so no nodes need to be rebuilt:
(rebuild-nodes-aux (rest worklist)
(aset1 'translation-array translation-array nodenum nodenum)
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
;; We mark the node as "examined" so it doesn't get added again:
(aset1 'worklist-array worklist-array nodenum :examined))
(if (fquotep expr)
;;it's a constant, so no nodes need to be rebuilt:
(rebuild-nodes-aux (rest worklist)
(aset1 'translation-array translation-array nodenum
nodenum ;todo: i'd like to say expr here, but that could cause translation-array to map nodes to things other than nodenums (which the callers would need to handle -- e.g., if a literal maps to a quotep)
)
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
;; We mark the node as "examined" so it doesn't get added again:
(aset1 'worklist-array worklist-array nodenum :examined))
;;it's a function call:
(let ((res (aref1 'worklist-array worklist-array nodenum)))
(if (eq res :examined)
;; The node has been examined, and since we are back to handling
;; it again, we know that its children have already been examined
;; and processed. So now we can process this node:
(b* (((mv erp new-args changep)
(translate-args-with-changep (dargs expr) translation-array))
((when erp) (mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)))
(if changep
;; TODO: It would be nice to evaluate ground terms here,
;; but that could cause translation-array to map nodes to
;; things other than nodenums (which the callers would
;; need to handle -- e.g., if a literal maps to a quotep).
(mv-let (erp new-nodenum dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(add-function-call-expr-to-dag-array (ffn-symb expr) new-args dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(if erp
(mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(rebuild-nodes-aux (rest worklist)
(aset1 'translation-array translation-array nodenum new-nodenum)
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
worklist-array)))
;; No change, so the node maps to itself:
(rebuild-nodes-aux (rest worklist)
(aset1 'translation-array translation-array nodenum nodenum)
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
worklist-array)))
;; We expand the node. This node's children have not
;; necessarily been processed, but if they've been examined,
;; they've been fully processed.
(let* ((unexamined-args (get-unexamined-nodenum-args (dargs expr) worklist-array nil))
;; TODO: Optimze the case where unexamined-args is nil?
(sorted-unexamined-args (merge-sort-< unexamined-args)))
(rebuild-nodes-aux (append sorted-unexamined-args worklist)
translation-array
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
(aset1 'worklist-array worklist-array nodenum :examined))))))))))))
;dup
(defthm all-<=-when-all-<
(implies (all-< x bound)
(all-<= x bound))
:hints (("Goal" :in-theory (enable all-< all-<=))))
(verify-guards rebuild-nodes-aux :hints (("Goal" :in-theory (e/d (<-of-car-when-all-< dargp-of-car-when-all-natp
all-<=-when-all-<)
(dargp
dargp-less-than
SORTEDP-<=)))))
(def-dag-builder-theorems
(rebuild-nodes-aux worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist worklist-array)
(mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
:hyps ((nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
;;(all-< (strip-cdrs dag-constant-alist) dag-len)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len)
))
(defthm array1p-of-mv-nth-1-of-rebuild-nodes-aux
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))
(array1p 'translation-array (mv-nth 1 (rebuild-nodes-aux worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist worklist-array))))
:hints (("Goal" :in-theory (enable rebuild-nodes-aux))))
(defthm alen1-of-mv-nth-1-of-rebuild-nodes-aux
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))
(equal (alen1 'translation-array (mv-nth 1 (rebuild-nodes-aux worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist worklist-array)))
(alen1 'translation-array translation-array)))
:hints (("Goal" :in-theory (enable rebuild-nodes-aux))))
(defthm translation-arrayp-aux-of-mv-nth-1-of-rebuild-nodes-aux
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len)
(array1p 'worklist-array worklist-array) ;maps nodes to :examined or nil
(= (alen1 'worklist-array worklist-array)
(alen1 'translation-array translation-array)))
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array))
(mv-nth '1 (rebuild-nodes-aux worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist worklist-array))))
:hints (("Goal" :in-theory (e/d (rebuild-nodes-aux) (dargp)))))
(defthm bounded-translation-arrayp-aux-of-mv-nth-1-of-rebuild-nodes-aux
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len)
(array1p 'worklist-array worklist-array) ;maps nodes to :examined or nil
(= (alen1 'worklist-array worklist-array)
(alen1 'translation-array translation-array)))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array))
(mv-nth 1 (rebuild-nodes-aux worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist worklist-array))
(mv-nth 3 (rebuild-nodes-aux worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist worklist-array))))
:hints (("Goal" :in-theory (e/d (rebuild-nodes-aux) (dargp)))))
;; Returns (mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist).
(defund rebuild-nodes (worklist ;should be sorted
translation-array ;maps each nodenum to nil (unhandled) or a nodenum (maybe the nodenum itself) [or a quotep - no, not currently]
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(declare (xargs :guard (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(sortedp-<= worklist)
(consp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))))
(rebuild-nodes-aux worklist
translation-array
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
(make-empty-array 'worklist-array (alen1 'translation-array translation-array))))
(def-dag-builder-theorems
(rebuild-nodes worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
:recursivep nil
:hyps ((nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
;;(all-< (strip-cdrs dag-constant-alist) dag-len)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len)
))
(defthm array1p-of-mv-nth-1-of-rebuild-nodes
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))
(array1p 'translation-array (mv-nth 1 (rebuild-nodes worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))))
:hints (("Goal" :in-theory (enable rebuild-nodes))))
(defthm alen1-of-mv-nth-1-of-rebuild-nodes
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))
(equal (alen1 'translation-array (mv-nth 1 (rebuild-nodes worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)))
(alen1 'translation-array translation-array)))
:hints (("Goal" :in-theory (enable rebuild-nodes))))
(defthm translation-arrayp-aux-of-mv-nth-1-of-rebuild-nodes
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(equal n (+ -1 (alen1 'translation-array translation-array))) ;done as hyp to allow better matching
(nat-listp worklist)
(consp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))
(translation-arrayp-aux n
(mv-nth 1 (rebuild-nodes worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))))
:hints (("Goal" :in-theory (enable rebuild-nodes))))
(defthm bounded-translation-arrayp-aux-of-mv-nth-1-of-rebuild-nodes
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(equal n (+ -1 (alen1 'translation-array translation-array))) ;done as hyp to allow better matching
(nat-listp worklist)
(consp worklist)
(all-< worklist dag-len)
(array1p 'translation-array translation-array)
(translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array)
(all-< worklist (alen1 'translation-array translation-array))
(bounded-translation-arrayp-aux (+ -1 (alen1 'translation-array translation-array)) translation-array dag-len))
(bounded-translation-arrayp-aux n
(mv-nth 1 (rebuild-nodes worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))
(mv-nth 3 (rebuild-nodes worklist translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))))
:hints (("Goal" :in-theory (enable rebuild-nodes))))
;; Returns (mv erp literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist).
;smashes 'translation-array (and 'tag-array ?)
;ffixme can the literal-nodenums returned ever contain a quotep?
;this could compute ground terms - but the caller would need to check for quoteps in the result
;doesn't change any existing nodes in the dag (just builds new ones)
;; TODO: Consider making a version of this for prover depth 0 which rebuilds
;; the array from scratch (since we can change existing nodes when at depth 0).
(defund rebuild-literals-with-substitution (literal-nodenums
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist
nodenum-to-replace
new-nodenum ;fixme allow this to be a quotep?
)
(declare (xargs :guard (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp literal-nodenums)
(all-< literal-nodenums dag-len)
(natp nodenum-to-replace)
(< nodenum-to-replace dag-len)
(natp new-nodenum)
(< new-nodenum dag-len))
:guard-hints (("Goal" :in-theory (e/d (all-integerp-when-all-natp all-rationalp-when-all-natp)
(myquotep dargp dargp-less-than))))))
(b* (((when (not (consp literal-nodenums))) ;must check since we take the max below
(mv (erp-nil) ;or perhaps this is an error. can it happen?
literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))
(sorted-literal-nodenums (merge-sort-< literal-nodenums)) ;; todo: somehow avoid doing this sorting over and over? keep the list sorted?
(max-literal-nodenum (car (last sorted-literal-nodenums)))
((when (< max-literal-nodenum nodenum-to-replace)) ;; may only happen when substituting for a var that doesn't appear in any other literal
;;No change, since nodenum-to-replace does not appear in any literal:
(mv (erp-nil)
literal-nodenums ;; the original literal-nodenums (so that the order is the same)
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))
(translation-array (make-empty-array 'translation-array (+ 1 max-literal-nodenum)))
;; ensure that nodenum-to-replace gets replaced with new-nodenum:
(translation-array (aset1 'translation-array translation-array nodenum-to-replace new-nodenum))
((mv erp translation-array dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
(rebuild-nodes sorted-literal-nodenums ;; initial worklist
translation-array
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))
((when erp) (mv erp literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist))
((mv changed-literal-nodenums
unchanged-literal-nodenums)
(translate-nodes literal-nodenums ;; could use sorted-literal-nodenums instead
translation-array
;; Initialize accumulator to include all uneffected nodes
nil nil)))
(mv (erp-nil)
;; We put the changed nodes first, in the hope that we will use them to
;; substitute next, creating a slightly larger term, and so on. The
;; unchanged-literal-nodenums here got reversed wrt the input, so if
;; we had a bad ordering last time, we may have a good ordering this
;; time:
(append changed-literal-nodenums unchanged-literal-nodenums)
dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)))
(defthm len-of-mv-nth-1-of-rebuild-literals-with-substitution
(implies (not (mv-nth 0 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum)))
(equal (len (mv-nth 1 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum)))
(len literal-nodenums)))
:hints (("Goal" :in-theory (enable rebuild-literals-with-substitution))))
(local (in-theory (enable all-integerp-when-all-natp
natp-of-+-of-1-alt))) ;for the call of def-dag-builder-theorems just below
(def-dag-builder-theorems
(rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum)
(mv erp literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist)
:recursivep nil
:hyps ((nat-listp literal-nodenums)
(all-< literal-nodenums dag-len)
(natp nodenum-to-replace)
(< nodenum-to-replace dag-len)
(natp new-nodenum)
(< new-nodenum dag-len)))
;gen?
(defthm nat-listp-of-mv-nth-1-of-rebuild-literals-with-substitution
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp literal-nodenums)
(all-< literal-nodenums dag-len)
(natp nodenum-to-replace)
(nat-listp acc)
(natp new-nodenum)
(< new-nodenum dag-len)
;; (not (mv-nth 0 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum)))
)
(nat-listp (mv-nth 1 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum))))
:hints (("Goal" :in-theory (e/d (rebuild-literals-with-substitution reverse-becomes-reverse-list) (;REVERSE-REMOVAL
natp)))))
(defthm true-listp-of-mv-nth-1-of-rebuild-literals-with-substitution
(implies (true-listp literal-nodenums)
(true-listp (mv-nth 1 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum))))
:hints (("Goal" :in-theory (e/d (rebuild-literals-with-substitution reverse-becomes-reverse-list) (;REVERSE-REMOVAL
natp)))))
(defthm all-<-of-mv-nth-1-of-rebuild-literals-with-substitution
(implies (and (wf-dagp 'dag-array dag-array dag-len 'dag-parent-array dag-parent-array dag-constant-alist dag-variable-alist)
(nat-listp literal-nodenums)
(all-< literal-nodenums dag-len)
(natp nodenum-to-replace)
(< nodenum-to-replace dag-len)
(nat-listp acc)
(natp new-nodenum)
(< new-nodenum dag-len)
;; (not (mv-nth 0 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum)))
(all-< acc dag-len)
)
(all-< (mv-nth 1 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum))
(mv-nth 3 (rebuild-literals-with-substitution literal-nodenums dag-array dag-len dag-parent-array dag-constant-alist dag-variable-alist nodenum-to-replace new-nodenum))))
:hints (("Goal" :in-theory (e/d (rebuild-literals-with-substitution reverse-becomes-reverse-list) (;REVERSE-REMOVAL
natp)))))
|
[
{
"context": ";;;; Copyright (c) 2011-2015 Henry Harrington <[email protected]>\n;;;; This code is li",
"end": 45,
"score": 0.999873697757721,
"start": 29,
"tag": "NAME",
"value": "Henry Harrington"
},
{
"context": ";;;; Copyright (c) 2011-2015 Henry Harrington <[email protected]>\n;;;; This code is licensed under the MIT license",
"end": 73,
"score": 0.9999341368675232,
"start": 47,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
supervisor/time.lisp
|
aberg001/Mezzano
| 1 |
;;;; Copyright (c) 2011-2015 Henry Harrington <[email protected]>
;;;; This code is licensed under the MIT license.
(in-package :mezzano.supervisor)
(defconstant +pit-irq+ 0)
(defvar *heartbeat-lock*)
(defvar *heartbeat-cvar*)
(defvar *rtc-lock*)
(defun pit-irq-handler (irq)
(declare (ignore irq))
(with-mutex (*heartbeat-lock*)
(condition-notify *heartbeat-cvar* t)))
(defun initialize-time ()
(when (not (boundp '*heartbeat-lock*))
(setf *heartbeat-lock* (make-mutex "Heartbeat lock" :spin)
*heartbeat-cvar* (make-condition-variable "Heartbeat"))
(setf *rtc-lock* (make-mutex "RTC lock" :spin)))
(i8259-hook-irq +pit-irq+ 'pit-irq-handler)
(i8259-unmask-irq +pit-irq+))
(defun wait-for-heartbeat ()
(with-mutex (*heartbeat-lock*)
(condition-wait *heartbeat-cvar* *heartbeat-lock*)))
;; RTC IO ports.
(defconstant +rtc-index-io-reg+ #x70)
(defconstant +rtc-data-io-reg+ #x71)
(defconstant +rtc-nmi-disable+ #x80)
;; RTC/CMOS registers.
(defconstant +rtc-second+ #x00)
(defconstant +rtc-minute+ #x02)
(defconstant +rtc-hour+ #x04)
(defconstant +rtc-hour-pm+ #x80
"When the RTC uses 12-hour mode, this bit specifies PM.")
(defconstant +rtc-weekday+ #x06)
(defconstant +rtc-day+ #x07)
(defconstant +rtc-month+ #x08)
(defconstant +rtc-year+ #x09)
(defconstant +rtc-century+ #x32)
(defconstant +rtc-status-a+ #x0A)
(defconstant +rtc-status-a-update-in-progress+ #x80)
(defconstant +rtc-status-b+ #x0B)
(defconstant +rtc-status-b-24-hour-mode+ #x02)
(defconstant +rtc-status-b-binary-mode+ #x04)
(defun rtc (register)
;; Setting the high bit of the index register
;; will disable some types of NMI.
(check-type register (unsigned-byte 7))
(setf (system:io-port/8 +rtc-index-io-reg+) register)
(system:io-port/8 +rtc-data-io-reg+))
(defun (setf rtc) (value register)
;; Setting the high bit of the index register
;; will disable some types of NMI.
(check-type register (unsigned-byte 7))
(setf (system:io-port/8 +rtc-index-io-reg+) register
(system:io-port/8 +rtc-data-io-reg+) value))
(defun read-rtc-time (&optional (century-boundary 2012))
"Read the time values from the RTC.
CENTURY-BOUNDARY is used to calculate the full year.
It should be the current year, or earlier."
;; http://wiki.osdev.org/CMOS
;; This repeatedly reads the RTC until the values match.
(with-mutex (*rtc-lock*)
(flet ((wait-for-rtc ()
"Wait for the update-in-progress flag to clear. Returns false if the RTC times out."
(dotimes (i 10000 nil)
(when (zerop (logand (rtc +rtc-status-a+) +rtc-status-a-update-in-progress+))
(return t))))
(conv-bcd (v)
"Convert a BCD byte to binary."
(+ (ldb (byte 4 0) v)
(* (ldb (byte 4 4) v) 10))))
;; Don't care about failure here.
(wait-for-rtc)
(let ((second (rtc +rtc-second+))
(minute (rtc +rtc-minute+))
(hour (rtc +rtc-hour+))
(day (rtc +rtc-day+))
(month (rtc +rtc-month+))
(year (rtc +rtc-year+))
(status-b (rtc +rtc-status-b+)))
;; Keep rereading until we get two consistent times.
(do ((last-second nil (prog1 second (setf second (rtc +rtc-second+))))
(last-minute nil (prog1 minute (setf minute (rtc +rtc-minute+))))
(last-hour nil (prog1 hour (setf hour (rtc +rtc-hour+))))
(last-day nil (prog1 day (setf day (rtc +rtc-day+))))
(last-month nil (prog1 month (setf month (rtc +rtc-month+))))
(last-year nil (prog1 year (setf year (rtc +rtc-year+)))))
((and (eql second last-second)
(eql minute last-minute)
(eql hour last-hour)
(eql day last-day)
(eql month last-month)
(eql year last-year)))
(when (not (wait-for-rtc))
;; RTC timed out, use these values anyway.
(return)))
(when (zerop (logand status-b +rtc-status-b-binary-mode+))
;; RTC is running in BCD mode.
(setf second (conv-bcd second)
minute (conv-bcd minute)
;; Preserve the 12-hour AM/PM bit.
hour (logior (conv-bcd (logand hour (lognot +rtc-hour-pm+)))
(logand hour +rtc-hour-pm+))
day (conv-bcd day)
month (conv-bcd month)
year (conv-bcd year)))
(when (and (not (logtest status-b +rtc-status-b-24-hour-mode+))
(logtest hour +rtc-hour-pm+))
;; RTC in 12-hour mode and it's PM.
(setf hour (rem (+ (logand hour (lognot +rtc-hour-pm+)) 12) 24)))
;; Calculate the full year.
(let ((century (* (truncate century-boundary 100) 100)))
(incf year century)
(when (< year century-boundary) (incf year 100)))
(values second minute hour day month year)))))
|
58864
|
;;;; Copyright (c) 2011-2015 <NAME> <<EMAIL>>
;;;; This code is licensed under the MIT license.
(in-package :mezzano.supervisor)
(defconstant +pit-irq+ 0)
(defvar *heartbeat-lock*)
(defvar *heartbeat-cvar*)
(defvar *rtc-lock*)
(defun pit-irq-handler (irq)
(declare (ignore irq))
(with-mutex (*heartbeat-lock*)
(condition-notify *heartbeat-cvar* t)))
(defun initialize-time ()
(when (not (boundp '*heartbeat-lock*))
(setf *heartbeat-lock* (make-mutex "Heartbeat lock" :spin)
*heartbeat-cvar* (make-condition-variable "Heartbeat"))
(setf *rtc-lock* (make-mutex "RTC lock" :spin)))
(i8259-hook-irq +pit-irq+ 'pit-irq-handler)
(i8259-unmask-irq +pit-irq+))
(defun wait-for-heartbeat ()
(with-mutex (*heartbeat-lock*)
(condition-wait *heartbeat-cvar* *heartbeat-lock*)))
;; RTC IO ports.
(defconstant +rtc-index-io-reg+ #x70)
(defconstant +rtc-data-io-reg+ #x71)
(defconstant +rtc-nmi-disable+ #x80)
;; RTC/CMOS registers.
(defconstant +rtc-second+ #x00)
(defconstant +rtc-minute+ #x02)
(defconstant +rtc-hour+ #x04)
(defconstant +rtc-hour-pm+ #x80
"When the RTC uses 12-hour mode, this bit specifies PM.")
(defconstant +rtc-weekday+ #x06)
(defconstant +rtc-day+ #x07)
(defconstant +rtc-month+ #x08)
(defconstant +rtc-year+ #x09)
(defconstant +rtc-century+ #x32)
(defconstant +rtc-status-a+ #x0A)
(defconstant +rtc-status-a-update-in-progress+ #x80)
(defconstant +rtc-status-b+ #x0B)
(defconstant +rtc-status-b-24-hour-mode+ #x02)
(defconstant +rtc-status-b-binary-mode+ #x04)
(defun rtc (register)
;; Setting the high bit of the index register
;; will disable some types of NMI.
(check-type register (unsigned-byte 7))
(setf (system:io-port/8 +rtc-index-io-reg+) register)
(system:io-port/8 +rtc-data-io-reg+))
(defun (setf rtc) (value register)
;; Setting the high bit of the index register
;; will disable some types of NMI.
(check-type register (unsigned-byte 7))
(setf (system:io-port/8 +rtc-index-io-reg+) register
(system:io-port/8 +rtc-data-io-reg+) value))
(defun read-rtc-time (&optional (century-boundary 2012))
"Read the time values from the RTC.
CENTURY-BOUNDARY is used to calculate the full year.
It should be the current year, or earlier."
;; http://wiki.osdev.org/CMOS
;; This repeatedly reads the RTC until the values match.
(with-mutex (*rtc-lock*)
(flet ((wait-for-rtc ()
"Wait for the update-in-progress flag to clear. Returns false if the RTC times out."
(dotimes (i 10000 nil)
(when (zerop (logand (rtc +rtc-status-a+) +rtc-status-a-update-in-progress+))
(return t))))
(conv-bcd (v)
"Convert a BCD byte to binary."
(+ (ldb (byte 4 0) v)
(* (ldb (byte 4 4) v) 10))))
;; Don't care about failure here.
(wait-for-rtc)
(let ((second (rtc +rtc-second+))
(minute (rtc +rtc-minute+))
(hour (rtc +rtc-hour+))
(day (rtc +rtc-day+))
(month (rtc +rtc-month+))
(year (rtc +rtc-year+))
(status-b (rtc +rtc-status-b+)))
;; Keep rereading until we get two consistent times.
(do ((last-second nil (prog1 second (setf second (rtc +rtc-second+))))
(last-minute nil (prog1 minute (setf minute (rtc +rtc-minute+))))
(last-hour nil (prog1 hour (setf hour (rtc +rtc-hour+))))
(last-day nil (prog1 day (setf day (rtc +rtc-day+))))
(last-month nil (prog1 month (setf month (rtc +rtc-month+))))
(last-year nil (prog1 year (setf year (rtc +rtc-year+)))))
((and (eql second last-second)
(eql minute last-minute)
(eql hour last-hour)
(eql day last-day)
(eql month last-month)
(eql year last-year)))
(when (not (wait-for-rtc))
;; RTC timed out, use these values anyway.
(return)))
(when (zerop (logand status-b +rtc-status-b-binary-mode+))
;; RTC is running in BCD mode.
(setf second (conv-bcd second)
minute (conv-bcd minute)
;; Preserve the 12-hour AM/PM bit.
hour (logior (conv-bcd (logand hour (lognot +rtc-hour-pm+)))
(logand hour +rtc-hour-pm+))
day (conv-bcd day)
month (conv-bcd month)
year (conv-bcd year)))
(when (and (not (logtest status-b +rtc-status-b-24-hour-mode+))
(logtest hour +rtc-hour-pm+))
;; RTC in 12-hour mode and it's PM.
(setf hour (rem (+ (logand hour (lognot +rtc-hour-pm+)) 12) 24)))
;; Calculate the full year.
(let ((century (* (truncate century-boundary 100) 100)))
(incf year century)
(when (< year century-boundary) (incf year 100)))
(values second minute hour day month year)))))
| true |
;;;; Copyright (c) 2011-2015 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;;; This code is licensed under the MIT license.
(in-package :mezzano.supervisor)
(defconstant +pit-irq+ 0)
(defvar *heartbeat-lock*)
(defvar *heartbeat-cvar*)
(defvar *rtc-lock*)
(defun pit-irq-handler (irq)
(declare (ignore irq))
(with-mutex (*heartbeat-lock*)
(condition-notify *heartbeat-cvar* t)))
(defun initialize-time ()
(when (not (boundp '*heartbeat-lock*))
(setf *heartbeat-lock* (make-mutex "Heartbeat lock" :spin)
*heartbeat-cvar* (make-condition-variable "Heartbeat"))
(setf *rtc-lock* (make-mutex "RTC lock" :spin)))
(i8259-hook-irq +pit-irq+ 'pit-irq-handler)
(i8259-unmask-irq +pit-irq+))
(defun wait-for-heartbeat ()
(with-mutex (*heartbeat-lock*)
(condition-wait *heartbeat-cvar* *heartbeat-lock*)))
;; RTC IO ports.
(defconstant +rtc-index-io-reg+ #x70)
(defconstant +rtc-data-io-reg+ #x71)
(defconstant +rtc-nmi-disable+ #x80)
;; RTC/CMOS registers.
(defconstant +rtc-second+ #x00)
(defconstant +rtc-minute+ #x02)
(defconstant +rtc-hour+ #x04)
(defconstant +rtc-hour-pm+ #x80
"When the RTC uses 12-hour mode, this bit specifies PM.")
(defconstant +rtc-weekday+ #x06)
(defconstant +rtc-day+ #x07)
(defconstant +rtc-month+ #x08)
(defconstant +rtc-year+ #x09)
(defconstant +rtc-century+ #x32)
(defconstant +rtc-status-a+ #x0A)
(defconstant +rtc-status-a-update-in-progress+ #x80)
(defconstant +rtc-status-b+ #x0B)
(defconstant +rtc-status-b-24-hour-mode+ #x02)
(defconstant +rtc-status-b-binary-mode+ #x04)
(defun rtc (register)
;; Setting the high bit of the index register
;; will disable some types of NMI.
(check-type register (unsigned-byte 7))
(setf (system:io-port/8 +rtc-index-io-reg+) register)
(system:io-port/8 +rtc-data-io-reg+))
(defun (setf rtc) (value register)
;; Setting the high bit of the index register
;; will disable some types of NMI.
(check-type register (unsigned-byte 7))
(setf (system:io-port/8 +rtc-index-io-reg+) register
(system:io-port/8 +rtc-data-io-reg+) value))
(defun read-rtc-time (&optional (century-boundary 2012))
"Read the time values from the RTC.
CENTURY-BOUNDARY is used to calculate the full year.
It should be the current year, or earlier."
;; http://wiki.osdev.org/CMOS
;; This repeatedly reads the RTC until the values match.
(with-mutex (*rtc-lock*)
(flet ((wait-for-rtc ()
"Wait for the update-in-progress flag to clear. Returns false if the RTC times out."
(dotimes (i 10000 nil)
(when (zerop (logand (rtc +rtc-status-a+) +rtc-status-a-update-in-progress+))
(return t))))
(conv-bcd (v)
"Convert a BCD byte to binary."
(+ (ldb (byte 4 0) v)
(* (ldb (byte 4 4) v) 10))))
;; Don't care about failure here.
(wait-for-rtc)
(let ((second (rtc +rtc-second+))
(minute (rtc +rtc-minute+))
(hour (rtc +rtc-hour+))
(day (rtc +rtc-day+))
(month (rtc +rtc-month+))
(year (rtc +rtc-year+))
(status-b (rtc +rtc-status-b+)))
;; Keep rereading until we get two consistent times.
(do ((last-second nil (prog1 second (setf second (rtc +rtc-second+))))
(last-minute nil (prog1 minute (setf minute (rtc +rtc-minute+))))
(last-hour nil (prog1 hour (setf hour (rtc +rtc-hour+))))
(last-day nil (prog1 day (setf day (rtc +rtc-day+))))
(last-month nil (prog1 month (setf month (rtc +rtc-month+))))
(last-year nil (prog1 year (setf year (rtc +rtc-year+)))))
((and (eql second last-second)
(eql minute last-minute)
(eql hour last-hour)
(eql day last-day)
(eql month last-month)
(eql year last-year)))
(when (not (wait-for-rtc))
;; RTC timed out, use these values anyway.
(return)))
(when (zerop (logand status-b +rtc-status-b-binary-mode+))
;; RTC is running in BCD mode.
(setf second (conv-bcd second)
minute (conv-bcd minute)
;; Preserve the 12-hour AM/PM bit.
hour (logior (conv-bcd (logand hour (lognot +rtc-hour-pm+)))
(logand hour +rtc-hour-pm+))
day (conv-bcd day)
month (conv-bcd month)
year (conv-bcd year)))
(when (and (not (logtest status-b +rtc-status-b-24-hour-mode+))
(logtest hour +rtc-hour-pm+))
;; RTC in 12-hour mode and it's PM.
(setf hour (rem (+ (logand hour (lognot +rtc-hour-pm+)) 12) 24)))
;; Calculate the full year.
(let ((century (* (truncate century-boundary 100) 100)))
(incf year century)
(when (< year century-boundary) (incf year 100)))
(values second minute hour day month year)))))
|
[
{
"context": ";;;; work-queue.lisp\n;;;;\n;;;; Copyright (c) 2017 Jeremiah LaRocco <[email protected]>\n\n(in-package #:wo",
"end": 66,
"score": 0.9998798966407776,
"start": 50,
"tag": "NAME",
"value": "Jeremiah LaRocco"
},
{
"context": "sp\n;;;;\n;;;; Copyright (c) 2017 Jeremiah LaRocco <[email protected]>\n\n(in-package #:work-queue)\n\n(defclass work-queue",
"end": 97,
"score": 0.9999344944953918,
"start": 68,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
work-queue.lisp
|
jl2/work-queue
| 0 |
;;;; work-queue.lisp
;;;;
;;;; Copyright (c) 2017 Jeremiah LaRocco <[email protected]>
(in-package #:work-queue)
(defclass work-queue ()
((thread-count :initform 8 :initarg :thread-count)
(consumer-function :initarg :consumer)
(finished :initform nil)
(threads :initform nil)
(jobs :initform nil :initarg :jobs)
(job-mutex :initform nil :initarg :job-mutex)
(job-cv :initform nil :initarg :job-cv)
(finish-mutex :initform nil :initarg :finish-mutex)
(finish-cv :initform nil :initarg :finish-cv))
(:documentation "A multi-threaded job queue."))
(defun create-worker-thread (wq)
"Create a worker thread that waits for jobs and calls consumer-function with them."
(bt:make-thread
(lambda ()
(with-slots (jobs finished finish-mutex finish-cv job-mutex job-cv consumer-function) wq
(let ((current-job nil)
(work-done nil))
(loop until work-done
do
(when current-job
(funcall consumer-function current-job)
(setf current-job nil))
(bt:with-lock-held (job-mutex)
(cond (jobs
(setf current-job (pop jobs))
(setf work-done nil))
(finished
(setf work-done t))
(t
(bt:condition-wait job-cv job-mutex))))))
(format t "Thread notifiying finish-cv.~%")
(bt:with-lock-held (finish-mutex)
(bt:condition-notify finish-cv)))
(format t "quitting ~%"))))
(defun create-work-queue (consumer &optional (thread-count 8))
"Create a work queue object and launch the specified number of threads."
(let ((wq (make-instance 'work-queue
:thread-count thread-count
:job-mutex (bt:make-lock)
:job-cv (bt:make-condition-variable)
:finish-mutex (bt:make-lock)
:finish-cv (bt:make-condition-variable)
:consumer consumer)))
(with-slots (threads jobs) wq
(dotimes (i thread-count)
(push (create-worker-thread wq) threads)))
wq))
(defun add-job (wq item)
"Add a job to the work queue."
(with-slots (finished job-mutex job-cv jobs) wq
(bt:with-lock-held (job-mutex)
(when finished
(error "Work queue is already finished."))
(push item jobs))
(bt:condition-notify job-cv)))
(defun destroy-work-queue (wq)
"Wait for all jobs to finish and join all the threads."
(with-slots (job-cv job-mutex finished finish-mutex finish-cv threads) wq
(bt:with-lock-held (finish-mutex)
(setf finished t))
(dotimes (i (length threads))
(bt:condition-notify job-cv))
(dolist (thread threads)
(bt:join-thread thread))
wq))
|
303
|
;;;; work-queue.lisp
;;;;
;;;; Copyright (c) 2017 <NAME> <<EMAIL>>
(in-package #:work-queue)
(defclass work-queue ()
((thread-count :initform 8 :initarg :thread-count)
(consumer-function :initarg :consumer)
(finished :initform nil)
(threads :initform nil)
(jobs :initform nil :initarg :jobs)
(job-mutex :initform nil :initarg :job-mutex)
(job-cv :initform nil :initarg :job-cv)
(finish-mutex :initform nil :initarg :finish-mutex)
(finish-cv :initform nil :initarg :finish-cv))
(:documentation "A multi-threaded job queue."))
(defun create-worker-thread (wq)
"Create a worker thread that waits for jobs and calls consumer-function with them."
(bt:make-thread
(lambda ()
(with-slots (jobs finished finish-mutex finish-cv job-mutex job-cv consumer-function) wq
(let ((current-job nil)
(work-done nil))
(loop until work-done
do
(when current-job
(funcall consumer-function current-job)
(setf current-job nil))
(bt:with-lock-held (job-mutex)
(cond (jobs
(setf current-job (pop jobs))
(setf work-done nil))
(finished
(setf work-done t))
(t
(bt:condition-wait job-cv job-mutex))))))
(format t "Thread notifiying finish-cv.~%")
(bt:with-lock-held (finish-mutex)
(bt:condition-notify finish-cv)))
(format t "quitting ~%"))))
(defun create-work-queue (consumer &optional (thread-count 8))
"Create a work queue object and launch the specified number of threads."
(let ((wq (make-instance 'work-queue
:thread-count thread-count
:job-mutex (bt:make-lock)
:job-cv (bt:make-condition-variable)
:finish-mutex (bt:make-lock)
:finish-cv (bt:make-condition-variable)
:consumer consumer)))
(with-slots (threads jobs) wq
(dotimes (i thread-count)
(push (create-worker-thread wq) threads)))
wq))
(defun add-job (wq item)
"Add a job to the work queue."
(with-slots (finished job-mutex job-cv jobs) wq
(bt:with-lock-held (job-mutex)
(when finished
(error "Work queue is already finished."))
(push item jobs))
(bt:condition-notify job-cv)))
(defun destroy-work-queue (wq)
"Wait for all jobs to finish and join all the threads."
(with-slots (job-cv job-mutex finished finish-mutex finish-cv threads) wq
(bt:with-lock-held (finish-mutex)
(setf finished t))
(dotimes (i (length threads))
(bt:condition-notify job-cv))
(dolist (thread threads)
(bt:join-thread thread))
wq))
| true |
;;;; work-queue.lisp
;;;;
;;;; Copyright (c) 2017 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
(in-package #:work-queue)
(defclass work-queue ()
((thread-count :initform 8 :initarg :thread-count)
(consumer-function :initarg :consumer)
(finished :initform nil)
(threads :initform nil)
(jobs :initform nil :initarg :jobs)
(job-mutex :initform nil :initarg :job-mutex)
(job-cv :initform nil :initarg :job-cv)
(finish-mutex :initform nil :initarg :finish-mutex)
(finish-cv :initform nil :initarg :finish-cv))
(:documentation "A multi-threaded job queue."))
(defun create-worker-thread (wq)
"Create a worker thread that waits for jobs and calls consumer-function with them."
(bt:make-thread
(lambda ()
(with-slots (jobs finished finish-mutex finish-cv job-mutex job-cv consumer-function) wq
(let ((current-job nil)
(work-done nil))
(loop until work-done
do
(when current-job
(funcall consumer-function current-job)
(setf current-job nil))
(bt:with-lock-held (job-mutex)
(cond (jobs
(setf current-job (pop jobs))
(setf work-done nil))
(finished
(setf work-done t))
(t
(bt:condition-wait job-cv job-mutex))))))
(format t "Thread notifiying finish-cv.~%")
(bt:with-lock-held (finish-mutex)
(bt:condition-notify finish-cv)))
(format t "quitting ~%"))))
(defun create-work-queue (consumer &optional (thread-count 8))
"Create a work queue object and launch the specified number of threads."
(let ((wq (make-instance 'work-queue
:thread-count thread-count
:job-mutex (bt:make-lock)
:job-cv (bt:make-condition-variable)
:finish-mutex (bt:make-lock)
:finish-cv (bt:make-condition-variable)
:consumer consumer)))
(with-slots (threads jobs) wq
(dotimes (i thread-count)
(push (create-worker-thread wq) threads)))
wq))
(defun add-job (wq item)
"Add a job to the work queue."
(with-slots (finished job-mutex job-cv jobs) wq
(bt:with-lock-held (job-mutex)
(when finished
(error "Work queue is already finished."))
(push item jobs))
(bt:condition-notify job-cv)))
(defun destroy-work-queue (wq)
"Wait for all jobs to finish and join all the threads."
(with-slots (job-cv job-mutex finished finish-mutex finish-cv threads) wq
(bt:with-lock-held (finish-mutex)
(setf finished t))
(dotimes (i (length threads))
(bt:condition-notify job-cv))
(dolist (thread threads)
(bt:join-thread thread))
wq))
|
[
{
"context": "rans.lisp\n\n#|\nThe MIT license.\n\nCopyright (c) 2010 Paul L. Krueger\n\nPermission is hereby granted, free of charge, to",
"end": 75,
"score": 0.9998793601989746,
"start": 60,
"tag": "NAME",
"value": "Paul L. Krueger"
}
] |
Utilities/path-trans.lisp
|
plkrueger/CocoaInterface
| 34 |
;; path-trans.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.
|#
(eval-when (:compile-toplevel :load-toplevel :execute)
(require :iu-classes)
(require :nslog-utils)
(require :ns-string-utils)
(require :assoc-array))
(in-package :iu)
;; debugging facility
;; Used primarily in binding-utils.lisp, which is dependent on this file
(defvar *log-bindings* nil)
(defun log-bindings (&optional (on-off t))
(setf *log-bindings* on-off))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; lisp-ptr-wrapper
;;;
;;; This is a class that encapsulates a pointer to a lisp object so we can pass this
;;; off to an Objective-C view and know what it points to when we get it back later.
;;; Added the ability to handle bindings.
#|
(defclass lisp-ptr-wrapper (ns:ns-object)
((lpw-lisp-ptr :accessor lpw-lisp-ptr)
(lpw-controller :accessor lpw-controller)
(lpw-depth :accessor lpw-depth)
(lpw-parent :accessor lpw-parent))
(:metaclass ns:+ns-object))
|#
(objc:defmethod (#/copyWithZone: :id)
((self lisp-ptr-wrapper) (zone (* #>NSZone)))
(when *log-bindings*
(ns-log-format "Copying wrapper for ~s" (lpw-lisp-ptr self)))
self)
(let ((kvc-observed (make-instance 'assoc-array :rank 2 :tests (list #'eql #'equal)))
(obj-wrappers (make-instance 'assoc-array :rank 2)))
;; this assoc-array keeps track of paths that are being observed and the
;; corresponding lisp-ptr-wrapper object that is ostensibly being observed.
(defun make-ptr-wrapper (ptr &key (depth 1) (parent nil) (controller nil))
(when *log-bindings*
(ns-log-format "Making wrapper for ~s" ptr))
(let ((lpw (make-instance 'lisp-ptr-wrapper)))
(setf (lpw-lisp-ptr lpw) ptr)
(setf (lpw-depth lpw) depth)
(setf (lpw-parent lpw) parent)
(setf (lpw-controller lpw) controller)
(setf (assoc-aref obj-wrappers controller ptr) lpw)
lpw))
(defmethod wrapper-for (lisp-obj &key (controller nil) (depth 0) (parent nil))
(or (assoc-aref obj-wrappers controller lisp-obj)
(setf (assoc-aref obj-wrappers controller lisp-obj)
(make-ptr-wrapper lisp-obj
:depth depth
:parent parent
:controller controller))))
(defmethod note-kvc-observed ((self lisp-ptr-wrapper) lisp-obj path)
(when *log-bindings*
(ns-log-format "Observing ~s for ~s" path lisp-obj))
(pushnew self (assoc-aref kvc-observed lisp-obj path)))
(defmethod will-change-value-for-key (owner key)
;; called from a lisp object to tell us that a value will be changed.
;; We find the lisp-ptr-wrapper instances that have been used to access
;; the owner via the specified key and call the appropriate
;; method to let KVC know what is going on.
;; Could also be called for a :kvo lisp slot in an objective-c instance
;; and if so we should call the willChange... method for this instance.
(when *log-bindings*
(ns-log-format "Will change ~s for ~s" key owner))
(let ((owner-lpws (assoc-aref kvc-observed owner key))
(objc-key (lisp-to-temp-nsstring (if (stringp key)
key
(lisp-to-objc-keypathname key)))))
(if (typep owner 'ns:ns-object)
(#/willChangeValueForKey: owner objc-key))
(dolist (lpw owner-lpws)
(when *log-bindings*
(ns-log-format "#/willChangeValueForKey: ~s ~s" lpw objc-key))
(#/willChangeValueForKey: lpw objc-key))))
(defmethod did-change-value-for-key (owner key)
;; called from a lisp object to tell us that a value changed.
;; We find the lisp-ptr-wrapper instances that have been used to access
;; the owner via the specified key and call the appropriate
;; method to lets KVC know what is going on.
;; Could also be called for a :kvo lisp slot in an objective-c instance.
;; If so, call the didChange... method for this instance.
(when *log-bindings*
(ns-log-format "Did change ~s for ~s" key owner))
(let ((owner-lpws (assoc-aref kvc-observed owner key))
(objc-key (lisp-to-temp-nsstring (if (stringp key)
key
(lisp-to-objc-keypathname key)))))
(if (typep owner 'ns:ns-object)
(#/didChangeValueForKey: owner objc-key))
(dolist (lpw owner-lpws)
(when *log-bindings*
(ns-log-format "#/didChangeValueForKey: ~s ~s" lpw objc-key))
(#/didChangeValueForKey: lpw objc-key))))
(defun kvc-observed ()
kvc-observed)
)
(defmacro objc-method-for (meth-name lisp-meth)
(let ((meth-sym (gentemp))
(lisp-fun (gentemp)))
`(let ((,meth-sym (intern (symbol-name ,meth-name) (find-package :nextstep-functions)))
(,lisp-fun ,lisp-meth))
(eval `(objc:defmethod (,,meth-sym :id)
((self ns:ns-object))
;; ns:ns-object is always passed, never a null pointer, but if a null object
;; needs to be passed it will encoded as a lisp-point-wrapper pointinG to nil.
;; So lisp functions must always be prepared to get nil as an argument.
;; Return value is always a wrapper so that when converted back to lisp we
;; get what was intended.
(wrapper-for (funcall ,,lisp-fun (coerce-obj self t))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Methods to support binding to Lisp slots and value translation between bound objects
(let ((key-returns (make-hash-table :test #'equal)))
;; key-returns tells us whether the value for a given key should be returned as a lisp-ptr-wrapper
;; or an Objective-C value converted from the the lisp value retrieved using the key. The legal
;; hash values are :path and :convert
(defun set-key-return (key-str role)
(setf (gethash key-str key-returns) role))
(defun key-return (key-str)
(gethash key-str key-returns nil))
)
(let ((path-trans (make-instance 'assoc-array :rank 2 :tests '(eql equal))))
(defun objc-to-lisp-keypathname (name-str)
;; translate a name from Objective-C to Lisp
;; Use standard translation for function/slot names except the use of
;; underscore (#\_) is used initially to delimit a package specifier
(let* ((package-end (if (char= (elt name-str 0) #\_)
(position #\_ name-str :start 1)))
(pkg-string (string-upcase (subseq name-str 1 package-end)))
(path-string (if package-end
(subseq name-str (1+ package-end))
name-str))
(pkg (or (and package-end
(find-package pkg-string))
(find-package :cl-user))))
;; cache the string we are translating so that we can reverse
;; translate to exactly the same string used by the developer.
(setf (assoc-aref path-trans pkg path-string) name-str)
(ccl::compute-lisp-name path-string pkg)))
(defun lisp-to-objc-keypathname (name)
;; translate name (symbol or string or function) from Lisp to Objective-C
;; If we previously cached a string that came from Objective-C and
;; was translated to this name, then translate back to it. This
;; prevents problems caused by alternative package names/nicknames
;; that the developer might have used in Interface Builder.
;; Use standard translation for function/slot names except prefix
;; package name and underscore if package is not cl-user
(if (functionp name)
(find-or-make-func-keypath name)
(let ((pkg (if (symbolp name)
(symbol-package name)
(find-package :cl-user)))
(name-str (string name))
(name-segments nil))
(or (assoc-aref path-trans pkg name-str)
(progn
(do* ((start 0 (1+ pos))
(pos (position #\- name-str)
(position #\- name-str :start start)))
((null pos) (setf name-segments (nreverse (cons (subseq name-str start) name-segments))))
(setf name-segments (cons (subseq name-str start pos) name-segments)))
(setf name-segments (cons (string-downcase (first name-segments))
(mapcar #'string-capitalize (rest name-segments))))
(unless (eq pkg (find-package :cl-user))
(setf name-segments (cons (concatenate 'string
"_"
(lisp-to-objc-keypathname (or (first (package-nicknames pkg))
(package-name pkg)))
"_")
name-segments)))
(apply #'concatenate 'string name-segments))))))
(defun find-or-make-func-keypath (lisp-func)
;; find a previously made symbol corresponding to the lisp object if it exists, or create one
;; Cache so we can easity translate in both directions.
;; Create an objc method that converts an objc argument to lisp, applies the method, and
;; converts it back to objc. This lets lisp functions be used as intermediate path elements
;; for bindings.
(or (assoc-aref path-trans lisp-func nil)
(let* ((sym-package (find-package :cl-user))
(sym (gentemp "Trans" sym-package))
(sym-name (symbol-name sym)))
(setf (assoc-aref path-trans sym-package sym-name) lisp-func)
(setf (assoc-aref path-trans lisp-func nil) sym-name)
(objc-method-for sym lisp-func)
sym-name)))
(defun func-for-keypath (keypath)
;; find the function represented by the keypath if it exists
(let ((func (assoc-aref path-trans (find-package :cl-user) keypath)))
(when (functionp func) func)))
(defun convert-path-element (pe)
(cond ((stringp pe)
pe)
((functionp pe)
(find-or-make-func-keypath pe))))
(defun convert-path-list (key-path)
;; key-path ::= <path-object> | ( <path-object>* )
;; path-object ::= <path-string> | <lisp-accessor-function>
;; path-string ::= "<path-elt-string>{.<path-string>}*
;; path-elt-string ::= any legal string for Objective-C keypaths
(let ((path-strs (if (listp key-path)
(mapcar #'convert-path-element key-path)
(list (convert-path-element key-path)))))
(dolist (ps (butlast path-strs))
(set-key-return ps :path))
(set-key-return (first (last path-strs)) :convert)
(lisp-to-temp-nsstring (format nil "~{~a~^.~}" path-strs))))
)
(provide :path-trans)
|
66042
|
;; path-trans.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.
|#
(eval-when (:compile-toplevel :load-toplevel :execute)
(require :iu-classes)
(require :nslog-utils)
(require :ns-string-utils)
(require :assoc-array))
(in-package :iu)
;; debugging facility
;; Used primarily in binding-utils.lisp, which is dependent on this file
(defvar *log-bindings* nil)
(defun log-bindings (&optional (on-off t))
(setf *log-bindings* on-off))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; lisp-ptr-wrapper
;;;
;;; This is a class that encapsulates a pointer to a lisp object so we can pass this
;;; off to an Objective-C view and know what it points to when we get it back later.
;;; Added the ability to handle bindings.
#|
(defclass lisp-ptr-wrapper (ns:ns-object)
((lpw-lisp-ptr :accessor lpw-lisp-ptr)
(lpw-controller :accessor lpw-controller)
(lpw-depth :accessor lpw-depth)
(lpw-parent :accessor lpw-parent))
(:metaclass ns:+ns-object))
|#
(objc:defmethod (#/copyWithZone: :id)
((self lisp-ptr-wrapper) (zone (* #>NSZone)))
(when *log-bindings*
(ns-log-format "Copying wrapper for ~s" (lpw-lisp-ptr self)))
self)
(let ((kvc-observed (make-instance 'assoc-array :rank 2 :tests (list #'eql #'equal)))
(obj-wrappers (make-instance 'assoc-array :rank 2)))
;; this assoc-array keeps track of paths that are being observed and the
;; corresponding lisp-ptr-wrapper object that is ostensibly being observed.
(defun make-ptr-wrapper (ptr &key (depth 1) (parent nil) (controller nil))
(when *log-bindings*
(ns-log-format "Making wrapper for ~s" ptr))
(let ((lpw (make-instance 'lisp-ptr-wrapper)))
(setf (lpw-lisp-ptr lpw) ptr)
(setf (lpw-depth lpw) depth)
(setf (lpw-parent lpw) parent)
(setf (lpw-controller lpw) controller)
(setf (assoc-aref obj-wrappers controller ptr) lpw)
lpw))
(defmethod wrapper-for (lisp-obj &key (controller nil) (depth 0) (parent nil))
(or (assoc-aref obj-wrappers controller lisp-obj)
(setf (assoc-aref obj-wrappers controller lisp-obj)
(make-ptr-wrapper lisp-obj
:depth depth
:parent parent
:controller controller))))
(defmethod note-kvc-observed ((self lisp-ptr-wrapper) lisp-obj path)
(when *log-bindings*
(ns-log-format "Observing ~s for ~s" path lisp-obj))
(pushnew self (assoc-aref kvc-observed lisp-obj path)))
(defmethod will-change-value-for-key (owner key)
;; called from a lisp object to tell us that a value will be changed.
;; We find the lisp-ptr-wrapper instances that have been used to access
;; the owner via the specified key and call the appropriate
;; method to let KVC know what is going on.
;; Could also be called for a :kvo lisp slot in an objective-c instance
;; and if so we should call the willChange... method for this instance.
(when *log-bindings*
(ns-log-format "Will change ~s for ~s" key owner))
(let ((owner-lpws (assoc-aref kvc-observed owner key))
(objc-key (lisp-to-temp-nsstring (if (stringp key)
key
(lisp-to-objc-keypathname key)))))
(if (typep owner 'ns:ns-object)
(#/willChangeValueForKey: owner objc-key))
(dolist (lpw owner-lpws)
(when *log-bindings*
(ns-log-format "#/willChangeValueForKey: ~s ~s" lpw objc-key))
(#/willChangeValueForKey: lpw objc-key))))
(defmethod did-change-value-for-key (owner key)
;; called from a lisp object to tell us that a value changed.
;; We find the lisp-ptr-wrapper instances that have been used to access
;; the owner via the specified key and call the appropriate
;; method to lets KVC know what is going on.
;; Could also be called for a :kvo lisp slot in an objective-c instance.
;; If so, call the didChange... method for this instance.
(when *log-bindings*
(ns-log-format "Did change ~s for ~s" key owner))
(let ((owner-lpws (assoc-aref kvc-observed owner key))
(objc-key (lisp-to-temp-nsstring (if (stringp key)
key
(lisp-to-objc-keypathname key)))))
(if (typep owner 'ns:ns-object)
(#/didChangeValueForKey: owner objc-key))
(dolist (lpw owner-lpws)
(when *log-bindings*
(ns-log-format "#/didChangeValueForKey: ~s ~s" lpw objc-key))
(#/didChangeValueForKey: lpw objc-key))))
(defun kvc-observed ()
kvc-observed)
)
(defmacro objc-method-for (meth-name lisp-meth)
(let ((meth-sym (gentemp))
(lisp-fun (gentemp)))
`(let ((,meth-sym (intern (symbol-name ,meth-name) (find-package :nextstep-functions)))
(,lisp-fun ,lisp-meth))
(eval `(objc:defmethod (,,meth-sym :id)
((self ns:ns-object))
;; ns:ns-object is always passed, never a null pointer, but if a null object
;; needs to be passed it will encoded as a lisp-point-wrapper pointinG to nil.
;; So lisp functions must always be prepared to get nil as an argument.
;; Return value is always a wrapper so that when converted back to lisp we
;; get what was intended.
(wrapper-for (funcall ,,lisp-fun (coerce-obj self t))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Methods to support binding to Lisp slots and value translation between bound objects
(let ((key-returns (make-hash-table :test #'equal)))
;; key-returns tells us whether the value for a given key should be returned as a lisp-ptr-wrapper
;; or an Objective-C value converted from the the lisp value retrieved using the key. The legal
;; hash values are :path and :convert
(defun set-key-return (key-str role)
(setf (gethash key-str key-returns) role))
(defun key-return (key-str)
(gethash key-str key-returns nil))
)
(let ((path-trans (make-instance 'assoc-array :rank 2 :tests '(eql equal))))
(defun objc-to-lisp-keypathname (name-str)
;; translate a name from Objective-C to Lisp
;; Use standard translation for function/slot names except the use of
;; underscore (#\_) is used initially to delimit a package specifier
(let* ((package-end (if (char= (elt name-str 0) #\_)
(position #\_ name-str :start 1)))
(pkg-string (string-upcase (subseq name-str 1 package-end)))
(path-string (if package-end
(subseq name-str (1+ package-end))
name-str))
(pkg (or (and package-end
(find-package pkg-string))
(find-package :cl-user))))
;; cache the string we are translating so that we can reverse
;; translate to exactly the same string used by the developer.
(setf (assoc-aref path-trans pkg path-string) name-str)
(ccl::compute-lisp-name path-string pkg)))
(defun lisp-to-objc-keypathname (name)
;; translate name (symbol or string or function) from Lisp to Objective-C
;; If we previously cached a string that came from Objective-C and
;; was translated to this name, then translate back to it. This
;; prevents problems caused by alternative package names/nicknames
;; that the developer might have used in Interface Builder.
;; Use standard translation for function/slot names except prefix
;; package name and underscore if package is not cl-user
(if (functionp name)
(find-or-make-func-keypath name)
(let ((pkg (if (symbolp name)
(symbol-package name)
(find-package :cl-user)))
(name-str (string name))
(name-segments nil))
(or (assoc-aref path-trans pkg name-str)
(progn
(do* ((start 0 (1+ pos))
(pos (position #\- name-str)
(position #\- name-str :start start)))
((null pos) (setf name-segments (nreverse (cons (subseq name-str start) name-segments))))
(setf name-segments (cons (subseq name-str start pos) name-segments)))
(setf name-segments (cons (string-downcase (first name-segments))
(mapcar #'string-capitalize (rest name-segments))))
(unless (eq pkg (find-package :cl-user))
(setf name-segments (cons (concatenate 'string
"_"
(lisp-to-objc-keypathname (or (first (package-nicknames pkg))
(package-name pkg)))
"_")
name-segments)))
(apply #'concatenate 'string name-segments))))))
(defun find-or-make-func-keypath (lisp-func)
;; find a previously made symbol corresponding to the lisp object if it exists, or create one
;; Cache so we can easity translate in both directions.
;; Create an objc method that converts an objc argument to lisp, applies the method, and
;; converts it back to objc. This lets lisp functions be used as intermediate path elements
;; for bindings.
(or (assoc-aref path-trans lisp-func nil)
(let* ((sym-package (find-package :cl-user))
(sym (gentemp "Trans" sym-package))
(sym-name (symbol-name sym)))
(setf (assoc-aref path-trans sym-package sym-name) lisp-func)
(setf (assoc-aref path-trans lisp-func nil) sym-name)
(objc-method-for sym lisp-func)
sym-name)))
(defun func-for-keypath (keypath)
;; find the function represented by the keypath if it exists
(let ((func (assoc-aref path-trans (find-package :cl-user) keypath)))
(when (functionp func) func)))
(defun convert-path-element (pe)
(cond ((stringp pe)
pe)
((functionp pe)
(find-or-make-func-keypath pe))))
(defun convert-path-list (key-path)
;; key-path ::= <path-object> | ( <path-object>* )
;; path-object ::= <path-string> | <lisp-accessor-function>
;; path-string ::= "<path-elt-string>{.<path-string>}*
;; path-elt-string ::= any legal string for Objective-C keypaths
(let ((path-strs (if (listp key-path)
(mapcar #'convert-path-element key-path)
(list (convert-path-element key-path)))))
(dolist (ps (butlast path-strs))
(set-key-return ps :path))
(set-key-return (first (last path-strs)) :convert)
(lisp-to-temp-nsstring (format nil "~{~a~^.~}" path-strs))))
)
(provide :path-trans)
| true |
;; path-trans.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.
|#
(eval-when (:compile-toplevel :load-toplevel :execute)
(require :iu-classes)
(require :nslog-utils)
(require :ns-string-utils)
(require :assoc-array))
(in-package :iu)
;; debugging facility
;; Used primarily in binding-utils.lisp, which is dependent on this file
(defvar *log-bindings* nil)
(defun log-bindings (&optional (on-off t))
(setf *log-bindings* on-off))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; lisp-ptr-wrapper
;;;
;;; This is a class that encapsulates a pointer to a lisp object so we can pass this
;;; off to an Objective-C view and know what it points to when we get it back later.
;;; Added the ability to handle bindings.
#|
(defclass lisp-ptr-wrapper (ns:ns-object)
((lpw-lisp-ptr :accessor lpw-lisp-ptr)
(lpw-controller :accessor lpw-controller)
(lpw-depth :accessor lpw-depth)
(lpw-parent :accessor lpw-parent))
(:metaclass ns:+ns-object))
|#
(objc:defmethod (#/copyWithZone: :id)
((self lisp-ptr-wrapper) (zone (* #>NSZone)))
(when *log-bindings*
(ns-log-format "Copying wrapper for ~s" (lpw-lisp-ptr self)))
self)
(let ((kvc-observed (make-instance 'assoc-array :rank 2 :tests (list #'eql #'equal)))
(obj-wrappers (make-instance 'assoc-array :rank 2)))
;; this assoc-array keeps track of paths that are being observed and the
;; corresponding lisp-ptr-wrapper object that is ostensibly being observed.
(defun make-ptr-wrapper (ptr &key (depth 1) (parent nil) (controller nil))
(when *log-bindings*
(ns-log-format "Making wrapper for ~s" ptr))
(let ((lpw (make-instance 'lisp-ptr-wrapper)))
(setf (lpw-lisp-ptr lpw) ptr)
(setf (lpw-depth lpw) depth)
(setf (lpw-parent lpw) parent)
(setf (lpw-controller lpw) controller)
(setf (assoc-aref obj-wrappers controller ptr) lpw)
lpw))
(defmethod wrapper-for (lisp-obj &key (controller nil) (depth 0) (parent nil))
(or (assoc-aref obj-wrappers controller lisp-obj)
(setf (assoc-aref obj-wrappers controller lisp-obj)
(make-ptr-wrapper lisp-obj
:depth depth
:parent parent
:controller controller))))
(defmethod note-kvc-observed ((self lisp-ptr-wrapper) lisp-obj path)
(when *log-bindings*
(ns-log-format "Observing ~s for ~s" path lisp-obj))
(pushnew self (assoc-aref kvc-observed lisp-obj path)))
(defmethod will-change-value-for-key (owner key)
;; called from a lisp object to tell us that a value will be changed.
;; We find the lisp-ptr-wrapper instances that have been used to access
;; the owner via the specified key and call the appropriate
;; method to let KVC know what is going on.
;; Could also be called for a :kvo lisp slot in an objective-c instance
;; and if so we should call the willChange... method for this instance.
(when *log-bindings*
(ns-log-format "Will change ~s for ~s" key owner))
(let ((owner-lpws (assoc-aref kvc-observed owner key))
(objc-key (lisp-to-temp-nsstring (if (stringp key)
key
(lisp-to-objc-keypathname key)))))
(if (typep owner 'ns:ns-object)
(#/willChangeValueForKey: owner objc-key))
(dolist (lpw owner-lpws)
(when *log-bindings*
(ns-log-format "#/willChangeValueForKey: ~s ~s" lpw objc-key))
(#/willChangeValueForKey: lpw objc-key))))
(defmethod did-change-value-for-key (owner key)
;; called from a lisp object to tell us that a value changed.
;; We find the lisp-ptr-wrapper instances that have been used to access
;; the owner via the specified key and call the appropriate
;; method to lets KVC know what is going on.
;; Could also be called for a :kvo lisp slot in an objective-c instance.
;; If so, call the didChange... method for this instance.
(when *log-bindings*
(ns-log-format "Did change ~s for ~s" key owner))
(let ((owner-lpws (assoc-aref kvc-observed owner key))
(objc-key (lisp-to-temp-nsstring (if (stringp key)
key
(lisp-to-objc-keypathname key)))))
(if (typep owner 'ns:ns-object)
(#/didChangeValueForKey: owner objc-key))
(dolist (lpw owner-lpws)
(when *log-bindings*
(ns-log-format "#/didChangeValueForKey: ~s ~s" lpw objc-key))
(#/didChangeValueForKey: lpw objc-key))))
(defun kvc-observed ()
kvc-observed)
)
(defmacro objc-method-for (meth-name lisp-meth)
(let ((meth-sym (gentemp))
(lisp-fun (gentemp)))
`(let ((,meth-sym (intern (symbol-name ,meth-name) (find-package :nextstep-functions)))
(,lisp-fun ,lisp-meth))
(eval `(objc:defmethod (,,meth-sym :id)
((self ns:ns-object))
;; ns:ns-object is always passed, never a null pointer, but if a null object
;; needs to be passed it will encoded as a lisp-point-wrapper pointinG to nil.
;; So lisp functions must always be prepared to get nil as an argument.
;; Return value is always a wrapper so that when converted back to lisp we
;; get what was intended.
(wrapper-for (funcall ,,lisp-fun (coerce-obj self t))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Methods to support binding to Lisp slots and value translation between bound objects
(let ((key-returns (make-hash-table :test #'equal)))
;; key-returns tells us whether the value for a given key should be returned as a lisp-ptr-wrapper
;; or an Objective-C value converted from the the lisp value retrieved using the key. The legal
;; hash values are :path and :convert
(defun set-key-return (key-str role)
(setf (gethash key-str key-returns) role))
(defun key-return (key-str)
(gethash key-str key-returns nil))
)
(let ((path-trans (make-instance 'assoc-array :rank 2 :tests '(eql equal))))
(defun objc-to-lisp-keypathname (name-str)
;; translate a name from Objective-C to Lisp
;; Use standard translation for function/slot names except the use of
;; underscore (#\_) is used initially to delimit a package specifier
(let* ((package-end (if (char= (elt name-str 0) #\_)
(position #\_ name-str :start 1)))
(pkg-string (string-upcase (subseq name-str 1 package-end)))
(path-string (if package-end
(subseq name-str (1+ package-end))
name-str))
(pkg (or (and package-end
(find-package pkg-string))
(find-package :cl-user))))
;; cache the string we are translating so that we can reverse
;; translate to exactly the same string used by the developer.
(setf (assoc-aref path-trans pkg path-string) name-str)
(ccl::compute-lisp-name path-string pkg)))
(defun lisp-to-objc-keypathname (name)
;; translate name (symbol or string or function) from Lisp to Objective-C
;; If we previously cached a string that came from Objective-C and
;; was translated to this name, then translate back to it. This
;; prevents problems caused by alternative package names/nicknames
;; that the developer might have used in Interface Builder.
;; Use standard translation for function/slot names except prefix
;; package name and underscore if package is not cl-user
(if (functionp name)
(find-or-make-func-keypath name)
(let ((pkg (if (symbolp name)
(symbol-package name)
(find-package :cl-user)))
(name-str (string name))
(name-segments nil))
(or (assoc-aref path-trans pkg name-str)
(progn
(do* ((start 0 (1+ pos))
(pos (position #\- name-str)
(position #\- name-str :start start)))
((null pos) (setf name-segments (nreverse (cons (subseq name-str start) name-segments))))
(setf name-segments (cons (subseq name-str start pos) name-segments)))
(setf name-segments (cons (string-downcase (first name-segments))
(mapcar #'string-capitalize (rest name-segments))))
(unless (eq pkg (find-package :cl-user))
(setf name-segments (cons (concatenate 'string
"_"
(lisp-to-objc-keypathname (or (first (package-nicknames pkg))
(package-name pkg)))
"_")
name-segments)))
(apply #'concatenate 'string name-segments))))))
(defun find-or-make-func-keypath (lisp-func)
;; find a previously made symbol corresponding to the lisp object if it exists, or create one
;; Cache so we can easity translate in both directions.
;; Create an objc method that converts an objc argument to lisp, applies the method, and
;; converts it back to objc. This lets lisp functions be used as intermediate path elements
;; for bindings.
(or (assoc-aref path-trans lisp-func nil)
(let* ((sym-package (find-package :cl-user))
(sym (gentemp "Trans" sym-package))
(sym-name (symbol-name sym)))
(setf (assoc-aref path-trans sym-package sym-name) lisp-func)
(setf (assoc-aref path-trans lisp-func nil) sym-name)
(objc-method-for sym lisp-func)
sym-name)))
(defun func-for-keypath (keypath)
;; find the function represented by the keypath if it exists
(let ((func (assoc-aref path-trans (find-package :cl-user) keypath)))
(when (functionp func) func)))
(defun convert-path-element (pe)
(cond ((stringp pe)
pe)
((functionp pe)
(find-or-make-func-keypath pe))))
(defun convert-path-list (key-path)
;; key-path ::= <path-object> | ( <path-object>* )
;; path-object ::= <path-string> | <lisp-accessor-function>
;; path-string ::= "<path-elt-string>{.<path-string>}*
;; path-elt-string ::= any legal string for Objective-C keypaths
(let ((path-strs (if (listp key-path)
(mapcar #'convert-path-element key-path)
(list (convert-path-element key-path)))))
(dolist (ps (butlast path-strs))
(set-key-return ps :path))
(set-key-return (first (last path-strs)) :convert)
(lisp-to-temp-nsstring (format nil "~{~a~^.~}" path-strs))))
)
(provide :path-trans)
|
[
{
"context": "escribe\n :prefix \"make-like - copyright (C) 2021 Anthony Green <[email protected]>\"\n :suffix \"Distributed u",
"end": 1797,
"score": 0.9998709559440613,
"start": 1784,
"tag": "NAME",
"value": "Anthony Green"
},
{
"context": "ix \"make-like - copyright (C) 2021 Anthony Green <[email protected]>\"\n :suffix \"Distributed under the terms of MIT ",
"end": 1819,
"score": 0.9999247789382935,
"start": 1799,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "e \"fixme\")\n (author \"Fix Me <[email protected]>\")\n ",
"end": 2512,
"score": 0.4947263300418854,
"start": 2510,
"tag": "USERNAME",
"value": "Me"
},
{
"context": "xme\")\n (author \"Fix Me <[email protected]>\")\n (description \"FIXME",
"end": 2531,
"score": 0.9999160766601562,
"start": 2514,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
make-like.lisp
|
atgreen/make-like
| 10 |
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: MAKE-LIKE; Base: 10 -*-"
;;; -----------------------------------------------------------------------
;;; make-like
;;;
;;; 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 #:make-like)
(defvar *template*
(with-open-file (stream "template.tar.gz" :element-type '(unsigned-byte 8))
(let ((seq (make-array (file-length stream) :element-type '(unsigned-byte 8))))
(read-sequence seq stream)
seq)))
(opts:define-opts
(:name :help
:description "print this help text"
:short #\h
:long "help"))
(defun usage ()
(opts:describe
:prefix "make-like - copyright (C) 2021 Anthony Green <[email protected]>"
:suffix "Distributed under the terms of MIT License. See the source code for details."
:usage-of "make-like"
:args "likefile"))
(defun unknown-option (condition)
(format t "warning: ~s option is unknown!~%" (opts:option condition))
(invoke-restart 'opts:skip-option))
(defmacro when-option ((options opt) &body body)
`(let ((it (getf ,options ,opt)))
(when it
,@body)))
(defun fatal-error (&rest format-string-and-parameters)
(format t "Error: ~A~%"
(apply #'format (cons nil format-string-and-parameters)))
(finish-output)
(sb-ext:exit :abort t))
(defun make-application (&key (app-name "fixme")
(author "Fix Me <[email protected]>")
(description "FIXME")
(source-header ";;; FIXME source-header")
(github-account "fixme-github-account")
(container-registry "quay.io/fixme"))
(when (fad:directory-exists-p app-name)
(fatal-error "Directory '~A' already exists" app-name))
(let ((app-dir (pathname (str:concat app-name "/"))))
(fad:delete-directory-and-files "_template" :if-does-not-exist :IGNORE)
(archive::extract-files-from-archive
(archive:open-archive 'archive:tar-archive
(chipz:make-decompressing-stream 'chipz:gzip
(flexi-streams:make-in-memory-input-stream *template*))
:direction :input))
(rename-file "_template" app-name)
(uiop:with-current-directory (app-dir)
(cl-fad:walk-directory
#p"." (lambda (filepath)
(let* ((template-filename (namestring filepath))
(filename (subseq template-filename 0 (- (length template-filename) 4)))
(template (alexandria:read-file-into-string filepath)))
(with-open-file (stream filename
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(princ (funcall (cl-template:compile-template template)
(list :app-name app-name
:author author
:description description
:source-header source-header
:github-account github-account
:container-registry container-registry))
stream)))
(delete-file filepath))
:follow-symlinks nil
:test (lambda (filename)
(str:ends-with? ".clt" (file-namestring filename))))
(rename-file "src/app.asd" (str:concat app-name ".asd"))
(rename-file "src/app.lisp" (str:concat app-name ".lisp")))))
(defun main (args)
(multiple-value-bind (options free-args)
(handler-case
(handler-bind ((opts:unknown-option #'unknown-option))
(opts:get-opts))
(opts:missing-arg (condition)
(format t "fatal: option ~s needs an argument!~%"
(opts:option condition)))
(opts:arg-parser-failed (condition)
(format t "fatal: cannot parse ~s as argument of ~s~%"
(opts:raw-arg condition)
(opts:option condition))))
(when-option (options :help)
(usage)
(sb-ext:exit))
(let ((num-args (length free-args)))
(if (eq 0 num-args)
(if (probe-file "likefile")
(load "likefile")
(fatal-error "No file specified, and no likefile"))
(if (eq 1 (length free-args))
(load (car free-args))
(usage))))))
|
50721
|
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: MAKE-LIKE; Base: 10 -*-"
;;; -----------------------------------------------------------------------
;;; make-like
;;;
;;; 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 #:make-like)
(defvar *template*
(with-open-file (stream "template.tar.gz" :element-type '(unsigned-byte 8))
(let ((seq (make-array (file-length stream) :element-type '(unsigned-byte 8))))
(read-sequence seq stream)
seq)))
(opts:define-opts
(:name :help
:description "print this help text"
:short #\h
:long "help"))
(defun usage ()
(opts:describe
:prefix "make-like - copyright (C) 2021 <NAME> <<EMAIL>>"
:suffix "Distributed under the terms of MIT License. See the source code for details."
:usage-of "make-like"
:args "likefile"))
(defun unknown-option (condition)
(format t "warning: ~s option is unknown!~%" (opts:option condition))
(invoke-restart 'opts:skip-option))
(defmacro when-option ((options opt) &body body)
`(let ((it (getf ,options ,opt)))
(when it
,@body)))
(defun fatal-error (&rest format-string-and-parameters)
(format t "Error: ~A~%"
(apply #'format (cons nil format-string-and-parameters)))
(finish-output)
(sb-ext:exit :abort t))
(defun make-application (&key (app-name "fixme")
(author "Fix Me <<EMAIL>>")
(description "FIXME")
(source-header ";;; FIXME source-header")
(github-account "fixme-github-account")
(container-registry "quay.io/fixme"))
(when (fad:directory-exists-p app-name)
(fatal-error "Directory '~A' already exists" app-name))
(let ((app-dir (pathname (str:concat app-name "/"))))
(fad:delete-directory-and-files "_template" :if-does-not-exist :IGNORE)
(archive::extract-files-from-archive
(archive:open-archive 'archive:tar-archive
(chipz:make-decompressing-stream 'chipz:gzip
(flexi-streams:make-in-memory-input-stream *template*))
:direction :input))
(rename-file "_template" app-name)
(uiop:with-current-directory (app-dir)
(cl-fad:walk-directory
#p"." (lambda (filepath)
(let* ((template-filename (namestring filepath))
(filename (subseq template-filename 0 (- (length template-filename) 4)))
(template (alexandria:read-file-into-string filepath)))
(with-open-file (stream filename
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(princ (funcall (cl-template:compile-template template)
(list :app-name app-name
:author author
:description description
:source-header source-header
:github-account github-account
:container-registry container-registry))
stream)))
(delete-file filepath))
:follow-symlinks nil
:test (lambda (filename)
(str:ends-with? ".clt" (file-namestring filename))))
(rename-file "src/app.asd" (str:concat app-name ".asd"))
(rename-file "src/app.lisp" (str:concat app-name ".lisp")))))
(defun main (args)
(multiple-value-bind (options free-args)
(handler-case
(handler-bind ((opts:unknown-option #'unknown-option))
(opts:get-opts))
(opts:missing-arg (condition)
(format t "fatal: option ~s needs an argument!~%"
(opts:option condition)))
(opts:arg-parser-failed (condition)
(format t "fatal: cannot parse ~s as argument of ~s~%"
(opts:raw-arg condition)
(opts:option condition))))
(when-option (options :help)
(usage)
(sb-ext:exit))
(let ((num-args (length free-args)))
(if (eq 0 num-args)
(if (probe-file "likefile")
(load "likefile")
(fatal-error "No file specified, and no likefile"))
(if (eq 1 (length free-args))
(load (car free-args))
(usage))))))
| true |
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: MAKE-LIKE; Base: 10 -*-"
;;; -----------------------------------------------------------------------
;;; make-like
;;;
;;; 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 #:make-like)
(defvar *template*
(with-open-file (stream "template.tar.gz" :element-type '(unsigned-byte 8))
(let ((seq (make-array (file-length stream) :element-type '(unsigned-byte 8))))
(read-sequence seq stream)
seq)))
(opts:define-opts
(:name :help
:description "print this help text"
:short #\h
:long "help"))
(defun usage ()
(opts:describe
:prefix "make-like - copyright (C) 2021 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:suffix "Distributed under the terms of MIT License. See the source code for details."
:usage-of "make-like"
:args "likefile"))
(defun unknown-option (condition)
(format t "warning: ~s option is unknown!~%" (opts:option condition))
(invoke-restart 'opts:skip-option))
(defmacro when-option ((options opt) &body body)
`(let ((it (getf ,options ,opt)))
(when it
,@body)))
(defun fatal-error (&rest format-string-and-parameters)
(format t "Error: ~A~%"
(apply #'format (cons nil format-string-and-parameters)))
(finish-output)
(sb-ext:exit :abort t))
(defun make-application (&key (app-name "fixme")
(author "Fix Me <PI:EMAIL:<EMAIL>END_PI>")
(description "FIXME")
(source-header ";;; FIXME source-header")
(github-account "fixme-github-account")
(container-registry "quay.io/fixme"))
(when (fad:directory-exists-p app-name)
(fatal-error "Directory '~A' already exists" app-name))
(let ((app-dir (pathname (str:concat app-name "/"))))
(fad:delete-directory-and-files "_template" :if-does-not-exist :IGNORE)
(archive::extract-files-from-archive
(archive:open-archive 'archive:tar-archive
(chipz:make-decompressing-stream 'chipz:gzip
(flexi-streams:make-in-memory-input-stream *template*))
:direction :input))
(rename-file "_template" app-name)
(uiop:with-current-directory (app-dir)
(cl-fad:walk-directory
#p"." (lambda (filepath)
(let* ((template-filename (namestring filepath))
(filename (subseq template-filename 0 (- (length template-filename) 4)))
(template (alexandria:read-file-into-string filepath)))
(with-open-file (stream filename
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(princ (funcall (cl-template:compile-template template)
(list :app-name app-name
:author author
:description description
:source-header source-header
:github-account github-account
:container-registry container-registry))
stream)))
(delete-file filepath))
:follow-symlinks nil
:test (lambda (filename)
(str:ends-with? ".clt" (file-namestring filename))))
(rename-file "src/app.asd" (str:concat app-name ".asd"))
(rename-file "src/app.lisp" (str:concat app-name ".lisp")))))
(defun main (args)
(multiple-value-bind (options free-args)
(handler-case
(handler-bind ((opts:unknown-option #'unknown-option))
(opts:get-opts))
(opts:missing-arg (condition)
(format t "fatal: option ~s needs an argument!~%"
(opts:option condition)))
(opts:arg-parser-failed (condition)
(format t "fatal: cannot parse ~s as argument of ~s~%"
(opts:raw-arg condition)
(opts:option condition))))
(when-option (options :help)
(usage)
(sb-ext:exit))
(let ((num-args (length free-args)))
(if (eq 0 num-args)
(if (probe-file "likefile")
(load "likefile")
(fatal-error "No file specified, and no likefile"))
(if (eq 1 (length free-args))
(load (car free-args))
(usage))))))
|
[
{
"context": "rt of trial\n (c) 2016 Shirakumo http://tymoon.eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n",
"end": 89,
"score": 0.9999178647994995,
"start": 71,
"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": 114,
"score": 0.9998920559883118,
"start": 100,
"tag": "NAME",
"value": "Nicolas Hafner"
},
{
"context": ".eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(in-package #:org.shirakumo.fraf.trial)\n\n(de",
"end": 134,
"score": 0.9999228715896606,
"start": 116,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
display.lisp
|
pupcraft/trial
| 0 |
#|
This file is a part of trial
(c) 2016 Shirakumo http://tymoon.eu ([email protected])
Author: Nicolas Hafner <[email protected]>
|#
(in-package #:org.shirakumo.fraf.trial)
(defclass display (renderable)
((context :initarg :context :accessor context)
(clear-color :initarg :clear-color :accessor clear-color))
(:default-initargs
:clear-color (vec 0.2 0.3 0.3)))
(defmethod initialize-instance :after ((display display) &rest initargs &key context title width height version profile double-buffering stereo-buffer vsync)
(declare (ignore title width height version profile double-buffering stereo-buffer vsync))
(unless context
(let ((args (loop for (k v) on initargs by #'cddr
for keep = (find k '(:title :width :height :version :profile :double-buffering :stereo-buffer :vsync))
when keep collect k when keep collect v)))
(setf context (setf (context display) (apply #'make-context NIL args)))))
(setf (handler context) display)
(add-gamepad-handler display)
(with-context ((context display))
(setup-rendering display)))
(defmethod finalize :after ((display display))
(remove-gamepad-handler display)
(finalize (context display)))
(defmethod handle (event (display display)))
(defmethod setup-rendering ((display display))
(reset-matrix (model-matrix))
(reset-matrix (view-matrix))
(reset-matrix (projection-matrix))
(reset-attributes (attribute-table))
(gl:stencil-mask #xFF)
(gl:clear-stencil #x00)
(gl:stencil-op :keep :keep :keep)
(gl:depth-mask T)
(gl:depth-func :lequal)
(gl:blend-func :src-alpha :one-minus-src-alpha)
(gl:clear-depth 1.0)
(gl:front-face :ccw)
(gl:cull-face :back)
(gl:hint :line-smooth-hint :nicest)
(enable :blend :multisample :cull-face :line-smooth :depth-test :depth-clamp))
(defmethod paint (source (target display)))
(defmethod render (source (target display))
(paint source target))
(defmethod render :around (source (target display))
;; Potentially release context every time to allow
;; other threads to grab it.
(let ((context (context target)))
(with-context (context :reentrant T)
(gl:viewport 0 0 (width context) (height context))
(let ((c (clear-color target)))
(gl:clear-color (vx c) (vy c) (vz c) (if (vec4-p c) (vw c) 0.0)))
(gl:clear :color-buffer :depth-buffer :stencil-buffer)
(call-next-method)
(swap-buffers context))))
(defmethod width ((display display))
(width (context display)))
(defmethod height ((display display))
(height (context display)))
|
35589
|
#|
This file is a part of trial
(c) 2016 Shirakumo http://tymoon.eu (<EMAIL>)
Author: <NAME> <<EMAIL>>
|#
(in-package #:org.shirakumo.fraf.trial)
(defclass display (renderable)
((context :initarg :context :accessor context)
(clear-color :initarg :clear-color :accessor clear-color))
(:default-initargs
:clear-color (vec 0.2 0.3 0.3)))
(defmethod initialize-instance :after ((display display) &rest initargs &key context title width height version profile double-buffering stereo-buffer vsync)
(declare (ignore title width height version profile double-buffering stereo-buffer vsync))
(unless context
(let ((args (loop for (k v) on initargs by #'cddr
for keep = (find k '(:title :width :height :version :profile :double-buffering :stereo-buffer :vsync))
when keep collect k when keep collect v)))
(setf context (setf (context display) (apply #'make-context NIL args)))))
(setf (handler context) display)
(add-gamepad-handler display)
(with-context ((context display))
(setup-rendering display)))
(defmethod finalize :after ((display display))
(remove-gamepad-handler display)
(finalize (context display)))
(defmethod handle (event (display display)))
(defmethod setup-rendering ((display display))
(reset-matrix (model-matrix))
(reset-matrix (view-matrix))
(reset-matrix (projection-matrix))
(reset-attributes (attribute-table))
(gl:stencil-mask #xFF)
(gl:clear-stencil #x00)
(gl:stencil-op :keep :keep :keep)
(gl:depth-mask T)
(gl:depth-func :lequal)
(gl:blend-func :src-alpha :one-minus-src-alpha)
(gl:clear-depth 1.0)
(gl:front-face :ccw)
(gl:cull-face :back)
(gl:hint :line-smooth-hint :nicest)
(enable :blend :multisample :cull-face :line-smooth :depth-test :depth-clamp))
(defmethod paint (source (target display)))
(defmethod render (source (target display))
(paint source target))
(defmethod render :around (source (target display))
;; Potentially release context every time to allow
;; other threads to grab it.
(let ((context (context target)))
(with-context (context :reentrant T)
(gl:viewport 0 0 (width context) (height context))
(let ((c (clear-color target)))
(gl:clear-color (vx c) (vy c) (vz c) (if (vec4-p c) (vw c) 0.0)))
(gl:clear :color-buffer :depth-buffer :stencil-buffer)
(call-next-method)
(swap-buffers context))))
(defmethod width ((display display))
(width (context display)))
(defmethod height ((display display))
(height (context display)))
| true |
#|
This file is a part of trial
(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.trial)
(defclass display (renderable)
((context :initarg :context :accessor context)
(clear-color :initarg :clear-color :accessor clear-color))
(:default-initargs
:clear-color (vec 0.2 0.3 0.3)))
(defmethod initialize-instance :after ((display display) &rest initargs &key context title width height version profile double-buffering stereo-buffer vsync)
(declare (ignore title width height version profile double-buffering stereo-buffer vsync))
(unless context
(let ((args (loop for (k v) on initargs by #'cddr
for keep = (find k '(:title :width :height :version :profile :double-buffering :stereo-buffer :vsync))
when keep collect k when keep collect v)))
(setf context (setf (context display) (apply #'make-context NIL args)))))
(setf (handler context) display)
(add-gamepad-handler display)
(with-context ((context display))
(setup-rendering display)))
(defmethod finalize :after ((display display))
(remove-gamepad-handler display)
(finalize (context display)))
(defmethod handle (event (display display)))
(defmethod setup-rendering ((display display))
(reset-matrix (model-matrix))
(reset-matrix (view-matrix))
(reset-matrix (projection-matrix))
(reset-attributes (attribute-table))
(gl:stencil-mask #xFF)
(gl:clear-stencil #x00)
(gl:stencil-op :keep :keep :keep)
(gl:depth-mask T)
(gl:depth-func :lequal)
(gl:blend-func :src-alpha :one-minus-src-alpha)
(gl:clear-depth 1.0)
(gl:front-face :ccw)
(gl:cull-face :back)
(gl:hint :line-smooth-hint :nicest)
(enable :blend :multisample :cull-face :line-smooth :depth-test :depth-clamp))
(defmethod paint (source (target display)))
(defmethod render (source (target display))
(paint source target))
(defmethod render :around (source (target display))
;; Potentially release context every time to allow
;; other threads to grab it.
(let ((context (context target)))
(with-context (context :reentrant T)
(gl:viewport 0 0 (width context) (height context))
(let ((c (clear-color target)))
(gl:clear-color (vx c) (vy c) (vz c) (if (vec4-p c) (vw c) 0.0)))
(gl:clear :color-buffer :depth-buffer :stencil-buffer)
(call-next-method)
(swap-buffers context))))
(defmethod width ((display display))
(width (context display)))
(defmethod height ((display display))
(height (context display)))
|
[
{
"context": "Header$\n\n $Log$\n\n Boxer\n Copyright 1985-2022 Andrea A. diSessa and the Estate of Edward H. Lay\n\n Portions of ",
"end": 133,
"score": 0.9998781681060791,
"start": 116,
"tag": "NAME",
"value": "Andrea A. diSessa"
},
{
"context": "ight 1985-2022 Andrea A. diSessa and the Estate of Edward H. Lay\n\n Portions of this code may be copyright 1982-",
"end": 165,
"score": 0.9933308362960815,
"start": 152,
"tag": "NAME",
"value": "Edward H. Lay"
}
] |
src/primitives/build.lisp
|
cben/boxer-sunrise
| 0 |
;;-*- Mode:Lisp; Syntax: Common-Lisp; package: Boxer; -*-
#|
$Header$
$Log$
Boxer
Copyright 1985-2022 Andrea A. diSessa and the Estate of Edward H. Lay
Portions of this code may be copyright 1982-1985 Massachusetts Institute of Technology. Those portions may be
used for any purpose, including commercial ones, providing that notice of MIT copyright is retained.
Licensed under the 3-Clause BSD license. You may not use this file except in compliance with this license.
https://opensource.org/licenses/BSD-3-Clause
+-Data--+
This file is part of the | BOXER | system
+-------+
This file contains BUILD and its supporting functions
Modification History (most recent at top)
4/21/03 merged current LW and MCL files, no diffs, updated copyright
|#
(in-package :boxer)
#|
The theory for build is that we cache a function on the editor box
which is the build template. A Fast implementation of BUILD is basically
centered around minimizing the amount of the template hierarchy that
needs to be walked in order to find imbedded EVAL's and UNBOX's. We
walk the template once (per modification) and generate a function that will
produce the correct output.
;;; For Example:
BUILD [ foo [] bar
[ @wowie literal
more stuff]
the last row ]
would generate the function:
There are several parts to this file.
o stack manipulation macros.
For now, we use a separate set. At some point in the future,
we may want to use the boxer stack primitives. We avoid it
for now so that lossage is localized and also until we have
a chance to think through the ramifications of having non
boxer objects pushed onto the boxer stack (especially if a
boxer error is signalled). Note: multiprocessing = Future
o A parser. This basically the same as the old build implementation
except that it parses into postfix notation and refers to subprimitives
which understand the stack convention
o Build Sub Primitives
o A code generator which takes the output of the parser and makes
a "compiled" build object
o Code which understands how to run a "compiled" build object.
|#
;;;; Compiled Build Objects
(defstruct (compiled-build-object (:include compiled-boxer-object)
(:conc-name cbo-)
(:constructor %make-compiled-build-object))
(forms nil)
(eval-list nil))
(defsubst cbo-code (x) (compiled-boxer-object-code x))
(defsubst cbo-args (x) (compiled-boxer-object-args x))
;;;; Formal Arg Objects
(defvar *build-function-arg-counter* 0)
(defvar *build-function-args* nil)
(defvar *build-function-values* nil)
(defmacro with-build-function-arg-collection (&body body)
`(let ((*build-function-arg-counter* 0)
(*build-function-args* nil)
(*build-function-values* nil))
(values (progn . ,body)
(nreverse *build-function-args*)
(let ((flattened-forms nil))
(dolist (value-form *build-function-values*)
(if (null (cdr value-form))
(push (car value-form) flattened-forms)
(dolist (value (nreverse value-form))
(push value flattened-forms))))
flattened-forms))))
(defstruct (build-function-arg (:predicate build-function-arg?))
(argpos 0))
(defstruct (build-fun+args (:predicate build-fun+args?)
(:print-function %print-build-fun+args)
(:constructor %make-build-fun+args))
(function nil)
(args nil))
(defun %print-build-fun+args (o s &optional depth)
(declare (ignore depth))
(format s "#< ~A ~A >"
(build-fun+args-function o) (build-fun+args-args o)))
(defun make-build-fun+args (fun &rest args)
(%make-build-fun+args :function fun :args args))
(defun new-build-arg ()
(let ((newarg (make-build-function-arg :argpos
*build-function-arg-counter*)))
(incf *build-function-arg-counter*)
newarg))
(defun get-build-arg (value-form)
(let ((prev-ref (position value-form *build-function-values* :test #'equal)))
(cond ((null prev-ref)
(let ((new (new-build-arg)))
(push new *build-function-args*)
(push value-form *build-function-values*)
new))
(t (nth prev-ref *build-function-args*)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; For BUILD
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun make-build-function-object (template)
(multiple-value-bind (parsed-template internal-arglist forms-to-be-evaled)
(walk-box-for-build template)
(let* ((codevec (allocate-storage-vector 32))
(pretty-arglist (mapcar #'(lambda (x)(declare (ignore x)) (gensym))
internal-arglist))
(object (%make-compiled-build-object
:code codevec
:args pretty-arglist
:forms forms-to-be-evaled)))
(generate-code parsed-template codevec (length internal-arglist))
(unless (null internal-arglist)
(setf (cbo-eval-list object)
(list*
(boxer-eval::make-compiled-boxer-function
:arglist pretty-arglist
:precedence 0
:infix-p nil
:object object)
forms-to-be-evaled)))
object)))
(defun execute-compiled-build-function (cbf)
(cond ((null (cbo-args cbf))
(funcall-0-arg-compiled-boxer-function cbf))
(t
(boxer-eval::recursive-eval-setup-append (cbo-eval-list cbf)))))
;;;; Build support
(defvar *interpolate-empty-rows-too?* t)
;;; The actual instructions and subprimitives that build uses
(define-instruction (interpolate-rows 33) ()
(let ((box (cbos-pop)))
(flet ((handle-rows (rows &optional port-to? (superior box))
(if *interpolate-empty-rows-too?*
(mapcan #'(lambda (row)
(let ((entries (evrow-pointers row)))
(if (null entries)
(list nil)
(list (mapcar
#'(lambda (x)
(if port-to?
(port-to-item
x (or superior (vp-target box)) t)
(get-pointer-value x box)))
entries)))))
rows)
(mapcan #'(lambda (row)
(let ((entries (evrow-pointers row)))
(if (null entries)
nil
(list (mapcar
#'(lambda (x)
(if port-to?
(port-to-item
x (or superior (vp-target box)) t)
(get-pointer-value x box)))
entries)))))
rows))))
(cbos-push
(cond ((numberp box)
(list (list box)))
((virtual-copy? box)
(handle-rows (vc-rows box)))
((virtual-port? box)
(multiple-value-bind (rows inlinks? new? vc-rows-entry)
(get-box-rows (get-port-target box))
(declare (ignore inlinks? new?))
(handle-rows rows t vc-rows-entry)))
(t (error "Don't know how to Unbox a ~S" box)))))))
;; gather the row-items by popping the stack n times...
(defun collect-n-list-from-stack (n)
(let ((list-items nil))
(dotimes (i n list-items)
(setq list-items (nconc list-items (list (cbos-pop)))))))
#|
(defun collect-n-list-from-stack (n)
(let ((list-items nil))
(dotimes (i n (nreverse list-items))
(push (cbos-pop) list-items))))
|#
(define-instruction (interpolate-n-unbox-results 34) (n)
(let ((row-items (collect-n-list-from-stack n))
(extra-rows-items nil)
(items nil))
(flet ((handle-extra-rows (x-rows)
(do* ((idx 0 (1+ idx))
(rows x-rows (cdr rows))
(row (car rows) (car rows)))
((null rows))
(cond ((>= idx (length extra-rows-items))
;; this must be the first case of an
;; extra row this deep
(setq extra-rows-items
(nconc extra-rows-items (list row))))
(t
;; there must already be some row items from
;; a previous unbox
(setf (nth idx extra-rows-items)
(nconc (nth idx extra-rows-items) row)))))))
(dolist (item row-items)
(cond ((listp item)
(setq items (nconc items (car item)))
(unless (null (cdr item))
;; are there extra rows ?
(handle-extra-rows (cdr item))))
(t ;; justa' vanilla item
(setq items (nconc items (list item))))))
(cbos-push
(cond ((null extra-rows-items)
;; don't make empty rows -- just return nil.
(if (null items)
nil
(make-evrow-from-entries items)))
(t (cons (make-evrow-from-entries items)
(mapcar #'make-evrow-from-entries extra-rows-items))))))))
(defun pname-from-value (value)
(when (or (symbolp value) (numberp value))
(let ((string (format nil "~A" value)))
(make-formatting-info :chas string :start 0 :stop (length string)))))
(define-instruction (stack-chunk 35) ()
(let ((lfp (cbos-pop)) (value (cbos-pop)) (rfp (cbos-pop)))
(cbos-push (make-chunk lfp (pname-from-value value) value rfp))))
;; because coallescing of token may fail (e.g. when one token turns
;; out to be a box), a value MAY be a list of several other values
(define-instruction (evrow-from-n-entries 36) (n)
(let ((ptrs nil))
(dotimes (i n)
(let ((value (cbos-pop)))
(setq ptrs (nconc ptrs (if (consp value)
(mapcar #'make-pointer value)
(list (make-pointer value)))))))
(cbos-push (make-evrow-from-pointers ptrs))))
(define-instruction (stack-virtual-copy 37) ()
(cbos-push (virtual-copy (cbos-pop) :top-level? (cbos-pop))))
;;; same as make-vc except that any lists encountered are assumed to be
;;; lists of evrows generated by the unbox handler and are flattened out.
;;; Also, removes NIL "rows," but always makes at least one row.
;;; Remember that (listp nil) is true.
(define-instruction (vc-for-build 38) (n-rows type name closet-p)
(let* ((rows (collect-n-list-from-stack n-rows))
(closet (when closet-p (prog1 (car rows) (setq rows (cdr rows)))))
(vc (if (every #'(lambda (x) (not (listp x))) rows)
(make-vc rows type name)
(let ((new-rows nil))
(dolist (row rows)
(unless (null row)
(if (consp row)
(setq new-rows (nconc (nreverse row) new-rows))
(push row new-rows))))
(make-vc (if (null new-rows)
(list (make-empty-evrow))
(nreverse new-rows))
type name)))))
(unless (null closet)
(setf (vc-closets vc) closet) (setf (vc-progenitor vc) :new))
(cbos-push vc)))
;; same as vc-for-build except that it expects the name to be on
;; the stack instead of in the arglist
(define-instruction (named-vc-for-build 39) (n-rows type closet-p)
(let* ((name (intern-in-bu-package
(string-upcase (box-text-string (cbos-pop)))))
(rows (collect-n-list-from-stack n-rows))
(closet (when closet-p (prog1 (car rows) (setq rows (cdr rows)))))
(vc (if (every #'(lambda (x) (not (listp x))) rows)
(make-vc rows type name)
(let ((new-rows nil))
(dolist (row rows)
(unless (null row)
(if (consp row)
(setq new-rows (nconc (nreverse row) new-rows))
(push row new-rows))))
(make-vc (if (null new-rows)
(list (make-empty-evrow))
(nreverse new-rows))
type name)))))
(unless (null closet)
(setf (vc-closets vc) closet) (setf (vc-progenitor vc) :new))
(cbos-push vc)))
;; named ports, name from stack, target as immediate arg
(define-instruction (named-port-for-build 40) (target)
(cbos-push (make-virtual-port :name (intern-in-bu-package
(string-upcase
(box-text-string (cbos-pop))))
:target target)))
;;;; Parsing a template
;;; these return 2 values: the result of the walk and a flag indicating
;;; whether or not imbedded atsigns or excls were encountered
;;; A row-form can have two possible representations: In the simple case
;;; when there are no unbox's, then a row form will be somthing like...
;;; (make-evrow-from-pointers (list <thing> <box-form> <thing> ...))
(defun canonicalize-prop-for-eval (prop)
(ecase prop
(bu::eval-it 'bu::run)
(bu::@ 'bu::@)))
(defvar *eval-props-that-build-handles* '(bu::eval-it bu::@))
(defun build-eval-prop? (eval-prop)
(fast-memq eval-prop *eval-props-that-build-handles*))
(defun walk-evrow-for-build (evrow sup-box ct)
(let ((row-args nil)
(constant-p t)
(unmatched-ev-prop nil)
(unbox-in-row? nil))
(labels ((unify-ev-props (existing-props new-props)
(append existing-props new-props))
(expand-ev-props-into-code (props value chunk)
(cond ((null props)
(error
"Why are you trying to expand ev-props when there arent any"))
((eq (car props) 'bu::eval-it)
(setq constant-p nil)
(get-build-arg
(list (if (null (cdr props))
(coerce-object-for-evaluator value)
(handle-eval-props (cdr props) value)))))
((eq (car props) 'bu::@)
(setq constant-p nil unbox-in-row? t)
`(,(get-build-arg
(list (if (null (cdr props))
(coerce-object-for-evaluator value)
(handle-eval-props (cdr props) value))))
interpolate-rows))
(t chunk)))
(pointer-handler (ptr)
(let* ((raw-chunk (get-pointer-value ptr sup-box))
(chunk-p (chunk-p raw-chunk))
(value (if chunk-p
(chunk-chunk raw-chunk)
raw-chunk))
(ev-props (when chunk-p
(getf (chunk-plist raw-chunk)
':eval-prop))))
(flet ((value-handler ()
;; returns either literal values or code to
;; produce a value
(cond ((or (numberp value) (symbolp value))
raw-chunk)
((or (virtual-port? value) (port-box? value))
(multiple-value-bind (form port-constant-p)
(walk-build-port value raw-chunk)
(when (and constant-p
(null port-constant-p))
(setq constant-p port-constant-p))
(cond ((or (null chunk-p) port-constant-p)
form)
(t
`(,(chunk-right-format raw-chunk)
,form
,(chunk-left-format raw-chunk)
stack-chunk)))))
((or (virtual-copy? value) (box? value))
(multiple-value-bind (bf box-constant-p)
(walk-build-box-internal value ct t)
(when (and constant-p
(null box-constant-p))
(setq constant-p box-constant-p))
(cond ((null chunk-p)
bf)
(t
`(,(chunk-right-format
raw-chunk)
,bf
,(chunk-left-format raw-chunk)
stack-chunk)))))
(t
(error "Don't know what to do with ~S"
value)))))
(cond ((and (null value)
(not (null ev-props)))
;; this should really unify with
;; what's already there
(setq unmatched-ev-prop
(unify-ev-props unmatched-ev-prop
ev-props))
':ev-props-only)
((and (null ev-props) (null unmatched-ev-prop))
(value-handler))
;; still need to put in code to preserve the
;; formatting info when merging results of run
;; time expressions
((null ev-props)
(let ((code (expand-ev-props-into-code
unmatched-ev-prop
value raw-chunk)))
(setq unmatched-ev-prop nil)
code))
(t
;; must be a chunk with ev-props in it
(let ((code (expand-ev-props-into-code
(unify-ev-props
unmatched-ev-prop
ev-props) value raw-chunk)))
(setq unmatched-ev-prop nil)
code)))))))
(dolist (pointer (evrow-pointers evrow))
(let ((ptr-val (pointer-handler pointer)))
(unless (eq ptr-val ':ev-props-only)
(push ptr-val row-args))))
(cond ((not (null constant-p))
(values (let ((l (length row-args)))
(append row-args
(list (make-build-fun+args
'evrow-from-n-entries l))))
t))
((null unbox-in-row?)
(values (let ((l (length row-args)))
(append row-args
(list (make-build-fun+args
'evrow-from-n-entries l))))
nil))
;; must be an unbox in the row
(t
(values (let ((l (length row-args)))
(append row-args
(list (make-build-fun+args
'interpolate-n-unbox-results l))))
nil))))))
;;; hack preservation of names here...
(defun walk-build-box-internal (box &optional creation-time top-level?)
(declare (values box-form constant-p))
(let ((row-forms nil)
(constant-p t)
(closet-p nil)
(ct (or creation-time
(and (virtual-copy? box) (vc-creation-time box)))))
(let ((closet (if (virtual-copy? box)
(vc-closets box)
(slot-value box 'closets))))
(unless (null closet)
(setq closet-p t)
(unless (evrow? closet) (setq closet (make-evrow-from-row closet)))
(multiple-value-bind (closet-form closet-constant-p)
(walk-evrow-for-build closet box ct)
(setq constant-p closet-constant-p)
(push closet-form row-forms))))
(dolist (row (get-box-rows box creation-time))
(multiple-value-bind (row-form row-constant-p)
(walk-evrow-for-build row box ct)
(push row-form row-forms)
(when (and constant-p
(null row-constant-p))
(setq constant-p row-constant-p))))
(let ((l (length row-forms))
(box-type (if (virtual-copy? box)
(vc-type box)
(class-name (class-of box))))
(box-name (if (virtual-copy? box)
(vc-name box)
(editor-box-name-symbol box))))
(cond ((char= (char (symbol-name box-name) 0) #\@)
;; should check to see if the rest of the symbol
;; is valid (no more ev prop chars)
(values
(append row-forms
(list (get-build-arg
(list (intern-in-bu-package
(subseq (symbol-name box-name)
(1+ (position #\@ (symbol-name
box-name)
:test #'char=))))))
(make-build-fun+args 'named-vc-for-build
l box-type closet-p)))
nil))
((null constant-p)
(values
(append row-forms
(list (make-build-fun+args 'vc-for-build l
box-type box-name closet-p)))
constant-p))
(t
(values (if (null top-level?)
`(nil ,box stack-virtual-copy)
`(T ,box stack-virtual-copy))
t))))))
(defun walk-build-port (port raw-chunk)
(let ((name (if (virtual-port? port)
(vp-name port)
(editor-box-name-symbol port))))
(cond ((char= (char (symbol-name name) 0) #\@)
(values
(list (get-build-arg
(list
(intern-in-bu-package
(subseq (symbol-name name)
(1+ (position #\@ (symbol-name name)
:test #'char=))))))
(make-build-fun+args 'named-port-for-build
(if (virtual-port? port)
(vp-target port)
(ports port))))
nil))
(t (values raw-chunk t)))))
;;; this is the top level function to call
(defun walk-box-for-build (box)
(declare (values template-function-body
template-function-arglist
forms-to-be-evaled))
(with-build-function-arg-collection
(walk-build-box-internal box nil t)))
;;;; The top level interface...
;;; Caching compiled-build-objects onto editor structure
;;; the build cache needs to be immediately flushed on modified
;;; rather than waiting for the eval to finish (see the modified
;;; function in editor.lisp)
(defun get-cached-build-function (box)
(getprop box 'cached-build-function))
(defun put-cached-build-function (box fun)
(setf (build-template? box) t) ; once a template always a template ?
(putprop box fun 'cached-build-function))
(defun decache-build-function (box)
(when (getprop box 'cached-build-function)
(putprop box nil 'cached-build-function)))
(defun build (template)
(setq template (box-or-port-target template))
(let* ((edbox (cond ((data-box? template) template)
((fast-eval-data-box? template)
(vc-progenitor template))))
(cached-function (unless (null edbox)
(get-cached-build-function edbox))))
(cond ((not (null cached-function))
(execute-compiled-build-function cached-function))
(t
(let ((new-fun (make-build-function-object template)))
(unless (or (null edbox)
(not (editor-box-cacheable?
edbox
(or (and (virtual-copy? template)
(vc-creation-time template))
(now)))))
(put-cached-build-function edbox new-fun))
(execute-compiled-build-function new-fun))))))
;;;; and into Boxer we go.....
(boxer-eval::defboxer-primitive bu::build (template)
(if (numberp template) template (build template)))
|
43966
|
;;-*- Mode:Lisp; Syntax: Common-Lisp; package: Boxer; -*-
#|
$Header$
$Log$
Boxer
Copyright 1985-2022 <NAME> and the Estate of <NAME>
Portions of this code may be copyright 1982-1985 Massachusetts Institute of Technology. Those portions may be
used for any purpose, including commercial ones, providing that notice of MIT copyright is retained.
Licensed under the 3-Clause BSD license. You may not use this file except in compliance with this license.
https://opensource.org/licenses/BSD-3-Clause
+-Data--+
This file is part of the | BOXER | system
+-------+
This file contains BUILD and its supporting functions
Modification History (most recent at top)
4/21/03 merged current LW and MCL files, no diffs, updated copyright
|#
(in-package :boxer)
#|
The theory for build is that we cache a function on the editor box
which is the build template. A Fast implementation of BUILD is basically
centered around minimizing the amount of the template hierarchy that
needs to be walked in order to find imbedded EVAL's and UNBOX's. We
walk the template once (per modification) and generate a function that will
produce the correct output.
;;; For Example:
BUILD [ foo [] bar
[ @wowie literal
more stuff]
the last row ]
would generate the function:
There are several parts to this file.
o stack manipulation macros.
For now, we use a separate set. At some point in the future,
we may want to use the boxer stack primitives. We avoid it
for now so that lossage is localized and also until we have
a chance to think through the ramifications of having non
boxer objects pushed onto the boxer stack (especially if a
boxer error is signalled). Note: multiprocessing = Future
o A parser. This basically the same as the old build implementation
except that it parses into postfix notation and refers to subprimitives
which understand the stack convention
o Build Sub Primitives
o A code generator which takes the output of the parser and makes
a "compiled" build object
o Code which understands how to run a "compiled" build object.
|#
;;;; Compiled Build Objects
(defstruct (compiled-build-object (:include compiled-boxer-object)
(:conc-name cbo-)
(:constructor %make-compiled-build-object))
(forms nil)
(eval-list nil))
(defsubst cbo-code (x) (compiled-boxer-object-code x))
(defsubst cbo-args (x) (compiled-boxer-object-args x))
;;;; Formal Arg Objects
(defvar *build-function-arg-counter* 0)
(defvar *build-function-args* nil)
(defvar *build-function-values* nil)
(defmacro with-build-function-arg-collection (&body body)
`(let ((*build-function-arg-counter* 0)
(*build-function-args* nil)
(*build-function-values* nil))
(values (progn . ,body)
(nreverse *build-function-args*)
(let ((flattened-forms nil))
(dolist (value-form *build-function-values*)
(if (null (cdr value-form))
(push (car value-form) flattened-forms)
(dolist (value (nreverse value-form))
(push value flattened-forms))))
flattened-forms))))
(defstruct (build-function-arg (:predicate build-function-arg?))
(argpos 0))
(defstruct (build-fun+args (:predicate build-fun+args?)
(:print-function %print-build-fun+args)
(:constructor %make-build-fun+args))
(function nil)
(args nil))
(defun %print-build-fun+args (o s &optional depth)
(declare (ignore depth))
(format s "#< ~A ~A >"
(build-fun+args-function o) (build-fun+args-args o)))
(defun make-build-fun+args (fun &rest args)
(%make-build-fun+args :function fun :args args))
(defun new-build-arg ()
(let ((newarg (make-build-function-arg :argpos
*build-function-arg-counter*)))
(incf *build-function-arg-counter*)
newarg))
(defun get-build-arg (value-form)
(let ((prev-ref (position value-form *build-function-values* :test #'equal)))
(cond ((null prev-ref)
(let ((new (new-build-arg)))
(push new *build-function-args*)
(push value-form *build-function-values*)
new))
(t (nth prev-ref *build-function-args*)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; For BUILD
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun make-build-function-object (template)
(multiple-value-bind (parsed-template internal-arglist forms-to-be-evaled)
(walk-box-for-build template)
(let* ((codevec (allocate-storage-vector 32))
(pretty-arglist (mapcar #'(lambda (x)(declare (ignore x)) (gensym))
internal-arglist))
(object (%make-compiled-build-object
:code codevec
:args pretty-arglist
:forms forms-to-be-evaled)))
(generate-code parsed-template codevec (length internal-arglist))
(unless (null internal-arglist)
(setf (cbo-eval-list object)
(list*
(boxer-eval::make-compiled-boxer-function
:arglist pretty-arglist
:precedence 0
:infix-p nil
:object object)
forms-to-be-evaled)))
object)))
(defun execute-compiled-build-function (cbf)
(cond ((null (cbo-args cbf))
(funcall-0-arg-compiled-boxer-function cbf))
(t
(boxer-eval::recursive-eval-setup-append (cbo-eval-list cbf)))))
;;;; Build support
(defvar *interpolate-empty-rows-too?* t)
;;; The actual instructions and subprimitives that build uses
(define-instruction (interpolate-rows 33) ()
(let ((box (cbos-pop)))
(flet ((handle-rows (rows &optional port-to? (superior box))
(if *interpolate-empty-rows-too?*
(mapcan #'(lambda (row)
(let ((entries (evrow-pointers row)))
(if (null entries)
(list nil)
(list (mapcar
#'(lambda (x)
(if port-to?
(port-to-item
x (or superior (vp-target box)) t)
(get-pointer-value x box)))
entries)))))
rows)
(mapcan #'(lambda (row)
(let ((entries (evrow-pointers row)))
(if (null entries)
nil
(list (mapcar
#'(lambda (x)
(if port-to?
(port-to-item
x (or superior (vp-target box)) t)
(get-pointer-value x box)))
entries)))))
rows))))
(cbos-push
(cond ((numberp box)
(list (list box)))
((virtual-copy? box)
(handle-rows (vc-rows box)))
((virtual-port? box)
(multiple-value-bind (rows inlinks? new? vc-rows-entry)
(get-box-rows (get-port-target box))
(declare (ignore inlinks? new?))
(handle-rows rows t vc-rows-entry)))
(t (error "Don't know how to Unbox a ~S" box)))))))
;; gather the row-items by popping the stack n times...
(defun collect-n-list-from-stack (n)
(let ((list-items nil))
(dotimes (i n list-items)
(setq list-items (nconc list-items (list (cbos-pop)))))))
#|
(defun collect-n-list-from-stack (n)
(let ((list-items nil))
(dotimes (i n (nreverse list-items))
(push (cbos-pop) list-items))))
|#
(define-instruction (interpolate-n-unbox-results 34) (n)
(let ((row-items (collect-n-list-from-stack n))
(extra-rows-items nil)
(items nil))
(flet ((handle-extra-rows (x-rows)
(do* ((idx 0 (1+ idx))
(rows x-rows (cdr rows))
(row (car rows) (car rows)))
((null rows))
(cond ((>= idx (length extra-rows-items))
;; this must be the first case of an
;; extra row this deep
(setq extra-rows-items
(nconc extra-rows-items (list row))))
(t
;; there must already be some row items from
;; a previous unbox
(setf (nth idx extra-rows-items)
(nconc (nth idx extra-rows-items) row)))))))
(dolist (item row-items)
(cond ((listp item)
(setq items (nconc items (car item)))
(unless (null (cdr item))
;; are there extra rows ?
(handle-extra-rows (cdr item))))
(t ;; justa' vanilla item
(setq items (nconc items (list item))))))
(cbos-push
(cond ((null extra-rows-items)
;; don't make empty rows -- just return nil.
(if (null items)
nil
(make-evrow-from-entries items)))
(t (cons (make-evrow-from-entries items)
(mapcar #'make-evrow-from-entries extra-rows-items))))))))
(defun pname-from-value (value)
(when (or (symbolp value) (numberp value))
(let ((string (format nil "~A" value)))
(make-formatting-info :chas string :start 0 :stop (length string)))))
(define-instruction (stack-chunk 35) ()
(let ((lfp (cbos-pop)) (value (cbos-pop)) (rfp (cbos-pop)))
(cbos-push (make-chunk lfp (pname-from-value value) value rfp))))
;; because coallescing of token may fail (e.g. when one token turns
;; out to be a box), a value MAY be a list of several other values
(define-instruction (evrow-from-n-entries 36) (n)
(let ((ptrs nil))
(dotimes (i n)
(let ((value (cbos-pop)))
(setq ptrs (nconc ptrs (if (consp value)
(mapcar #'make-pointer value)
(list (make-pointer value)))))))
(cbos-push (make-evrow-from-pointers ptrs))))
(define-instruction (stack-virtual-copy 37) ()
(cbos-push (virtual-copy (cbos-pop) :top-level? (cbos-pop))))
;;; same as make-vc except that any lists encountered are assumed to be
;;; lists of evrows generated by the unbox handler and are flattened out.
;;; Also, removes NIL "rows," but always makes at least one row.
;;; Remember that (listp nil) is true.
(define-instruction (vc-for-build 38) (n-rows type name closet-p)
(let* ((rows (collect-n-list-from-stack n-rows))
(closet (when closet-p (prog1 (car rows) (setq rows (cdr rows)))))
(vc (if (every #'(lambda (x) (not (listp x))) rows)
(make-vc rows type name)
(let ((new-rows nil))
(dolist (row rows)
(unless (null row)
(if (consp row)
(setq new-rows (nconc (nreverse row) new-rows))
(push row new-rows))))
(make-vc (if (null new-rows)
(list (make-empty-evrow))
(nreverse new-rows))
type name)))))
(unless (null closet)
(setf (vc-closets vc) closet) (setf (vc-progenitor vc) :new))
(cbos-push vc)))
;; same as vc-for-build except that it expects the name to be on
;; the stack instead of in the arglist
(define-instruction (named-vc-for-build 39) (n-rows type closet-p)
(let* ((name (intern-in-bu-package
(string-upcase (box-text-string (cbos-pop)))))
(rows (collect-n-list-from-stack n-rows))
(closet (when closet-p (prog1 (car rows) (setq rows (cdr rows)))))
(vc (if (every #'(lambda (x) (not (listp x))) rows)
(make-vc rows type name)
(let ((new-rows nil))
(dolist (row rows)
(unless (null row)
(if (consp row)
(setq new-rows (nconc (nreverse row) new-rows))
(push row new-rows))))
(make-vc (if (null new-rows)
(list (make-empty-evrow))
(nreverse new-rows))
type name)))))
(unless (null closet)
(setf (vc-closets vc) closet) (setf (vc-progenitor vc) :new))
(cbos-push vc)))
;; named ports, name from stack, target as immediate arg
(define-instruction (named-port-for-build 40) (target)
(cbos-push (make-virtual-port :name (intern-in-bu-package
(string-upcase
(box-text-string (cbos-pop))))
:target target)))
;;;; Parsing a template
;;; these return 2 values: the result of the walk and a flag indicating
;;; whether or not imbedded atsigns or excls were encountered
;;; A row-form can have two possible representations: In the simple case
;;; when there are no unbox's, then a row form will be somthing like...
;;; (make-evrow-from-pointers (list <thing> <box-form> <thing> ...))
(defun canonicalize-prop-for-eval (prop)
(ecase prop
(bu::eval-it 'bu::run)
(bu::@ 'bu::@)))
(defvar *eval-props-that-build-handles* '(bu::eval-it bu::@))
(defun build-eval-prop? (eval-prop)
(fast-memq eval-prop *eval-props-that-build-handles*))
(defun walk-evrow-for-build (evrow sup-box ct)
(let ((row-args nil)
(constant-p t)
(unmatched-ev-prop nil)
(unbox-in-row? nil))
(labels ((unify-ev-props (existing-props new-props)
(append existing-props new-props))
(expand-ev-props-into-code (props value chunk)
(cond ((null props)
(error
"Why are you trying to expand ev-props when there arent any"))
((eq (car props) 'bu::eval-it)
(setq constant-p nil)
(get-build-arg
(list (if (null (cdr props))
(coerce-object-for-evaluator value)
(handle-eval-props (cdr props) value)))))
((eq (car props) 'bu::@)
(setq constant-p nil unbox-in-row? t)
`(,(get-build-arg
(list (if (null (cdr props))
(coerce-object-for-evaluator value)
(handle-eval-props (cdr props) value))))
interpolate-rows))
(t chunk)))
(pointer-handler (ptr)
(let* ((raw-chunk (get-pointer-value ptr sup-box))
(chunk-p (chunk-p raw-chunk))
(value (if chunk-p
(chunk-chunk raw-chunk)
raw-chunk))
(ev-props (when chunk-p
(getf (chunk-plist raw-chunk)
':eval-prop))))
(flet ((value-handler ()
;; returns either literal values or code to
;; produce a value
(cond ((or (numberp value) (symbolp value))
raw-chunk)
((or (virtual-port? value) (port-box? value))
(multiple-value-bind (form port-constant-p)
(walk-build-port value raw-chunk)
(when (and constant-p
(null port-constant-p))
(setq constant-p port-constant-p))
(cond ((or (null chunk-p) port-constant-p)
form)
(t
`(,(chunk-right-format raw-chunk)
,form
,(chunk-left-format raw-chunk)
stack-chunk)))))
((or (virtual-copy? value) (box? value))
(multiple-value-bind (bf box-constant-p)
(walk-build-box-internal value ct t)
(when (and constant-p
(null box-constant-p))
(setq constant-p box-constant-p))
(cond ((null chunk-p)
bf)
(t
`(,(chunk-right-format
raw-chunk)
,bf
,(chunk-left-format raw-chunk)
stack-chunk)))))
(t
(error "Don't know what to do with ~S"
value)))))
(cond ((and (null value)
(not (null ev-props)))
;; this should really unify with
;; what's already there
(setq unmatched-ev-prop
(unify-ev-props unmatched-ev-prop
ev-props))
':ev-props-only)
((and (null ev-props) (null unmatched-ev-prop))
(value-handler))
;; still need to put in code to preserve the
;; formatting info when merging results of run
;; time expressions
((null ev-props)
(let ((code (expand-ev-props-into-code
unmatched-ev-prop
value raw-chunk)))
(setq unmatched-ev-prop nil)
code))
(t
;; must be a chunk with ev-props in it
(let ((code (expand-ev-props-into-code
(unify-ev-props
unmatched-ev-prop
ev-props) value raw-chunk)))
(setq unmatched-ev-prop nil)
code)))))))
(dolist (pointer (evrow-pointers evrow))
(let ((ptr-val (pointer-handler pointer)))
(unless (eq ptr-val ':ev-props-only)
(push ptr-val row-args))))
(cond ((not (null constant-p))
(values (let ((l (length row-args)))
(append row-args
(list (make-build-fun+args
'evrow-from-n-entries l))))
t))
((null unbox-in-row?)
(values (let ((l (length row-args)))
(append row-args
(list (make-build-fun+args
'evrow-from-n-entries l))))
nil))
;; must be an unbox in the row
(t
(values (let ((l (length row-args)))
(append row-args
(list (make-build-fun+args
'interpolate-n-unbox-results l))))
nil))))))
;;; hack preservation of names here...
(defun walk-build-box-internal (box &optional creation-time top-level?)
(declare (values box-form constant-p))
(let ((row-forms nil)
(constant-p t)
(closet-p nil)
(ct (or creation-time
(and (virtual-copy? box) (vc-creation-time box)))))
(let ((closet (if (virtual-copy? box)
(vc-closets box)
(slot-value box 'closets))))
(unless (null closet)
(setq closet-p t)
(unless (evrow? closet) (setq closet (make-evrow-from-row closet)))
(multiple-value-bind (closet-form closet-constant-p)
(walk-evrow-for-build closet box ct)
(setq constant-p closet-constant-p)
(push closet-form row-forms))))
(dolist (row (get-box-rows box creation-time))
(multiple-value-bind (row-form row-constant-p)
(walk-evrow-for-build row box ct)
(push row-form row-forms)
(when (and constant-p
(null row-constant-p))
(setq constant-p row-constant-p))))
(let ((l (length row-forms))
(box-type (if (virtual-copy? box)
(vc-type box)
(class-name (class-of box))))
(box-name (if (virtual-copy? box)
(vc-name box)
(editor-box-name-symbol box))))
(cond ((char= (char (symbol-name box-name) 0) #\@)
;; should check to see if the rest of the symbol
;; is valid (no more ev prop chars)
(values
(append row-forms
(list (get-build-arg
(list (intern-in-bu-package
(subseq (symbol-name box-name)
(1+ (position #\@ (symbol-name
box-name)
:test #'char=))))))
(make-build-fun+args 'named-vc-for-build
l box-type closet-p)))
nil))
((null constant-p)
(values
(append row-forms
(list (make-build-fun+args 'vc-for-build l
box-type box-name closet-p)))
constant-p))
(t
(values (if (null top-level?)
`(nil ,box stack-virtual-copy)
`(T ,box stack-virtual-copy))
t))))))
(defun walk-build-port (port raw-chunk)
(let ((name (if (virtual-port? port)
(vp-name port)
(editor-box-name-symbol port))))
(cond ((char= (char (symbol-name name) 0) #\@)
(values
(list (get-build-arg
(list
(intern-in-bu-package
(subseq (symbol-name name)
(1+ (position #\@ (symbol-name name)
:test #'char=))))))
(make-build-fun+args 'named-port-for-build
(if (virtual-port? port)
(vp-target port)
(ports port))))
nil))
(t (values raw-chunk t)))))
;;; this is the top level function to call
(defun walk-box-for-build (box)
(declare (values template-function-body
template-function-arglist
forms-to-be-evaled))
(with-build-function-arg-collection
(walk-build-box-internal box nil t)))
;;;; The top level interface...
;;; Caching compiled-build-objects onto editor structure
;;; the build cache needs to be immediately flushed on modified
;;; rather than waiting for the eval to finish (see the modified
;;; function in editor.lisp)
(defun get-cached-build-function (box)
(getprop box 'cached-build-function))
(defun put-cached-build-function (box fun)
(setf (build-template? box) t) ; once a template always a template ?
(putprop box fun 'cached-build-function))
(defun decache-build-function (box)
(when (getprop box 'cached-build-function)
(putprop box nil 'cached-build-function)))
(defun build (template)
(setq template (box-or-port-target template))
(let* ((edbox (cond ((data-box? template) template)
((fast-eval-data-box? template)
(vc-progenitor template))))
(cached-function (unless (null edbox)
(get-cached-build-function edbox))))
(cond ((not (null cached-function))
(execute-compiled-build-function cached-function))
(t
(let ((new-fun (make-build-function-object template)))
(unless (or (null edbox)
(not (editor-box-cacheable?
edbox
(or (and (virtual-copy? template)
(vc-creation-time template))
(now)))))
(put-cached-build-function edbox new-fun))
(execute-compiled-build-function new-fun))))))
;;;; and into Boxer we go.....
(boxer-eval::defboxer-primitive bu::build (template)
(if (numberp template) template (build template)))
| true |
;;-*- Mode:Lisp; Syntax: Common-Lisp; package: Boxer; -*-
#|
$Header$
$Log$
Boxer
Copyright 1985-2022 PI:NAME:<NAME>END_PI and the Estate of PI:NAME:<NAME>END_PI
Portions of this code may be copyright 1982-1985 Massachusetts Institute of Technology. Those portions may be
used for any purpose, including commercial ones, providing that notice of MIT copyright is retained.
Licensed under the 3-Clause BSD license. You may not use this file except in compliance with this license.
https://opensource.org/licenses/BSD-3-Clause
+-Data--+
This file is part of the | BOXER | system
+-------+
This file contains BUILD and its supporting functions
Modification History (most recent at top)
4/21/03 merged current LW and MCL files, no diffs, updated copyright
|#
(in-package :boxer)
#|
The theory for build is that we cache a function on the editor box
which is the build template. A Fast implementation of BUILD is basically
centered around minimizing the amount of the template hierarchy that
needs to be walked in order to find imbedded EVAL's and UNBOX's. We
walk the template once (per modification) and generate a function that will
produce the correct output.
;;; For Example:
BUILD [ foo [] bar
[ @wowie literal
more stuff]
the last row ]
would generate the function:
There are several parts to this file.
o stack manipulation macros.
For now, we use a separate set. At some point in the future,
we may want to use the boxer stack primitives. We avoid it
for now so that lossage is localized and also until we have
a chance to think through the ramifications of having non
boxer objects pushed onto the boxer stack (especially if a
boxer error is signalled). Note: multiprocessing = Future
o A parser. This basically the same as the old build implementation
except that it parses into postfix notation and refers to subprimitives
which understand the stack convention
o Build Sub Primitives
o A code generator which takes the output of the parser and makes
a "compiled" build object
o Code which understands how to run a "compiled" build object.
|#
;;;; Compiled Build Objects
(defstruct (compiled-build-object (:include compiled-boxer-object)
(:conc-name cbo-)
(:constructor %make-compiled-build-object))
(forms nil)
(eval-list nil))
(defsubst cbo-code (x) (compiled-boxer-object-code x))
(defsubst cbo-args (x) (compiled-boxer-object-args x))
;;;; Formal Arg Objects
(defvar *build-function-arg-counter* 0)
(defvar *build-function-args* nil)
(defvar *build-function-values* nil)
(defmacro with-build-function-arg-collection (&body body)
`(let ((*build-function-arg-counter* 0)
(*build-function-args* nil)
(*build-function-values* nil))
(values (progn . ,body)
(nreverse *build-function-args*)
(let ((flattened-forms nil))
(dolist (value-form *build-function-values*)
(if (null (cdr value-form))
(push (car value-form) flattened-forms)
(dolist (value (nreverse value-form))
(push value flattened-forms))))
flattened-forms))))
(defstruct (build-function-arg (:predicate build-function-arg?))
(argpos 0))
(defstruct (build-fun+args (:predicate build-fun+args?)
(:print-function %print-build-fun+args)
(:constructor %make-build-fun+args))
(function nil)
(args nil))
(defun %print-build-fun+args (o s &optional depth)
(declare (ignore depth))
(format s "#< ~A ~A >"
(build-fun+args-function o) (build-fun+args-args o)))
(defun make-build-fun+args (fun &rest args)
(%make-build-fun+args :function fun :args args))
(defun new-build-arg ()
(let ((newarg (make-build-function-arg :argpos
*build-function-arg-counter*)))
(incf *build-function-arg-counter*)
newarg))
(defun get-build-arg (value-form)
(let ((prev-ref (position value-form *build-function-values* :test #'equal)))
(cond ((null prev-ref)
(let ((new (new-build-arg)))
(push new *build-function-args*)
(push value-form *build-function-values*)
new))
(t (nth prev-ref *build-function-args*)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; For BUILD
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun make-build-function-object (template)
(multiple-value-bind (parsed-template internal-arglist forms-to-be-evaled)
(walk-box-for-build template)
(let* ((codevec (allocate-storage-vector 32))
(pretty-arglist (mapcar #'(lambda (x)(declare (ignore x)) (gensym))
internal-arglist))
(object (%make-compiled-build-object
:code codevec
:args pretty-arglist
:forms forms-to-be-evaled)))
(generate-code parsed-template codevec (length internal-arglist))
(unless (null internal-arglist)
(setf (cbo-eval-list object)
(list*
(boxer-eval::make-compiled-boxer-function
:arglist pretty-arglist
:precedence 0
:infix-p nil
:object object)
forms-to-be-evaled)))
object)))
(defun execute-compiled-build-function (cbf)
(cond ((null (cbo-args cbf))
(funcall-0-arg-compiled-boxer-function cbf))
(t
(boxer-eval::recursive-eval-setup-append (cbo-eval-list cbf)))))
;;;; Build support
(defvar *interpolate-empty-rows-too?* t)
;;; The actual instructions and subprimitives that build uses
(define-instruction (interpolate-rows 33) ()
(let ((box (cbos-pop)))
(flet ((handle-rows (rows &optional port-to? (superior box))
(if *interpolate-empty-rows-too?*
(mapcan #'(lambda (row)
(let ((entries (evrow-pointers row)))
(if (null entries)
(list nil)
(list (mapcar
#'(lambda (x)
(if port-to?
(port-to-item
x (or superior (vp-target box)) t)
(get-pointer-value x box)))
entries)))))
rows)
(mapcan #'(lambda (row)
(let ((entries (evrow-pointers row)))
(if (null entries)
nil
(list (mapcar
#'(lambda (x)
(if port-to?
(port-to-item
x (or superior (vp-target box)) t)
(get-pointer-value x box)))
entries)))))
rows))))
(cbos-push
(cond ((numberp box)
(list (list box)))
((virtual-copy? box)
(handle-rows (vc-rows box)))
((virtual-port? box)
(multiple-value-bind (rows inlinks? new? vc-rows-entry)
(get-box-rows (get-port-target box))
(declare (ignore inlinks? new?))
(handle-rows rows t vc-rows-entry)))
(t (error "Don't know how to Unbox a ~S" box)))))))
;; gather the row-items by popping the stack n times...
(defun collect-n-list-from-stack (n)
(let ((list-items nil))
(dotimes (i n list-items)
(setq list-items (nconc list-items (list (cbos-pop)))))))
#|
(defun collect-n-list-from-stack (n)
(let ((list-items nil))
(dotimes (i n (nreverse list-items))
(push (cbos-pop) list-items))))
|#
(define-instruction (interpolate-n-unbox-results 34) (n)
(let ((row-items (collect-n-list-from-stack n))
(extra-rows-items nil)
(items nil))
(flet ((handle-extra-rows (x-rows)
(do* ((idx 0 (1+ idx))
(rows x-rows (cdr rows))
(row (car rows) (car rows)))
((null rows))
(cond ((>= idx (length extra-rows-items))
;; this must be the first case of an
;; extra row this deep
(setq extra-rows-items
(nconc extra-rows-items (list row))))
(t
;; there must already be some row items from
;; a previous unbox
(setf (nth idx extra-rows-items)
(nconc (nth idx extra-rows-items) row)))))))
(dolist (item row-items)
(cond ((listp item)
(setq items (nconc items (car item)))
(unless (null (cdr item))
;; are there extra rows ?
(handle-extra-rows (cdr item))))
(t ;; justa' vanilla item
(setq items (nconc items (list item))))))
(cbos-push
(cond ((null extra-rows-items)
;; don't make empty rows -- just return nil.
(if (null items)
nil
(make-evrow-from-entries items)))
(t (cons (make-evrow-from-entries items)
(mapcar #'make-evrow-from-entries extra-rows-items))))))))
(defun pname-from-value (value)
(when (or (symbolp value) (numberp value))
(let ((string (format nil "~A" value)))
(make-formatting-info :chas string :start 0 :stop (length string)))))
(define-instruction (stack-chunk 35) ()
(let ((lfp (cbos-pop)) (value (cbos-pop)) (rfp (cbos-pop)))
(cbos-push (make-chunk lfp (pname-from-value value) value rfp))))
;; because coallescing of token may fail (e.g. when one token turns
;; out to be a box), a value MAY be a list of several other values
(define-instruction (evrow-from-n-entries 36) (n)
(let ((ptrs nil))
(dotimes (i n)
(let ((value (cbos-pop)))
(setq ptrs (nconc ptrs (if (consp value)
(mapcar #'make-pointer value)
(list (make-pointer value)))))))
(cbos-push (make-evrow-from-pointers ptrs))))
(define-instruction (stack-virtual-copy 37) ()
(cbos-push (virtual-copy (cbos-pop) :top-level? (cbos-pop))))
;;; same as make-vc except that any lists encountered are assumed to be
;;; lists of evrows generated by the unbox handler and are flattened out.
;;; Also, removes NIL "rows," but always makes at least one row.
;;; Remember that (listp nil) is true.
(define-instruction (vc-for-build 38) (n-rows type name closet-p)
(let* ((rows (collect-n-list-from-stack n-rows))
(closet (when closet-p (prog1 (car rows) (setq rows (cdr rows)))))
(vc (if (every #'(lambda (x) (not (listp x))) rows)
(make-vc rows type name)
(let ((new-rows nil))
(dolist (row rows)
(unless (null row)
(if (consp row)
(setq new-rows (nconc (nreverse row) new-rows))
(push row new-rows))))
(make-vc (if (null new-rows)
(list (make-empty-evrow))
(nreverse new-rows))
type name)))))
(unless (null closet)
(setf (vc-closets vc) closet) (setf (vc-progenitor vc) :new))
(cbos-push vc)))
;; same as vc-for-build except that it expects the name to be on
;; the stack instead of in the arglist
(define-instruction (named-vc-for-build 39) (n-rows type closet-p)
(let* ((name (intern-in-bu-package
(string-upcase (box-text-string (cbos-pop)))))
(rows (collect-n-list-from-stack n-rows))
(closet (when closet-p (prog1 (car rows) (setq rows (cdr rows)))))
(vc (if (every #'(lambda (x) (not (listp x))) rows)
(make-vc rows type name)
(let ((new-rows nil))
(dolist (row rows)
(unless (null row)
(if (consp row)
(setq new-rows (nconc (nreverse row) new-rows))
(push row new-rows))))
(make-vc (if (null new-rows)
(list (make-empty-evrow))
(nreverse new-rows))
type name)))))
(unless (null closet)
(setf (vc-closets vc) closet) (setf (vc-progenitor vc) :new))
(cbos-push vc)))
;; named ports, name from stack, target as immediate arg
(define-instruction (named-port-for-build 40) (target)
(cbos-push (make-virtual-port :name (intern-in-bu-package
(string-upcase
(box-text-string (cbos-pop))))
:target target)))
;;;; Parsing a template
;;; these return 2 values: the result of the walk and a flag indicating
;;; whether or not imbedded atsigns or excls were encountered
;;; A row-form can have two possible representations: In the simple case
;;; when there are no unbox's, then a row form will be somthing like...
;;; (make-evrow-from-pointers (list <thing> <box-form> <thing> ...))
(defun canonicalize-prop-for-eval (prop)
(ecase prop
(bu::eval-it 'bu::run)
(bu::@ 'bu::@)))
(defvar *eval-props-that-build-handles* '(bu::eval-it bu::@))
(defun build-eval-prop? (eval-prop)
(fast-memq eval-prop *eval-props-that-build-handles*))
(defun walk-evrow-for-build (evrow sup-box ct)
(let ((row-args nil)
(constant-p t)
(unmatched-ev-prop nil)
(unbox-in-row? nil))
(labels ((unify-ev-props (existing-props new-props)
(append existing-props new-props))
(expand-ev-props-into-code (props value chunk)
(cond ((null props)
(error
"Why are you trying to expand ev-props when there arent any"))
((eq (car props) 'bu::eval-it)
(setq constant-p nil)
(get-build-arg
(list (if (null (cdr props))
(coerce-object-for-evaluator value)
(handle-eval-props (cdr props) value)))))
((eq (car props) 'bu::@)
(setq constant-p nil unbox-in-row? t)
`(,(get-build-arg
(list (if (null (cdr props))
(coerce-object-for-evaluator value)
(handle-eval-props (cdr props) value))))
interpolate-rows))
(t chunk)))
(pointer-handler (ptr)
(let* ((raw-chunk (get-pointer-value ptr sup-box))
(chunk-p (chunk-p raw-chunk))
(value (if chunk-p
(chunk-chunk raw-chunk)
raw-chunk))
(ev-props (when chunk-p
(getf (chunk-plist raw-chunk)
':eval-prop))))
(flet ((value-handler ()
;; returns either literal values or code to
;; produce a value
(cond ((or (numberp value) (symbolp value))
raw-chunk)
((or (virtual-port? value) (port-box? value))
(multiple-value-bind (form port-constant-p)
(walk-build-port value raw-chunk)
(when (and constant-p
(null port-constant-p))
(setq constant-p port-constant-p))
(cond ((or (null chunk-p) port-constant-p)
form)
(t
`(,(chunk-right-format raw-chunk)
,form
,(chunk-left-format raw-chunk)
stack-chunk)))))
((or (virtual-copy? value) (box? value))
(multiple-value-bind (bf box-constant-p)
(walk-build-box-internal value ct t)
(when (and constant-p
(null box-constant-p))
(setq constant-p box-constant-p))
(cond ((null chunk-p)
bf)
(t
`(,(chunk-right-format
raw-chunk)
,bf
,(chunk-left-format raw-chunk)
stack-chunk)))))
(t
(error "Don't know what to do with ~S"
value)))))
(cond ((and (null value)
(not (null ev-props)))
;; this should really unify with
;; what's already there
(setq unmatched-ev-prop
(unify-ev-props unmatched-ev-prop
ev-props))
':ev-props-only)
((and (null ev-props) (null unmatched-ev-prop))
(value-handler))
;; still need to put in code to preserve the
;; formatting info when merging results of run
;; time expressions
((null ev-props)
(let ((code (expand-ev-props-into-code
unmatched-ev-prop
value raw-chunk)))
(setq unmatched-ev-prop nil)
code))
(t
;; must be a chunk with ev-props in it
(let ((code (expand-ev-props-into-code
(unify-ev-props
unmatched-ev-prop
ev-props) value raw-chunk)))
(setq unmatched-ev-prop nil)
code)))))))
(dolist (pointer (evrow-pointers evrow))
(let ((ptr-val (pointer-handler pointer)))
(unless (eq ptr-val ':ev-props-only)
(push ptr-val row-args))))
(cond ((not (null constant-p))
(values (let ((l (length row-args)))
(append row-args
(list (make-build-fun+args
'evrow-from-n-entries l))))
t))
((null unbox-in-row?)
(values (let ((l (length row-args)))
(append row-args
(list (make-build-fun+args
'evrow-from-n-entries l))))
nil))
;; must be an unbox in the row
(t
(values (let ((l (length row-args)))
(append row-args
(list (make-build-fun+args
'interpolate-n-unbox-results l))))
nil))))))
;;; hack preservation of names here...
(defun walk-build-box-internal (box &optional creation-time top-level?)
(declare (values box-form constant-p))
(let ((row-forms nil)
(constant-p t)
(closet-p nil)
(ct (or creation-time
(and (virtual-copy? box) (vc-creation-time box)))))
(let ((closet (if (virtual-copy? box)
(vc-closets box)
(slot-value box 'closets))))
(unless (null closet)
(setq closet-p t)
(unless (evrow? closet) (setq closet (make-evrow-from-row closet)))
(multiple-value-bind (closet-form closet-constant-p)
(walk-evrow-for-build closet box ct)
(setq constant-p closet-constant-p)
(push closet-form row-forms))))
(dolist (row (get-box-rows box creation-time))
(multiple-value-bind (row-form row-constant-p)
(walk-evrow-for-build row box ct)
(push row-form row-forms)
(when (and constant-p
(null row-constant-p))
(setq constant-p row-constant-p))))
(let ((l (length row-forms))
(box-type (if (virtual-copy? box)
(vc-type box)
(class-name (class-of box))))
(box-name (if (virtual-copy? box)
(vc-name box)
(editor-box-name-symbol box))))
(cond ((char= (char (symbol-name box-name) 0) #\@)
;; should check to see if the rest of the symbol
;; is valid (no more ev prop chars)
(values
(append row-forms
(list (get-build-arg
(list (intern-in-bu-package
(subseq (symbol-name box-name)
(1+ (position #\@ (symbol-name
box-name)
:test #'char=))))))
(make-build-fun+args 'named-vc-for-build
l box-type closet-p)))
nil))
((null constant-p)
(values
(append row-forms
(list (make-build-fun+args 'vc-for-build l
box-type box-name closet-p)))
constant-p))
(t
(values (if (null top-level?)
`(nil ,box stack-virtual-copy)
`(T ,box stack-virtual-copy))
t))))))
(defun walk-build-port (port raw-chunk)
(let ((name (if (virtual-port? port)
(vp-name port)
(editor-box-name-symbol port))))
(cond ((char= (char (symbol-name name) 0) #\@)
(values
(list (get-build-arg
(list
(intern-in-bu-package
(subseq (symbol-name name)
(1+ (position #\@ (symbol-name name)
:test #'char=))))))
(make-build-fun+args 'named-port-for-build
(if (virtual-port? port)
(vp-target port)
(ports port))))
nil))
(t (values raw-chunk t)))))
;;; this is the top level function to call
(defun walk-box-for-build (box)
(declare (values template-function-body
template-function-arglist
forms-to-be-evaled))
(with-build-function-arg-collection
(walk-build-box-internal box nil t)))
;;;; The top level interface...
;;; Caching compiled-build-objects onto editor structure
;;; the build cache needs to be immediately flushed on modified
;;; rather than waiting for the eval to finish (see the modified
;;; function in editor.lisp)
(defun get-cached-build-function (box)
(getprop box 'cached-build-function))
(defun put-cached-build-function (box fun)
(setf (build-template? box) t) ; once a template always a template ?
(putprop box fun 'cached-build-function))
(defun decache-build-function (box)
(when (getprop box 'cached-build-function)
(putprop box nil 'cached-build-function)))
(defun build (template)
(setq template (box-or-port-target template))
(let* ((edbox (cond ((data-box? template) template)
((fast-eval-data-box? template)
(vc-progenitor template))))
(cached-function (unless (null edbox)
(get-cached-build-function edbox))))
(cond ((not (null cached-function))
(execute-compiled-build-function cached-function))
(t
(let ((new-fun (make-build-function-object template)))
(unless (or (null edbox)
(not (editor-box-cacheable?
edbox
(or (and (virtual-copy? template)
(vc-creation-time template))
(now)))))
(put-cached-build-function edbox new-fun))
(execute-compiled-build-function new-fun))))))
;;;; and into Boxer we go.....
(boxer-eval::defboxer-primitive bu::build (template)
(if (numberp template) template (build template)))
|
[
{
"context": "#||\r\n\r\nMakeFile.lisp\r\n~~~~~~~~~~~~\r\nAuthors: Disha Puri, Sandip Ray, Kecheng Hao, Fei Xie\r\nLast Updated: ",
"end": 55,
"score": 0.9998458623886108,
"start": 45,
"tag": "NAME",
"value": "Disha Puri"
},
{
"context": "\nMakeFile.lisp\r\n~~~~~~~~~~~~\r\nAuthors: Disha Puri, Sandip Ray, Kecheng Hao, Fei Xie\r\nLast Updated: 12th April 2",
"end": 67,
"score": 0.9997847676277161,
"start": 57,
"tag": "NAME",
"value": "Sandip Ray"
},
{
"context": "sp\r\n~~~~~~~~~~~~\r\nAuthors: Disha Puri, Sandip Ray, Kecheng Hao, Fei Xie\r\nLast Updated: 12th April 2014\r\n||#\r\n\r\n\r",
"end": 80,
"score": 0.9997998476028442,
"start": 69,
"tag": "NAME",
"value": "Kecheng Hao"
},
{
"context": "~~~\r\nAuthors: Disha Puri, Sandip Ray, Kecheng Hao, Fei Xie\r\nLast Updated: 12th April 2014\r\n||#\r\n\r\n\r\n(ubt! 1)",
"end": 89,
"score": 0.9997305870056152,
"start": 82,
"tag": "NAME",
"value": "Fei Xie"
}
] |
books/workshops/2014/puri-ray-hao-xie/support/Make.lsp
|
mayankmanj/acl2
| 305 |
#||
MakeFile.lisp
~~~~~~~~~~~~
Authors: Disha Puri, Sandip Ray, Kecheng Hao, Fei Xie
Last Updated: 12th April 2014
||#
(ubt! 1)
(certify-book "functions")
(u)
(certify-book "semantics")
(u)
(certify-book "general-theorems" 0 t :skip-proofs-okp t)
(u)
(certify-book "superstep-construction" 0 t :skip-proofs-okp t)
(u)
(certify-book "seq-pp-equivalence" 0 t :skip-proofs-okp t)
(u)
|
80258
|
#||
MakeFile.lisp
~~~~~~~~~~~~
Authors: <NAME>, <NAME>, <NAME>, <NAME>
Last Updated: 12th April 2014
||#
(ubt! 1)
(certify-book "functions")
(u)
(certify-book "semantics")
(u)
(certify-book "general-theorems" 0 t :skip-proofs-okp t)
(u)
(certify-book "superstep-construction" 0 t :skip-proofs-okp t)
(u)
(certify-book "seq-pp-equivalence" 0 t :skip-proofs-okp t)
(u)
| true |
#||
MakeFile.lisp
~~~~~~~~~~~~
Authors: PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
Last Updated: 12th April 2014
||#
(ubt! 1)
(certify-book "functions")
(u)
(certify-book "semantics")
(u)
(certify-book "general-theorems" 0 t :skip-proofs-okp t)
(u)
(certify-book "superstep-construction" 0 t :skip-proofs-okp t)
(u)
(certify-book "seq-pp-equivalence" 0 t :skip-proofs-okp t)
(u)
|
[
{
"context": "part of for\n (c) 2016 Shirakumo http://tymoon.eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n",
"end": 87,
"score": 0.9999182820320129,
"start": 69,
"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": 112,
"score": 0.9998958110809326,
"start": 98,
"tag": "NAME",
"value": "Nicolas Hafner"
},
{
"context": ".eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(in-package #:org.shirakumo.for.iterator)\n\n(",
"end": 132,
"score": 0.9999234080314636,
"start": 114,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
iterator.lisp
|
Shinmera/for
| 38 |
#|
This file is a part of for
(c) 2016 Shirakumo http://tymoon.eu ([email protected])
Author: Nicolas Hafner <[email protected]>
|#
(in-package #:org.shirakumo.for.iterator)
(defgeneric has-more (iterator))
(defgeneric next (iterator))
(defgeneric current (iterator))
(defgeneric (setf current) (value iterator))
(defgeneric end (iterator))
(defgeneric make-iterator (object &key &allow-other-keys))
(defgeneric step-functions (iterator))
(defclass iterator ()
((object :initarg :object :accessor object)
(current :accessor current)))
(defmethod next :around ((iterator iterator))
(setf (slot-value iterator 'current) (call-next-method)))
(defmethod end ((iterator iterator)))
(defmethod step-functions ((iterator iterator))
(values (lambda () (next iterator))
(lambda () (has-more iterator))
(lambda (value) (setf (current iterator) value))
(lambda () (end iterator))))
(defclass list-iterator (iterator)
())
(defmethod initialize-instance :after ((iterator list-iterator) &key object)
(setf (object iterator) (cons NIL object)))
(defmethod has-more ((iterator list-iterator))
(cdr (object iterator)))
(defmethod next ((iterator list-iterator))
(setf (object iterator) (cdr (object iterator)))
(car (object iterator)))
(defmethod (setf current) (value (iterator list-iterator))
(setf (car (object iterator)) value))
(defmethod step-functions ((iterator list-iterator))
(let ((list (object iterator)))
(declare (type list list))
(values
(lambda ()
(setf list (cdr list))
(car list))
(lambda ()
(cdr list))
(lambda (value)
(setf (car list) value))
(lambda ()))))
(defmethod make-iterator ((list list) &key)
(make-instance 'list-iterator :object list))
(defclass vector-iterator (iterator)
((start :initarg :start :accessor start))
(:default-initargs :start 0))
(defmethod has-more ((iterator vector-iterator))
(< (start iterator) (length (object iterator))))
(defmethod next ((iterator vector-iterator))
(prog1 (aref (object iterator) (start iterator))
(incf (start iterator))))
(defmethod (setf current) (value (iterator vector-iterator))
(setf (aref (object iterator) (1- (start iterator))) value))
(defmethod step-functions ((iterator vector-iterator))
(let ((vec (object iterator))
(i (start iterator)))
(declare (type vector vec))
(declare (type (unsigned-byte 32) i))
(values
(lambda ()
(prog1 (aref vec i)
(incf i)))
(lambda ()
(< i (length vec)))
(lambda (value)
(setf (aref vec i) value))
(lambda ()))))
(defmethod make-iterator ((vector vector) &key (start 0))
(make-instance 'vector-iterator :object vector :start start))
(defclass array-iterator (vector-iterator)
((total-length :accessor total-length)))
(defmethod initialize-instance :after ((iterator array-iterator) &key object)
(setf (total-length iterator) (array-total-size object)))
(defmethod has-more ((iterator array-iterator))
(< (start iterator) (total-length iterator)))
(defmethod next ((iterator array-iterator))
(prog1 (row-major-aref (object iterator) (start iterator))
(incf (start iterator))))
(defmethod (setf current) (value (iterator array-iterator))
(setf (row-major-aref (object iterator) (1- (start iterator))) value))
(defmethod step-functions ((iterator array-iterator))
(let ((arr (object iterator))
(total (total-length iterator))
(i (start iterator)))
(declare (type vector arr))
(declare (type (unsigned-byte 32) total i))
(values
(lambda ()
(prog1 (row-major-aref arr i)
(incf i)))
(lambda ()
(< i total))
(lambda (value)
(setf (row-major-aref arr i) value))
(lambda ()))))
(defmethod make-iterator ((array array) &key (start 0))
(make-instance 'array-iterator :object array :start start))
(defclass sequence-iterator (iterator)
((iterator :accessor iterator)))
(defmethod initialize-instance :after ((iterator sequence-iterator) &key object start end)
(setf (iterator iterator) (multiple-value-list
(#+sbcl sb-sequence:make-sequence-iterator
#+abcl sequence:make-sequence-iterator
#-(or sbcl abcl) (lambda (&rest _)
(declare (ignore _))
(error "This implementation has extensible sequences, but is not supported by FOR. Please contact the maintainer."))
object :start start :end end))))
(defmethod has-more ((iterator sequence-iterator))
(destructuring-bind (state limit from-end step endp . _) (iterator iterator)
(declare (ignore _))
(not (funcall endp (object iterator) state limit from-end))))
(defmethod next ((iterator sequence-iterator))
(destructuring-bind (state limit from-end step endp element . _) (iterator iterator)
(declare (ignore limit endp _))
(prog1 (funcall element (object iterator) state)
(funcall step (object iterator) state from-end))))
(defmethod (setf current) (value (iterator sequence-iterator))
(destructuring-bind (state limit from-end step endp element set . _) (iterator iterator)
(declare (ignore limit from-end step endp element _))
(funcall set value (object iterator) state)))
(defmethod step-functions ((iterator sequence-iterator))
(let ((object (object iterator)))
(destructuring-bind (state limit from-end step endp element set . _) (iterator iterator)
(declare (ignore _))
(values
(lambda ()
(prog1 (funcall element object state)
(funcall step object state from-end)))
(lambda ()
(not (funcall endp object state limit from-end)))
(lambda (value)
(funcall set value object state))
(lambda ())))))
(defmethod make-iterator ((sequence sequence) &key)
(make-instance 'sequence-iterator :object sequence))
(defclass stream-iterator (iterator)
((buffer :accessor buffer)
(index :initform 1 :accessor index)
(limit :initform 1 :accessor limit)
(close-stream :initarg :close-stream :accessor close-stream)))
(defmethod initialize-instance :after ((iterator stream-iterator) &key (buffer-size 4096) object)
(setf (buffer iterator) (make-array buffer-size :element-type (stream-element-type object))))
(defmethod has-more ((iterator stream-iterator))
(when (= (index iterator) (limit iterator))
(setf (limit iterator) (read-sequence (buffer iterator) (object iterator)))
(setf (index iterator) 0))
(not (= 0 (limit iterator))))
(defmethod next ((iterator stream-iterator))
(prog1 (aref (buffer iterator) (index iterator))
(incf (index iterator))))
(defmethod (setf current) ((value integer) (iterator stream-iterator))
(write-byte value (object iterator)))
(defmethod (setf current) ((value character) (iterator stream-iterator))
(write-char value (object iterator)))
(defmethod (setf current) ((value sequence) (iterator stream-iterator))
(write-sequence value (object iterator)))
(defmethod end ((iterator stream-iterator))
(when (close-stream iterator)
(close (object iterator))))
(defmethod step-functions ((iterator stream-iterator))
(let ((object (object iterator))
(buffer (buffer iterator))
(index (index iterator))
(limit (limit iterator)))
(declare (type stream object))
(values
(lambda ()
(prog1 (aref buffer index)
(incf index)))
(lambda ()
(when (= index limit)
(setf limit (read-sequence buffer object))
(setf index 0))
(not (= 0 limit)))
(lambda (value)
(etypecase value
(integer (write-byte value object))
(character (write-char value object))
(sequence (write-sequence value object))))
(if (close-stream iterator)
(lambda ()
(close object))
(lambda ())))))
(defclass stream-line-iterator (iterator)
((buffer :initform NIL :accessor buffer)
(close-stream :initarg :close-stream :accessor close-stream)))
(defmethod has-more ((iterator stream-line-iterator))
(or (buffer iterator)
(setf (buffer iterator) (read-line (object iterator) NIL NIL))))
(defmethod next ((iterator stream-line-iterator))
(let ((buffer (buffer iterator)))
(cond (buffer
(setf (buffer iterator) NIL)
buffer)
(T
(read-line (object iterator))))))
(defmethod end ((iterator stream-line-iterator))
(when (close-stream iterator)
(close (object iterator))))
(defmethod step-functions ((iterator stream-line-iterator))
(let ((object (object iterator))
(buffer (buffer iterator)))
(values
(lambda ()
(cond (buffer
(setf buffer NIL)
buffer)
(T
(read-line object))))
(lambda ()
(or buffer
(setf buffer (read-line object NIL NIL))))
(lambda (value)
(declare (ignore value))
(error "Cannot write to a STREAM-LINE-ITERATOR."))
(if (close-stream iterator)
(lambda ()
(close object))
(lambda ())))))
(defmethod make-iterator ((stream stream) &key (buffer-size 4096) close-stream)
(case buffer-size
((:line :lines)
(make-instance 'stream-line-iterator :object stream :close-stream close-stream))
(T (make-instance 'stream-iterator :object stream :buffer-size buffer-size :close-stream close-stream))))
(defclass directory-iterator (list-iterator)
())
(defmethod initialize-instance :after ((iterator directory-iterator) &key object)
(setf (object iterator) (cons NIL (directory object))))
(defmethod make-iterator ((pathname pathname) &key buffer-size (element-type 'character))
(if (wild-pathname-p pathname)
(make-instance 'directory-iterator :object pathname)
(make-iterator (open pathname :element-type element-type) :buffer-size buffer-size :close-stream T)))
(defclass random-iterator (iterator)
((limit :initarg :limit :reader limit))
(:default-initargs
:limit 1.0f0))
(defmethod has-more ((iterator random-iterator))
T)
(defmethod next ((iterator random-iterator))
(random (limit iterator) (object iterator)))
(defmethod step-functions ((iterator random-iterator))
(let ((object (object iterator))
(limit (limit iterator)))
(values
(lambda ()
(random limit object))
(lambda ()
T)
(lambda (value)
(declare (ignore value))
(error "Cannot write to a RANDOM-ITERATOR."))
(lambda ()))))
(defmethod make-iterator ((random-state random-state) &key (limit 1.0))
(make-instance 'random-iterator :object random-state :limit limit))
(defclass package-iterator (iterator)
((prefetch :initform NIL :accessor prefetch))
(:default-initargs
:status '(:internal :external :inherited)))
(defmethod initialize-instance :after ((iterator package-iterator) &key object status)
(setf (object iterator) (org.shirakumo.for::package-iterator object status)))
(defmethod has-more ((iterator package-iterator))
(if (prefetch iterator)
(car (prefetch iterator))
(multiple-value-bind (more symb) (funcall (object iterator))
(setf (prefetch iterator) (cons more symb))
more)))
(defmethod next ((iterator package-iterator))
(if (prefetch iterator)
(prog1 (cdr (prefetch iterator))
(setf (prefetch iterator) NIL))
(nth-value 1 (funcall (object iterator)))))
(defmethod step-functions ((iterator package-iterator))
(let ((object (object iterator))
(prefetch (prefetch iterator)))
(values
(lambda ()
(if prefetch
(prog1 (cdr prefetch)
(setf prefetch NIL))
(nth-value 1 (funcall object))))
(lambda ()
(if prefetch
(car prefetch)
(multiple-value-bind (more symb) (funcall object)
(setf prefetch (cons more symb))
more)))
(lambda (value)
(declare (ignore value))
(error "Cannot write to a PACKAGE-ITERATOR."))
(lambda ()))))
(defmethod make-iterator ((package package) &key)
(make-instance 'package-iterator :object package))
(defclass hash-table-iterator (iterator)
((iterator :initform NIL :accessor iterator)
(prefetch :initform NIL :accessor prefetch)))
(defmethod initialize-instance :after ((iterator hash-table-iterator) &key object)
(setf (iterator iterator) (org.shirakumo.for::hash-table-iterator object)))
(defmethod has-more ((iterator hash-table-iterator))
(if (prefetch iterator)
(car (prefetch iterator))
(multiple-value-bind (more key val) (funcall (iterator iterator))
(setf (prefetch iterator) (list more key val))
more)))
(defmethod next ((iterator hash-table-iterator))
(if (prefetch iterator)
(prog1 (rest (prefetch iterator))
(setf (prefetch iterator) NIL))
(multiple-value-bind (more key val) (funcall (iterator iterator))
(declare (ignore more))
(list key val))))
(defmethod (setf current) (value (iterator hash-table-iterator))
(setf (gethash (first (current iterator)) (object iterator)) value))
(defmethod step-functions ((iterator hash-table-iterator))
(let ((object (object iterator))
(prefetch (prefetch iterator))
(iterator (iterator iterator))
current)
(declare (type hash-table object))
(declare (type function iterator))
(values
(lambda ()
(if prefetch
(prog1 (setf current (rest prefetch))
(setf prefetch NIL))
(multiple-value-bind (more key val) (funcall iterator)
(declare (ignore more))
(setf current (list key val)))))
(lambda ()
(if prefetch
(car prefetch)
(multiple-value-bind (more key val) (funcall iterator)
(setf prefetch (list more key val))
more)))
(lambda (value)
(setf (gethash (first current) object) value))
(lambda ()))))
(defmethod make-iterator ((hash-table hash-table) &key)
(make-instance 'hash-table-iterator :object hash-table))
|
89812
|
#|
This file is a part of for
(c) 2016 Shirakumo http://tymoon.eu (<EMAIL>)
Author: <NAME> <<EMAIL>>
|#
(in-package #:org.shirakumo.for.iterator)
(defgeneric has-more (iterator))
(defgeneric next (iterator))
(defgeneric current (iterator))
(defgeneric (setf current) (value iterator))
(defgeneric end (iterator))
(defgeneric make-iterator (object &key &allow-other-keys))
(defgeneric step-functions (iterator))
(defclass iterator ()
((object :initarg :object :accessor object)
(current :accessor current)))
(defmethod next :around ((iterator iterator))
(setf (slot-value iterator 'current) (call-next-method)))
(defmethod end ((iterator iterator)))
(defmethod step-functions ((iterator iterator))
(values (lambda () (next iterator))
(lambda () (has-more iterator))
(lambda (value) (setf (current iterator) value))
(lambda () (end iterator))))
(defclass list-iterator (iterator)
())
(defmethod initialize-instance :after ((iterator list-iterator) &key object)
(setf (object iterator) (cons NIL object)))
(defmethod has-more ((iterator list-iterator))
(cdr (object iterator)))
(defmethod next ((iterator list-iterator))
(setf (object iterator) (cdr (object iterator)))
(car (object iterator)))
(defmethod (setf current) (value (iterator list-iterator))
(setf (car (object iterator)) value))
(defmethod step-functions ((iterator list-iterator))
(let ((list (object iterator)))
(declare (type list list))
(values
(lambda ()
(setf list (cdr list))
(car list))
(lambda ()
(cdr list))
(lambda (value)
(setf (car list) value))
(lambda ()))))
(defmethod make-iterator ((list list) &key)
(make-instance 'list-iterator :object list))
(defclass vector-iterator (iterator)
((start :initarg :start :accessor start))
(:default-initargs :start 0))
(defmethod has-more ((iterator vector-iterator))
(< (start iterator) (length (object iterator))))
(defmethod next ((iterator vector-iterator))
(prog1 (aref (object iterator) (start iterator))
(incf (start iterator))))
(defmethod (setf current) (value (iterator vector-iterator))
(setf (aref (object iterator) (1- (start iterator))) value))
(defmethod step-functions ((iterator vector-iterator))
(let ((vec (object iterator))
(i (start iterator)))
(declare (type vector vec))
(declare (type (unsigned-byte 32) i))
(values
(lambda ()
(prog1 (aref vec i)
(incf i)))
(lambda ()
(< i (length vec)))
(lambda (value)
(setf (aref vec i) value))
(lambda ()))))
(defmethod make-iterator ((vector vector) &key (start 0))
(make-instance 'vector-iterator :object vector :start start))
(defclass array-iterator (vector-iterator)
((total-length :accessor total-length)))
(defmethod initialize-instance :after ((iterator array-iterator) &key object)
(setf (total-length iterator) (array-total-size object)))
(defmethod has-more ((iterator array-iterator))
(< (start iterator) (total-length iterator)))
(defmethod next ((iterator array-iterator))
(prog1 (row-major-aref (object iterator) (start iterator))
(incf (start iterator))))
(defmethod (setf current) (value (iterator array-iterator))
(setf (row-major-aref (object iterator) (1- (start iterator))) value))
(defmethod step-functions ((iterator array-iterator))
(let ((arr (object iterator))
(total (total-length iterator))
(i (start iterator)))
(declare (type vector arr))
(declare (type (unsigned-byte 32) total i))
(values
(lambda ()
(prog1 (row-major-aref arr i)
(incf i)))
(lambda ()
(< i total))
(lambda (value)
(setf (row-major-aref arr i) value))
(lambda ()))))
(defmethod make-iterator ((array array) &key (start 0))
(make-instance 'array-iterator :object array :start start))
(defclass sequence-iterator (iterator)
((iterator :accessor iterator)))
(defmethod initialize-instance :after ((iterator sequence-iterator) &key object start end)
(setf (iterator iterator) (multiple-value-list
(#+sbcl sb-sequence:make-sequence-iterator
#+abcl sequence:make-sequence-iterator
#-(or sbcl abcl) (lambda (&rest _)
(declare (ignore _))
(error "This implementation has extensible sequences, but is not supported by FOR. Please contact the maintainer."))
object :start start :end end))))
(defmethod has-more ((iterator sequence-iterator))
(destructuring-bind (state limit from-end step endp . _) (iterator iterator)
(declare (ignore _))
(not (funcall endp (object iterator) state limit from-end))))
(defmethod next ((iterator sequence-iterator))
(destructuring-bind (state limit from-end step endp element . _) (iterator iterator)
(declare (ignore limit endp _))
(prog1 (funcall element (object iterator) state)
(funcall step (object iterator) state from-end))))
(defmethod (setf current) (value (iterator sequence-iterator))
(destructuring-bind (state limit from-end step endp element set . _) (iterator iterator)
(declare (ignore limit from-end step endp element _))
(funcall set value (object iterator) state)))
(defmethod step-functions ((iterator sequence-iterator))
(let ((object (object iterator)))
(destructuring-bind (state limit from-end step endp element set . _) (iterator iterator)
(declare (ignore _))
(values
(lambda ()
(prog1 (funcall element object state)
(funcall step object state from-end)))
(lambda ()
(not (funcall endp object state limit from-end)))
(lambda (value)
(funcall set value object state))
(lambda ())))))
(defmethod make-iterator ((sequence sequence) &key)
(make-instance 'sequence-iterator :object sequence))
(defclass stream-iterator (iterator)
((buffer :accessor buffer)
(index :initform 1 :accessor index)
(limit :initform 1 :accessor limit)
(close-stream :initarg :close-stream :accessor close-stream)))
(defmethod initialize-instance :after ((iterator stream-iterator) &key (buffer-size 4096) object)
(setf (buffer iterator) (make-array buffer-size :element-type (stream-element-type object))))
(defmethod has-more ((iterator stream-iterator))
(when (= (index iterator) (limit iterator))
(setf (limit iterator) (read-sequence (buffer iterator) (object iterator)))
(setf (index iterator) 0))
(not (= 0 (limit iterator))))
(defmethod next ((iterator stream-iterator))
(prog1 (aref (buffer iterator) (index iterator))
(incf (index iterator))))
(defmethod (setf current) ((value integer) (iterator stream-iterator))
(write-byte value (object iterator)))
(defmethod (setf current) ((value character) (iterator stream-iterator))
(write-char value (object iterator)))
(defmethod (setf current) ((value sequence) (iterator stream-iterator))
(write-sequence value (object iterator)))
(defmethod end ((iterator stream-iterator))
(when (close-stream iterator)
(close (object iterator))))
(defmethod step-functions ((iterator stream-iterator))
(let ((object (object iterator))
(buffer (buffer iterator))
(index (index iterator))
(limit (limit iterator)))
(declare (type stream object))
(values
(lambda ()
(prog1 (aref buffer index)
(incf index)))
(lambda ()
(when (= index limit)
(setf limit (read-sequence buffer object))
(setf index 0))
(not (= 0 limit)))
(lambda (value)
(etypecase value
(integer (write-byte value object))
(character (write-char value object))
(sequence (write-sequence value object))))
(if (close-stream iterator)
(lambda ()
(close object))
(lambda ())))))
(defclass stream-line-iterator (iterator)
((buffer :initform NIL :accessor buffer)
(close-stream :initarg :close-stream :accessor close-stream)))
(defmethod has-more ((iterator stream-line-iterator))
(or (buffer iterator)
(setf (buffer iterator) (read-line (object iterator) NIL NIL))))
(defmethod next ((iterator stream-line-iterator))
(let ((buffer (buffer iterator)))
(cond (buffer
(setf (buffer iterator) NIL)
buffer)
(T
(read-line (object iterator))))))
(defmethod end ((iterator stream-line-iterator))
(when (close-stream iterator)
(close (object iterator))))
(defmethod step-functions ((iterator stream-line-iterator))
(let ((object (object iterator))
(buffer (buffer iterator)))
(values
(lambda ()
(cond (buffer
(setf buffer NIL)
buffer)
(T
(read-line object))))
(lambda ()
(or buffer
(setf buffer (read-line object NIL NIL))))
(lambda (value)
(declare (ignore value))
(error "Cannot write to a STREAM-LINE-ITERATOR."))
(if (close-stream iterator)
(lambda ()
(close object))
(lambda ())))))
(defmethod make-iterator ((stream stream) &key (buffer-size 4096) close-stream)
(case buffer-size
((:line :lines)
(make-instance 'stream-line-iterator :object stream :close-stream close-stream))
(T (make-instance 'stream-iterator :object stream :buffer-size buffer-size :close-stream close-stream))))
(defclass directory-iterator (list-iterator)
())
(defmethod initialize-instance :after ((iterator directory-iterator) &key object)
(setf (object iterator) (cons NIL (directory object))))
(defmethod make-iterator ((pathname pathname) &key buffer-size (element-type 'character))
(if (wild-pathname-p pathname)
(make-instance 'directory-iterator :object pathname)
(make-iterator (open pathname :element-type element-type) :buffer-size buffer-size :close-stream T)))
(defclass random-iterator (iterator)
((limit :initarg :limit :reader limit))
(:default-initargs
:limit 1.0f0))
(defmethod has-more ((iterator random-iterator))
T)
(defmethod next ((iterator random-iterator))
(random (limit iterator) (object iterator)))
(defmethod step-functions ((iterator random-iterator))
(let ((object (object iterator))
(limit (limit iterator)))
(values
(lambda ()
(random limit object))
(lambda ()
T)
(lambda (value)
(declare (ignore value))
(error "Cannot write to a RANDOM-ITERATOR."))
(lambda ()))))
(defmethod make-iterator ((random-state random-state) &key (limit 1.0))
(make-instance 'random-iterator :object random-state :limit limit))
(defclass package-iterator (iterator)
((prefetch :initform NIL :accessor prefetch))
(:default-initargs
:status '(:internal :external :inherited)))
(defmethod initialize-instance :after ((iterator package-iterator) &key object status)
(setf (object iterator) (org.shirakumo.for::package-iterator object status)))
(defmethod has-more ((iterator package-iterator))
(if (prefetch iterator)
(car (prefetch iterator))
(multiple-value-bind (more symb) (funcall (object iterator))
(setf (prefetch iterator) (cons more symb))
more)))
(defmethod next ((iterator package-iterator))
(if (prefetch iterator)
(prog1 (cdr (prefetch iterator))
(setf (prefetch iterator) NIL))
(nth-value 1 (funcall (object iterator)))))
(defmethod step-functions ((iterator package-iterator))
(let ((object (object iterator))
(prefetch (prefetch iterator)))
(values
(lambda ()
(if prefetch
(prog1 (cdr prefetch)
(setf prefetch NIL))
(nth-value 1 (funcall object))))
(lambda ()
(if prefetch
(car prefetch)
(multiple-value-bind (more symb) (funcall object)
(setf prefetch (cons more symb))
more)))
(lambda (value)
(declare (ignore value))
(error "Cannot write to a PACKAGE-ITERATOR."))
(lambda ()))))
(defmethod make-iterator ((package package) &key)
(make-instance 'package-iterator :object package))
(defclass hash-table-iterator (iterator)
((iterator :initform NIL :accessor iterator)
(prefetch :initform NIL :accessor prefetch)))
(defmethod initialize-instance :after ((iterator hash-table-iterator) &key object)
(setf (iterator iterator) (org.shirakumo.for::hash-table-iterator object)))
(defmethod has-more ((iterator hash-table-iterator))
(if (prefetch iterator)
(car (prefetch iterator))
(multiple-value-bind (more key val) (funcall (iterator iterator))
(setf (prefetch iterator) (list more key val))
more)))
(defmethod next ((iterator hash-table-iterator))
(if (prefetch iterator)
(prog1 (rest (prefetch iterator))
(setf (prefetch iterator) NIL))
(multiple-value-bind (more key val) (funcall (iterator iterator))
(declare (ignore more))
(list key val))))
(defmethod (setf current) (value (iterator hash-table-iterator))
(setf (gethash (first (current iterator)) (object iterator)) value))
(defmethod step-functions ((iterator hash-table-iterator))
(let ((object (object iterator))
(prefetch (prefetch iterator))
(iterator (iterator iterator))
current)
(declare (type hash-table object))
(declare (type function iterator))
(values
(lambda ()
(if prefetch
(prog1 (setf current (rest prefetch))
(setf prefetch NIL))
(multiple-value-bind (more key val) (funcall iterator)
(declare (ignore more))
(setf current (list key val)))))
(lambda ()
(if prefetch
(car prefetch)
(multiple-value-bind (more key val) (funcall iterator)
(setf prefetch (list more key val))
more)))
(lambda (value)
(setf (gethash (first current) object) value))
(lambda ()))))
(defmethod make-iterator ((hash-table hash-table) &key)
(make-instance 'hash-table-iterator :object hash-table))
| true |
#|
This file is a part of for
(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.for.iterator)
(defgeneric has-more (iterator))
(defgeneric next (iterator))
(defgeneric current (iterator))
(defgeneric (setf current) (value iterator))
(defgeneric end (iterator))
(defgeneric make-iterator (object &key &allow-other-keys))
(defgeneric step-functions (iterator))
(defclass iterator ()
((object :initarg :object :accessor object)
(current :accessor current)))
(defmethod next :around ((iterator iterator))
(setf (slot-value iterator 'current) (call-next-method)))
(defmethod end ((iterator iterator)))
(defmethod step-functions ((iterator iterator))
(values (lambda () (next iterator))
(lambda () (has-more iterator))
(lambda (value) (setf (current iterator) value))
(lambda () (end iterator))))
(defclass list-iterator (iterator)
())
(defmethod initialize-instance :after ((iterator list-iterator) &key object)
(setf (object iterator) (cons NIL object)))
(defmethod has-more ((iterator list-iterator))
(cdr (object iterator)))
(defmethod next ((iterator list-iterator))
(setf (object iterator) (cdr (object iterator)))
(car (object iterator)))
(defmethod (setf current) (value (iterator list-iterator))
(setf (car (object iterator)) value))
(defmethod step-functions ((iterator list-iterator))
(let ((list (object iterator)))
(declare (type list list))
(values
(lambda ()
(setf list (cdr list))
(car list))
(lambda ()
(cdr list))
(lambda (value)
(setf (car list) value))
(lambda ()))))
(defmethod make-iterator ((list list) &key)
(make-instance 'list-iterator :object list))
(defclass vector-iterator (iterator)
((start :initarg :start :accessor start))
(:default-initargs :start 0))
(defmethod has-more ((iterator vector-iterator))
(< (start iterator) (length (object iterator))))
(defmethod next ((iterator vector-iterator))
(prog1 (aref (object iterator) (start iterator))
(incf (start iterator))))
(defmethod (setf current) (value (iterator vector-iterator))
(setf (aref (object iterator) (1- (start iterator))) value))
(defmethod step-functions ((iterator vector-iterator))
(let ((vec (object iterator))
(i (start iterator)))
(declare (type vector vec))
(declare (type (unsigned-byte 32) i))
(values
(lambda ()
(prog1 (aref vec i)
(incf i)))
(lambda ()
(< i (length vec)))
(lambda (value)
(setf (aref vec i) value))
(lambda ()))))
(defmethod make-iterator ((vector vector) &key (start 0))
(make-instance 'vector-iterator :object vector :start start))
(defclass array-iterator (vector-iterator)
((total-length :accessor total-length)))
(defmethod initialize-instance :after ((iterator array-iterator) &key object)
(setf (total-length iterator) (array-total-size object)))
(defmethod has-more ((iterator array-iterator))
(< (start iterator) (total-length iterator)))
(defmethod next ((iterator array-iterator))
(prog1 (row-major-aref (object iterator) (start iterator))
(incf (start iterator))))
(defmethod (setf current) (value (iterator array-iterator))
(setf (row-major-aref (object iterator) (1- (start iterator))) value))
(defmethod step-functions ((iterator array-iterator))
(let ((arr (object iterator))
(total (total-length iterator))
(i (start iterator)))
(declare (type vector arr))
(declare (type (unsigned-byte 32) total i))
(values
(lambda ()
(prog1 (row-major-aref arr i)
(incf i)))
(lambda ()
(< i total))
(lambda (value)
(setf (row-major-aref arr i) value))
(lambda ()))))
(defmethod make-iterator ((array array) &key (start 0))
(make-instance 'array-iterator :object array :start start))
(defclass sequence-iterator (iterator)
((iterator :accessor iterator)))
(defmethod initialize-instance :after ((iterator sequence-iterator) &key object start end)
(setf (iterator iterator) (multiple-value-list
(#+sbcl sb-sequence:make-sequence-iterator
#+abcl sequence:make-sequence-iterator
#-(or sbcl abcl) (lambda (&rest _)
(declare (ignore _))
(error "This implementation has extensible sequences, but is not supported by FOR. Please contact the maintainer."))
object :start start :end end))))
(defmethod has-more ((iterator sequence-iterator))
(destructuring-bind (state limit from-end step endp . _) (iterator iterator)
(declare (ignore _))
(not (funcall endp (object iterator) state limit from-end))))
(defmethod next ((iterator sequence-iterator))
(destructuring-bind (state limit from-end step endp element . _) (iterator iterator)
(declare (ignore limit endp _))
(prog1 (funcall element (object iterator) state)
(funcall step (object iterator) state from-end))))
(defmethod (setf current) (value (iterator sequence-iterator))
(destructuring-bind (state limit from-end step endp element set . _) (iterator iterator)
(declare (ignore limit from-end step endp element _))
(funcall set value (object iterator) state)))
(defmethod step-functions ((iterator sequence-iterator))
(let ((object (object iterator)))
(destructuring-bind (state limit from-end step endp element set . _) (iterator iterator)
(declare (ignore _))
(values
(lambda ()
(prog1 (funcall element object state)
(funcall step object state from-end)))
(lambda ()
(not (funcall endp object state limit from-end)))
(lambda (value)
(funcall set value object state))
(lambda ())))))
(defmethod make-iterator ((sequence sequence) &key)
(make-instance 'sequence-iterator :object sequence))
(defclass stream-iterator (iterator)
((buffer :accessor buffer)
(index :initform 1 :accessor index)
(limit :initform 1 :accessor limit)
(close-stream :initarg :close-stream :accessor close-stream)))
(defmethod initialize-instance :after ((iterator stream-iterator) &key (buffer-size 4096) object)
(setf (buffer iterator) (make-array buffer-size :element-type (stream-element-type object))))
(defmethod has-more ((iterator stream-iterator))
(when (= (index iterator) (limit iterator))
(setf (limit iterator) (read-sequence (buffer iterator) (object iterator)))
(setf (index iterator) 0))
(not (= 0 (limit iterator))))
(defmethod next ((iterator stream-iterator))
(prog1 (aref (buffer iterator) (index iterator))
(incf (index iterator))))
(defmethod (setf current) ((value integer) (iterator stream-iterator))
(write-byte value (object iterator)))
(defmethod (setf current) ((value character) (iterator stream-iterator))
(write-char value (object iterator)))
(defmethod (setf current) ((value sequence) (iterator stream-iterator))
(write-sequence value (object iterator)))
(defmethod end ((iterator stream-iterator))
(when (close-stream iterator)
(close (object iterator))))
(defmethod step-functions ((iterator stream-iterator))
(let ((object (object iterator))
(buffer (buffer iterator))
(index (index iterator))
(limit (limit iterator)))
(declare (type stream object))
(values
(lambda ()
(prog1 (aref buffer index)
(incf index)))
(lambda ()
(when (= index limit)
(setf limit (read-sequence buffer object))
(setf index 0))
(not (= 0 limit)))
(lambda (value)
(etypecase value
(integer (write-byte value object))
(character (write-char value object))
(sequence (write-sequence value object))))
(if (close-stream iterator)
(lambda ()
(close object))
(lambda ())))))
(defclass stream-line-iterator (iterator)
((buffer :initform NIL :accessor buffer)
(close-stream :initarg :close-stream :accessor close-stream)))
(defmethod has-more ((iterator stream-line-iterator))
(or (buffer iterator)
(setf (buffer iterator) (read-line (object iterator) NIL NIL))))
(defmethod next ((iterator stream-line-iterator))
(let ((buffer (buffer iterator)))
(cond (buffer
(setf (buffer iterator) NIL)
buffer)
(T
(read-line (object iterator))))))
(defmethod end ((iterator stream-line-iterator))
(when (close-stream iterator)
(close (object iterator))))
(defmethod step-functions ((iterator stream-line-iterator))
(let ((object (object iterator))
(buffer (buffer iterator)))
(values
(lambda ()
(cond (buffer
(setf buffer NIL)
buffer)
(T
(read-line object))))
(lambda ()
(or buffer
(setf buffer (read-line object NIL NIL))))
(lambda (value)
(declare (ignore value))
(error "Cannot write to a STREAM-LINE-ITERATOR."))
(if (close-stream iterator)
(lambda ()
(close object))
(lambda ())))))
(defmethod make-iterator ((stream stream) &key (buffer-size 4096) close-stream)
(case buffer-size
((:line :lines)
(make-instance 'stream-line-iterator :object stream :close-stream close-stream))
(T (make-instance 'stream-iterator :object stream :buffer-size buffer-size :close-stream close-stream))))
(defclass directory-iterator (list-iterator)
())
(defmethod initialize-instance :after ((iterator directory-iterator) &key object)
(setf (object iterator) (cons NIL (directory object))))
(defmethod make-iterator ((pathname pathname) &key buffer-size (element-type 'character))
(if (wild-pathname-p pathname)
(make-instance 'directory-iterator :object pathname)
(make-iterator (open pathname :element-type element-type) :buffer-size buffer-size :close-stream T)))
(defclass random-iterator (iterator)
((limit :initarg :limit :reader limit))
(:default-initargs
:limit 1.0f0))
(defmethod has-more ((iterator random-iterator))
T)
(defmethod next ((iterator random-iterator))
(random (limit iterator) (object iterator)))
(defmethod step-functions ((iterator random-iterator))
(let ((object (object iterator))
(limit (limit iterator)))
(values
(lambda ()
(random limit object))
(lambda ()
T)
(lambda (value)
(declare (ignore value))
(error "Cannot write to a RANDOM-ITERATOR."))
(lambda ()))))
(defmethod make-iterator ((random-state random-state) &key (limit 1.0))
(make-instance 'random-iterator :object random-state :limit limit))
(defclass package-iterator (iterator)
((prefetch :initform NIL :accessor prefetch))
(:default-initargs
:status '(:internal :external :inherited)))
(defmethod initialize-instance :after ((iterator package-iterator) &key object status)
(setf (object iterator) (org.shirakumo.for::package-iterator object status)))
(defmethod has-more ((iterator package-iterator))
(if (prefetch iterator)
(car (prefetch iterator))
(multiple-value-bind (more symb) (funcall (object iterator))
(setf (prefetch iterator) (cons more symb))
more)))
(defmethod next ((iterator package-iterator))
(if (prefetch iterator)
(prog1 (cdr (prefetch iterator))
(setf (prefetch iterator) NIL))
(nth-value 1 (funcall (object iterator)))))
(defmethod step-functions ((iterator package-iterator))
(let ((object (object iterator))
(prefetch (prefetch iterator)))
(values
(lambda ()
(if prefetch
(prog1 (cdr prefetch)
(setf prefetch NIL))
(nth-value 1 (funcall object))))
(lambda ()
(if prefetch
(car prefetch)
(multiple-value-bind (more symb) (funcall object)
(setf prefetch (cons more symb))
more)))
(lambda (value)
(declare (ignore value))
(error "Cannot write to a PACKAGE-ITERATOR."))
(lambda ()))))
(defmethod make-iterator ((package package) &key)
(make-instance 'package-iterator :object package))
(defclass hash-table-iterator (iterator)
((iterator :initform NIL :accessor iterator)
(prefetch :initform NIL :accessor prefetch)))
(defmethod initialize-instance :after ((iterator hash-table-iterator) &key object)
(setf (iterator iterator) (org.shirakumo.for::hash-table-iterator object)))
(defmethod has-more ((iterator hash-table-iterator))
(if (prefetch iterator)
(car (prefetch iterator))
(multiple-value-bind (more key val) (funcall (iterator iterator))
(setf (prefetch iterator) (list more key val))
more)))
(defmethod next ((iterator hash-table-iterator))
(if (prefetch iterator)
(prog1 (rest (prefetch iterator))
(setf (prefetch iterator) NIL))
(multiple-value-bind (more key val) (funcall (iterator iterator))
(declare (ignore more))
(list key val))))
(defmethod (setf current) (value (iterator hash-table-iterator))
(setf (gethash (first (current iterator)) (object iterator)) value))
(defmethod step-functions ((iterator hash-table-iterator))
(let ((object (object iterator))
(prefetch (prefetch iterator))
(iterator (iterator iterator))
current)
(declare (type hash-table object))
(declare (type function iterator))
(values
(lambda ()
(if prefetch
(prog1 (setf current (rest prefetch))
(setf prefetch NIL))
(multiple-value-bind (more key val) (funcall iterator)
(declare (ignore more))
(setf current (list key val)))))
(lambda ()
(if prefetch
(car prefetch)
(multiple-value-bind (more key val) (funcall iterator)
(setf prefetch (list more key val))
more)))
(lambda (value)
(setf (gethash (first current) object) value))
(lambda ()))))
(defmethod make-iterator ((hash-table hash-table) &key)
(make-instance 'hash-table-iterator :object hash-table))
|
[
{
"context": ";-*- Mode: Lisp -*-\n;;;; Author: Paul Dietz\n;;;; Created: Thu Aug 28 10:41:34 2003\n;;;; Cont",
"end": 49,
"score": 0.9998608827590942,
"start": 39,
"tag": "NAME",
"value": "Paul Dietz"
}
] |
programs/ansi-test/numbers/times.lsp
|
TeamSPoon/wam_common_lisp_devel_workspace
| 8 |
;-*- Mode: Lisp -*-
;;;; Author: Paul Dietz
;;;; Created: Thu Aug 28 10:41:34 2003
;;;; Contains: Tests of the multiplication function *
(deftest *.1
(*)
1)
(deftest *.2
(loop for x in *numbers*
unless (eql x (* x))
collect x)
nil)
(deftest *.3
(loop for x in *numbers*
for x1 = (* x 1)
for x2 = (* 1 x)
unless (and (eql x x1) (eql x x2) (eql x1 x2))
collect (list x x1 x2))
nil)
(deftest *.4
(loop for x in *numbers*
for x1 = (* x 0)
for x2 = (* 0 x)
unless (and (= x1 0) (= x2 0))
collect (list x x1 x2))
nil)
(deftest *.5
(loop for bound in '(1.0s0 1.0f0 1.0d0 1.0l0)
nconc
(loop for x = (random bound)
for x1 = (* x -1)
for x2 = (* -1 x)
for x3 = (* x bound)
for x4 = (* bound x)
repeat 1000
unless (and (eql (- x) x1) (eql (- x) x2)
(eql x x3) (eql x x4))
collect (list x x1 x2 x3 x4)))
nil)
(deftest *.6
(let* ((upper-bound (* 1000 1000 1000 1000))
(lower-bound (- upper-bound))
(spread (1+ (- upper-bound lower-bound))))
(loop for x = (random-from-interval upper-bound)
for y = (random-from-interval upper-bound)
for prod = (* x y)
for prod2 = (integer-times x y)
repeat 1000
unless (eql prod prod2)
collect (list x y prod prod2)))
nil)
(deftest *.7
(let* ((upper-bound (* 1000 1000 1000))
(lower-bound (- upper-bound))
(spread (1+ (- upper-bound lower-bound))))
(loop for x = (+ (rational (random (float spread 1.0f0))) lower-bound)
for y = (+ (rational (random (float spread 1.0f0))) lower-bound)
for prod = (* x y)
for prod2 = (rat-times x y)
repeat 1000
unless (eql prod prod2)
collect (list x y prod prod2)))
nil)
;; Testing of multiplication by integer constants
(deftest *.8
(let ((bound (isqrt most-positive-fixnum)))
(loop
for x = (random bound)
for y = (random bound)
for f = (eval `(function (lambda (z)
(declare (optimize (speed 3) (safety 0)))
(declare (type (integer 0 (,bound)) z))
(* ,x z))))
for prod = (funcall f y)
repeat 100
unless (and (eql prod (* x y))
(eql prod (integer-times x y)))
collect (progn (format t "Failed on ~A~%" (list x y prod))
(list x y prod (* x y) (integer-times x y)))))
nil)
(deftest *.9
(let* ((upper-bound (* 1000 1000 1000 1000)))
(flet ((%r () (random-from-interval upper-bound)))
(loop for xr = (%r)
for xc = (%r)
for x = (complex xr xc)
for yr = (%r)
for yc = (%r)
for y = (complex yr yc)
for prod = (* x y)
repeat 1000
unless (and (eql (realpart prod) (- (integer-times xr yr)
(integer-times xc yc)))
(eql (imagpart prod) (+ (integer-times xr yc)
(integer-times xc yr))))
collect (list x y prod))))
nil)
(deftest *.10
(let* ((upper-bound (* 1000 1000 1000 1000))
(lower-bound (- upper-bound))
(spread (1+ (- upper-bound lower-bound))))
(flet ((%r () (+ (rational (random (float spread 1.0f0))) lower-bound)))
(loop for xr = (%r)
for xc = (%r)
for x = (complex xr xc)
for yr = (%r)
for yc = (%r)
for y = (complex yr yc)
for prod = (* x y)
repeat 1000
unless (and (eql (realpart prod) (- (rat-times xr yr)
(rat-times xc yc)))
(eql (imagpart prod) (+ (rat-times xr yc)
(rat-times xc yr))))
collect (list x y prod))))
nil)
(deftest *.11
(let ((prod 1) (args nil))
(loop for i from 1 to (min 256 (1- call-arguments-limit))
do (push i args)
do (setq prod (* prod i))
always (eql (apply #'* args) prod)))
t)
(deftest *.12
(loop
for x in '(1.0s0 1.0f0 1.0d0 1.0l0)
for radix = (float-radix x)
for (k eps-r eps-f) = (multiple-value-list (find-epsilon x))
nconc
(loop for i from 1 to k
for y = (+ x (expt radix (- i)))
nconc
(loop for j from 1 to (- k i)
for z = (+ x (expt radix (- j)))
unless (eql (* y z)
(+ x
(expt radix (- i))
(expt radix (- j))
(expt radix (- (+ i j)))))
collect (list x i j))))
nil)
(deftest *.13
(loop
for x in '(1.0s0 1.0f0 1.0d0 1.0l0)
for radix = (float-radix x)
for (k eps-r eps-f) = (multiple-value-list (find-epsilon x))
nconc
(loop for i from 1 to k
for y = (- x (expt radix (- i)))
nconc
(loop for j from 1 to (- k i)
for z = (- x (expt radix (- j)))
unless (eql (* y z)
(+ x
(- (expt radix (- i)))
(- (expt radix (- j)))
(expt radix (- (+ i j)))))
collect (list x i j))))
nil)
;;; Float contagion
(deftest *.14
(let ((bound (- (sqrt most-positive-short-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'short-float))
collect (list x y p)))
nil)
(deftest *.15
(let ((bound (- (sqrt most-positive-single-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'single-float))
collect (list x y p)))
nil)
(deftest *.16
(let ((bound (- (sqrt most-positive-double-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'double-float))
collect (list x y p)))
nil)
(deftest *.17
(let ((bound (- (sqrt most-positive-long-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'long-float))
collect (list x y p)))
nil)
(deftest *.18
(let ((bound (- (sqrt most-positive-short-float) 1))
(bound2 (- (sqrt most-positive-single-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound2)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'single-float))
collect (list x y p)))
nil)
(deftest *.19
(let ((bound (- (sqrt most-positive-short-float) 1))
(bound2 (- (sqrt most-positive-double-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound2)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'double-float))
collect (list x y p)))
nil)
(deftest *.20
(let ((bound (- (sqrt most-positive-short-float) 1))
(bound2 (- (sqrt most-positive-long-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound2)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'long-float))
collect (list x y p)))
nil)
(deftest *.21
(let ((bound (- (sqrt most-positive-single-float) 1))
(bound2 (- (sqrt most-positive-double-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound2)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'double-float))
collect (list x y p)))
nil)
(deftest *.22
(let ((bound (- (sqrt most-positive-single-float) 1))
(bound2 (- (sqrt most-positive-long-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound2)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'long-float))
collect (list x y p)))
nil)
(deftest *.23
(let ((bound (- (sqrt most-positive-double-float) 1))
(bound2 (- (sqrt most-positive-long-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound2)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'long-float))
collect (list x y p)))
nil)
(deftest *.24
(loop
for type in '(short-float single-float double-float long-float)
for bits in '(13 24 50 50)
for bound = (ash 1 (floor bits 2))
nconc
(loop for i = (random bound)
for x = (coerce i type)
for j = (random bound)
for y = (coerce j type)
for prod = (* x y)
repeat 1000
unless (and (eql prod (coerce (* i j) type))
(eql prod (* y x)))
collect (list i j x y (* x y) (coerce (* i j) type))))
nil)
(deftest *.25
(loop
for type in '(short-float single-float double-float long-float)
for bits in '(13 24 50 50)
for bound = (ash 1 (- bits 2))
when (= (float-radix (coerce 1.0 type)) 2)
nconc
(loop for i = (random bound)
for x = (coerce i type)
for j = (* i 2)
for y = (coerce j type)
repeat 1000
unless (eql (* 2 x) y)
collect (list i j x (* 2 x) y)))
nil)
;;; Shows a compiler bug in sbcl/cmucl
(deftest *.26
(eqlt (funcall (compile nil
'(lambda (x y)
(declare (type (single-float -10.0 10.0) x)
(type (double-float -1.0d100 1.0d100) y))
(* x y)))
1.0f0 1.0d0)
1.0d0)
t)
(deftest *.27
(loop
for type in '(short-float single-float double-float long-float)
for bits in '(13 24 50 50)
for bound = (ash 1 (floor bits 2))
nconc
(loop for i = (random bound)
for x = (coerce i type)
for j = (random bound)
for y = (coerce j type)
for one = (coerce 1.0 type)
for cx = (complex one x)
for cy = (complex one y)
for prod = (* cx cy)
repeat 1000
unless (and (eql prod (complex (coerce (- 1 (* i j)) type)
(coerce (+ i j) type)))
(eql prod (* cy cx)))
collect (list type i j x y (* cx cy))))
nil)
;;; Test that explicit calls to macroexpand in subforms
;;; are done in the correct environment
(deftest *.28
(macrolet ((%m (z) z))
(values
(* (expand-in-current-env (%m 2)))
(* (expand-in-current-env (%m 3)) 4)
(* 5 (expand-in-current-env (%m 3)))))
2 12 15)
;;; Order of evaluation tests
(deftest times.order.1
(let ((i 0) x y)
(values
(* (progn (setf x (incf i)) 2)
(progn (setf y (incf i)) 3))
i x y))
6 2 1 2)
(deftest times.order.2
(let ((i 0) x y z)
(values
(* (progn (setf x (incf i)) 2)
(progn (setf y (incf i)) 3)
(progn (setf z (incf i)) 5))
i x y z))
30 3 1 2 3)
|
82423
|
;-*- Mode: Lisp -*-
;;;; Author: <NAME>
;;;; Created: Thu Aug 28 10:41:34 2003
;;;; Contains: Tests of the multiplication function *
(deftest *.1
(*)
1)
(deftest *.2
(loop for x in *numbers*
unless (eql x (* x))
collect x)
nil)
(deftest *.3
(loop for x in *numbers*
for x1 = (* x 1)
for x2 = (* 1 x)
unless (and (eql x x1) (eql x x2) (eql x1 x2))
collect (list x x1 x2))
nil)
(deftest *.4
(loop for x in *numbers*
for x1 = (* x 0)
for x2 = (* 0 x)
unless (and (= x1 0) (= x2 0))
collect (list x x1 x2))
nil)
(deftest *.5
(loop for bound in '(1.0s0 1.0f0 1.0d0 1.0l0)
nconc
(loop for x = (random bound)
for x1 = (* x -1)
for x2 = (* -1 x)
for x3 = (* x bound)
for x4 = (* bound x)
repeat 1000
unless (and (eql (- x) x1) (eql (- x) x2)
(eql x x3) (eql x x4))
collect (list x x1 x2 x3 x4)))
nil)
(deftest *.6
(let* ((upper-bound (* 1000 1000 1000 1000))
(lower-bound (- upper-bound))
(spread (1+ (- upper-bound lower-bound))))
(loop for x = (random-from-interval upper-bound)
for y = (random-from-interval upper-bound)
for prod = (* x y)
for prod2 = (integer-times x y)
repeat 1000
unless (eql prod prod2)
collect (list x y prod prod2)))
nil)
(deftest *.7
(let* ((upper-bound (* 1000 1000 1000))
(lower-bound (- upper-bound))
(spread (1+ (- upper-bound lower-bound))))
(loop for x = (+ (rational (random (float spread 1.0f0))) lower-bound)
for y = (+ (rational (random (float spread 1.0f0))) lower-bound)
for prod = (* x y)
for prod2 = (rat-times x y)
repeat 1000
unless (eql prod prod2)
collect (list x y prod prod2)))
nil)
;; Testing of multiplication by integer constants
(deftest *.8
(let ((bound (isqrt most-positive-fixnum)))
(loop
for x = (random bound)
for y = (random bound)
for f = (eval `(function (lambda (z)
(declare (optimize (speed 3) (safety 0)))
(declare (type (integer 0 (,bound)) z))
(* ,x z))))
for prod = (funcall f y)
repeat 100
unless (and (eql prod (* x y))
(eql prod (integer-times x y)))
collect (progn (format t "Failed on ~A~%" (list x y prod))
(list x y prod (* x y) (integer-times x y)))))
nil)
(deftest *.9
(let* ((upper-bound (* 1000 1000 1000 1000)))
(flet ((%r () (random-from-interval upper-bound)))
(loop for xr = (%r)
for xc = (%r)
for x = (complex xr xc)
for yr = (%r)
for yc = (%r)
for y = (complex yr yc)
for prod = (* x y)
repeat 1000
unless (and (eql (realpart prod) (- (integer-times xr yr)
(integer-times xc yc)))
(eql (imagpart prod) (+ (integer-times xr yc)
(integer-times xc yr))))
collect (list x y prod))))
nil)
(deftest *.10
(let* ((upper-bound (* 1000 1000 1000 1000))
(lower-bound (- upper-bound))
(spread (1+ (- upper-bound lower-bound))))
(flet ((%r () (+ (rational (random (float spread 1.0f0))) lower-bound)))
(loop for xr = (%r)
for xc = (%r)
for x = (complex xr xc)
for yr = (%r)
for yc = (%r)
for y = (complex yr yc)
for prod = (* x y)
repeat 1000
unless (and (eql (realpart prod) (- (rat-times xr yr)
(rat-times xc yc)))
(eql (imagpart prod) (+ (rat-times xr yc)
(rat-times xc yr))))
collect (list x y prod))))
nil)
(deftest *.11
(let ((prod 1) (args nil))
(loop for i from 1 to (min 256 (1- call-arguments-limit))
do (push i args)
do (setq prod (* prod i))
always (eql (apply #'* args) prod)))
t)
(deftest *.12
(loop
for x in '(1.0s0 1.0f0 1.0d0 1.0l0)
for radix = (float-radix x)
for (k eps-r eps-f) = (multiple-value-list (find-epsilon x))
nconc
(loop for i from 1 to k
for y = (+ x (expt radix (- i)))
nconc
(loop for j from 1 to (- k i)
for z = (+ x (expt radix (- j)))
unless (eql (* y z)
(+ x
(expt radix (- i))
(expt radix (- j))
(expt radix (- (+ i j)))))
collect (list x i j))))
nil)
(deftest *.13
(loop
for x in '(1.0s0 1.0f0 1.0d0 1.0l0)
for radix = (float-radix x)
for (k eps-r eps-f) = (multiple-value-list (find-epsilon x))
nconc
(loop for i from 1 to k
for y = (- x (expt radix (- i)))
nconc
(loop for j from 1 to (- k i)
for z = (- x (expt radix (- j)))
unless (eql (* y z)
(+ x
(- (expt radix (- i)))
(- (expt radix (- j)))
(expt radix (- (+ i j)))))
collect (list x i j))))
nil)
;;; Float contagion
(deftest *.14
(let ((bound (- (sqrt most-positive-short-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'short-float))
collect (list x y p)))
nil)
(deftest *.15
(let ((bound (- (sqrt most-positive-single-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'single-float))
collect (list x y p)))
nil)
(deftest *.16
(let ((bound (- (sqrt most-positive-double-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'double-float))
collect (list x y p)))
nil)
(deftest *.17
(let ((bound (- (sqrt most-positive-long-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'long-float))
collect (list x y p)))
nil)
(deftest *.18
(let ((bound (- (sqrt most-positive-short-float) 1))
(bound2 (- (sqrt most-positive-single-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound2)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'single-float))
collect (list x y p)))
nil)
(deftest *.19
(let ((bound (- (sqrt most-positive-short-float) 1))
(bound2 (- (sqrt most-positive-double-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound2)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'double-float))
collect (list x y p)))
nil)
(deftest *.20
(let ((bound (- (sqrt most-positive-short-float) 1))
(bound2 (- (sqrt most-positive-long-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound2)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'long-float))
collect (list x y p)))
nil)
(deftest *.21
(let ((bound (- (sqrt most-positive-single-float) 1))
(bound2 (- (sqrt most-positive-double-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound2)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'double-float))
collect (list x y p)))
nil)
(deftest *.22
(let ((bound (- (sqrt most-positive-single-float) 1))
(bound2 (- (sqrt most-positive-long-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound2)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'long-float))
collect (list x y p)))
nil)
(deftest *.23
(let ((bound (- (sqrt most-positive-double-float) 1))
(bound2 (- (sqrt most-positive-long-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound2)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'long-float))
collect (list x y p)))
nil)
(deftest *.24
(loop
for type in '(short-float single-float double-float long-float)
for bits in '(13 24 50 50)
for bound = (ash 1 (floor bits 2))
nconc
(loop for i = (random bound)
for x = (coerce i type)
for j = (random bound)
for y = (coerce j type)
for prod = (* x y)
repeat 1000
unless (and (eql prod (coerce (* i j) type))
(eql prod (* y x)))
collect (list i j x y (* x y) (coerce (* i j) type))))
nil)
(deftest *.25
(loop
for type in '(short-float single-float double-float long-float)
for bits in '(13 24 50 50)
for bound = (ash 1 (- bits 2))
when (= (float-radix (coerce 1.0 type)) 2)
nconc
(loop for i = (random bound)
for x = (coerce i type)
for j = (* i 2)
for y = (coerce j type)
repeat 1000
unless (eql (* 2 x) y)
collect (list i j x (* 2 x) y)))
nil)
;;; Shows a compiler bug in sbcl/cmucl
(deftest *.26
(eqlt (funcall (compile nil
'(lambda (x y)
(declare (type (single-float -10.0 10.0) x)
(type (double-float -1.0d100 1.0d100) y))
(* x y)))
1.0f0 1.0d0)
1.0d0)
t)
(deftest *.27
(loop
for type in '(short-float single-float double-float long-float)
for bits in '(13 24 50 50)
for bound = (ash 1 (floor bits 2))
nconc
(loop for i = (random bound)
for x = (coerce i type)
for j = (random bound)
for y = (coerce j type)
for one = (coerce 1.0 type)
for cx = (complex one x)
for cy = (complex one y)
for prod = (* cx cy)
repeat 1000
unless (and (eql prod (complex (coerce (- 1 (* i j)) type)
(coerce (+ i j) type)))
(eql prod (* cy cx)))
collect (list type i j x y (* cx cy))))
nil)
;;; Test that explicit calls to macroexpand in subforms
;;; are done in the correct environment
(deftest *.28
(macrolet ((%m (z) z))
(values
(* (expand-in-current-env (%m 2)))
(* (expand-in-current-env (%m 3)) 4)
(* 5 (expand-in-current-env (%m 3)))))
2 12 15)
;;; Order of evaluation tests
(deftest times.order.1
(let ((i 0) x y)
(values
(* (progn (setf x (incf i)) 2)
(progn (setf y (incf i)) 3))
i x y))
6 2 1 2)
(deftest times.order.2
(let ((i 0) x y z)
(values
(* (progn (setf x (incf i)) 2)
(progn (setf y (incf i)) 3)
(progn (setf z (incf i)) 5))
i x y z))
30 3 1 2 3)
| true |
;-*- Mode: Lisp -*-
;;;; Author: PI:NAME:<NAME>END_PI
;;;; Created: Thu Aug 28 10:41:34 2003
;;;; Contains: Tests of the multiplication function *
(deftest *.1
(*)
1)
(deftest *.2
(loop for x in *numbers*
unless (eql x (* x))
collect x)
nil)
(deftest *.3
(loop for x in *numbers*
for x1 = (* x 1)
for x2 = (* 1 x)
unless (and (eql x x1) (eql x x2) (eql x1 x2))
collect (list x x1 x2))
nil)
(deftest *.4
(loop for x in *numbers*
for x1 = (* x 0)
for x2 = (* 0 x)
unless (and (= x1 0) (= x2 0))
collect (list x x1 x2))
nil)
(deftest *.5
(loop for bound in '(1.0s0 1.0f0 1.0d0 1.0l0)
nconc
(loop for x = (random bound)
for x1 = (* x -1)
for x2 = (* -1 x)
for x3 = (* x bound)
for x4 = (* bound x)
repeat 1000
unless (and (eql (- x) x1) (eql (- x) x2)
(eql x x3) (eql x x4))
collect (list x x1 x2 x3 x4)))
nil)
(deftest *.6
(let* ((upper-bound (* 1000 1000 1000 1000))
(lower-bound (- upper-bound))
(spread (1+ (- upper-bound lower-bound))))
(loop for x = (random-from-interval upper-bound)
for y = (random-from-interval upper-bound)
for prod = (* x y)
for prod2 = (integer-times x y)
repeat 1000
unless (eql prod prod2)
collect (list x y prod prod2)))
nil)
(deftest *.7
(let* ((upper-bound (* 1000 1000 1000))
(lower-bound (- upper-bound))
(spread (1+ (- upper-bound lower-bound))))
(loop for x = (+ (rational (random (float spread 1.0f0))) lower-bound)
for y = (+ (rational (random (float spread 1.0f0))) lower-bound)
for prod = (* x y)
for prod2 = (rat-times x y)
repeat 1000
unless (eql prod prod2)
collect (list x y prod prod2)))
nil)
;; Testing of multiplication by integer constants
(deftest *.8
(let ((bound (isqrt most-positive-fixnum)))
(loop
for x = (random bound)
for y = (random bound)
for f = (eval `(function (lambda (z)
(declare (optimize (speed 3) (safety 0)))
(declare (type (integer 0 (,bound)) z))
(* ,x z))))
for prod = (funcall f y)
repeat 100
unless (and (eql prod (* x y))
(eql prod (integer-times x y)))
collect (progn (format t "Failed on ~A~%" (list x y prod))
(list x y prod (* x y) (integer-times x y)))))
nil)
(deftest *.9
(let* ((upper-bound (* 1000 1000 1000 1000)))
(flet ((%r () (random-from-interval upper-bound)))
(loop for xr = (%r)
for xc = (%r)
for x = (complex xr xc)
for yr = (%r)
for yc = (%r)
for y = (complex yr yc)
for prod = (* x y)
repeat 1000
unless (and (eql (realpart prod) (- (integer-times xr yr)
(integer-times xc yc)))
(eql (imagpart prod) (+ (integer-times xr yc)
(integer-times xc yr))))
collect (list x y prod))))
nil)
(deftest *.10
(let* ((upper-bound (* 1000 1000 1000 1000))
(lower-bound (- upper-bound))
(spread (1+ (- upper-bound lower-bound))))
(flet ((%r () (+ (rational (random (float spread 1.0f0))) lower-bound)))
(loop for xr = (%r)
for xc = (%r)
for x = (complex xr xc)
for yr = (%r)
for yc = (%r)
for y = (complex yr yc)
for prod = (* x y)
repeat 1000
unless (and (eql (realpart prod) (- (rat-times xr yr)
(rat-times xc yc)))
(eql (imagpart prod) (+ (rat-times xr yc)
(rat-times xc yr))))
collect (list x y prod))))
nil)
(deftest *.11
(let ((prod 1) (args nil))
(loop for i from 1 to (min 256 (1- call-arguments-limit))
do (push i args)
do (setq prod (* prod i))
always (eql (apply #'* args) prod)))
t)
(deftest *.12
(loop
for x in '(1.0s0 1.0f0 1.0d0 1.0l0)
for radix = (float-radix x)
for (k eps-r eps-f) = (multiple-value-list (find-epsilon x))
nconc
(loop for i from 1 to k
for y = (+ x (expt radix (- i)))
nconc
(loop for j from 1 to (- k i)
for z = (+ x (expt radix (- j)))
unless (eql (* y z)
(+ x
(expt radix (- i))
(expt radix (- j))
(expt radix (- (+ i j)))))
collect (list x i j))))
nil)
(deftest *.13
(loop
for x in '(1.0s0 1.0f0 1.0d0 1.0l0)
for radix = (float-radix x)
for (k eps-r eps-f) = (multiple-value-list (find-epsilon x))
nconc
(loop for i from 1 to k
for y = (- x (expt radix (- i)))
nconc
(loop for j from 1 to (- k i)
for z = (- x (expt radix (- j)))
unless (eql (* y z)
(+ x
(- (expt radix (- i)))
(- (expt radix (- j)))
(expt radix (- (+ i j)))))
collect (list x i j))))
nil)
;;; Float contagion
(deftest *.14
(let ((bound (- (sqrt most-positive-short-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'short-float))
collect (list x y p)))
nil)
(deftest *.15
(let ((bound (- (sqrt most-positive-single-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'single-float))
collect (list x y p)))
nil)
(deftest *.16
(let ((bound (- (sqrt most-positive-double-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'double-float))
collect (list x y p)))
nil)
(deftest *.17
(let ((bound (- (sqrt most-positive-long-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'long-float))
collect (list x y p)))
nil)
(deftest *.18
(let ((bound (- (sqrt most-positive-short-float) 1))
(bound2 (- (sqrt most-positive-single-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound2)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'single-float))
collect (list x y p)))
nil)
(deftest *.19
(let ((bound (- (sqrt most-positive-short-float) 1))
(bound2 (- (sqrt most-positive-double-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound2)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'double-float))
collect (list x y p)))
nil)
(deftest *.20
(let ((bound (- (sqrt most-positive-short-float) 1))
(bound2 (- (sqrt most-positive-long-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound2)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'long-float))
collect (list x y p)))
nil)
(deftest *.21
(let ((bound (- (sqrt most-positive-single-float) 1))
(bound2 (- (sqrt most-positive-double-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound2)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'double-float))
collect (list x y p)))
nil)
(deftest *.22
(let ((bound (- (sqrt most-positive-single-float) 1))
(bound2 (- (sqrt most-positive-long-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound2)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'long-float))
collect (list x y p)))
nil)
(deftest *.23
(let ((bound (- (sqrt most-positive-double-float) 1))
(bound2 (- (sqrt most-positive-long-float) 1)))
(loop for x = (random-from-interval bound)
for y = (random-from-interval bound2)
for p = (* x y)
repeat 1000
unless (and (eql p (* y x))
(typep p 'long-float))
collect (list x y p)))
nil)
(deftest *.24
(loop
for type in '(short-float single-float double-float long-float)
for bits in '(13 24 50 50)
for bound = (ash 1 (floor bits 2))
nconc
(loop for i = (random bound)
for x = (coerce i type)
for j = (random bound)
for y = (coerce j type)
for prod = (* x y)
repeat 1000
unless (and (eql prod (coerce (* i j) type))
(eql prod (* y x)))
collect (list i j x y (* x y) (coerce (* i j) type))))
nil)
(deftest *.25
(loop
for type in '(short-float single-float double-float long-float)
for bits in '(13 24 50 50)
for bound = (ash 1 (- bits 2))
when (= (float-radix (coerce 1.0 type)) 2)
nconc
(loop for i = (random bound)
for x = (coerce i type)
for j = (* i 2)
for y = (coerce j type)
repeat 1000
unless (eql (* 2 x) y)
collect (list i j x (* 2 x) y)))
nil)
;;; Shows a compiler bug in sbcl/cmucl
(deftest *.26
(eqlt (funcall (compile nil
'(lambda (x y)
(declare (type (single-float -10.0 10.0) x)
(type (double-float -1.0d100 1.0d100) y))
(* x y)))
1.0f0 1.0d0)
1.0d0)
t)
(deftest *.27
(loop
for type in '(short-float single-float double-float long-float)
for bits in '(13 24 50 50)
for bound = (ash 1 (floor bits 2))
nconc
(loop for i = (random bound)
for x = (coerce i type)
for j = (random bound)
for y = (coerce j type)
for one = (coerce 1.0 type)
for cx = (complex one x)
for cy = (complex one y)
for prod = (* cx cy)
repeat 1000
unless (and (eql prod (complex (coerce (- 1 (* i j)) type)
(coerce (+ i j) type)))
(eql prod (* cy cx)))
collect (list type i j x y (* cx cy))))
nil)
;;; Test that explicit calls to macroexpand in subforms
;;; are done in the correct environment
(deftest *.28
(macrolet ((%m (z) z))
(values
(* (expand-in-current-env (%m 2)))
(* (expand-in-current-env (%m 3)) 4)
(* 5 (expand-in-current-env (%m 3)))))
2 12 15)
;;; Order of evaluation tests
(deftest times.order.1
(let ((i 0) x y)
(values
(* (progn (setf x (incf i)) 2)
(progn (setf y (incf i)) 3))
i x y))
6 2 1 2)
(deftest times.order.2
(let ((i 0) x y z)
(values
(* (progn (setf x (incf i)) 2)
(progn (setf y (incf i)) 3)
(progn (setf z (incf i)) 5))
i x y z))
30 3 1 2 3)
|
[
{
"context": "n Common Lisp.\"\n :version \"0.0.1\"\n :author \"Augustus Huang <[email protected]>\"\n :components ((:fil",
"end": 188,
"score": 0.9998953938484192,
"start": 174,
"tag": "NAME",
"value": "Augustus Huang"
},
{
"context": " :version \"0.0.1\"\n :author \"Augustus Huang <[email protected]>\"\n :components ((:file \"package\")\n\t\t (:file \"t",
"end": 213,
"score": 0.9999279975891113,
"start": 190,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " of brainluck.\"\n :version \"0.0.1\"\n :author \"Augustus Huang <[email protected]>\"\n :components ((:fil",
"end": 470,
"score": 0.999894917011261,
"start": 456,
"tag": "NAME",
"value": "Augustus Huang"
},
{
"context": " :version \"0.0.1\"\n :author \"Augustus Huang <[email protected]>\"\n :components ((:file \"bf-test\")))\n",
"end": 495,
"score": 0.9999291896820068,
"start": 472,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
brainluck.asd
|
AugustusHuang/brainluck
| 1 |
(in-package :asdf-user)
(defsystem :brainluck
:name "brainluck"
:description "Brainluck, a Brainfuck interpreter in Common Lisp."
:version "0.0.1"
:author "Augustus Huang <[email protected]>"
:components ((:file "package")
(:file "top" :depends-on ("package"))))
(defsystem :brainluck.test
:depends-on (:brainluck)
:name "brainluck-test"
:description "Test suite of brainluck."
:version "0.0.1"
:author "Augustus Huang <[email protected]>"
:components ((:file "bf-test")))
|
43598
|
(in-package :asdf-user)
(defsystem :brainluck
:name "brainluck"
:description "Brainluck, a Brainfuck interpreter in Common Lisp."
:version "0.0.1"
:author "<NAME> <<EMAIL>>"
:components ((:file "package")
(:file "top" :depends-on ("package"))))
(defsystem :brainluck.test
:depends-on (:brainluck)
:name "brainluck-test"
:description "Test suite of brainluck."
:version "0.0.1"
:author "<NAME> <<EMAIL>>"
:components ((:file "bf-test")))
| true |
(in-package :asdf-user)
(defsystem :brainluck
:name "brainluck"
:description "Brainluck, a Brainfuck interpreter in Common Lisp."
:version "0.0.1"
:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:components ((:file "package")
(:file "top" :depends-on ("package"))))
(defsystem :brainluck.test
:depends-on (:brainluck)
:name "brainluck-test"
:description "Test suite of brainluck."
:version "0.0.1"
:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:components ((:file "bf-test")))
|
[
{
"context": "tion \"Re-implementation of 'cl-annot', authored by Tomohiro Matsuyama.\"\n :license \"WTFPL\"\n :author \"YOKOTA Yuki <y2q.",
"end": 109,
"score": 0.9998481869697571,
"start": 91,
"tag": "NAME",
"value": "Tomohiro Matsuyama"
},
{
"context": "omohiro Matsuyama.\"\n :license \"WTFPL\"\n :author \"YOKOTA Yuki <[email protected]>\"\n :depends-on (#:alexa",
"end": 153,
"score": 0.9998188018798828,
"start": 142,
"tag": "NAME",
"value": "YOKOTA Yuki"
},
{
"context": "yama.\"\n :license \"WTFPL\"\n :author \"YOKOTA Yuki <[email protected]>\"\n :depends-on (#:alexandria #:named-readtables)",
"end": 178,
"score": 0.9999305605888367,
"start": 155,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
cl-annot-revisit.asd
|
y2q-actionman/cl-annot-revisit
| 0 |
(defsystem #:cl-annot-revisit
:description "Re-implementation of 'cl-annot', authored by Tomohiro Matsuyama."
:license "WTFPL"
:author "YOKOTA Yuki <[email protected]>"
:depends-on (#:alexandria #:named-readtables)
:serial t
:components ((:file "package")
(:module "at-macro"
:components
((:file "package")
(:file "condition" :depends-on ("package"))
(:file "util" :depends-on ("package"))
(:file "eval-when" :depends-on ("package"))
(:file "form-traversal" :depends-on ("package"))
(:file "declaration" :depends-on ("util" "form-traversal"))
(:file "declamation" :depends-on ("declaration"))
(:file "documentation" :depends-on ("util" "form-traversal"))
(:file "export" :depends-on ("util" "form-traversal"))
(:file "defclass" :depends-on ("export"))
(:file "defstruct" :depends-on ("defclass"
"documentation"))
(:file "slot" :depends-on ("package"))))
(:module "at-syntax"
:serial t
:components
((:file "package")
(:file "reader")
(:file "definitions"))))
:in-order-to ((test-op (test-op #:cl-annot-revisit-test))))
|
47929
|
(defsystem #:cl-annot-revisit
:description "Re-implementation of 'cl-annot', authored by <NAME>."
:license "WTFPL"
:author "<NAME> <<EMAIL>>"
:depends-on (#:alexandria #:named-readtables)
:serial t
:components ((:file "package")
(:module "at-macro"
:components
((:file "package")
(:file "condition" :depends-on ("package"))
(:file "util" :depends-on ("package"))
(:file "eval-when" :depends-on ("package"))
(:file "form-traversal" :depends-on ("package"))
(:file "declaration" :depends-on ("util" "form-traversal"))
(:file "declamation" :depends-on ("declaration"))
(:file "documentation" :depends-on ("util" "form-traversal"))
(:file "export" :depends-on ("util" "form-traversal"))
(:file "defclass" :depends-on ("export"))
(:file "defstruct" :depends-on ("defclass"
"documentation"))
(:file "slot" :depends-on ("package"))))
(:module "at-syntax"
:serial t
:components
((:file "package")
(:file "reader")
(:file "definitions"))))
:in-order-to ((test-op (test-op #:cl-annot-revisit-test))))
| true |
(defsystem #:cl-annot-revisit
:description "Re-implementation of 'cl-annot', authored by PI:NAME:<NAME>END_PI."
:license "WTFPL"
:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:depends-on (#:alexandria #:named-readtables)
:serial t
:components ((:file "package")
(:module "at-macro"
:components
((:file "package")
(:file "condition" :depends-on ("package"))
(:file "util" :depends-on ("package"))
(:file "eval-when" :depends-on ("package"))
(:file "form-traversal" :depends-on ("package"))
(:file "declaration" :depends-on ("util" "form-traversal"))
(:file "declamation" :depends-on ("declaration"))
(:file "documentation" :depends-on ("util" "form-traversal"))
(:file "export" :depends-on ("util" "form-traversal"))
(:file "defclass" :depends-on ("export"))
(:file "defstruct" :depends-on ("defclass"
"documentation"))
(:file "slot" :depends-on ("package"))))
(:module "at-syntax"
:serial t
:components
((:file "package")
(:file "reader")
(:file "definitions"))))
:in-order-to ((test-op (test-op #:cl-annot-revisit-test))))
|
[
{
"context": ";;;\n;;; src/repo.lisp\n;;; ©2022 James Hunt\n;;;\n;;; This file defines routines for interactin",
"end": 42,
"score": 0.9997944831848145,
"start": 32,
"tag": "NAME",
"value": "James Hunt"
}
] |
src/repo.lisp
|
jhunt/buildr
| 0 |
;;;
;;; src/repo.lisp
;;; ©2022 James Hunt
;;;
;;; This file defines routines for interacting
;;; with configured git repositories. Several
;;; of these are wrappers around their GIT-*
;;; counterparts; REPO-CLONE wraps GIT-CLONE to
;;; supply all of the url, branch, and key path
;;; arguments on your behalf, for example.
;;;
(in-package #:buildr)
(defsimpleclass repo
(url key branch workdir))
(defun repo-path (repo relative)
"Formulate a new path, relative to the repository working directory"
(format nil "~A/~A" (repo-workdir repo) relative))
(defmacro with-fresh-repo ((var repo) &body body)
"Allocates a fresh copy of REPO, with a new temporary WORKDIR bound"
(let ((wd (gensym))
(tmp (gensym)))
`(with-workdir (,wd)
(let* ((,tmp ,repo)
(,var (make-repo :url (repo-url ,tmp)
:key (repo-key ,tmp)
:branch (repo-branch ,tmp)
:workdir ,wd)))
,@body))))
(defun repo-clone (repo)
"Clone the REPO into its working directory"
(git-clone (repo-workdir repo)
(repo-url repo)
(repo-branch repo)
(repo-key repo)))
(defun repo-dirty? (repo)
"Predicate to check if there are changes in WORKDIR that need to be committed"
(git-dirty? (repo-workdir repo)))
(defun repo-commit (repo msg)
"Commit all new and modified files in WORKDIR, using MSG as the commit log message"
(git-commit (repo-workdir repo) msg))
(defun repo-push (repo)
"Push the git commits from the local working copy to its upstream origin (same branch)"
(git-push (repo-workdir repo)
(repo-branch repo)))
(defun repo-head-sha1 (repo)
"Get the HEAD SHA1 commit-ish from the working copy"
(git-head-sha1 (repo-workdir repo)))
(defun repo-read-config (repo)
"Read the .buildr.yml file from the REPO working directory"
(let ((raw (ignore-errors
(yaml:parse
(pathname
(format nil "~A.buildr.yml"
(repo-workdir repo)))))))
(when raw
(loop for k being each hash-key in raw
for v being each hash-value in raw
do
(setf (gethash k raw)
`(:target ,(or (gethash "target" v)
"buildr-rebase")
:rebase ,(gethash "rebase" v)))))
raw))
|
10600
|
;;;
;;; src/repo.lisp
;;; ©2022 <NAME>
;;;
;;; This file defines routines for interacting
;;; with configured git repositories. Several
;;; of these are wrappers around their GIT-*
;;; counterparts; REPO-CLONE wraps GIT-CLONE to
;;; supply all of the url, branch, and key path
;;; arguments on your behalf, for example.
;;;
(in-package #:buildr)
(defsimpleclass repo
(url key branch workdir))
(defun repo-path (repo relative)
"Formulate a new path, relative to the repository working directory"
(format nil "~A/~A" (repo-workdir repo) relative))
(defmacro with-fresh-repo ((var repo) &body body)
"Allocates a fresh copy of REPO, with a new temporary WORKDIR bound"
(let ((wd (gensym))
(tmp (gensym)))
`(with-workdir (,wd)
(let* ((,tmp ,repo)
(,var (make-repo :url (repo-url ,tmp)
:key (repo-key ,tmp)
:branch (repo-branch ,tmp)
:workdir ,wd)))
,@body))))
(defun repo-clone (repo)
"Clone the REPO into its working directory"
(git-clone (repo-workdir repo)
(repo-url repo)
(repo-branch repo)
(repo-key repo)))
(defun repo-dirty? (repo)
"Predicate to check if there are changes in WORKDIR that need to be committed"
(git-dirty? (repo-workdir repo)))
(defun repo-commit (repo msg)
"Commit all new and modified files in WORKDIR, using MSG as the commit log message"
(git-commit (repo-workdir repo) msg))
(defun repo-push (repo)
"Push the git commits from the local working copy to its upstream origin (same branch)"
(git-push (repo-workdir repo)
(repo-branch repo)))
(defun repo-head-sha1 (repo)
"Get the HEAD SHA1 commit-ish from the working copy"
(git-head-sha1 (repo-workdir repo)))
(defun repo-read-config (repo)
"Read the .buildr.yml file from the REPO working directory"
(let ((raw (ignore-errors
(yaml:parse
(pathname
(format nil "~A.buildr.yml"
(repo-workdir repo)))))))
(when raw
(loop for k being each hash-key in raw
for v being each hash-value in raw
do
(setf (gethash k raw)
`(:target ,(or (gethash "target" v)
"buildr-rebase")
:rebase ,(gethash "rebase" v)))))
raw))
| true |
;;;
;;; src/repo.lisp
;;; ©2022 PI:NAME:<NAME>END_PI
;;;
;;; This file defines routines for interacting
;;; with configured git repositories. Several
;;; of these are wrappers around their GIT-*
;;; counterparts; REPO-CLONE wraps GIT-CLONE to
;;; supply all of the url, branch, and key path
;;; arguments on your behalf, for example.
;;;
(in-package #:buildr)
(defsimpleclass repo
(url key branch workdir))
(defun repo-path (repo relative)
"Formulate a new path, relative to the repository working directory"
(format nil "~A/~A" (repo-workdir repo) relative))
(defmacro with-fresh-repo ((var repo) &body body)
"Allocates a fresh copy of REPO, with a new temporary WORKDIR bound"
(let ((wd (gensym))
(tmp (gensym)))
`(with-workdir (,wd)
(let* ((,tmp ,repo)
(,var (make-repo :url (repo-url ,tmp)
:key (repo-key ,tmp)
:branch (repo-branch ,tmp)
:workdir ,wd)))
,@body))))
(defun repo-clone (repo)
"Clone the REPO into its working directory"
(git-clone (repo-workdir repo)
(repo-url repo)
(repo-branch repo)
(repo-key repo)))
(defun repo-dirty? (repo)
"Predicate to check if there are changes in WORKDIR that need to be committed"
(git-dirty? (repo-workdir repo)))
(defun repo-commit (repo msg)
"Commit all new and modified files in WORKDIR, using MSG as the commit log message"
(git-commit (repo-workdir repo) msg))
(defun repo-push (repo)
"Push the git commits from the local working copy to its upstream origin (same branch)"
(git-push (repo-workdir repo)
(repo-branch repo)))
(defun repo-head-sha1 (repo)
"Get the HEAD SHA1 commit-ish from the working copy"
(git-head-sha1 (repo-workdir repo)))
(defun repo-read-config (repo)
"Read the .buildr.yml file from the REPO working directory"
(let ((raw (ignore-errors
(yaml:parse
(pathname
(format nil "~A.buildr.yml"
(repo-workdir repo)))))))
(when raw
(loop for k being each hash-key in raw
for v being each hash-value in raw
do
(setf (gethash k raw)
`(:target ,(or (gethash "target" v)
"buildr-rebase")
:rebase ,(gethash "rebase" v)))))
raw))
|
[
{
"context": "t of Maiden\n (c) 2016 Shirakumo http://tymoon.eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n",
"end": 90,
"score": 0.9998681545257568,
"start": 72,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "umo http://tymoon.eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(in-package #:maiden-use",
"end": 115,
"score": 0.9998862147331238,
"start": 101,
"tag": "NAME",
"value": "Nicolas Hafner"
},
{
"context": ".eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(in-package #:maiden-user)\n(defpackage #:mai",
"end": 135,
"score": 0.9998968839645386,
"start": 117,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
agents/weather/package.lisp
|
Shirakumo/maiden
| 50 |
#|
This file is a part of Maiden
(c) 2016 Shirakumo http://tymoon.eu ([email protected])
Author: Nicolas Hafner <[email protected]>
|#
(in-package #:maiden-user)
(defpackage #:maiden-weather
(:nicknames #:org.shirakumo.maiden.agents.weather)
(:use #:cl #:maiden #:maiden-api-access #:maiden-storage #:maiden-client-entities #:maiden-commands)
;; weather.lisp
(:export
#:weather-data
#:location-coordinates
#:location-weather-data
#:format-weather-data
#:format-daily-forecast
#:weather
#:weather-dwim
#:weather-location
#:forecast-location
#:weather-user
#:forecast-user))
|
71149
|
#|
This file is a part of Maiden
(c) 2016 Shirakumo http://tymoon.eu (<EMAIL>)
Author: <NAME> <<EMAIL>>
|#
(in-package #:maiden-user)
(defpackage #:maiden-weather
(:nicknames #:org.shirakumo.maiden.agents.weather)
(:use #:cl #:maiden #:maiden-api-access #:maiden-storage #:maiden-client-entities #:maiden-commands)
;; weather.lisp
(:export
#:weather-data
#:location-coordinates
#:location-weather-data
#:format-weather-data
#:format-daily-forecast
#:weather
#:weather-dwim
#:weather-location
#:forecast-location
#:weather-user
#:forecast-user))
| true |
#|
This file is a part of Maiden
(c) 2016 Shirakumo http://tymoon.eu (PI:EMAIL:<EMAIL>END_PI)
Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
|#
(in-package #:maiden-user)
(defpackage #:maiden-weather
(:nicknames #:org.shirakumo.maiden.agents.weather)
(:use #:cl #:maiden #:maiden-api-access #:maiden-storage #:maiden-client-entities #:maiden-commands)
;; weather.lisp
(:export
#:weather-data
#:location-coordinates
#:location-weather-data
#:format-weather-data
#:format-daily-forecast
#:weather
#:weather-dwim
#:weather-location
#:forecast-location
#:weather-user
#:forecast-user))
|
[
{
"context": ";;; copyright (c) Polos Ruetz\n\n(ffi:clines \"#include <stdlib.h>\")\n\n(in-package ",
"end": 29,
"score": 0.9998911023139954,
"start": 18,
"tag": "NAME",
"value": "Polos Ruetz"
}
] |
src/lisp/ini.lisp
|
lisp-mirror/eql5
| 5 |
;;; copyright (c) Polos Ruetz
(ffi:clines "#include <stdlib.h>")
(in-package :eql)
(defvar *break-on-errors* nil "Unless NIL, causes a simple (BREAK) on any EQL error.")
(defvar *byte-array-as-string* nil "Indicates to print a byte array as string, not as vector. See e.g. QPROPERTIES.")
(defvar *slime-mode* nil)
(defvar *qtpl* nil "To set in ~/.eclrc only; the same as command line option -qtpl.")
(defmacro alias (s1 s2)
`(setf (symbol-function ',s1) (function ,s2)))
(defmacro qlet ((&rest pairs) &body body)
"args: (((variable-1 expression-1) (variable-2 expression-2) ...) &body body)
Similar to <code>let*</code> (and to local C++ variables).<br><br>Creates temporary Qt objects, deleting them at the end of the <code>qlet</code> body.<br>If <code>expression</code> is a string, it will be substituted with <code>(qnew expression)</code>, optionally including constructor arguments.<br><br>This macro is convenient for e.g. local <code>QPainter</code> objects, in order to guarantee C++ destructors being called after leaving a local scope.
(qlet ((painter \"QPainter\"))
...)
(qlet ((reg-exp \"QRegExp(QString)\" \"^\\\\S+$\"))
...)"
(let ((vars (mapcar (lambda (x) (if (consp x) (first x) x)) pairs))
(exps (mapcar (lambda (x)
(if (consp x)
(let ((exp (rest x)))
(if (stringp (first exp))
(apply 'list 'qnew exp)
(first exp)))
nil))
pairs)))
`(let* ,(mapcar 'list vars exps)
(unwind-protect
(progn
,@body)
,(if (second vars)
`(progn . ,(mapcar (lambda (var) (list 'qdelete var))
(nreverse vars)))
`(qdelete ,(first vars)))))))
(defmacro qinvoke-methods (object &rest functions)
"args: (object &rest functions)
alias: qfuns
A simple syntax for nested <code>qfun</code> calls.
(qfuns object \"funA\" \"funB\" \"funC\") ; expands to: (qfun (qfun (qfun object \"funA\") \"funB\") \"funC\")
(qfuns object (\"funA\" 1) (\"funB\" a b c)) ; expands to: (qfun (qfun object \"funA\" 1) \"funB\" a b c)
(qfuns \"QApplication\" \"font\" \"family\")
(qfuns *table-view* \"model\" (\"index\" 0 2) \"data\" \"toString\")
;; alternatively:
(! (\"funC\" \"funB\" \"funA\" object))
(! ((\"funB\" a b c) (\"funA\" 1) object))
(! (\"family\" \"font\" \"QApplication\"))
(! (\"toString\" \"data\" (\"index\" 0 2) \"model\" *table-view*))
;; using wrapper functions, the above reads:
(|funC| (|funB| (|funA| object)))
(|funB| (|funA| object 1) a b c)
(|family| (|font.QApplication|))
(|toString| (|data| (|index| (|model| *table-view*) 0 2)))"
(let (form)
(dolist (fun functions)
(setf form (append (list 'qfun (or form object)) (x:ensure-list fun))))
form))
(defmacro qfuns (object &rest functions) ; alias
`(qinvoke-methods ,object ,@functions))
(defmacro ! (fun/s &rest args)
(if args
(let (call)
(when (consp (first args))
(cond ((and (stringp (caar args))
(char= #\Q (char (caar args) 0)))
(setf call :cast))
((eql :qt (caar args))
(setf call :qt))))
(case call
(:cast
`(qfun* ,(cadar args) ,(caar args) ,fun/s ,@(rest args)))
(:qt
`(qfun+ ,(cadar args) ,fun/s ,@(rest args)))
(t
`(qfun ,(first args) ,fun/s ,@(rest args)))))
`(qfuns ,@(reverse fun/s))))
(defmacro x:do-with (with &body body) ; re-definition from package :X because of EQL:QFUN
(when (atom with)
(setf with (list 'qfun with)))
`(progn
,@(mapcar (lambda (line)
;; needed for Qt wrappers (see "all-wrappers.lisp")
(if (and (eql 'qfun (first line))
(symbolp (third line)))
(cons (third line) (cons (second line) (nthcdr 3 line)))
line))
(mapcar (lambda (line)
(append with (if (or (atom line)
(eql 'quote (first line)))
(list line)
line)))
body))))
(defmacro defvar-ui (main &rest names)
"args: (main-widget &rest variables)
This macro simplifies the definition of UI variables:
(defvar-ui *main*
*label*
*line-edit*
...)
;; the above will expand to:
(progn
(defvar *label* (qfind-child *main* \"label\"))
(defvar *line-edit* (qfind-child *main* \"line_edit\"))
...)"
`(progn
,@(mapcar (lambda (name)
`(defvar ,name (qfind-child ,main ,(string-downcase (substitute #\_ #\- (string-trim "*" (symbol-name name)))))))
names)))
(defun %reference-name ()
(format nil "%~A%" (gensym)))
(defmacro qsingle-shot (milliseconds function)
;; check for LAMBDA, #'LAMBDA
(if (find (first function) '(lambda function))
;; hold a reference (will be called later from Qt event loop)
`(%qsingle-shot ,milliseconds (setf (symbol-function (intern ,(%reference-name))) ; lambda
,function))
`(%qsingle-shot ,milliseconds ,function))) ; 'foo
(defmacro qlater (function)
"args: (function)
Convenience macro: a <code>qsingle-shot</code> with a <code>0</code> timeout.<br>This will call <code>function</code> as soon as the Qt event loop is idle.
(qlater 'delayed-ini)"
`(qsingle-shot 0 ,function))
(defun %ensure-persistent-function (fun)
(typecase fun
(symbol ; 'foo
fun)
(function ; lambda
;; hold a reference (will be called later from Qt event loop)
(setf (symbol-function (intern (%reference-name)))
fun))))
(defun %make-vector ()
(make-array 0 :adjustable t :fill-pointer t))
(defun %break (&rest args)
(apply 'break args))
(defun %windows-version ()
(qfun "QSysInfo" "windowsVersion"))
(let ((eql5-home (namestring (merge-pathnames ".eql5/" (user-homedir-pathname)))))
(defun set-home (path)
(setf eql5-home path))
(defun in-home (&rest files)
(apply 'concatenate 'string eql5-home files)))
(let ((eql5-src #.(let ((path (namestring *default-pathname-defaults*))) ; hard-code EQL5 directory
(subseq path 0 (- (length path) (length "src/"))))))
(defun set-src (path)
(setf eql5-src path))
(defun in-src (&rest files)
(apply 'concatenate 'string eql5-src files)))
(defun qsignal (name)
"args: (name)
Needed in functions which expect a <code>const char*</code> Qt signal (not needed in <code>qconnect</code>)."
(concatenate 'string "2" name))
(defun qslot (name)
"args: (name)
Needed in functions which expect a <code>const char*</code> Qt slot (not needed in <code>qconnect</code>)."
(concatenate 'string "1" name))
(defun qenums (class-name &optional enum-name)
(%qenums class-name enum-name))
(defun qfind-bound (&optional class-name)
"args: (&optional class-name)
Finds all symbols bound to Qt objects, returning both the Qt class names and the respective Lisp variables.<br>Optionally finds the occurrencies of the passed Qt class name only.
(qfind-bound \"QLineEdit\")"
(let ((found (qfind-bound* class-name)))
(when found
(let ((tab-stop (1+ (apply 'max (mapcar (lambda (x) (length (car x))) found)))))
(dolist (el found)
(princ (format nil "~%~A~VT~(~S~)" ; "~VT" doesn't work on all terminals
(car el) tab-stop (cdr el))))))))
(defun qfind-bound* (&optional class-name)
"args: (&optional class-name)
Like <code>qfind-bound</code>, but returning the results as list of conses."
(if (and class-name
(not (qid class-name)))
(%error-msg "QFIND-BOUND" (list class-name))
(let (qt-objects)
(do-all-symbols (s)
(when (and (not (find (symbol-package s) #.'(list (find-package :si) (find-package :ext))))
(boundp s)
(ignore-errors (ensure-qt-object (symbol-value s)))
(or (not class-name)
(string= class-name (qt-object-name (symbol-value s)))))
(pushnew s qt-objects)))
(stable-sort (sort (mapcar (lambda (s) (cons (qt-object-name (symbol-value s)) s))
qt-objects)
'string< :key 'cdr)
'string< :key 'car))))
(defun qproperties (object &optional (depth 1) qml)
"args: (object &optional (depth 1))
Prints all current properties of <code>object</code>, searching both all Qt properties and all Qt methods which don't require arguments (marked with '<b>*</b>').<br>Optionally pass a <code>depth</code> indicating how many super-classes to include. Pass <code>T</code> to include all super-classes.
(qproperties (|font.QApplication|))
(qproperties (qnew \"QVariant(QString)\" \"42\"))
(qproperties *tool-button* 2) ; depth 2: both QToolButton and QAbstractButton"
(let ((object* (ensure-qt-object object)))
(when (qt-object-p object*)
(labels ((null-qt-object (obj)
(qt-object 0 0 (qt-object-id obj)))
(readable (obj fun ret)
(cond ((and *byte-array-as-string*
(string= "QByteArray" ret))
(x:bytes-to-string obj))
((string= "dynamicPropertyNames" fun)
(mapcar 'x:bytes-to-string obj))
((qt-object-p obj)
(let ((name (qt-object-name obj)))
(cond ((search name "QColor QLocale")
(! "name" obj))
((search name "QDate QTime QDateTime QFont QUrl QKeySequence")
(! "toString" obj))
((search name "QPixmap QImage QPicture QIcon QBitmap QDate QDateTime QTime QTextCursor QVariant QMargins QSqlQuery QWebElement")
(if (and (not (zerop (qt-object-pointer obj)))
(! "isNull" obj))
(null-qt-object obj)
obj))
((search name "QModelIndex")
(if (! "isValid" obj)
obj
(null-qt-object obj)))
((search name "QRegExp")
(if (! "isEmpty" obj)
(null-qt-object obj)
obj))
(t
obj))))
(t
obj))))
(let ((name (qt-object-name object*))
documentations functions properties)
(x:while (and name (not (eql 0 depth)))
(push (first (qapropos* nil (if qml object* name) nil qml))
documentations)
(setf name (qsuper-class-name name))
(when (numberp depth)
(decf depth)))
(dolist (docu documentations)
(dolist (type (if qml '("Properties:") '("Properties:" "Methods:")))
(dolist (fun (rest (find type (rest docu) :key 'first :test 'string=)))
(when (and (not (x:starts-with "void " fun))
(not (x:starts-with "constructor " fun))
(not (x:ends-with " static" fun))
(or (not (find #\( fun))
(search "()" fun))
;; state changing or copying functions
(notany (lambda (x) (search x fun))
'(" clone" " copy" " disconnect" " take" " create")))
(push fun functions)
(when (char= #\P (char type 0)) ; "Properties:"
(push (x:string-substitute "" " const" (subseq fun (1+ (position #\Space fun))))
properties))))))
(when functions
(setf functions (mapcar (lambda (fun)
(setf fun (x:string-substitute "" "const " fun)
fun (x:string-substitute "" " const" fun))
(let* ((p2 (position #\( fun))
(p1 (position #\Space fun :from-end t :end p2)))
(cons (subseq fun (1+ p1) p2) ; function name
(subseq fun 0 p1)))) ; return type
functions))
(setf functions (sort (remove-duplicates functions :test 'string= :key 'first)
'string< :key 'first))
(let ((tab-stop (+ 2 (apply 'max (mapcar (lambda (x) (length (first x))) functions)))))
(dolist (fun-ret functions)
(let* ((fun (car fun-ret))
(ret (cdr fun-ret))
(prop-p (find fun properties :test 'string=)))
(princ (format nil "~%~A~C~VT~S" ; "~VT" doesn't work on all terminals
fun
(if prop-p #\Space #\*)
tab-stop
(readable (if prop-p (qget object* fun) (! fun object*))
fun
ret))))))
(terpri)
(terpri)
(values)))))))
(defun qproperties* (object)
"args: (object)
Similar to <code>qproperties</code>, but listing all properties (including user defined ones) of the passed <code>object</code> instance.<br>This is only useful for e.g. <code>QQuickItem</code> derived classes, which don't have a corresponding C++ class, in order to list all QML properties.
(qproperties* (qml:find-quick-item \"myItem\"))"
(qproperties object 1 t))
(defun ignore-io-streams ()
(setf *standard-output* (make-broadcast-stream)
*trace-output* *standard-output*
*error-output* *standard-output*
*terminal-io* (make-two-way-stream (make-string-input-stream "")
*standard-output*)))
;;; top-level / slime-mode processing Qt events (command line options "-qtpl" and "-slime")
(defvar *slime-hook-file* nil)
(defun load-slime-auxiliary-file ()
(if (eql :repl-hook *slime-mode*) ; to set in "eql-start-swank.lisp"
(if (and (find-package :swank)
(find-symbol "*SLIME-REPL-EVAL-HOOKS*" :swank))
(load (or *slime-hook-file* (in-home "slime/repl-hook"))) ; Slime mode "REPL hook"
(qsingle-shot 500 'load-slime-auxiliary-file)) ; we need to wait for Emacs "slime-connect"
(load (x:check-recompile (in-home "lib/thread-safe"))))) ; Slime mode "thread safe" (default)
#+threads
(defun %read-thread ()
(si::tpl-prompt)
(unless (find-package :ecl-readline)
(princ "> "))
(let ((form (si::%tpl-read)))
(qrun-on-ui-thread (lambda () (eval-top-level form)) nil))
(values))
(defun start-read-thread ()
#+threads
(mp:process-run-function :read '%read-thread)
#-threads
(error "ECL threads not enabled, can't process Qt events."))
(defun eval-top-level (form)
;; needed to avoid unrecoverable BREAK on errors during READ (command line option "-qtpl")
(when (stringp form)
(handler-case (setf form (read-from-string form))
(error (err)
(princ err)))
(si::feed-top-level form))
(finish-output)
(start-read-thread))
(defun exec-with-simple-restart ()
(if *slime-mode*
(progn
(load-slime-auxiliary-file)
(loop
(with-simple-restart (restart-qt-events "Last resort only - prefer \"Return to SLIME's top level\"")
(qexec))))
(exec-with-simple-restart-dialog)))
(let (loaded)
(defun exec-with-simple-restart-dialog ()
(when *qtpl*
;; command line option "-qtpl" only, see "restart-dialog.lisp"
(unless loaded
(setf loaded t)
(load (in-home "lib/restart-dialog")))
(funcall (find-symbol "EXEC-WITH-SIMPLE-RESTART" :restart-dialog)))))
(defmacro qeval (&rest forms)
;; this macro will be redefined in Slime mode (see "../../slime/repl-hook.lisp")
"args: (&rest forms)
Slime mode <code>:repl-hook</code> only (not needed in default Slime mode): evaluate forms in GUI thread. Defaults to a simple <code>progn</code> outside of Slime."
(if (second forms)
(cons 'progn forms)
(first forms)))
;;; qt-object
(defstruct (qt-object (:constructor qt-object (pointer unique id &optional finalize)))
(pointer 0 :type integer)
(unique 0 :type integer)
(id 0 :type fixnum)
(finalize nil :type boolean))
(defun new-qt-object (pointer unique id finalize)
(let ((obj (qt-object pointer unique id finalize)))
(when finalize
(ext:set-finalizer obj 'qdelete))
obj))
(defmethod print-object ((object qt-object) s)
(print-unreadable-object (object s :type nil :identity nil)
(let* ((unique (qt-object-unique object))
(pointer (qt-object-pointer object))
(nullp (zerop pointer)))
(format s "~A~A ~A~A~A"
(qt-object-name object)
(if (and (plusp (qt-object-id object))
(plusp pointer))
(format nil " ~S" (qfun object "objectName"))
"")
(if nullp
"NULL"
(format nil "0x~X" pointer))
(if (or (zerop unique) nullp)
""
(format nil " [~D]" unique))
(if (qt-object-finalize object)
" GC"
"")))))
(defmacro tr (source &optional context (plural-number -1))
"args: (source &optional context plural-number)
Macro expanding to <code>qtranslate</code>, which calls <code>QCoreApplication::translate()</code>.<br>Both <code>source</code> and <code>context</code> can be Lisp forms evaluating to constant strings (at compile time).<br>The <code>context</code> argument defaults to the Lisp file name. For the <code>plural-number</code>, see Qt Assistant."
;; see compiler-macro in "my_app/tr.lisp"
(let ((source* (ignore-errors (eval source)))
(context* (ignore-errors (eval context))))
`(eql:qtranslate ,(if (stringp context*)
context*
(if *compile-file-truename* (file-namestring *compile-file-truename*) ""))
,source*
,plural-number)))
(defun qset-null (obj &optional (test t))
"args: (object)
Sets the Qt object pointer to <code>0</code>. This function is called automatically after <code>qdel</code>."
(if test ; after e.g. QDELETE, we don't need to test (faster)
(let ((obj* (ensure-qt-object obj)))
(when (qt-object-p obj*)
(setf (qt-object-pointer obj*) 0)))
(setf (qt-object-pointer obj) 0)))
(defun qgui (&optional ev)
"args: (&optional process-events)
Launches the EQL convenience GUI.<br>If you don't have an interactive environment, you can pass <code>T</code> to run a pseudo Qt event loop. A better option is to start the tool like so:<br><code>eql5 -qgui</code>, in order to run the Qt event loop natively."
(let (found)
(when (find-package :gui)
(let ((gui (find-symbol "*GUI*" :gui)))
(when gui
(setf found t)
(setf gui (symbol-value gui))
(qfun gui "show")
(qfun gui "raise"))))
(unless found
(in-package :eql-user)
(load (in-home "lib/gui"))))
(when ev
(loop
(qprocess-events)
(sleep 0.05))))
(defun qeql (obj1 obj2)
"args: (object1 object2)
Returns <code>T</code> for same instances of a Qt class. Comparing <code>QVariant</code> values will work, too.<br>To test for same Qt classes only, do:
(= (qt-object-id object1) (qt-object-id object2))"
(let ((obj1* (ensure-qt-object obj1))
(obj2* (ensure-qt-object obj2)))
(when (and (qt-object-p obj1*)
(qt-object-p obj2*))
(let ((v-id (qid "QVariant")))
(if (= v-id (qt-object-id obj1*) (qt-object-id obj2*))
(eql::%qvariant-equal obj1* obj2*)
(let ((u1 (qt-object-unique obj1*))
(u2 (qt-object-unique obj2*)))
(or (and (not (zerop u1))
(= u1 u2))
(and (= (qt-object-id obj1*)
(qt-object-id obj2*))
(= (qt-object-pointer obj1*)
(qt-object-pointer obj2*))))))))))
(defun qnull-object (obj)
"args: (object)
alias: qnull
Checks for a <code>0</code> Qt object pointer."
(let ((obj* (ensure-qt-object obj)))
(when (qt-object-p obj*)
(zerop (qt-object-pointer obj*)))))
(defun qdelete (obj &optional later)
(%qdelete obj later))
(defun %string-or-nil (x)
(typecase x
(string
x)
(symbol
(unless (member x '(t nil))
(symbol-name x)))))
(defun qapropos (&optional name class type offset)
(let ((name* (%string-or-nil name)))
(when (and (not name*)
(not class)
(not (y-or-n-p "Print documentation of all Qt classes?")))
(return-from qapropos))
(let ((main (%qapropos name* class type offset)))
(dolist (sub1 main)
(format t "~%~%~A~%" (first sub1))
(dolist (sub2 (rest sub1))
(format t "~% ~A~%~%" (first sub2))
(dolist (sub3 (rest sub2))
(let* ((par (position #\( sub3))
(x (if par
(position #\Space sub3 :end par :from-end t)
(position #\Space sub3))))
(format t " ~A~A~%" (make-string (max 0 (- 15 x))) sub3)))))))
(terpri)
nil)
(defun qapropos* (&optional name class type offset)
"args: (&optional search-string class-name)
Similar to <code>qapropos</code>, returning the results as nested list."
(%qapropos (%string-or-nil name) class type offset))
(defun qnew-instance (name &rest arguments)
(%qnew-instance name arguments))
(defun qnew-instance* (name &rest arguments)
"args: (class-name &rest arguments/properties)
alias: qnew*
Convenience function for the REPL.<br>Same as <code>qnew</code>, but showing the object immediately (if of type <code>QWidget</code>)."
(let ((obj (%qnew-instance name arguments)))
(when (and obj
(plusp (qt-object-id obj))
(! "isWidgetType" obj))
(! "show" obj))
obj))
(defun qinvoke-method (object function-name &rest arguments)
(%qinvoke-method object nil function-name arguments))
(defun qinvoke-method* (object cast-class-name function-name &rest arguments)
"args: (object cast-class-name function-name &rest arguments)
alias: qfun*
Similar to <code>qinvoke-method</code>, additionally passing a class name, enforcing a cast to that class.<br>Note that this cast is not type safe (the same as a C cast, so dirty hacks are possible).<br><br>Note: using the (recommended) wrapper functions (see <code>qfun</code>), casts are applied automatically where needed.
(qfun* graphics-text-item \"QGraphicsItem\" \"setPos\" (list x y)) ; multiple inheritance problem
(qfun* event \"QKeyEvent\" \"key\") ; not needed with QADD-EVENT-FILTER
;; alternatively:
(! \"setPos\" (\"QGraphicsItem\" graphics-text-item) (list x y))
(! \"key\" (\"QKeyEvent\" event))
;; better/recommended:
(|setPos| graphics-text-item (list x y))"
(%qinvoke-method object cast-class-name function-name arguments))
(defun qinvoke-method+ (object function-name &rest arguments)
"args: (object function-name &rest arguments)
alias: qfun+
Use this variant to call user defined functions (declared <code>Q_INVOKABLE</code>), slots, signals from external C++ classes.<br><br>In order to call ordinary functions, slots, signals from external C++ classes, just use the ordinary <code>qfun</code>.
(qfun+ *qt-main* \"foo\") ; see Qt_EQL
;; alternatively:
(! \"foo\" (:qt *qt-main*))"
(%qinvoke-method object :qt function-name arguments))
(defun qconnect (from signal to &optional slot)
(%qconnect from signal to slot))
(defun qdisconnect (from &optional signal to slot)
(%qdisconnect from signal to slot))
(defun qobject-names (&optional type)
(%qobject-names type))
(defun qui-class (file &optional var)
(%qui-class file var))
(defun qmessage-box (x)
"args: (x)
alias: qmsg
Convenience function: a simple message box, converting <code>x</code> to a string if necessary.<br>Returns its argument (just like <code>print</code>)."
#+android
(! "information" "QMessageBox" nil
"EQL5"
(if (stringp x) x (prin1-to-string x)))
#-android
(qlet ((msg "QMessageBox"
"icon" |QMessageBox.Information|
"text" (if (stringp x) x (prin1-to-string x))))
(! "setWindowTitle" msg "EQL5")
(dolist (fun '("show" "raise" "exec")) ; "raise" needed in some situations (e.g. OSX)
(qfun msg fun)))
x)
(defun qset-color (widget role color)
"args: (widget color-role color)
Convenience function for simple color settings (avoiding <code>QPalette</code> boilerplate).<br>Use <code>QPalette</code> directly for anything more involved.
(qset-color widget |QPalette.Window| \"white\")"
(qlet ((pal (qget widget "palette"))) ; QLET: safer than GC for very frequent calls
(qfun pal "setColor(QPalette::ColorRole,QColor)" role color)
(qset widget "palette" pal))
color)
(defun qexec (&optional ms)
(%qexec ms))
(defun qsleep (seconds)
"args: (seconds)
Similar to <code>sleep</code>, but continuing to process Qt events."
(%qexec (floor (* 1000 seconds)))
nil)
(defun qfind-children (object &optional object-name class-name)
(%qfind-children object object-name class-name))
(let (loaded)
(defun qselect (&optional on-selected)
"args: (&optional on-selected)
alias: qsel
Allows to select (by clicking) any (child) widget.<br>The variable <code>qsel:*q*</code> is set to the latest selected widget.<br><br>Optionally pass a function to be called upon selecting, with the selected widget as argument.
(qsel (lambda (widget) (qmsg widget)))"
(unless loaded
(setf loaded t)
(load (in-home "lib/qselect")))
(%qselect on-selected)))
(let (loaded)
(defun quic (&optional (ui.h "ui.h") (ui.lisp "ui.lisp") (ui-package :ui) &rest properties)
"args: (&optional (file.h \"ui.h\") (file.lisp \"ui.lisp\") (ui-package :ui))
Takes C++ code from a file generated by the <code>uic</code> user interface compiler, and generates the corresponding EQL code.<br>See also command line option <code>-quic</code>."
(unless loaded
(setf loaded t)
(load (in-home "lib/quic")))
(funcall (intern "RUN" :quic) ui.h ui.lisp ui-package properties)))
(defun qrequire (module &optional quiet)
(%qrequire module quiet))
(defun qload-c++ (library-name &optional unload)
(%qload-c++ library-name unload))
(defun define-qt-wrappers (qt-library &rest what)
"args: (qt-library &rest what)
Defines Lisp methods for all Qt methods/signals/slots of given library.<br>(See example <code>Qt_EQL/trafficlight/</code>).
(define-qt-wrappers *c++*) ; generate wrappers (see \"Qt_EQL/\")
(define-qt-wrappers *c++* :slots) ; Qt slots only (any of :methods :slots :signals)
(my-qt-function *c++* x y) ; instead of: (! \"myQtFunction\" (:qt *c++*) x y)"
(let ((all-functions (cdar (qapropos* nil (ensure-qt-object qt-library)))))
(unless what
(setf what '(:methods :slots :signals)))
(dolist (functions (loop :for el :in what :collect
(concatenate 'string (string-capitalize el) ":")))
(dolist (fun (rest (find functions all-functions
:key 'first :test 'string=)))
(let* ((p (position #\( fun))
(qt-name (subseq fun (1+ (position #\Space fun :from-end t :end p)) p))
(lisp-name (intern (with-output-to-string (s)
(x:do-string (ch qt-name)
(if (upper-case-p ch)
(format s "-~C" ch)
(write-char (char-upcase ch) s)))))))
;; no way to avoid EVAL here (excluding non-portable hacks)
(eval `(defgeneric ,lisp-name (object &rest arguments)))
(eval `(defmethod ,lisp-name ((object qt-object) &rest arguments)
(%qinvoke-method object :qt ,qt-name arguments))))))))
#+linux
(defun %ini-auto-reload (library-name watcher on-file-change)
(multiple-value-bind (object file-name)
(qload-c++ library-name)
(when file-name
(qfun watcher "addPath" file-name)
(qconnect watcher "fileChanged(QString)" on-file-change))
object))
#+linux
(defmacro qauto-reload-c++ (variable library-name)
"args: (variable library-name)
<b>Linux only.</b><br><br>Extends <code>qload-c++</code> (see <code>Qt_EQL/</code>).<br><br>Defines a global variable (see return value of <code>qload-c++</code>), which will be updated on every change of the C++ plugin (e.g. after recompiling, the plugin will automatically be reloaded, and the <code>variable</code> will be set to its new value).<br><br>If you want to be notified on every change of the plugin, set <code>*<variable>-reloaded*</code>. It will then be called after reloading, passing both the variable name and the plugin name.<br>See <code>qload-c++</code> for an example how to call plugin functions.
(qauto-reload-c++ *c++* \"eql_cpp\")
(setf *c++-reloaded* (lambda (var lib) (qapropos nil (symbol-value var)))) ; optional: set a notifier"
(let* ((name (string-trim "*" (symbol-name variable)))
(reloaded (intern (format nil "*~A-RELOADED*" name)))
(watcher (intern (format nil "*~A-WATCHER*" name))))
`(progn
(defvar ,watcher (qnew "QFileSystemWatcher"))
(defvar ,variable (%ini-auto-reload ,library-name ,watcher
(lambda (name)
(let ((file-name (first (qfun ,watcher "files"))))
(qfun ,watcher "removePath" file-name)
(setf ,variable (qload-c++ ,library-name))
(qfun ,watcher "addPath" file-name))
(when ,reloaded
(funcall ,reloaded ',variable ,library-name)))))
(defvar ,reloaded nil))))
(defun qrun-on-ui-thread (function &optional (blocking t))
(%qrun-on-ui-thread function blocking))
#+threads
(defvar *gui-thread* mp:*current-process*)
(defmacro qrun-on-ui-thread* (&body body)
"args: (&body body)
alias: qrun*
Convenience macro for <code>qrun</code>, wrapping <code>body</code> in a closure (passing arguments, return values).
(qrun* (|setValue| ui:*progress-bar* value))
(let ((item (qrun* (qnew \"QTableWidgetItem\")))) ; return value(s)
...)"
#+threads
(let ((values (gensym)))
`(if (eql *gui-thread* mp:*current-process*)
,(if (second body)
(cons 'progn body)
(first body))
(let (,values)
(qrun (lambda ()
(setf ,values (multiple-value-list ,(if (second body)
(cons 'progn body)
(first body))))))
(values-list ,values))))
#-threads
(if (second body)
(cons 'progn body)
(first body)))
(defmacro qrun* (&body body) ; alias
`(qrun-on-ui-thread* ,@body))
(defun qload (file-name)
"args: (file-name)
Convenience function for Slime (or when loading EQL files from an ECL thread).<br>Loading files that create many Qt objects can be slow on the Slime REPL (many thread switches).<br>This function reduces all thread switches (GUI related) to a single one."
(qrun* (load file-name)))
(defun qquit (&optional (exit-status 0) (kill-all-threads t))
"args: (&optional (exit-status 0) (kill-all-threads t))
alias: qq
Terminates EQL. Use this function to quit gracefully, <b>not</b> <code>ext:quit</code>.<br><br>Negative values for <code>exit-status</code> will call <code>abort()</code> instead of normal program exit (e.g. to prevent infinite error message loops in some nasty cases)."
(declare (ignore kill-all-threads)) ; only here to be equivalent to EXT:QUIT
(assert (typep exit-status 'fixnum))
(qfun (qapp) "aboutToQuit")
(qfun (qapp) "quit")
(ffi:c-inline nil nil :void "cl_shutdown();" :one-liner t :side-effects t)
(if (minusp exit-status)
(ffi:c-inline nil nil :void "abort();" :one-liner t :side-effects t)
(ffi:c-inline (exit-status) (:int) :void "exit(#0);" :one-liner t :side-effects t)))
;; simplify using CLOS; see example "X-extras/CLOS-encapsulation.lisp"
(defgeneric the-qt-object (object)
(:documentation "Return the QT-OBJECT to be used whenever OBJECT is used as argument to any EQL function."))
(defun ensure-qt-object (object &optional quiet)
"args: (object)
Returns the <code>qt-object</code> of the given class/struct (see method <code>the-qt-object</code> in example <code>X-extras/CLOS-encapsulation.lisp</code>).<br>This function is used internally whenever a <code>qt-object</code> argument is expected."
(cond ((null object) ; e.g. passing NIL as parent widget: (qnew "QWidget(QWidget*)" nil)
nil)
((qt-object-p object)
object)
((let ((object* (if quiet
(ignore-errors (the-qt-object object))
(the-qt-object object))))
(if (qt-object-p object*)
object*
(unless quiet
(error "THE-QT-OBJECT returned ~S for class ~A, which is not of required type QT-OBJECT." object* object)))))))
(alias qnew qnew-instance)
(alias qnew* qnew-instance*)
(alias qdel qdelete)
(alias qget qproperty)
(alias qset qset-property)
(alias qfun qinvoke-method)
(alias qfun* qinvoke-method*)
(alias qfun+ qinvoke-method+)
(alias qmsg qmessage-box)
(alias qnull qnull-object)
(alias qrun qrun-on-ui-thread)
(alias qsel qselect)
(alias qq qquit)
;; add property :function-lambda-list to plist of EQL functions (inspired by ext:function-lambda-list)
(dolist (el (list (cons 'define-qt-wrappers '(qt-library &rest what))
(cons 'defvar-ui '(main-widget &rest variables))
(cons 'ensure-qt-object '(object))
(cons 'in-home '(&rest file-names))
(cons 'qadd-event-filter '(object event function))
(cons 'qapropos '(&optional search-string class-name))
(cons 'qapropos* '(&optional search-string class-name))
(cons 'qauto-reload-c++ '(variable library-name))
(cons 'qconnect '(caller signal receiver/function &optional slot))
(cons 'qcopy '(object))
(cons 'qdelete '(object))
(cons 'qdel '(object))
(cons 'qdisconnect '(caller &optional signal receiver/function slot))
(cons 'qenums '(class-name &optional enum-name))
(cons 'qeql '(object1 object2))
(cons 'qescape '(string))
(cons 'qexec '(&optional milliseconds))
(cons 'qfind-bound '(&optional class-name))
(cons 'qfind-bound* '(&optional class-name))
(cons 'qfind-child '(object object-name))
(cons 'qfind-children '(object &optional object-name class-name))
(cons 'qfrom-utf8 '(byte-array))
(cons 'qfun '(object function-name &rest arguments))
(cons 'qfun* '(object cast-class-name function-name &rest arguments))
(cons 'qfun+ '(object function-name &rest arguments))
(cons 'qfuns '(object &rest functions))
(cons 'qget '(object name))
(cons 'qgui '(&optional process-events))
(cons 'qid '(class-name))
(cons 'qinvoke-method '(object function-name &rest arguments))
(cons 'qinvoke-method* '(object cast-class-name function-name &rest arguments))
(cons 'qinvoke-method+ '(object function-name &rest arguments))
(cons 'qinvoke-methods '(object &rest functions))
(cons 'qlater '(function))
(cons 'qload '(file-name))
(cons 'qload-c++ '(library-name &optional unload))
(cons 'qload-ui '(file-name))
(cons 'qlocal8bit '(string))
(cons 'qmessage-box '(x))
(cons 'qmsg '(x))
(cons 'qnew '(class-name &rest arguments/properties))
(cons 'qnew-instance '(class-name &rest arguments/properties))
(cons 'qnew* '(class-name &rest arguments/properties))
(cons 'qnew-instance* '(class-name &rest arguments/properties))
(cons 'qnull '(object))
(cons 'qnull-object '(object))
(cons 'qobject-names '(&optional type))
(cons 'qoverride '(object name function))
(cons 'qproperties '(object &optional (depth 1)))
(cons 'qproperties* '(object))
(cons 'qproperty '(object name))
(cons 'qquit '(&optional (exit-status 0) (kill-all-threads t)))
(cons 'qremove-event-filter '(handle))
(cons 'qrequire '(module &optional quiet))
(cons 'qrgb '(red green blue &optional (alpha 255)))
(cons 'qrun '(function))
(cons 'qrun-on-ui-thread '(function))
(cons 'qrun* '(&body body))
(cons 'qrun-on-ui-thread* '(&body body))
(cons 'qset-null '(object))
(cons 'qset '(object name value))
(cons 'qset-color '(widget color-role color))
(cons 'qset-property '(object name value))
(cons 'qsignal '(name))
(cons 'qsingle-shot '(milliseconds function))
(cons 'qsleep '(seconds))
(cons 'qslot '(name))
(cons 'qstatic-meta-object '(class-name))
(cons 'qsuper-class-name '(class-name))
(cons 'qt-object-id '(object))
(cons 'qt-object-name '(object))
(cons 'qt-object-p '(object))
(cons 'qt-object-pointer '(object))
(cons 'qt-object-unique '(object))
(cons 'qt-object-? '(object))
(cons 'quic '(&optional (file.h "ui.h") (file.lisp "ui.lisp") (ui-package :ui)))
(cons 'qui-class '(file-name &optional object-name))
(cons 'qui-names '(file-name))
(cons 'qutf8 '(string))
(cons 'qvariant-from-value '(value type-name))
(cons 'qvariant-value '(object))
(cons 'tr '(source &optional context plural-number))))
(setf (get (car el) :function-lambda-list) (cdr el)))
;;; undocumented convenience hacks
(defun qt-object-to-string (object)
"String representation of a QT-OBJECT."
(when (qt-object-p object)
(format nil "(QT-OBJECT ~D ~D ~D)"
(qt-object-pointer object)
(qt-object-unique object)
(qt-object-id object))))
(defun qt-object-from-string (string)
"Restores a QT-OBJECT from its string representation."
(let ((exp (read-from-string string)))
(when (eql 'qt-object (first exp))
(apply (first exp) (rest exp)))))
;;; for android logging (EQL5-Android only, see "../eql.cpp")
(defun qlog (arg1 &rest args)
;; (qlog 12)
;; (qlog 1 "plus" 2 "gives" 6/2)
;; (qlog "x ~A y ~A" x y)
(%qlog (if (and (stringp arg1)
(find #\~ arg1))
(apply 'format nil arg1 args)
(x:join (mapcar 'princ-to-string (cons arg1 args))))))
;;; The following are modified/simplified functions taken from "src/lsp/top.lsp" (see ECL sources)
(in-package :si)
(defun feed-top-level (form)
(catch *quit-tag*
(let ((*debugger-hook* nil)
(*tpl-level* -1))
(%tpl form))))
(defun %read-lines ()
;; allow multi-line expressions (command line option "-qtpl")
(let (lines)
(loop
(let ((line (read-line)))
(setf lines (if lines (format nil "~A~%~A" lines line) line))
;; test for balanced parenthesis; if yes, we have a READ-able expression
;; (see READ-FROM-STRING in EVAL-TOP-LEVEL)
(multiple-value-bind (_ x)
(ignore-errors
(read-from-string (format nil "(~A)" (let ((lines* (copy-seq lines)))
(x:while-it (position #\\ lines*)
(setf lines* (replace lines* " " :start1 x:it)))
(remove-if-not (lambda (ch)
(find ch '(#\Space #\Newline #\( #\) #\" #\;)))
lines*)))))
(when (numberp x)
(return (if (find (string-upcase lines) '("NIL" "()") :test 'string=) ; avoid strange BREAK on NIL values
"'()"
lines))))))))
(defun %tpl-read (&aux (*read-suppress* nil))
(finish-output)
(loop
(case (peek-char nil *standard-input* nil :EOF)
((#\))
(warn "Ignoring an unmatched right parenthesis.")
(read-char))
((#\space #\tab)
(read-char))
((#\newline #\return)
(read-char)
;; avoid repeating prompt on successive empty lines:
(let ((command (tpl-make-command :newline "")))
(when command (return command))))
(:EOF
(terpri)
(return (tpl-make-command :EOF "")))
(#\:
(let ((exp (read-preserving-whitespace)))
(return (cond ((find exp '(:qq :exit))
"(eql:qquit)")
((find exp '(:qa :abort))
"(eql:qquit -1)")
(t
tpl-make-command exp (read-line))))))
(#\?
(read-char)
(case (peek-char nil *standard-input* nil :EOF)
((#\space #\tab #\newline #\return :EOF)
(return (tpl-make-command :HELP (read-line))))
(t
(unread-char #\?)
(return (read-preserving-whitespace)))))
;; We use READ-PRESERVING-WHITESPACE because with READ, if an
;; error happens within the reader, and we perform a ":C" or
;; (CONTINUE), the reader will wait for an inexistent #\Newline.
(t
(return (%read-lines))))))
(defun %break-where ()
(when (> *tpl-level* 0)
(tpl-print-current)))
(defun %tpl (form &key ((:commands *tpl-commands*) tpl-commands)
((:prompt-hook *tpl-prompt-hook*) *tpl-prompt-hook*)
(broken-at nil)
(quiet nil))
#-ecl-min
(declare (c::policy-debug-ihs-frame))
(let* ((*ihs-base* *ihs-top*)
(*ihs-top* (if broken-at (ihs-search t broken-at) (ihs-top)))
(*ihs-current* (if broken-at (ihs-prev *ihs-top*) *ihs-top*))
(*frs-base* (or (sch-frs-base *frs-top* *ihs-base*) (1+ (frs-top))))
(*frs-top* (frs-top))
(*quit-tags* (cons *quit-tag* *quit-tags*))
(*quit-tag* *quit-tags*) ; any unique new value
(*tpl-level* (1+ *tpl-level*))
(break-level *break-level*)
values -)
(set-break-env)
(set-current-ihs)
(flet ((rep ()
;; We let warnings pass by this way "warn" does the
;; work. It is conventional not to trap anything
;; that is not a SERIOUS-CONDITION. Otherwise we
;; would be interferring the behavior of code that relies
;; on conditions for communication (for instance our compiler)
;; and which expect nothing to happen by default.
(handler-bind
((serious-condition
(lambda (condition)
(cond ((< break-level 1)
;; Toplevel should enter the debugger on any condition.
)
(*allow-recursive-debug*
;; We are told to let the debugger handle this.
)
(t
(format t "~&Debugger received error of type: ~A~%~A~%~
Error flushed.~%"
(type-of condition) condition)
(clear-input)
(return-from rep t) ;; go back into the debugger loop.
)
)
)))
(with-grabbed-console
(unless quiet
(%break-where)
(setf quiet t))
(if form
(setq - form
form nil)
(setq - (locally (declare (notinline tpl-read))
(tpl-prompt)
(tpl-read))))
(setq values (multiple-value-list
(eval-with-env - *break-env*))
/// // // / / values *** ** ** * * (car /) +++ ++ ++ + + -)
(tpl-print values)))))
(when
(catch *quit-tag*
(if (zerop break-level)
(with-simple-restart
(restart-toplevel "Go back to Top-Level REPL.")
(rep))
(with-simple-restart
(restart-debugger "Go back to debugger level ~D." break-level)
(rep)))
nil)
(setf quiet nil)))))
|
91068
|
;;; copyright (c) <NAME>
(ffi:clines "#include <stdlib.h>")
(in-package :eql)
(defvar *break-on-errors* nil "Unless NIL, causes a simple (BREAK) on any EQL error.")
(defvar *byte-array-as-string* nil "Indicates to print a byte array as string, not as vector. See e.g. QPROPERTIES.")
(defvar *slime-mode* nil)
(defvar *qtpl* nil "To set in ~/.eclrc only; the same as command line option -qtpl.")
(defmacro alias (s1 s2)
`(setf (symbol-function ',s1) (function ,s2)))
(defmacro qlet ((&rest pairs) &body body)
"args: (((variable-1 expression-1) (variable-2 expression-2) ...) &body body)
Similar to <code>let*</code> (and to local C++ variables).<br><br>Creates temporary Qt objects, deleting them at the end of the <code>qlet</code> body.<br>If <code>expression</code> is a string, it will be substituted with <code>(qnew expression)</code>, optionally including constructor arguments.<br><br>This macro is convenient for e.g. local <code>QPainter</code> objects, in order to guarantee C++ destructors being called after leaving a local scope.
(qlet ((painter \"QPainter\"))
...)
(qlet ((reg-exp \"QRegExp(QString)\" \"^\\\\S+$\"))
...)"
(let ((vars (mapcar (lambda (x) (if (consp x) (first x) x)) pairs))
(exps (mapcar (lambda (x)
(if (consp x)
(let ((exp (rest x)))
(if (stringp (first exp))
(apply 'list 'qnew exp)
(first exp)))
nil))
pairs)))
`(let* ,(mapcar 'list vars exps)
(unwind-protect
(progn
,@body)
,(if (second vars)
`(progn . ,(mapcar (lambda (var) (list 'qdelete var))
(nreverse vars)))
`(qdelete ,(first vars)))))))
(defmacro qinvoke-methods (object &rest functions)
"args: (object &rest functions)
alias: qfuns
A simple syntax for nested <code>qfun</code> calls.
(qfuns object \"funA\" \"funB\" \"funC\") ; expands to: (qfun (qfun (qfun object \"funA\") \"funB\") \"funC\")
(qfuns object (\"funA\" 1) (\"funB\" a b c)) ; expands to: (qfun (qfun object \"funA\" 1) \"funB\" a b c)
(qfuns \"QApplication\" \"font\" \"family\")
(qfuns *table-view* \"model\" (\"index\" 0 2) \"data\" \"toString\")
;; alternatively:
(! (\"funC\" \"funB\" \"funA\" object))
(! ((\"funB\" a b c) (\"funA\" 1) object))
(! (\"family\" \"font\" \"QApplication\"))
(! (\"toString\" \"data\" (\"index\" 0 2) \"model\" *table-view*))
;; using wrapper functions, the above reads:
(|funC| (|funB| (|funA| object)))
(|funB| (|funA| object 1) a b c)
(|family| (|font.QApplication|))
(|toString| (|data| (|index| (|model| *table-view*) 0 2)))"
(let (form)
(dolist (fun functions)
(setf form (append (list 'qfun (or form object)) (x:ensure-list fun))))
form))
(defmacro qfuns (object &rest functions) ; alias
`(qinvoke-methods ,object ,@functions))
(defmacro ! (fun/s &rest args)
(if args
(let (call)
(when (consp (first args))
(cond ((and (stringp (caar args))
(char= #\Q (char (caar args) 0)))
(setf call :cast))
((eql :qt (caar args))
(setf call :qt))))
(case call
(:cast
`(qfun* ,(cadar args) ,(caar args) ,fun/s ,@(rest args)))
(:qt
`(qfun+ ,(cadar args) ,fun/s ,@(rest args)))
(t
`(qfun ,(first args) ,fun/s ,@(rest args)))))
`(qfuns ,@(reverse fun/s))))
(defmacro x:do-with (with &body body) ; re-definition from package :X because of EQL:QFUN
(when (atom with)
(setf with (list 'qfun with)))
`(progn
,@(mapcar (lambda (line)
;; needed for Qt wrappers (see "all-wrappers.lisp")
(if (and (eql 'qfun (first line))
(symbolp (third line)))
(cons (third line) (cons (second line) (nthcdr 3 line)))
line))
(mapcar (lambda (line)
(append with (if (or (atom line)
(eql 'quote (first line)))
(list line)
line)))
body))))
(defmacro defvar-ui (main &rest names)
"args: (main-widget &rest variables)
This macro simplifies the definition of UI variables:
(defvar-ui *main*
*label*
*line-edit*
...)
;; the above will expand to:
(progn
(defvar *label* (qfind-child *main* \"label\"))
(defvar *line-edit* (qfind-child *main* \"line_edit\"))
...)"
`(progn
,@(mapcar (lambda (name)
`(defvar ,name (qfind-child ,main ,(string-downcase (substitute #\_ #\- (string-trim "*" (symbol-name name)))))))
names)))
(defun %reference-name ()
(format nil "%~A%" (gensym)))
(defmacro qsingle-shot (milliseconds function)
;; check for LAMBDA, #'LAMBDA
(if (find (first function) '(lambda function))
;; hold a reference (will be called later from Qt event loop)
`(%qsingle-shot ,milliseconds (setf (symbol-function (intern ,(%reference-name))) ; lambda
,function))
`(%qsingle-shot ,milliseconds ,function))) ; 'foo
(defmacro qlater (function)
"args: (function)
Convenience macro: a <code>qsingle-shot</code> with a <code>0</code> timeout.<br>This will call <code>function</code> as soon as the Qt event loop is idle.
(qlater 'delayed-ini)"
`(qsingle-shot 0 ,function))
(defun %ensure-persistent-function (fun)
(typecase fun
(symbol ; 'foo
fun)
(function ; lambda
;; hold a reference (will be called later from Qt event loop)
(setf (symbol-function (intern (%reference-name)))
fun))))
(defun %make-vector ()
(make-array 0 :adjustable t :fill-pointer t))
(defun %break (&rest args)
(apply 'break args))
(defun %windows-version ()
(qfun "QSysInfo" "windowsVersion"))
(let ((eql5-home (namestring (merge-pathnames ".eql5/" (user-homedir-pathname)))))
(defun set-home (path)
(setf eql5-home path))
(defun in-home (&rest files)
(apply 'concatenate 'string eql5-home files)))
(let ((eql5-src #.(let ((path (namestring *default-pathname-defaults*))) ; hard-code EQL5 directory
(subseq path 0 (- (length path) (length "src/"))))))
(defun set-src (path)
(setf eql5-src path))
(defun in-src (&rest files)
(apply 'concatenate 'string eql5-src files)))
(defun qsignal (name)
"args: (name)
Needed in functions which expect a <code>const char*</code> Qt signal (not needed in <code>qconnect</code>)."
(concatenate 'string "2" name))
(defun qslot (name)
"args: (name)
Needed in functions which expect a <code>const char*</code> Qt slot (not needed in <code>qconnect</code>)."
(concatenate 'string "1" name))
(defun qenums (class-name &optional enum-name)
(%qenums class-name enum-name))
(defun qfind-bound (&optional class-name)
"args: (&optional class-name)
Finds all symbols bound to Qt objects, returning both the Qt class names and the respective Lisp variables.<br>Optionally finds the occurrencies of the passed Qt class name only.
(qfind-bound \"QLineEdit\")"
(let ((found (qfind-bound* class-name)))
(when found
(let ((tab-stop (1+ (apply 'max (mapcar (lambda (x) (length (car x))) found)))))
(dolist (el found)
(princ (format nil "~%~A~VT~(~S~)" ; "~VT" doesn't work on all terminals
(car el) tab-stop (cdr el))))))))
(defun qfind-bound* (&optional class-name)
"args: (&optional class-name)
Like <code>qfind-bound</code>, but returning the results as list of conses."
(if (and class-name
(not (qid class-name)))
(%error-msg "QFIND-BOUND" (list class-name))
(let (qt-objects)
(do-all-symbols (s)
(when (and (not (find (symbol-package s) #.'(list (find-package :si) (find-package :ext))))
(boundp s)
(ignore-errors (ensure-qt-object (symbol-value s)))
(or (not class-name)
(string= class-name (qt-object-name (symbol-value s)))))
(pushnew s qt-objects)))
(stable-sort (sort (mapcar (lambda (s) (cons (qt-object-name (symbol-value s)) s))
qt-objects)
'string< :key 'cdr)
'string< :key 'car))))
(defun qproperties (object &optional (depth 1) qml)
"args: (object &optional (depth 1))
Prints all current properties of <code>object</code>, searching both all Qt properties and all Qt methods which don't require arguments (marked with '<b>*</b>').<br>Optionally pass a <code>depth</code> indicating how many super-classes to include. Pass <code>T</code> to include all super-classes.
(qproperties (|font.QApplication|))
(qproperties (qnew \"QVariant(QString)\" \"42\"))
(qproperties *tool-button* 2) ; depth 2: both QToolButton and QAbstractButton"
(let ((object* (ensure-qt-object object)))
(when (qt-object-p object*)
(labels ((null-qt-object (obj)
(qt-object 0 0 (qt-object-id obj)))
(readable (obj fun ret)
(cond ((and *byte-array-as-string*
(string= "QByteArray" ret))
(x:bytes-to-string obj))
((string= "dynamicPropertyNames" fun)
(mapcar 'x:bytes-to-string obj))
((qt-object-p obj)
(let ((name (qt-object-name obj)))
(cond ((search name "QColor QLocale")
(! "name" obj))
((search name "QDate QTime QDateTime QFont QUrl QKeySequence")
(! "toString" obj))
((search name "QPixmap QImage QPicture QIcon QBitmap QDate QDateTime QTime QTextCursor QVariant QMargins QSqlQuery QWebElement")
(if (and (not (zerop (qt-object-pointer obj)))
(! "isNull" obj))
(null-qt-object obj)
obj))
((search name "QModelIndex")
(if (! "isValid" obj)
obj
(null-qt-object obj)))
((search name "QRegExp")
(if (! "isEmpty" obj)
(null-qt-object obj)
obj))
(t
obj))))
(t
obj))))
(let ((name (qt-object-name object*))
documentations functions properties)
(x:while (and name (not (eql 0 depth)))
(push (first (qapropos* nil (if qml object* name) nil qml))
documentations)
(setf name (qsuper-class-name name))
(when (numberp depth)
(decf depth)))
(dolist (docu documentations)
(dolist (type (if qml '("Properties:") '("Properties:" "Methods:")))
(dolist (fun (rest (find type (rest docu) :key 'first :test 'string=)))
(when (and (not (x:starts-with "void " fun))
(not (x:starts-with "constructor " fun))
(not (x:ends-with " static" fun))
(or (not (find #\( fun))
(search "()" fun))
;; state changing or copying functions
(notany (lambda (x) (search x fun))
'(" clone" " copy" " disconnect" " take" " create")))
(push fun functions)
(when (char= #\P (char type 0)) ; "Properties:"
(push (x:string-substitute "" " const" (subseq fun (1+ (position #\Space fun))))
properties))))))
(when functions
(setf functions (mapcar (lambda (fun)
(setf fun (x:string-substitute "" "const " fun)
fun (x:string-substitute "" " const" fun))
(let* ((p2 (position #\( fun))
(p1 (position #\Space fun :from-end t :end p2)))
(cons (subseq fun (1+ p1) p2) ; function name
(subseq fun 0 p1)))) ; return type
functions))
(setf functions (sort (remove-duplicates functions :test 'string= :key 'first)
'string< :key 'first))
(let ((tab-stop (+ 2 (apply 'max (mapcar (lambda (x) (length (first x))) functions)))))
(dolist (fun-ret functions)
(let* ((fun (car fun-ret))
(ret (cdr fun-ret))
(prop-p (find fun properties :test 'string=)))
(princ (format nil "~%~A~C~VT~S" ; "~VT" doesn't work on all terminals
fun
(if prop-p #\Space #\*)
tab-stop
(readable (if prop-p (qget object* fun) (! fun object*))
fun
ret))))))
(terpri)
(terpri)
(values)))))))
(defun qproperties* (object)
"args: (object)
Similar to <code>qproperties</code>, but listing all properties (including user defined ones) of the passed <code>object</code> instance.<br>This is only useful for e.g. <code>QQuickItem</code> derived classes, which don't have a corresponding C++ class, in order to list all QML properties.
(qproperties* (qml:find-quick-item \"myItem\"))"
(qproperties object 1 t))
(defun ignore-io-streams ()
(setf *standard-output* (make-broadcast-stream)
*trace-output* *standard-output*
*error-output* *standard-output*
*terminal-io* (make-two-way-stream (make-string-input-stream "")
*standard-output*)))
;;; top-level / slime-mode processing Qt events (command line options "-qtpl" and "-slime")
(defvar *slime-hook-file* nil)
(defun load-slime-auxiliary-file ()
(if (eql :repl-hook *slime-mode*) ; to set in "eql-start-swank.lisp"
(if (and (find-package :swank)
(find-symbol "*SLIME-REPL-EVAL-HOOKS*" :swank))
(load (or *slime-hook-file* (in-home "slime/repl-hook"))) ; Slime mode "REPL hook"
(qsingle-shot 500 'load-slime-auxiliary-file)) ; we need to wait for Emacs "slime-connect"
(load (x:check-recompile (in-home "lib/thread-safe"))))) ; Slime mode "thread safe" (default)
#+threads
(defun %read-thread ()
(si::tpl-prompt)
(unless (find-package :ecl-readline)
(princ "> "))
(let ((form (si::%tpl-read)))
(qrun-on-ui-thread (lambda () (eval-top-level form)) nil))
(values))
(defun start-read-thread ()
#+threads
(mp:process-run-function :read '%read-thread)
#-threads
(error "ECL threads not enabled, can't process Qt events."))
(defun eval-top-level (form)
;; needed to avoid unrecoverable BREAK on errors during READ (command line option "-qtpl")
(when (stringp form)
(handler-case (setf form (read-from-string form))
(error (err)
(princ err)))
(si::feed-top-level form))
(finish-output)
(start-read-thread))
(defun exec-with-simple-restart ()
(if *slime-mode*
(progn
(load-slime-auxiliary-file)
(loop
(with-simple-restart (restart-qt-events "Last resort only - prefer \"Return to SLIME's top level\"")
(qexec))))
(exec-with-simple-restart-dialog)))
(let (loaded)
(defun exec-with-simple-restart-dialog ()
(when *qtpl*
;; command line option "-qtpl" only, see "restart-dialog.lisp"
(unless loaded
(setf loaded t)
(load (in-home "lib/restart-dialog")))
(funcall (find-symbol "EXEC-WITH-SIMPLE-RESTART" :restart-dialog)))))
(defmacro qeval (&rest forms)
;; this macro will be redefined in Slime mode (see "../../slime/repl-hook.lisp")
"args: (&rest forms)
Slime mode <code>:repl-hook</code> only (not needed in default Slime mode): evaluate forms in GUI thread. Defaults to a simple <code>progn</code> outside of Slime."
(if (second forms)
(cons 'progn forms)
(first forms)))
;;; qt-object
(defstruct (qt-object (:constructor qt-object (pointer unique id &optional finalize)))
(pointer 0 :type integer)
(unique 0 :type integer)
(id 0 :type fixnum)
(finalize nil :type boolean))
(defun new-qt-object (pointer unique id finalize)
(let ((obj (qt-object pointer unique id finalize)))
(when finalize
(ext:set-finalizer obj 'qdelete))
obj))
(defmethod print-object ((object qt-object) s)
(print-unreadable-object (object s :type nil :identity nil)
(let* ((unique (qt-object-unique object))
(pointer (qt-object-pointer object))
(nullp (zerop pointer)))
(format s "~A~A ~A~A~A"
(qt-object-name object)
(if (and (plusp (qt-object-id object))
(plusp pointer))
(format nil " ~S" (qfun object "objectName"))
"")
(if nullp
"NULL"
(format nil "0x~X" pointer))
(if (or (zerop unique) nullp)
""
(format nil " [~D]" unique))
(if (qt-object-finalize object)
" GC"
"")))))
(defmacro tr (source &optional context (plural-number -1))
"args: (source &optional context plural-number)
Macro expanding to <code>qtranslate</code>, which calls <code>QCoreApplication::translate()</code>.<br>Both <code>source</code> and <code>context</code> can be Lisp forms evaluating to constant strings (at compile time).<br>The <code>context</code> argument defaults to the Lisp file name. For the <code>plural-number</code>, see Qt Assistant."
;; see compiler-macro in "my_app/tr.lisp"
(let ((source* (ignore-errors (eval source)))
(context* (ignore-errors (eval context))))
`(eql:qtranslate ,(if (stringp context*)
context*
(if *compile-file-truename* (file-namestring *compile-file-truename*) ""))
,source*
,plural-number)))
(defun qset-null (obj &optional (test t))
"args: (object)
Sets the Qt object pointer to <code>0</code>. This function is called automatically after <code>qdel</code>."
(if test ; after e.g. QDELETE, we don't need to test (faster)
(let ((obj* (ensure-qt-object obj)))
(when (qt-object-p obj*)
(setf (qt-object-pointer obj*) 0)))
(setf (qt-object-pointer obj) 0)))
(defun qgui (&optional ev)
"args: (&optional process-events)
Launches the EQL convenience GUI.<br>If you don't have an interactive environment, you can pass <code>T</code> to run a pseudo Qt event loop. A better option is to start the tool like so:<br><code>eql5 -qgui</code>, in order to run the Qt event loop natively."
(let (found)
(when (find-package :gui)
(let ((gui (find-symbol "*GUI*" :gui)))
(when gui
(setf found t)
(setf gui (symbol-value gui))
(qfun gui "show")
(qfun gui "raise"))))
(unless found
(in-package :eql-user)
(load (in-home "lib/gui"))))
(when ev
(loop
(qprocess-events)
(sleep 0.05))))
(defun qeql (obj1 obj2)
"args: (object1 object2)
Returns <code>T</code> for same instances of a Qt class. Comparing <code>QVariant</code> values will work, too.<br>To test for same Qt classes only, do:
(= (qt-object-id object1) (qt-object-id object2))"
(let ((obj1* (ensure-qt-object obj1))
(obj2* (ensure-qt-object obj2)))
(when (and (qt-object-p obj1*)
(qt-object-p obj2*))
(let ((v-id (qid "QVariant")))
(if (= v-id (qt-object-id obj1*) (qt-object-id obj2*))
(eql::%qvariant-equal obj1* obj2*)
(let ((u1 (qt-object-unique obj1*))
(u2 (qt-object-unique obj2*)))
(or (and (not (zerop u1))
(= u1 u2))
(and (= (qt-object-id obj1*)
(qt-object-id obj2*))
(= (qt-object-pointer obj1*)
(qt-object-pointer obj2*))))))))))
(defun qnull-object (obj)
"args: (object)
alias: qnull
Checks for a <code>0</code> Qt object pointer."
(let ((obj* (ensure-qt-object obj)))
(when (qt-object-p obj*)
(zerop (qt-object-pointer obj*)))))
(defun qdelete (obj &optional later)
(%qdelete obj later))
(defun %string-or-nil (x)
(typecase x
(string
x)
(symbol
(unless (member x '(t nil))
(symbol-name x)))))
(defun qapropos (&optional name class type offset)
(let ((name* (%string-or-nil name)))
(when (and (not name*)
(not class)
(not (y-or-n-p "Print documentation of all Qt classes?")))
(return-from qapropos))
(let ((main (%qapropos name* class type offset)))
(dolist (sub1 main)
(format t "~%~%~A~%" (first sub1))
(dolist (sub2 (rest sub1))
(format t "~% ~A~%~%" (first sub2))
(dolist (sub3 (rest sub2))
(let* ((par (position #\( sub3))
(x (if par
(position #\Space sub3 :end par :from-end t)
(position #\Space sub3))))
(format t " ~A~A~%" (make-string (max 0 (- 15 x))) sub3)))))))
(terpri)
nil)
(defun qapropos* (&optional name class type offset)
"args: (&optional search-string class-name)
Similar to <code>qapropos</code>, returning the results as nested list."
(%qapropos (%string-or-nil name) class type offset))
(defun qnew-instance (name &rest arguments)
(%qnew-instance name arguments))
(defun qnew-instance* (name &rest arguments)
"args: (class-name &rest arguments/properties)
alias: qnew*
Convenience function for the REPL.<br>Same as <code>qnew</code>, but showing the object immediately (if of type <code>QWidget</code>)."
(let ((obj (%qnew-instance name arguments)))
(when (and obj
(plusp (qt-object-id obj))
(! "isWidgetType" obj))
(! "show" obj))
obj))
(defun qinvoke-method (object function-name &rest arguments)
(%qinvoke-method object nil function-name arguments))
(defun qinvoke-method* (object cast-class-name function-name &rest arguments)
"args: (object cast-class-name function-name &rest arguments)
alias: qfun*
Similar to <code>qinvoke-method</code>, additionally passing a class name, enforcing a cast to that class.<br>Note that this cast is not type safe (the same as a C cast, so dirty hacks are possible).<br><br>Note: using the (recommended) wrapper functions (see <code>qfun</code>), casts are applied automatically where needed.
(qfun* graphics-text-item \"QGraphicsItem\" \"setPos\" (list x y)) ; multiple inheritance problem
(qfun* event \"QKeyEvent\" \"key\") ; not needed with QADD-EVENT-FILTER
;; alternatively:
(! \"setPos\" (\"QGraphicsItem\" graphics-text-item) (list x y))
(! \"key\" (\"QKeyEvent\" event))
;; better/recommended:
(|setPos| graphics-text-item (list x y))"
(%qinvoke-method object cast-class-name function-name arguments))
(defun qinvoke-method+ (object function-name &rest arguments)
"args: (object function-name &rest arguments)
alias: qfun+
Use this variant to call user defined functions (declared <code>Q_INVOKABLE</code>), slots, signals from external C++ classes.<br><br>In order to call ordinary functions, slots, signals from external C++ classes, just use the ordinary <code>qfun</code>.
(qfun+ *qt-main* \"foo\") ; see Qt_EQL
;; alternatively:
(! \"foo\" (:qt *qt-main*))"
(%qinvoke-method object :qt function-name arguments))
(defun qconnect (from signal to &optional slot)
(%qconnect from signal to slot))
(defun qdisconnect (from &optional signal to slot)
(%qdisconnect from signal to slot))
(defun qobject-names (&optional type)
(%qobject-names type))
(defun qui-class (file &optional var)
(%qui-class file var))
(defun qmessage-box (x)
"args: (x)
alias: qmsg
Convenience function: a simple message box, converting <code>x</code> to a string if necessary.<br>Returns its argument (just like <code>print</code>)."
#+android
(! "information" "QMessageBox" nil
"EQL5"
(if (stringp x) x (prin1-to-string x)))
#-android
(qlet ((msg "QMessageBox"
"icon" |QMessageBox.Information|
"text" (if (stringp x) x (prin1-to-string x))))
(! "setWindowTitle" msg "EQL5")
(dolist (fun '("show" "raise" "exec")) ; "raise" needed in some situations (e.g. OSX)
(qfun msg fun)))
x)
(defun qset-color (widget role color)
"args: (widget color-role color)
Convenience function for simple color settings (avoiding <code>QPalette</code> boilerplate).<br>Use <code>QPalette</code> directly for anything more involved.
(qset-color widget |QPalette.Window| \"white\")"
(qlet ((pal (qget widget "palette"))) ; QLET: safer than GC for very frequent calls
(qfun pal "setColor(QPalette::ColorRole,QColor)" role color)
(qset widget "palette" pal))
color)
(defun qexec (&optional ms)
(%qexec ms))
(defun qsleep (seconds)
"args: (seconds)
Similar to <code>sleep</code>, but continuing to process Qt events."
(%qexec (floor (* 1000 seconds)))
nil)
(defun qfind-children (object &optional object-name class-name)
(%qfind-children object object-name class-name))
(let (loaded)
(defun qselect (&optional on-selected)
"args: (&optional on-selected)
alias: qsel
Allows to select (by clicking) any (child) widget.<br>The variable <code>qsel:*q*</code> is set to the latest selected widget.<br><br>Optionally pass a function to be called upon selecting, with the selected widget as argument.
(qsel (lambda (widget) (qmsg widget)))"
(unless loaded
(setf loaded t)
(load (in-home "lib/qselect")))
(%qselect on-selected)))
(let (loaded)
(defun quic (&optional (ui.h "ui.h") (ui.lisp "ui.lisp") (ui-package :ui) &rest properties)
"args: (&optional (file.h \"ui.h\") (file.lisp \"ui.lisp\") (ui-package :ui))
Takes C++ code from a file generated by the <code>uic</code> user interface compiler, and generates the corresponding EQL code.<br>See also command line option <code>-quic</code>."
(unless loaded
(setf loaded t)
(load (in-home "lib/quic")))
(funcall (intern "RUN" :quic) ui.h ui.lisp ui-package properties)))
(defun qrequire (module &optional quiet)
(%qrequire module quiet))
(defun qload-c++ (library-name &optional unload)
(%qload-c++ library-name unload))
(defun define-qt-wrappers (qt-library &rest what)
"args: (qt-library &rest what)
Defines Lisp methods for all Qt methods/signals/slots of given library.<br>(See example <code>Qt_EQL/trafficlight/</code>).
(define-qt-wrappers *c++*) ; generate wrappers (see \"Qt_EQL/\")
(define-qt-wrappers *c++* :slots) ; Qt slots only (any of :methods :slots :signals)
(my-qt-function *c++* x y) ; instead of: (! \"myQtFunction\" (:qt *c++*) x y)"
(let ((all-functions (cdar (qapropos* nil (ensure-qt-object qt-library)))))
(unless what
(setf what '(:methods :slots :signals)))
(dolist (functions (loop :for el :in what :collect
(concatenate 'string (string-capitalize el) ":")))
(dolist (fun (rest (find functions all-functions
:key 'first :test 'string=)))
(let* ((p (position #\( fun))
(qt-name (subseq fun (1+ (position #\Space fun :from-end t :end p)) p))
(lisp-name (intern (with-output-to-string (s)
(x:do-string (ch qt-name)
(if (upper-case-p ch)
(format s "-~C" ch)
(write-char (char-upcase ch) s)))))))
;; no way to avoid EVAL here (excluding non-portable hacks)
(eval `(defgeneric ,lisp-name (object &rest arguments)))
(eval `(defmethod ,lisp-name ((object qt-object) &rest arguments)
(%qinvoke-method object :qt ,qt-name arguments))))))))
#+linux
(defun %ini-auto-reload (library-name watcher on-file-change)
(multiple-value-bind (object file-name)
(qload-c++ library-name)
(when file-name
(qfun watcher "addPath" file-name)
(qconnect watcher "fileChanged(QString)" on-file-change))
object))
#+linux
(defmacro qauto-reload-c++ (variable library-name)
"args: (variable library-name)
<b>Linux only.</b><br><br>Extends <code>qload-c++</code> (see <code>Qt_EQL/</code>).<br><br>Defines a global variable (see return value of <code>qload-c++</code>), which will be updated on every change of the C++ plugin (e.g. after recompiling, the plugin will automatically be reloaded, and the <code>variable</code> will be set to its new value).<br><br>If you want to be notified on every change of the plugin, set <code>*<variable>-reloaded*</code>. It will then be called after reloading, passing both the variable name and the plugin name.<br>See <code>qload-c++</code> for an example how to call plugin functions.
(qauto-reload-c++ *c++* \"eql_cpp\")
(setf *c++-reloaded* (lambda (var lib) (qapropos nil (symbol-value var)))) ; optional: set a notifier"
(let* ((name (string-trim "*" (symbol-name variable)))
(reloaded (intern (format nil "*~A-RELOADED*" name)))
(watcher (intern (format nil "*~A-WATCHER*" name))))
`(progn
(defvar ,watcher (qnew "QFileSystemWatcher"))
(defvar ,variable (%ini-auto-reload ,library-name ,watcher
(lambda (name)
(let ((file-name (first (qfun ,watcher "files"))))
(qfun ,watcher "removePath" file-name)
(setf ,variable (qload-c++ ,library-name))
(qfun ,watcher "addPath" file-name))
(when ,reloaded
(funcall ,reloaded ',variable ,library-name)))))
(defvar ,reloaded nil))))
(defun qrun-on-ui-thread (function &optional (blocking t))
(%qrun-on-ui-thread function blocking))
#+threads
(defvar *gui-thread* mp:*current-process*)
(defmacro qrun-on-ui-thread* (&body body)
"args: (&body body)
alias: qrun*
Convenience macro for <code>qrun</code>, wrapping <code>body</code> in a closure (passing arguments, return values).
(qrun* (|setValue| ui:*progress-bar* value))
(let ((item (qrun* (qnew \"QTableWidgetItem\")))) ; return value(s)
...)"
#+threads
(let ((values (gensym)))
`(if (eql *gui-thread* mp:*current-process*)
,(if (second body)
(cons 'progn body)
(first body))
(let (,values)
(qrun (lambda ()
(setf ,values (multiple-value-list ,(if (second body)
(cons 'progn body)
(first body))))))
(values-list ,values))))
#-threads
(if (second body)
(cons 'progn body)
(first body)))
(defmacro qrun* (&body body) ; alias
`(qrun-on-ui-thread* ,@body))
(defun qload (file-name)
"args: (file-name)
Convenience function for Slime (or when loading EQL files from an ECL thread).<br>Loading files that create many Qt objects can be slow on the Slime REPL (many thread switches).<br>This function reduces all thread switches (GUI related) to a single one."
(qrun* (load file-name)))
(defun qquit (&optional (exit-status 0) (kill-all-threads t))
"args: (&optional (exit-status 0) (kill-all-threads t))
alias: qq
Terminates EQL. Use this function to quit gracefully, <b>not</b> <code>ext:quit</code>.<br><br>Negative values for <code>exit-status</code> will call <code>abort()</code> instead of normal program exit (e.g. to prevent infinite error message loops in some nasty cases)."
(declare (ignore kill-all-threads)) ; only here to be equivalent to EXT:QUIT
(assert (typep exit-status 'fixnum))
(qfun (qapp) "aboutToQuit")
(qfun (qapp) "quit")
(ffi:c-inline nil nil :void "cl_shutdown();" :one-liner t :side-effects t)
(if (minusp exit-status)
(ffi:c-inline nil nil :void "abort();" :one-liner t :side-effects t)
(ffi:c-inline (exit-status) (:int) :void "exit(#0);" :one-liner t :side-effects t)))
;; simplify using CLOS; see example "X-extras/CLOS-encapsulation.lisp"
(defgeneric the-qt-object (object)
(:documentation "Return the QT-OBJECT to be used whenever OBJECT is used as argument to any EQL function."))
(defun ensure-qt-object (object &optional quiet)
"args: (object)
Returns the <code>qt-object</code> of the given class/struct (see method <code>the-qt-object</code> in example <code>X-extras/CLOS-encapsulation.lisp</code>).<br>This function is used internally whenever a <code>qt-object</code> argument is expected."
(cond ((null object) ; e.g. passing NIL as parent widget: (qnew "QWidget(QWidget*)" nil)
nil)
((qt-object-p object)
object)
((let ((object* (if quiet
(ignore-errors (the-qt-object object))
(the-qt-object object))))
(if (qt-object-p object*)
object*
(unless quiet
(error "THE-QT-OBJECT returned ~S for class ~A, which is not of required type QT-OBJECT." object* object)))))))
(alias qnew qnew-instance)
(alias qnew* qnew-instance*)
(alias qdel qdelete)
(alias qget qproperty)
(alias qset qset-property)
(alias qfun qinvoke-method)
(alias qfun* qinvoke-method*)
(alias qfun+ qinvoke-method+)
(alias qmsg qmessage-box)
(alias qnull qnull-object)
(alias qrun qrun-on-ui-thread)
(alias qsel qselect)
(alias qq qquit)
;; add property :function-lambda-list to plist of EQL functions (inspired by ext:function-lambda-list)
(dolist (el (list (cons 'define-qt-wrappers '(qt-library &rest what))
(cons 'defvar-ui '(main-widget &rest variables))
(cons 'ensure-qt-object '(object))
(cons 'in-home '(&rest file-names))
(cons 'qadd-event-filter '(object event function))
(cons 'qapropos '(&optional search-string class-name))
(cons 'qapropos* '(&optional search-string class-name))
(cons 'qauto-reload-c++ '(variable library-name))
(cons 'qconnect '(caller signal receiver/function &optional slot))
(cons 'qcopy '(object))
(cons 'qdelete '(object))
(cons 'qdel '(object))
(cons 'qdisconnect '(caller &optional signal receiver/function slot))
(cons 'qenums '(class-name &optional enum-name))
(cons 'qeql '(object1 object2))
(cons 'qescape '(string))
(cons 'qexec '(&optional milliseconds))
(cons 'qfind-bound '(&optional class-name))
(cons 'qfind-bound* '(&optional class-name))
(cons 'qfind-child '(object object-name))
(cons 'qfind-children '(object &optional object-name class-name))
(cons 'qfrom-utf8 '(byte-array))
(cons 'qfun '(object function-name &rest arguments))
(cons 'qfun* '(object cast-class-name function-name &rest arguments))
(cons 'qfun+ '(object function-name &rest arguments))
(cons 'qfuns '(object &rest functions))
(cons 'qget '(object name))
(cons 'qgui '(&optional process-events))
(cons 'qid '(class-name))
(cons 'qinvoke-method '(object function-name &rest arguments))
(cons 'qinvoke-method* '(object cast-class-name function-name &rest arguments))
(cons 'qinvoke-method+ '(object function-name &rest arguments))
(cons 'qinvoke-methods '(object &rest functions))
(cons 'qlater '(function))
(cons 'qload '(file-name))
(cons 'qload-c++ '(library-name &optional unload))
(cons 'qload-ui '(file-name))
(cons 'qlocal8bit '(string))
(cons 'qmessage-box '(x))
(cons 'qmsg '(x))
(cons 'qnew '(class-name &rest arguments/properties))
(cons 'qnew-instance '(class-name &rest arguments/properties))
(cons 'qnew* '(class-name &rest arguments/properties))
(cons 'qnew-instance* '(class-name &rest arguments/properties))
(cons 'qnull '(object))
(cons 'qnull-object '(object))
(cons 'qobject-names '(&optional type))
(cons 'qoverride '(object name function))
(cons 'qproperties '(object &optional (depth 1)))
(cons 'qproperties* '(object))
(cons 'qproperty '(object name))
(cons 'qquit '(&optional (exit-status 0) (kill-all-threads t)))
(cons 'qremove-event-filter '(handle))
(cons 'qrequire '(module &optional quiet))
(cons 'qrgb '(red green blue &optional (alpha 255)))
(cons 'qrun '(function))
(cons 'qrun-on-ui-thread '(function))
(cons 'qrun* '(&body body))
(cons 'qrun-on-ui-thread* '(&body body))
(cons 'qset-null '(object))
(cons 'qset '(object name value))
(cons 'qset-color '(widget color-role color))
(cons 'qset-property '(object name value))
(cons 'qsignal '(name))
(cons 'qsingle-shot '(milliseconds function))
(cons 'qsleep '(seconds))
(cons 'qslot '(name))
(cons 'qstatic-meta-object '(class-name))
(cons 'qsuper-class-name '(class-name))
(cons 'qt-object-id '(object))
(cons 'qt-object-name '(object))
(cons 'qt-object-p '(object))
(cons 'qt-object-pointer '(object))
(cons 'qt-object-unique '(object))
(cons 'qt-object-? '(object))
(cons 'quic '(&optional (file.h "ui.h") (file.lisp "ui.lisp") (ui-package :ui)))
(cons 'qui-class '(file-name &optional object-name))
(cons 'qui-names '(file-name))
(cons 'qutf8 '(string))
(cons 'qvariant-from-value '(value type-name))
(cons 'qvariant-value '(object))
(cons 'tr '(source &optional context plural-number))))
(setf (get (car el) :function-lambda-list) (cdr el)))
;;; undocumented convenience hacks
(defun qt-object-to-string (object)
"String representation of a QT-OBJECT."
(when (qt-object-p object)
(format nil "(QT-OBJECT ~D ~D ~D)"
(qt-object-pointer object)
(qt-object-unique object)
(qt-object-id object))))
(defun qt-object-from-string (string)
"Restores a QT-OBJECT from its string representation."
(let ((exp (read-from-string string)))
(when (eql 'qt-object (first exp))
(apply (first exp) (rest exp)))))
;;; for android logging (EQL5-Android only, see "../eql.cpp")
(defun qlog (arg1 &rest args)
;; (qlog 12)
;; (qlog 1 "plus" 2 "gives" 6/2)
;; (qlog "x ~A y ~A" x y)
(%qlog (if (and (stringp arg1)
(find #\~ arg1))
(apply 'format nil arg1 args)
(x:join (mapcar 'princ-to-string (cons arg1 args))))))
;;; The following are modified/simplified functions taken from "src/lsp/top.lsp" (see ECL sources)
(in-package :si)
(defun feed-top-level (form)
(catch *quit-tag*
(let ((*debugger-hook* nil)
(*tpl-level* -1))
(%tpl form))))
(defun %read-lines ()
;; allow multi-line expressions (command line option "-qtpl")
(let (lines)
(loop
(let ((line (read-line)))
(setf lines (if lines (format nil "~A~%~A" lines line) line))
;; test for balanced parenthesis; if yes, we have a READ-able expression
;; (see READ-FROM-STRING in EVAL-TOP-LEVEL)
(multiple-value-bind (_ x)
(ignore-errors
(read-from-string (format nil "(~A)" (let ((lines* (copy-seq lines)))
(x:while-it (position #\\ lines*)
(setf lines* (replace lines* " " :start1 x:it)))
(remove-if-not (lambda (ch)
(find ch '(#\Space #\Newline #\( #\) #\" #\;)))
lines*)))))
(when (numberp x)
(return (if (find (string-upcase lines) '("NIL" "()") :test 'string=) ; avoid strange BREAK on NIL values
"'()"
lines))))))))
(defun %tpl-read (&aux (*read-suppress* nil))
(finish-output)
(loop
(case (peek-char nil *standard-input* nil :EOF)
((#\))
(warn "Ignoring an unmatched right parenthesis.")
(read-char))
((#\space #\tab)
(read-char))
((#\newline #\return)
(read-char)
;; avoid repeating prompt on successive empty lines:
(let ((command (tpl-make-command :newline "")))
(when command (return command))))
(:EOF
(terpri)
(return (tpl-make-command :EOF "")))
(#\:
(let ((exp (read-preserving-whitespace)))
(return (cond ((find exp '(:qq :exit))
"(eql:qquit)")
((find exp '(:qa :abort))
"(eql:qquit -1)")
(t
tpl-make-command exp (read-line))))))
(#\?
(read-char)
(case (peek-char nil *standard-input* nil :EOF)
((#\space #\tab #\newline #\return :EOF)
(return (tpl-make-command :HELP (read-line))))
(t
(unread-char #\?)
(return (read-preserving-whitespace)))))
;; We use READ-PRESERVING-WHITESPACE because with READ, if an
;; error happens within the reader, and we perform a ":C" or
;; (CONTINUE), the reader will wait for an inexistent #\Newline.
(t
(return (%read-lines))))))
(defun %break-where ()
(when (> *tpl-level* 0)
(tpl-print-current)))
(defun %tpl (form &key ((:commands *tpl-commands*) tpl-commands)
((:prompt-hook *tpl-prompt-hook*) *tpl-prompt-hook*)
(broken-at nil)
(quiet nil))
#-ecl-min
(declare (c::policy-debug-ihs-frame))
(let* ((*ihs-base* *ihs-top*)
(*ihs-top* (if broken-at (ihs-search t broken-at) (ihs-top)))
(*ihs-current* (if broken-at (ihs-prev *ihs-top*) *ihs-top*))
(*frs-base* (or (sch-frs-base *frs-top* *ihs-base*) (1+ (frs-top))))
(*frs-top* (frs-top))
(*quit-tags* (cons *quit-tag* *quit-tags*))
(*quit-tag* *quit-tags*) ; any unique new value
(*tpl-level* (1+ *tpl-level*))
(break-level *break-level*)
values -)
(set-break-env)
(set-current-ihs)
(flet ((rep ()
;; We let warnings pass by this way "warn" does the
;; work. It is conventional not to trap anything
;; that is not a SERIOUS-CONDITION. Otherwise we
;; would be interferring the behavior of code that relies
;; on conditions for communication (for instance our compiler)
;; and which expect nothing to happen by default.
(handler-bind
((serious-condition
(lambda (condition)
(cond ((< break-level 1)
;; Toplevel should enter the debugger on any condition.
)
(*allow-recursive-debug*
;; We are told to let the debugger handle this.
)
(t
(format t "~&Debugger received error of type: ~A~%~A~%~
Error flushed.~%"
(type-of condition) condition)
(clear-input)
(return-from rep t) ;; go back into the debugger loop.
)
)
)))
(with-grabbed-console
(unless quiet
(%break-where)
(setf quiet t))
(if form
(setq - form
form nil)
(setq - (locally (declare (notinline tpl-read))
(tpl-prompt)
(tpl-read))))
(setq values (multiple-value-list
(eval-with-env - *break-env*))
/// // // / / values *** ** ** * * (car /) +++ ++ ++ + + -)
(tpl-print values)))))
(when
(catch *quit-tag*
(if (zerop break-level)
(with-simple-restart
(restart-toplevel "Go back to Top-Level REPL.")
(rep))
(with-simple-restart
(restart-debugger "Go back to debugger level ~D." break-level)
(rep)))
nil)
(setf quiet nil)))))
| true |
;;; copyright (c) PI:NAME:<NAME>END_PI
(ffi:clines "#include <stdlib.h>")
(in-package :eql)
(defvar *break-on-errors* nil "Unless NIL, causes a simple (BREAK) on any EQL error.")
(defvar *byte-array-as-string* nil "Indicates to print a byte array as string, not as vector. See e.g. QPROPERTIES.")
(defvar *slime-mode* nil)
(defvar *qtpl* nil "To set in ~/.eclrc only; the same as command line option -qtpl.")
(defmacro alias (s1 s2)
`(setf (symbol-function ',s1) (function ,s2)))
(defmacro qlet ((&rest pairs) &body body)
"args: (((variable-1 expression-1) (variable-2 expression-2) ...) &body body)
Similar to <code>let*</code> (and to local C++ variables).<br><br>Creates temporary Qt objects, deleting them at the end of the <code>qlet</code> body.<br>If <code>expression</code> is a string, it will be substituted with <code>(qnew expression)</code>, optionally including constructor arguments.<br><br>This macro is convenient for e.g. local <code>QPainter</code> objects, in order to guarantee C++ destructors being called after leaving a local scope.
(qlet ((painter \"QPainter\"))
...)
(qlet ((reg-exp \"QRegExp(QString)\" \"^\\\\S+$\"))
...)"
(let ((vars (mapcar (lambda (x) (if (consp x) (first x) x)) pairs))
(exps (mapcar (lambda (x)
(if (consp x)
(let ((exp (rest x)))
(if (stringp (first exp))
(apply 'list 'qnew exp)
(first exp)))
nil))
pairs)))
`(let* ,(mapcar 'list vars exps)
(unwind-protect
(progn
,@body)
,(if (second vars)
`(progn . ,(mapcar (lambda (var) (list 'qdelete var))
(nreverse vars)))
`(qdelete ,(first vars)))))))
(defmacro qinvoke-methods (object &rest functions)
"args: (object &rest functions)
alias: qfuns
A simple syntax for nested <code>qfun</code> calls.
(qfuns object \"funA\" \"funB\" \"funC\") ; expands to: (qfun (qfun (qfun object \"funA\") \"funB\") \"funC\")
(qfuns object (\"funA\" 1) (\"funB\" a b c)) ; expands to: (qfun (qfun object \"funA\" 1) \"funB\" a b c)
(qfuns \"QApplication\" \"font\" \"family\")
(qfuns *table-view* \"model\" (\"index\" 0 2) \"data\" \"toString\")
;; alternatively:
(! (\"funC\" \"funB\" \"funA\" object))
(! ((\"funB\" a b c) (\"funA\" 1) object))
(! (\"family\" \"font\" \"QApplication\"))
(! (\"toString\" \"data\" (\"index\" 0 2) \"model\" *table-view*))
;; using wrapper functions, the above reads:
(|funC| (|funB| (|funA| object)))
(|funB| (|funA| object 1) a b c)
(|family| (|font.QApplication|))
(|toString| (|data| (|index| (|model| *table-view*) 0 2)))"
(let (form)
(dolist (fun functions)
(setf form (append (list 'qfun (or form object)) (x:ensure-list fun))))
form))
(defmacro qfuns (object &rest functions) ; alias
`(qinvoke-methods ,object ,@functions))
(defmacro ! (fun/s &rest args)
(if args
(let (call)
(when (consp (first args))
(cond ((and (stringp (caar args))
(char= #\Q (char (caar args) 0)))
(setf call :cast))
((eql :qt (caar args))
(setf call :qt))))
(case call
(:cast
`(qfun* ,(cadar args) ,(caar args) ,fun/s ,@(rest args)))
(:qt
`(qfun+ ,(cadar args) ,fun/s ,@(rest args)))
(t
`(qfun ,(first args) ,fun/s ,@(rest args)))))
`(qfuns ,@(reverse fun/s))))
(defmacro x:do-with (with &body body) ; re-definition from package :X because of EQL:QFUN
(when (atom with)
(setf with (list 'qfun with)))
`(progn
,@(mapcar (lambda (line)
;; needed for Qt wrappers (see "all-wrappers.lisp")
(if (and (eql 'qfun (first line))
(symbolp (third line)))
(cons (third line) (cons (second line) (nthcdr 3 line)))
line))
(mapcar (lambda (line)
(append with (if (or (atom line)
(eql 'quote (first line)))
(list line)
line)))
body))))
(defmacro defvar-ui (main &rest names)
"args: (main-widget &rest variables)
This macro simplifies the definition of UI variables:
(defvar-ui *main*
*label*
*line-edit*
...)
;; the above will expand to:
(progn
(defvar *label* (qfind-child *main* \"label\"))
(defvar *line-edit* (qfind-child *main* \"line_edit\"))
...)"
`(progn
,@(mapcar (lambda (name)
`(defvar ,name (qfind-child ,main ,(string-downcase (substitute #\_ #\- (string-trim "*" (symbol-name name)))))))
names)))
(defun %reference-name ()
(format nil "%~A%" (gensym)))
(defmacro qsingle-shot (milliseconds function)
;; check for LAMBDA, #'LAMBDA
(if (find (first function) '(lambda function))
;; hold a reference (will be called later from Qt event loop)
`(%qsingle-shot ,milliseconds (setf (symbol-function (intern ,(%reference-name))) ; lambda
,function))
`(%qsingle-shot ,milliseconds ,function))) ; 'foo
(defmacro qlater (function)
"args: (function)
Convenience macro: a <code>qsingle-shot</code> with a <code>0</code> timeout.<br>This will call <code>function</code> as soon as the Qt event loop is idle.
(qlater 'delayed-ini)"
`(qsingle-shot 0 ,function))
(defun %ensure-persistent-function (fun)
(typecase fun
(symbol ; 'foo
fun)
(function ; lambda
;; hold a reference (will be called later from Qt event loop)
(setf (symbol-function (intern (%reference-name)))
fun))))
(defun %make-vector ()
(make-array 0 :adjustable t :fill-pointer t))
(defun %break (&rest args)
(apply 'break args))
(defun %windows-version ()
(qfun "QSysInfo" "windowsVersion"))
(let ((eql5-home (namestring (merge-pathnames ".eql5/" (user-homedir-pathname)))))
(defun set-home (path)
(setf eql5-home path))
(defun in-home (&rest files)
(apply 'concatenate 'string eql5-home files)))
(let ((eql5-src #.(let ((path (namestring *default-pathname-defaults*))) ; hard-code EQL5 directory
(subseq path 0 (- (length path) (length "src/"))))))
(defun set-src (path)
(setf eql5-src path))
(defun in-src (&rest files)
(apply 'concatenate 'string eql5-src files)))
(defun qsignal (name)
"args: (name)
Needed in functions which expect a <code>const char*</code> Qt signal (not needed in <code>qconnect</code>)."
(concatenate 'string "2" name))
(defun qslot (name)
"args: (name)
Needed in functions which expect a <code>const char*</code> Qt slot (not needed in <code>qconnect</code>)."
(concatenate 'string "1" name))
(defun qenums (class-name &optional enum-name)
(%qenums class-name enum-name))
(defun qfind-bound (&optional class-name)
"args: (&optional class-name)
Finds all symbols bound to Qt objects, returning both the Qt class names and the respective Lisp variables.<br>Optionally finds the occurrencies of the passed Qt class name only.
(qfind-bound \"QLineEdit\")"
(let ((found (qfind-bound* class-name)))
(when found
(let ((tab-stop (1+ (apply 'max (mapcar (lambda (x) (length (car x))) found)))))
(dolist (el found)
(princ (format nil "~%~A~VT~(~S~)" ; "~VT" doesn't work on all terminals
(car el) tab-stop (cdr el))))))))
(defun qfind-bound* (&optional class-name)
"args: (&optional class-name)
Like <code>qfind-bound</code>, but returning the results as list of conses."
(if (and class-name
(not (qid class-name)))
(%error-msg "QFIND-BOUND" (list class-name))
(let (qt-objects)
(do-all-symbols (s)
(when (and (not (find (symbol-package s) #.'(list (find-package :si) (find-package :ext))))
(boundp s)
(ignore-errors (ensure-qt-object (symbol-value s)))
(or (not class-name)
(string= class-name (qt-object-name (symbol-value s)))))
(pushnew s qt-objects)))
(stable-sort (sort (mapcar (lambda (s) (cons (qt-object-name (symbol-value s)) s))
qt-objects)
'string< :key 'cdr)
'string< :key 'car))))
(defun qproperties (object &optional (depth 1) qml)
"args: (object &optional (depth 1))
Prints all current properties of <code>object</code>, searching both all Qt properties and all Qt methods which don't require arguments (marked with '<b>*</b>').<br>Optionally pass a <code>depth</code> indicating how many super-classes to include. Pass <code>T</code> to include all super-classes.
(qproperties (|font.QApplication|))
(qproperties (qnew \"QVariant(QString)\" \"42\"))
(qproperties *tool-button* 2) ; depth 2: both QToolButton and QAbstractButton"
(let ((object* (ensure-qt-object object)))
(when (qt-object-p object*)
(labels ((null-qt-object (obj)
(qt-object 0 0 (qt-object-id obj)))
(readable (obj fun ret)
(cond ((and *byte-array-as-string*
(string= "QByteArray" ret))
(x:bytes-to-string obj))
((string= "dynamicPropertyNames" fun)
(mapcar 'x:bytes-to-string obj))
((qt-object-p obj)
(let ((name (qt-object-name obj)))
(cond ((search name "QColor QLocale")
(! "name" obj))
((search name "QDate QTime QDateTime QFont QUrl QKeySequence")
(! "toString" obj))
((search name "QPixmap QImage QPicture QIcon QBitmap QDate QDateTime QTime QTextCursor QVariant QMargins QSqlQuery QWebElement")
(if (and (not (zerop (qt-object-pointer obj)))
(! "isNull" obj))
(null-qt-object obj)
obj))
((search name "QModelIndex")
(if (! "isValid" obj)
obj
(null-qt-object obj)))
((search name "QRegExp")
(if (! "isEmpty" obj)
(null-qt-object obj)
obj))
(t
obj))))
(t
obj))))
(let ((name (qt-object-name object*))
documentations functions properties)
(x:while (and name (not (eql 0 depth)))
(push (first (qapropos* nil (if qml object* name) nil qml))
documentations)
(setf name (qsuper-class-name name))
(when (numberp depth)
(decf depth)))
(dolist (docu documentations)
(dolist (type (if qml '("Properties:") '("Properties:" "Methods:")))
(dolist (fun (rest (find type (rest docu) :key 'first :test 'string=)))
(when (and (not (x:starts-with "void " fun))
(not (x:starts-with "constructor " fun))
(not (x:ends-with " static" fun))
(or (not (find #\( fun))
(search "()" fun))
;; state changing or copying functions
(notany (lambda (x) (search x fun))
'(" clone" " copy" " disconnect" " take" " create")))
(push fun functions)
(when (char= #\P (char type 0)) ; "Properties:"
(push (x:string-substitute "" " const" (subseq fun (1+ (position #\Space fun))))
properties))))))
(when functions
(setf functions (mapcar (lambda (fun)
(setf fun (x:string-substitute "" "const " fun)
fun (x:string-substitute "" " const" fun))
(let* ((p2 (position #\( fun))
(p1 (position #\Space fun :from-end t :end p2)))
(cons (subseq fun (1+ p1) p2) ; function name
(subseq fun 0 p1)))) ; return type
functions))
(setf functions (sort (remove-duplicates functions :test 'string= :key 'first)
'string< :key 'first))
(let ((tab-stop (+ 2 (apply 'max (mapcar (lambda (x) (length (first x))) functions)))))
(dolist (fun-ret functions)
(let* ((fun (car fun-ret))
(ret (cdr fun-ret))
(prop-p (find fun properties :test 'string=)))
(princ (format nil "~%~A~C~VT~S" ; "~VT" doesn't work on all terminals
fun
(if prop-p #\Space #\*)
tab-stop
(readable (if prop-p (qget object* fun) (! fun object*))
fun
ret))))))
(terpri)
(terpri)
(values)))))))
(defun qproperties* (object)
"args: (object)
Similar to <code>qproperties</code>, but listing all properties (including user defined ones) of the passed <code>object</code> instance.<br>This is only useful for e.g. <code>QQuickItem</code> derived classes, which don't have a corresponding C++ class, in order to list all QML properties.
(qproperties* (qml:find-quick-item \"myItem\"))"
(qproperties object 1 t))
(defun ignore-io-streams ()
(setf *standard-output* (make-broadcast-stream)
*trace-output* *standard-output*
*error-output* *standard-output*
*terminal-io* (make-two-way-stream (make-string-input-stream "")
*standard-output*)))
;;; top-level / slime-mode processing Qt events (command line options "-qtpl" and "-slime")
(defvar *slime-hook-file* nil)
(defun load-slime-auxiliary-file ()
(if (eql :repl-hook *slime-mode*) ; to set in "eql-start-swank.lisp"
(if (and (find-package :swank)
(find-symbol "*SLIME-REPL-EVAL-HOOKS*" :swank))
(load (or *slime-hook-file* (in-home "slime/repl-hook"))) ; Slime mode "REPL hook"
(qsingle-shot 500 'load-slime-auxiliary-file)) ; we need to wait for Emacs "slime-connect"
(load (x:check-recompile (in-home "lib/thread-safe"))))) ; Slime mode "thread safe" (default)
#+threads
(defun %read-thread ()
(si::tpl-prompt)
(unless (find-package :ecl-readline)
(princ "> "))
(let ((form (si::%tpl-read)))
(qrun-on-ui-thread (lambda () (eval-top-level form)) nil))
(values))
(defun start-read-thread ()
#+threads
(mp:process-run-function :read '%read-thread)
#-threads
(error "ECL threads not enabled, can't process Qt events."))
(defun eval-top-level (form)
;; needed to avoid unrecoverable BREAK on errors during READ (command line option "-qtpl")
(when (stringp form)
(handler-case (setf form (read-from-string form))
(error (err)
(princ err)))
(si::feed-top-level form))
(finish-output)
(start-read-thread))
(defun exec-with-simple-restart ()
(if *slime-mode*
(progn
(load-slime-auxiliary-file)
(loop
(with-simple-restart (restart-qt-events "Last resort only - prefer \"Return to SLIME's top level\"")
(qexec))))
(exec-with-simple-restart-dialog)))
(let (loaded)
(defun exec-with-simple-restart-dialog ()
(when *qtpl*
;; command line option "-qtpl" only, see "restart-dialog.lisp"
(unless loaded
(setf loaded t)
(load (in-home "lib/restart-dialog")))
(funcall (find-symbol "EXEC-WITH-SIMPLE-RESTART" :restart-dialog)))))
(defmacro qeval (&rest forms)
;; this macro will be redefined in Slime mode (see "../../slime/repl-hook.lisp")
"args: (&rest forms)
Slime mode <code>:repl-hook</code> only (not needed in default Slime mode): evaluate forms in GUI thread. Defaults to a simple <code>progn</code> outside of Slime."
(if (second forms)
(cons 'progn forms)
(first forms)))
;;; qt-object
(defstruct (qt-object (:constructor qt-object (pointer unique id &optional finalize)))
(pointer 0 :type integer)
(unique 0 :type integer)
(id 0 :type fixnum)
(finalize nil :type boolean))
(defun new-qt-object (pointer unique id finalize)
(let ((obj (qt-object pointer unique id finalize)))
(when finalize
(ext:set-finalizer obj 'qdelete))
obj))
(defmethod print-object ((object qt-object) s)
(print-unreadable-object (object s :type nil :identity nil)
(let* ((unique (qt-object-unique object))
(pointer (qt-object-pointer object))
(nullp (zerop pointer)))
(format s "~A~A ~A~A~A"
(qt-object-name object)
(if (and (plusp (qt-object-id object))
(plusp pointer))
(format nil " ~S" (qfun object "objectName"))
"")
(if nullp
"NULL"
(format nil "0x~X" pointer))
(if (or (zerop unique) nullp)
""
(format nil " [~D]" unique))
(if (qt-object-finalize object)
" GC"
"")))))
(defmacro tr (source &optional context (plural-number -1))
"args: (source &optional context plural-number)
Macro expanding to <code>qtranslate</code>, which calls <code>QCoreApplication::translate()</code>.<br>Both <code>source</code> and <code>context</code> can be Lisp forms evaluating to constant strings (at compile time).<br>The <code>context</code> argument defaults to the Lisp file name. For the <code>plural-number</code>, see Qt Assistant."
;; see compiler-macro in "my_app/tr.lisp"
(let ((source* (ignore-errors (eval source)))
(context* (ignore-errors (eval context))))
`(eql:qtranslate ,(if (stringp context*)
context*
(if *compile-file-truename* (file-namestring *compile-file-truename*) ""))
,source*
,plural-number)))
(defun qset-null (obj &optional (test t))
"args: (object)
Sets the Qt object pointer to <code>0</code>. This function is called automatically after <code>qdel</code>."
(if test ; after e.g. QDELETE, we don't need to test (faster)
(let ((obj* (ensure-qt-object obj)))
(when (qt-object-p obj*)
(setf (qt-object-pointer obj*) 0)))
(setf (qt-object-pointer obj) 0)))
(defun qgui (&optional ev)
"args: (&optional process-events)
Launches the EQL convenience GUI.<br>If you don't have an interactive environment, you can pass <code>T</code> to run a pseudo Qt event loop. A better option is to start the tool like so:<br><code>eql5 -qgui</code>, in order to run the Qt event loop natively."
(let (found)
(when (find-package :gui)
(let ((gui (find-symbol "*GUI*" :gui)))
(when gui
(setf found t)
(setf gui (symbol-value gui))
(qfun gui "show")
(qfun gui "raise"))))
(unless found
(in-package :eql-user)
(load (in-home "lib/gui"))))
(when ev
(loop
(qprocess-events)
(sleep 0.05))))
(defun qeql (obj1 obj2)
"args: (object1 object2)
Returns <code>T</code> for same instances of a Qt class. Comparing <code>QVariant</code> values will work, too.<br>To test for same Qt classes only, do:
(= (qt-object-id object1) (qt-object-id object2))"
(let ((obj1* (ensure-qt-object obj1))
(obj2* (ensure-qt-object obj2)))
(when (and (qt-object-p obj1*)
(qt-object-p obj2*))
(let ((v-id (qid "QVariant")))
(if (= v-id (qt-object-id obj1*) (qt-object-id obj2*))
(eql::%qvariant-equal obj1* obj2*)
(let ((u1 (qt-object-unique obj1*))
(u2 (qt-object-unique obj2*)))
(or (and (not (zerop u1))
(= u1 u2))
(and (= (qt-object-id obj1*)
(qt-object-id obj2*))
(= (qt-object-pointer obj1*)
(qt-object-pointer obj2*))))))))))
(defun qnull-object (obj)
"args: (object)
alias: qnull
Checks for a <code>0</code> Qt object pointer."
(let ((obj* (ensure-qt-object obj)))
(when (qt-object-p obj*)
(zerop (qt-object-pointer obj*)))))
(defun qdelete (obj &optional later)
(%qdelete obj later))
(defun %string-or-nil (x)
(typecase x
(string
x)
(symbol
(unless (member x '(t nil))
(symbol-name x)))))
(defun qapropos (&optional name class type offset)
(let ((name* (%string-or-nil name)))
(when (and (not name*)
(not class)
(not (y-or-n-p "Print documentation of all Qt classes?")))
(return-from qapropos))
(let ((main (%qapropos name* class type offset)))
(dolist (sub1 main)
(format t "~%~%~A~%" (first sub1))
(dolist (sub2 (rest sub1))
(format t "~% ~A~%~%" (first sub2))
(dolist (sub3 (rest sub2))
(let* ((par (position #\( sub3))
(x (if par
(position #\Space sub3 :end par :from-end t)
(position #\Space sub3))))
(format t " ~A~A~%" (make-string (max 0 (- 15 x))) sub3)))))))
(terpri)
nil)
(defun qapropos* (&optional name class type offset)
"args: (&optional search-string class-name)
Similar to <code>qapropos</code>, returning the results as nested list."
(%qapropos (%string-or-nil name) class type offset))
(defun qnew-instance (name &rest arguments)
(%qnew-instance name arguments))
(defun qnew-instance* (name &rest arguments)
"args: (class-name &rest arguments/properties)
alias: qnew*
Convenience function for the REPL.<br>Same as <code>qnew</code>, but showing the object immediately (if of type <code>QWidget</code>)."
(let ((obj (%qnew-instance name arguments)))
(when (and obj
(plusp (qt-object-id obj))
(! "isWidgetType" obj))
(! "show" obj))
obj))
(defun qinvoke-method (object function-name &rest arguments)
(%qinvoke-method object nil function-name arguments))
(defun qinvoke-method* (object cast-class-name function-name &rest arguments)
"args: (object cast-class-name function-name &rest arguments)
alias: qfun*
Similar to <code>qinvoke-method</code>, additionally passing a class name, enforcing a cast to that class.<br>Note that this cast is not type safe (the same as a C cast, so dirty hacks are possible).<br><br>Note: using the (recommended) wrapper functions (see <code>qfun</code>), casts are applied automatically where needed.
(qfun* graphics-text-item \"QGraphicsItem\" \"setPos\" (list x y)) ; multiple inheritance problem
(qfun* event \"QKeyEvent\" \"key\") ; not needed with QADD-EVENT-FILTER
;; alternatively:
(! \"setPos\" (\"QGraphicsItem\" graphics-text-item) (list x y))
(! \"key\" (\"QKeyEvent\" event))
;; better/recommended:
(|setPos| graphics-text-item (list x y))"
(%qinvoke-method object cast-class-name function-name arguments))
(defun qinvoke-method+ (object function-name &rest arguments)
"args: (object function-name &rest arguments)
alias: qfun+
Use this variant to call user defined functions (declared <code>Q_INVOKABLE</code>), slots, signals from external C++ classes.<br><br>In order to call ordinary functions, slots, signals from external C++ classes, just use the ordinary <code>qfun</code>.
(qfun+ *qt-main* \"foo\") ; see Qt_EQL
;; alternatively:
(! \"foo\" (:qt *qt-main*))"
(%qinvoke-method object :qt function-name arguments))
(defun qconnect (from signal to &optional slot)
(%qconnect from signal to slot))
(defun qdisconnect (from &optional signal to slot)
(%qdisconnect from signal to slot))
(defun qobject-names (&optional type)
(%qobject-names type))
(defun qui-class (file &optional var)
(%qui-class file var))
(defun qmessage-box (x)
"args: (x)
alias: qmsg
Convenience function: a simple message box, converting <code>x</code> to a string if necessary.<br>Returns its argument (just like <code>print</code>)."
#+android
(! "information" "QMessageBox" nil
"EQL5"
(if (stringp x) x (prin1-to-string x)))
#-android
(qlet ((msg "QMessageBox"
"icon" |QMessageBox.Information|
"text" (if (stringp x) x (prin1-to-string x))))
(! "setWindowTitle" msg "EQL5")
(dolist (fun '("show" "raise" "exec")) ; "raise" needed in some situations (e.g. OSX)
(qfun msg fun)))
x)
(defun qset-color (widget role color)
"args: (widget color-role color)
Convenience function for simple color settings (avoiding <code>QPalette</code> boilerplate).<br>Use <code>QPalette</code> directly for anything more involved.
(qset-color widget |QPalette.Window| \"white\")"
(qlet ((pal (qget widget "palette"))) ; QLET: safer than GC for very frequent calls
(qfun pal "setColor(QPalette::ColorRole,QColor)" role color)
(qset widget "palette" pal))
color)
(defun qexec (&optional ms)
(%qexec ms))
(defun qsleep (seconds)
"args: (seconds)
Similar to <code>sleep</code>, but continuing to process Qt events."
(%qexec (floor (* 1000 seconds)))
nil)
(defun qfind-children (object &optional object-name class-name)
(%qfind-children object object-name class-name))
(let (loaded)
(defun qselect (&optional on-selected)
"args: (&optional on-selected)
alias: qsel
Allows to select (by clicking) any (child) widget.<br>The variable <code>qsel:*q*</code> is set to the latest selected widget.<br><br>Optionally pass a function to be called upon selecting, with the selected widget as argument.
(qsel (lambda (widget) (qmsg widget)))"
(unless loaded
(setf loaded t)
(load (in-home "lib/qselect")))
(%qselect on-selected)))
(let (loaded)
(defun quic (&optional (ui.h "ui.h") (ui.lisp "ui.lisp") (ui-package :ui) &rest properties)
"args: (&optional (file.h \"ui.h\") (file.lisp \"ui.lisp\") (ui-package :ui))
Takes C++ code from a file generated by the <code>uic</code> user interface compiler, and generates the corresponding EQL code.<br>See also command line option <code>-quic</code>."
(unless loaded
(setf loaded t)
(load (in-home "lib/quic")))
(funcall (intern "RUN" :quic) ui.h ui.lisp ui-package properties)))
(defun qrequire (module &optional quiet)
(%qrequire module quiet))
(defun qload-c++ (library-name &optional unload)
(%qload-c++ library-name unload))
(defun define-qt-wrappers (qt-library &rest what)
"args: (qt-library &rest what)
Defines Lisp methods for all Qt methods/signals/slots of given library.<br>(See example <code>Qt_EQL/trafficlight/</code>).
(define-qt-wrappers *c++*) ; generate wrappers (see \"Qt_EQL/\")
(define-qt-wrappers *c++* :slots) ; Qt slots only (any of :methods :slots :signals)
(my-qt-function *c++* x y) ; instead of: (! \"myQtFunction\" (:qt *c++*) x y)"
(let ((all-functions (cdar (qapropos* nil (ensure-qt-object qt-library)))))
(unless what
(setf what '(:methods :slots :signals)))
(dolist (functions (loop :for el :in what :collect
(concatenate 'string (string-capitalize el) ":")))
(dolist (fun (rest (find functions all-functions
:key 'first :test 'string=)))
(let* ((p (position #\( fun))
(qt-name (subseq fun (1+ (position #\Space fun :from-end t :end p)) p))
(lisp-name (intern (with-output-to-string (s)
(x:do-string (ch qt-name)
(if (upper-case-p ch)
(format s "-~C" ch)
(write-char (char-upcase ch) s)))))))
;; no way to avoid EVAL here (excluding non-portable hacks)
(eval `(defgeneric ,lisp-name (object &rest arguments)))
(eval `(defmethod ,lisp-name ((object qt-object) &rest arguments)
(%qinvoke-method object :qt ,qt-name arguments))))))))
#+linux
(defun %ini-auto-reload (library-name watcher on-file-change)
(multiple-value-bind (object file-name)
(qload-c++ library-name)
(when file-name
(qfun watcher "addPath" file-name)
(qconnect watcher "fileChanged(QString)" on-file-change))
object))
#+linux
(defmacro qauto-reload-c++ (variable library-name)
"args: (variable library-name)
<b>Linux only.</b><br><br>Extends <code>qload-c++</code> (see <code>Qt_EQL/</code>).<br><br>Defines a global variable (see return value of <code>qload-c++</code>), which will be updated on every change of the C++ plugin (e.g. after recompiling, the plugin will automatically be reloaded, and the <code>variable</code> will be set to its new value).<br><br>If you want to be notified on every change of the plugin, set <code>*<variable>-reloaded*</code>. It will then be called after reloading, passing both the variable name and the plugin name.<br>See <code>qload-c++</code> for an example how to call plugin functions.
(qauto-reload-c++ *c++* \"eql_cpp\")
(setf *c++-reloaded* (lambda (var lib) (qapropos nil (symbol-value var)))) ; optional: set a notifier"
(let* ((name (string-trim "*" (symbol-name variable)))
(reloaded (intern (format nil "*~A-RELOADED*" name)))
(watcher (intern (format nil "*~A-WATCHER*" name))))
`(progn
(defvar ,watcher (qnew "QFileSystemWatcher"))
(defvar ,variable (%ini-auto-reload ,library-name ,watcher
(lambda (name)
(let ((file-name (first (qfun ,watcher "files"))))
(qfun ,watcher "removePath" file-name)
(setf ,variable (qload-c++ ,library-name))
(qfun ,watcher "addPath" file-name))
(when ,reloaded
(funcall ,reloaded ',variable ,library-name)))))
(defvar ,reloaded nil))))
(defun qrun-on-ui-thread (function &optional (blocking t))
(%qrun-on-ui-thread function blocking))
#+threads
(defvar *gui-thread* mp:*current-process*)
(defmacro qrun-on-ui-thread* (&body body)
"args: (&body body)
alias: qrun*
Convenience macro for <code>qrun</code>, wrapping <code>body</code> in a closure (passing arguments, return values).
(qrun* (|setValue| ui:*progress-bar* value))
(let ((item (qrun* (qnew \"QTableWidgetItem\")))) ; return value(s)
...)"
#+threads
(let ((values (gensym)))
`(if (eql *gui-thread* mp:*current-process*)
,(if (second body)
(cons 'progn body)
(first body))
(let (,values)
(qrun (lambda ()
(setf ,values (multiple-value-list ,(if (second body)
(cons 'progn body)
(first body))))))
(values-list ,values))))
#-threads
(if (second body)
(cons 'progn body)
(first body)))
(defmacro qrun* (&body body) ; alias
`(qrun-on-ui-thread* ,@body))
(defun qload (file-name)
"args: (file-name)
Convenience function for Slime (or when loading EQL files from an ECL thread).<br>Loading files that create many Qt objects can be slow on the Slime REPL (many thread switches).<br>This function reduces all thread switches (GUI related) to a single one."
(qrun* (load file-name)))
(defun qquit (&optional (exit-status 0) (kill-all-threads t))
"args: (&optional (exit-status 0) (kill-all-threads t))
alias: qq
Terminates EQL. Use this function to quit gracefully, <b>not</b> <code>ext:quit</code>.<br><br>Negative values for <code>exit-status</code> will call <code>abort()</code> instead of normal program exit (e.g. to prevent infinite error message loops in some nasty cases)."
(declare (ignore kill-all-threads)) ; only here to be equivalent to EXT:QUIT
(assert (typep exit-status 'fixnum))
(qfun (qapp) "aboutToQuit")
(qfun (qapp) "quit")
(ffi:c-inline nil nil :void "cl_shutdown();" :one-liner t :side-effects t)
(if (minusp exit-status)
(ffi:c-inline nil nil :void "abort();" :one-liner t :side-effects t)
(ffi:c-inline (exit-status) (:int) :void "exit(#0);" :one-liner t :side-effects t)))
;; simplify using CLOS; see example "X-extras/CLOS-encapsulation.lisp"
(defgeneric the-qt-object (object)
(:documentation "Return the QT-OBJECT to be used whenever OBJECT is used as argument to any EQL function."))
(defun ensure-qt-object (object &optional quiet)
"args: (object)
Returns the <code>qt-object</code> of the given class/struct (see method <code>the-qt-object</code> in example <code>X-extras/CLOS-encapsulation.lisp</code>).<br>This function is used internally whenever a <code>qt-object</code> argument is expected."
(cond ((null object) ; e.g. passing NIL as parent widget: (qnew "QWidget(QWidget*)" nil)
nil)
((qt-object-p object)
object)
((let ((object* (if quiet
(ignore-errors (the-qt-object object))
(the-qt-object object))))
(if (qt-object-p object*)
object*
(unless quiet
(error "THE-QT-OBJECT returned ~S for class ~A, which is not of required type QT-OBJECT." object* object)))))))
(alias qnew qnew-instance)
(alias qnew* qnew-instance*)
(alias qdel qdelete)
(alias qget qproperty)
(alias qset qset-property)
(alias qfun qinvoke-method)
(alias qfun* qinvoke-method*)
(alias qfun+ qinvoke-method+)
(alias qmsg qmessage-box)
(alias qnull qnull-object)
(alias qrun qrun-on-ui-thread)
(alias qsel qselect)
(alias qq qquit)
;; add property :function-lambda-list to plist of EQL functions (inspired by ext:function-lambda-list)
(dolist (el (list (cons 'define-qt-wrappers '(qt-library &rest what))
(cons 'defvar-ui '(main-widget &rest variables))
(cons 'ensure-qt-object '(object))
(cons 'in-home '(&rest file-names))
(cons 'qadd-event-filter '(object event function))
(cons 'qapropos '(&optional search-string class-name))
(cons 'qapropos* '(&optional search-string class-name))
(cons 'qauto-reload-c++ '(variable library-name))
(cons 'qconnect '(caller signal receiver/function &optional slot))
(cons 'qcopy '(object))
(cons 'qdelete '(object))
(cons 'qdel '(object))
(cons 'qdisconnect '(caller &optional signal receiver/function slot))
(cons 'qenums '(class-name &optional enum-name))
(cons 'qeql '(object1 object2))
(cons 'qescape '(string))
(cons 'qexec '(&optional milliseconds))
(cons 'qfind-bound '(&optional class-name))
(cons 'qfind-bound* '(&optional class-name))
(cons 'qfind-child '(object object-name))
(cons 'qfind-children '(object &optional object-name class-name))
(cons 'qfrom-utf8 '(byte-array))
(cons 'qfun '(object function-name &rest arguments))
(cons 'qfun* '(object cast-class-name function-name &rest arguments))
(cons 'qfun+ '(object function-name &rest arguments))
(cons 'qfuns '(object &rest functions))
(cons 'qget '(object name))
(cons 'qgui '(&optional process-events))
(cons 'qid '(class-name))
(cons 'qinvoke-method '(object function-name &rest arguments))
(cons 'qinvoke-method* '(object cast-class-name function-name &rest arguments))
(cons 'qinvoke-method+ '(object function-name &rest arguments))
(cons 'qinvoke-methods '(object &rest functions))
(cons 'qlater '(function))
(cons 'qload '(file-name))
(cons 'qload-c++ '(library-name &optional unload))
(cons 'qload-ui '(file-name))
(cons 'qlocal8bit '(string))
(cons 'qmessage-box '(x))
(cons 'qmsg '(x))
(cons 'qnew '(class-name &rest arguments/properties))
(cons 'qnew-instance '(class-name &rest arguments/properties))
(cons 'qnew* '(class-name &rest arguments/properties))
(cons 'qnew-instance* '(class-name &rest arguments/properties))
(cons 'qnull '(object))
(cons 'qnull-object '(object))
(cons 'qobject-names '(&optional type))
(cons 'qoverride '(object name function))
(cons 'qproperties '(object &optional (depth 1)))
(cons 'qproperties* '(object))
(cons 'qproperty '(object name))
(cons 'qquit '(&optional (exit-status 0) (kill-all-threads t)))
(cons 'qremove-event-filter '(handle))
(cons 'qrequire '(module &optional quiet))
(cons 'qrgb '(red green blue &optional (alpha 255)))
(cons 'qrun '(function))
(cons 'qrun-on-ui-thread '(function))
(cons 'qrun* '(&body body))
(cons 'qrun-on-ui-thread* '(&body body))
(cons 'qset-null '(object))
(cons 'qset '(object name value))
(cons 'qset-color '(widget color-role color))
(cons 'qset-property '(object name value))
(cons 'qsignal '(name))
(cons 'qsingle-shot '(milliseconds function))
(cons 'qsleep '(seconds))
(cons 'qslot '(name))
(cons 'qstatic-meta-object '(class-name))
(cons 'qsuper-class-name '(class-name))
(cons 'qt-object-id '(object))
(cons 'qt-object-name '(object))
(cons 'qt-object-p '(object))
(cons 'qt-object-pointer '(object))
(cons 'qt-object-unique '(object))
(cons 'qt-object-? '(object))
(cons 'quic '(&optional (file.h "ui.h") (file.lisp "ui.lisp") (ui-package :ui)))
(cons 'qui-class '(file-name &optional object-name))
(cons 'qui-names '(file-name))
(cons 'qutf8 '(string))
(cons 'qvariant-from-value '(value type-name))
(cons 'qvariant-value '(object))
(cons 'tr '(source &optional context plural-number))))
(setf (get (car el) :function-lambda-list) (cdr el)))
;;; undocumented convenience hacks
(defun qt-object-to-string (object)
"String representation of a QT-OBJECT."
(when (qt-object-p object)
(format nil "(QT-OBJECT ~D ~D ~D)"
(qt-object-pointer object)
(qt-object-unique object)
(qt-object-id object))))
(defun qt-object-from-string (string)
"Restores a QT-OBJECT from its string representation."
(let ((exp (read-from-string string)))
(when (eql 'qt-object (first exp))
(apply (first exp) (rest exp)))))
;;; for android logging (EQL5-Android only, see "../eql.cpp")
(defun qlog (arg1 &rest args)
;; (qlog 12)
;; (qlog 1 "plus" 2 "gives" 6/2)
;; (qlog "x ~A y ~A" x y)
(%qlog (if (and (stringp arg1)
(find #\~ arg1))
(apply 'format nil arg1 args)
(x:join (mapcar 'princ-to-string (cons arg1 args))))))
;;; The following are modified/simplified functions taken from "src/lsp/top.lsp" (see ECL sources)
(in-package :si)
(defun feed-top-level (form)
(catch *quit-tag*
(let ((*debugger-hook* nil)
(*tpl-level* -1))
(%tpl form))))
(defun %read-lines ()
;; allow multi-line expressions (command line option "-qtpl")
(let (lines)
(loop
(let ((line (read-line)))
(setf lines (if lines (format nil "~A~%~A" lines line) line))
;; test for balanced parenthesis; if yes, we have a READ-able expression
;; (see READ-FROM-STRING in EVAL-TOP-LEVEL)
(multiple-value-bind (_ x)
(ignore-errors
(read-from-string (format nil "(~A)" (let ((lines* (copy-seq lines)))
(x:while-it (position #\\ lines*)
(setf lines* (replace lines* " " :start1 x:it)))
(remove-if-not (lambda (ch)
(find ch '(#\Space #\Newline #\( #\) #\" #\;)))
lines*)))))
(when (numberp x)
(return (if (find (string-upcase lines) '("NIL" "()") :test 'string=) ; avoid strange BREAK on NIL values
"'()"
lines))))))))
(defun %tpl-read (&aux (*read-suppress* nil))
(finish-output)
(loop
(case (peek-char nil *standard-input* nil :EOF)
((#\))
(warn "Ignoring an unmatched right parenthesis.")
(read-char))
((#\space #\tab)
(read-char))
((#\newline #\return)
(read-char)
;; avoid repeating prompt on successive empty lines:
(let ((command (tpl-make-command :newline "")))
(when command (return command))))
(:EOF
(terpri)
(return (tpl-make-command :EOF "")))
(#\:
(let ((exp (read-preserving-whitespace)))
(return (cond ((find exp '(:qq :exit))
"(eql:qquit)")
((find exp '(:qa :abort))
"(eql:qquit -1)")
(t
tpl-make-command exp (read-line))))))
(#\?
(read-char)
(case (peek-char nil *standard-input* nil :EOF)
((#\space #\tab #\newline #\return :EOF)
(return (tpl-make-command :HELP (read-line))))
(t
(unread-char #\?)
(return (read-preserving-whitespace)))))
;; We use READ-PRESERVING-WHITESPACE because with READ, if an
;; error happens within the reader, and we perform a ":C" or
;; (CONTINUE), the reader will wait for an inexistent #\Newline.
(t
(return (%read-lines))))))
(defun %break-where ()
(when (> *tpl-level* 0)
(tpl-print-current)))
(defun %tpl (form &key ((:commands *tpl-commands*) tpl-commands)
((:prompt-hook *tpl-prompt-hook*) *tpl-prompt-hook*)
(broken-at nil)
(quiet nil))
#-ecl-min
(declare (c::policy-debug-ihs-frame))
(let* ((*ihs-base* *ihs-top*)
(*ihs-top* (if broken-at (ihs-search t broken-at) (ihs-top)))
(*ihs-current* (if broken-at (ihs-prev *ihs-top*) *ihs-top*))
(*frs-base* (or (sch-frs-base *frs-top* *ihs-base*) (1+ (frs-top))))
(*frs-top* (frs-top))
(*quit-tags* (cons *quit-tag* *quit-tags*))
(*quit-tag* *quit-tags*) ; any unique new value
(*tpl-level* (1+ *tpl-level*))
(break-level *break-level*)
values -)
(set-break-env)
(set-current-ihs)
(flet ((rep ()
;; We let warnings pass by this way "warn" does the
;; work. It is conventional not to trap anything
;; that is not a SERIOUS-CONDITION. Otherwise we
;; would be interferring the behavior of code that relies
;; on conditions for communication (for instance our compiler)
;; and which expect nothing to happen by default.
(handler-bind
((serious-condition
(lambda (condition)
(cond ((< break-level 1)
;; Toplevel should enter the debugger on any condition.
)
(*allow-recursive-debug*
;; We are told to let the debugger handle this.
)
(t
(format t "~&Debugger received error of type: ~A~%~A~%~
Error flushed.~%"
(type-of condition) condition)
(clear-input)
(return-from rep t) ;; go back into the debugger loop.
)
)
)))
(with-grabbed-console
(unless quiet
(%break-where)
(setf quiet t))
(if form
(setq - form
form nil)
(setq - (locally (declare (notinline tpl-read))
(tpl-prompt)
(tpl-read))))
(setq values (multiple-value-list
(eval-with-env - *break-env*))
/// // // / / values *** ** ** * * (car /) +++ ++ ++ + + -)
(tpl-print values)))))
(when
(catch *quit-tag*
(if (zerop break-level)
(with-simple-restart
(restart-toplevel "Go back to Top-Level REPL.")
(rep))
(with-simple-restart
(restart-debugger "Go back to debugger level ~D." break-level)
(rep)))
nil)
(setf quiet nil)))))
|
[
{
"context": "SSIBILITY OF SUCH DAMAGE.\n\n; Original Author(s):\n; Shilpi Goel <[email protected]>\n; Contributing Au",
"end": 1763,
"score": 0.9998947978019714,
"start": 1752,
"tag": "NAME",
"value": "Shilpi Goel"
},
{
"context": "GE.\n\n; Original Author(s):\n; Shilpi Goel <[email protected]>\n; Contributing Author(s):\n; Alessandro Coglio ",
"end": 1794,
"score": 0.9999332427978516,
"start": 1773,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "[email protected]>\n; Contributing Author(s):\n; Alessandro Coglio <[email protected]>\n\n(in-package \"X86ISA\")\n\n;;",
"end": 1841,
"score": 0.999889075756073,
"start": 1824,
"tag": "NAME",
"value": "Alessandro Coglio"
},
{
"context": "\n; Contributing Author(s):\n; Alessandro Coglio <[email protected]>\n\n(in-package \"X86ISA\")\n\n;; =====================",
"end": 1863,
"score": 0.9999316334724426,
"start": 1845,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/projects/x86isa/machine/instructions/rotate-and-shift.lisp
|
mayankmanj/acl2
| 305 |
; X86ISA Library
; Note: The license below is based on the template at:
; http://opensource.org/licenses/BSD-3-Clause
; Copyright (C) 2015, Regents of the University of Texas
; Copyright (C) 2018, Kestrel Technology, LLC
; All rights reserved.
; 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 copyright holders 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.
; Original Author(s):
; Shilpi Goel <[email protected]>
; Contributing Author(s):
; Alessandro Coglio <[email protected]>
(in-package "X86ISA")
;; ======================================================================
(include-book "shifts-spec"
:ttags (:include-raw :syscall-exec :other-non-det :undef-flg))
(include-book "rotates-spec"
:ttags (:include-raw :syscall-exec :other-non-det :undef-flg))
(include-book "../decoding-and-spec-utils"
:ttags (:include-raw :syscall-exec :other-non-det :undef-flg))
(local (include-book "centaur/bitops/ihs-extensions" :dir :system))
;; ======================================================================
;; INSTRUCTION: SAL/SAR/SHL/SHR/RCL/RCR/ROL/ROR
;; ======================================================================
(local
(defrule add-to-*ip-integerp-type
(implies (and (integerp *ip)
(integerp delta))
(integerp (mv-nth 1 (add-to-*ip proc-mode *ip delta x86))))
:in-theory (e/d (add-to-*ip) ())
:rule-classes (:rewrite :type-prescription)))
(def-inst x86-sal/sar/shl/shr/rcl/rcr/rol/ror
:guard (not (equal (modr/m->reg modr/m) 6))
:guard-hints (("Goal"
:in-theory (e/d ()
(unsigned-byte-p
not force (force)))))
:parents (one-byte-opcodes)
:returns (x86 x86p :hyp (x86p x86)
:hints (("Goal" :in-theory
(e/d ()
(trunc
select-operand-size
mv-nth-0-of-add-to-*ip-when-64-bit-modep
mv-nth-1-of-add-to-*ip-when-64-bit-modep
signed-byte-p
unsigned-byte-p
not force (force))))))
:long
"<p>
Op/En: MI<br/>
C0/0: ROL r/m8, imm8<br/>
C0/1: ROR r/m8, imm8<br/>
C0/2: RCL r/m8, imm8<br/>
C0/3: RCR r/m8, imm8<br/>
C0/4: SAL/SHL r/m8, imm8<br/>
C0/5: SHR r/m8, imm8<br/>
C0/7: SAR r/m8, imm8<br/>
C1/0: ROL r/m16/32/64, imm8<br/>
C1/1: ROR r/m16/32/64, imm8<br/>
C1/2: RCL r/m16/32/64, imm8<br/>
C1/3: RCR r/m16/32/64, imm8<br/>
C1/4: SAL/SHL r/m16/32/64, imm8<br/>
C1/5: SHR r/m16/32/64, imm8<br/>
C1/7: SAR r/m16/32/64. imm8<br/>
</p>
<p>
Op/En: M1<br/>
D0/0: ROL r/m8, 1<br/>
D0/1: ROR r/m8, 1<br/>
D0/2: RCL r/m8, 1<br/>
D0/3: RCR r/m8, 1<br/>
D0/4: SAL/SHL r/m8, 1<br/>
D0/5: SHR r/m8, 1<br/>
D0/7: SAR r/m8, 1<br/>
D1/0: ROL r/m16/32/64, 1<br/>
D1/1: ROR r/m16/32/64, 1<br/>
D1/2: RCL r/m16/32/64, 1<br/>
D1/3: RCR r/m16/32/64, 1<br/>
D1/4: SAL/SHL r/m16/32/64, 1<br/>
D1/5: SHR r/m16/32/64, 1<br/>
D1/7: SAR r/m16/32/64, 1<br/>
</p>
<p>
Op/En: MC<br/>
D2/0: ROL r/m8, CL<br/>
D2/1: ROR r/m8, CL<br/>
D2/2: RCL r/m8, CL<br/>
D2/3: RCR r/m8, CL<br/>
D2/4: SAL/SHL r/m8, CL<br/>
D2/5: SHR r/m8, CL<br/>
D2/7: SAR r/m8, CL<br/>
D3/0: ROL r/m16/32/64, CL<br/>
D3/1: ROR r/m16/32/64, CL<br/>
D3/2: RCL r/m16/32/64, CL<br/>
D3/3: RCR r/m16/32/64, CL<br/>
D3/4: SAL/SHL r/m16/32/64, CL<br/>
D3/5: SHR r/m16/32/64, CL<br/>
D3/7: SAR r/m16/32/64, CL<br/>
</p>"
:modr/m t
:body
(b* ((p2 (prefixes->seg prefixes))
(p4? (equal #.*addr-size-override* (prefixes->adr prefixes)))
(byte-operand? (or (equal opcode #xC0)
(equal opcode #xD0)
(equal opcode #xD2)))
((the (integer 0 8) ?reg/mem-size)
(select-operand-size
proc-mode byte-operand? rex-byte nil prefixes nil nil nil x86))
(seg-reg (select-segment-register proc-mode p2 p4? mod r/m sib x86))
(inst-ac? t)
((mv flg0 ?reg/mem (the (unsigned-byte 3) increment-RIP-by) addr x86)
(x86-operand-from-modr/m-and-sib-bytes
proc-mode #.*gpr-access* reg/mem-size inst-ac?
nil ;; Not a memory pointer operand
seg-reg p4? temp-rip rex-byte r/m mod sib
;; Bytes of immediate data (only relevant when RIP-relative
;; addressing is done to get ?reg/mem operand)
(if (or (equal opcode #xC0)
(equal opcode #xC1))
1
0)
x86))
((when flg0)
(!!ms-fresh :x86-operand-from-modr/m-and-sib-bytes flg0))
((mv flg (the (signed-byte #.*max-linear-address-size*) temp-rip))
(add-to-*ip proc-mode temp-rip increment-RIP-by x86))
((when flg) (!!ms-fresh :rip-increment-error flg))
((mv flg1 shift/rotate-by x86)
(case opcode
((#xD0 #xD1)
(mv nil 1 x86))
((#xD2 #xD3)
(mv nil (rr08 *rcx* rex-byte x86) x86))
((#xC0 #xC1)
(rme-size-opt proc-mode 1 temp-rip #.*cs* :x nil x86))
(otherwise ;; will not be reached
(mv nil 0 x86))))
((when flg1)
(!!ms-fresh :rme-size-error flg1))
(countMask (if (logbitp #.*w* rex-byte)
#x3F
#x1F))
(shift/rotate-by (logand countMask shift/rotate-by))
((mv flg (the (signed-byte #.*max-linear-address-size+1*) temp-rip))
(if (or (equal opcode #xC0)
(equal opcode #xC1))
(add-to-*ip proc-mode temp-rip 1 x86)
(mv nil temp-rip)))
((when flg) (!!ms-fresh :rip-increment-error flg))
(badlength? (check-instruction-length start-rip temp-rip 0))
((when badlength?)
(!!fault-fresh :gp 0 :instruction-length badlength?)) ;; #GP(0)
;; Computing the flags and the result:
(input-rflags (the (unsigned-byte 32) (rflags x86)))
((mv result
(the (unsigned-byte 32) output-rflags)
(the (unsigned-byte 32) undefined-flags))
(case reg
(0
;; ROL
(rol-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
(1
;; ROR
(ror-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
(2
;; RCL
(rcl-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
(3
;; RCR
(rcr-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
(4
;; SAL/SHL
(sal/shl-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
(5
;; SHR
(shr-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
(7
;; SAR
(sar-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
;; The guard for this function will ensure that we don't
;; reach here.
(otherwise
(mv 0 0 0))))
;; Update the x86 state:
(x86 (write-user-rflags output-rflags undefined-flags x86))
((mv flg2 x86)
(x86-operand-to-reg/mem proc-mode reg/mem-size
inst-ac?
nil ;; Not a memory pointer operand
;; TO-DO@Shilpi: Remove this trunc.
(trunc reg/mem-size result)
seg-reg
addr
rex-byte
r/m
mod
x86))
;; Note: If flg2 is non-nil, we bail out without changing the x86 state.
((when flg2)
(!!ms-fresh :x86-operand-to-reg/mem flg2))
(x86 (write-*ip proc-mode temp-rip x86)))
x86))
;; ======================================================================
;; INSTRUCTION: SHLD/SHRD
;; ======================================================================
(def-inst x86-shld/shrd
:returns (x86 x86p :hyp (x86p x86))
:parents (one-byte-opcodes)
:short "Double-precision shift left or right."
:long
"<p>
Op/En: MRI<br/>
0F A4: SHLD r/m16, r16, imm8<br/>
0F A4: SHLD r/m32, r32, imm8<br/>
0F A4: SHLD r/m64, r64, imm8<br/>
</p>
<p>
Op/En: MRC<br/>
0F A5: SHLD r/m16, r16, CL<br/>
0F A5: SHLD r/m32, r32, CL<br/>
0F A5: SHLD r/m64, r64, CL<br/>
</p>
<p>
Op/En: MRI<br/>
0F AC: SHRD r/m16, r16, imm8<br/>
0F AC: SHRD r/m32, r32, imm8<br/>
0F AC: SHRD r/m64, r64, imm8<br/>
</p>
<p>
Op/En: MRC<br/>
0F AD: SHRD r/m16, r16, CL<br/>
0F AD: SHRD r/m32, r32, CL<br/>
0F AD: SHRD r/m64, r64, CL<br/>
</p>"
:modr/m t
:body
(b* ((p2 (prefixes->seg prefixes))
(p4? (equal #.*addr-size-override* (prefixes->adr prefixes)))
((the (integer 2 8) operand-size)
(select-operand-size proc-mode
nil ; not a byte operand
rex-byte
nil ; not an immediate operand
prefixes
nil ; no 64-bit default in 64-bit mode
nil ; don't ignore REX in 64-bit mode
nil ; don't ignore P3 in 64-bit mode
x86))
(seg-reg (select-segment-register proc-mode p2 p4? mod r/m sib x86))
;; read destination operand:
(inst-ac? t)
((mv flg dst-value increment-rip-by dst-addr x86)
(x86-operand-from-modr/m-and-sib-bytes proc-mode
#.*gpr-access*
operand-size
inst-ac?
nil ; not memory pointer operand
seg-reg
p4?
temp-rip
rex-byte
r/m
mod sib
1 ; imm8
x86))
((when flg) (!!ms-fresh :x86-operand-from-modr/m-and-sib-bytes flg))
((mv flg (the (signed-byte #.*max-linear-address-size*) temp-rip))
(add-to-*ip proc-mode temp-rip increment-rip-by x86))
((when flg) (!!ms-fresh :rip-increment-error flg))
;; read source operand:
(src-value (rgfi-size operand-size
(reg-index reg rex-byte #.*r*)
rex-byte
x86))
;; read count operand:
((mv flg count x86)
(case opcode
((#xA4 #xAC) (rme-size-opt proc-mode 1 temp-rip #.*cs* :x nil x86))
((#xA5 #xAD) (mv nil (rr08 *rcx* rex-byte x86) x86))
(otherwise (mv nil 0 x86)))) ; unreachable
((when flg) (!!ms-fresh :rme-size-error flg))
((mv flg (the (signed-byte #.*max-linear-address-size*) temp-rip))
(case opcode
((#xA4 #xAC) (add-to-*ip proc-mode temp-rip 1 x86))
((#xA5 #xAD) (mv nil temp-rip))
(otherwise (mv nil 0)))) ; unreachable
((when flg) (!!ms-fresh :rip-increment-error flg))
;; check instruction length now that we have read all of it:
(badlength? (check-instruction-length start-rip temp-rip 0))
((when badlength?)
(!!fault-fresh :gp 0 :instruction-length badlength?)) ;; #GP(0)
;; mask count according to pseudocode (the text only mentions masking
;; when CL is used, but the pseudocode masks also if imm8 is used):
(count-mask (if (logbitp #.*w* rex-byte)
#x3f
#x1f))
(count (logand count-mask count))
;; compute result and flags:
(input-rflags (the (unsigned-byte 32) (rflags x86)))
((mv result
result-undefined?
(the (unsigned-byte 32) output-rflags)
(the (unsigned-byte 32) undefined-flags))
(case opcode
((#xA4 #xA5) (shld-spec
operand-size dst-value src-value count input-rflags))
((#xAC #xAD) (shrd-spec
operand-size dst-value src-value count input-rflags))
(otherwise (mv 0 nil 0 0)))) ; unreachable
((mv result x86)
(if result-undefined?
(undef-read x86)
(mv result x86)))
;; update the state:
(x86 (write-user-rflags output-rflags undefined-flags x86))
((mv flg x86)
(x86-operand-to-reg/mem proc-mode
operand-size
inst-ac?
nil ;; not memory pointer operand
(trunc operand-size result) ; TODO: remove trunc
seg-reg
dst-addr
rex-byte
r/m
mod
x86))
((when flg) (!!ms-fresh :x86-operand-to-reg/mem flg))
(x86 (write-*ip proc-mode temp-rip x86)))
x86))
;; ======================================================================
|
18826
|
; X86ISA Library
; Note: The license below is based on the template at:
; http://opensource.org/licenses/BSD-3-Clause
; Copyright (C) 2015, Regents of the University of Texas
; Copyright (C) 2018, Kestrel Technology, LLC
; All rights reserved.
; 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 copyright holders 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.
; Original Author(s):
; <NAME> <<EMAIL>>
; Contributing Author(s):
; <NAME> <<EMAIL>>
(in-package "X86ISA")
;; ======================================================================
(include-book "shifts-spec"
:ttags (:include-raw :syscall-exec :other-non-det :undef-flg))
(include-book "rotates-spec"
:ttags (:include-raw :syscall-exec :other-non-det :undef-flg))
(include-book "../decoding-and-spec-utils"
:ttags (:include-raw :syscall-exec :other-non-det :undef-flg))
(local (include-book "centaur/bitops/ihs-extensions" :dir :system))
;; ======================================================================
;; INSTRUCTION: SAL/SAR/SHL/SHR/RCL/RCR/ROL/ROR
;; ======================================================================
(local
(defrule add-to-*ip-integerp-type
(implies (and (integerp *ip)
(integerp delta))
(integerp (mv-nth 1 (add-to-*ip proc-mode *ip delta x86))))
:in-theory (e/d (add-to-*ip) ())
:rule-classes (:rewrite :type-prescription)))
(def-inst x86-sal/sar/shl/shr/rcl/rcr/rol/ror
:guard (not (equal (modr/m->reg modr/m) 6))
:guard-hints (("Goal"
:in-theory (e/d ()
(unsigned-byte-p
not force (force)))))
:parents (one-byte-opcodes)
:returns (x86 x86p :hyp (x86p x86)
:hints (("Goal" :in-theory
(e/d ()
(trunc
select-operand-size
mv-nth-0-of-add-to-*ip-when-64-bit-modep
mv-nth-1-of-add-to-*ip-when-64-bit-modep
signed-byte-p
unsigned-byte-p
not force (force))))))
:long
"<p>
Op/En: MI<br/>
C0/0: ROL r/m8, imm8<br/>
C0/1: ROR r/m8, imm8<br/>
C0/2: RCL r/m8, imm8<br/>
C0/3: RCR r/m8, imm8<br/>
C0/4: SAL/SHL r/m8, imm8<br/>
C0/5: SHR r/m8, imm8<br/>
C0/7: SAR r/m8, imm8<br/>
C1/0: ROL r/m16/32/64, imm8<br/>
C1/1: ROR r/m16/32/64, imm8<br/>
C1/2: RCL r/m16/32/64, imm8<br/>
C1/3: RCR r/m16/32/64, imm8<br/>
C1/4: SAL/SHL r/m16/32/64, imm8<br/>
C1/5: SHR r/m16/32/64, imm8<br/>
C1/7: SAR r/m16/32/64. imm8<br/>
</p>
<p>
Op/En: M1<br/>
D0/0: ROL r/m8, 1<br/>
D0/1: ROR r/m8, 1<br/>
D0/2: RCL r/m8, 1<br/>
D0/3: RCR r/m8, 1<br/>
D0/4: SAL/SHL r/m8, 1<br/>
D0/5: SHR r/m8, 1<br/>
D0/7: SAR r/m8, 1<br/>
D1/0: ROL r/m16/32/64, 1<br/>
D1/1: ROR r/m16/32/64, 1<br/>
D1/2: RCL r/m16/32/64, 1<br/>
D1/3: RCR r/m16/32/64, 1<br/>
D1/4: SAL/SHL r/m16/32/64, 1<br/>
D1/5: SHR r/m16/32/64, 1<br/>
D1/7: SAR r/m16/32/64, 1<br/>
</p>
<p>
Op/En: MC<br/>
D2/0: ROL r/m8, CL<br/>
D2/1: ROR r/m8, CL<br/>
D2/2: RCL r/m8, CL<br/>
D2/3: RCR r/m8, CL<br/>
D2/4: SAL/SHL r/m8, CL<br/>
D2/5: SHR r/m8, CL<br/>
D2/7: SAR r/m8, CL<br/>
D3/0: ROL r/m16/32/64, CL<br/>
D3/1: ROR r/m16/32/64, CL<br/>
D3/2: RCL r/m16/32/64, CL<br/>
D3/3: RCR r/m16/32/64, CL<br/>
D3/4: SAL/SHL r/m16/32/64, CL<br/>
D3/5: SHR r/m16/32/64, CL<br/>
D3/7: SAR r/m16/32/64, CL<br/>
</p>"
:modr/m t
:body
(b* ((p2 (prefixes->seg prefixes))
(p4? (equal #.*addr-size-override* (prefixes->adr prefixes)))
(byte-operand? (or (equal opcode #xC0)
(equal opcode #xD0)
(equal opcode #xD2)))
((the (integer 0 8) ?reg/mem-size)
(select-operand-size
proc-mode byte-operand? rex-byte nil prefixes nil nil nil x86))
(seg-reg (select-segment-register proc-mode p2 p4? mod r/m sib x86))
(inst-ac? t)
((mv flg0 ?reg/mem (the (unsigned-byte 3) increment-RIP-by) addr x86)
(x86-operand-from-modr/m-and-sib-bytes
proc-mode #.*gpr-access* reg/mem-size inst-ac?
nil ;; Not a memory pointer operand
seg-reg p4? temp-rip rex-byte r/m mod sib
;; Bytes of immediate data (only relevant when RIP-relative
;; addressing is done to get ?reg/mem operand)
(if (or (equal opcode #xC0)
(equal opcode #xC1))
1
0)
x86))
((when flg0)
(!!ms-fresh :x86-operand-from-modr/m-and-sib-bytes flg0))
((mv flg (the (signed-byte #.*max-linear-address-size*) temp-rip))
(add-to-*ip proc-mode temp-rip increment-RIP-by x86))
((when flg) (!!ms-fresh :rip-increment-error flg))
((mv flg1 shift/rotate-by x86)
(case opcode
((#xD0 #xD1)
(mv nil 1 x86))
((#xD2 #xD3)
(mv nil (rr08 *rcx* rex-byte x86) x86))
((#xC0 #xC1)
(rme-size-opt proc-mode 1 temp-rip #.*cs* :x nil x86))
(otherwise ;; will not be reached
(mv nil 0 x86))))
((when flg1)
(!!ms-fresh :rme-size-error flg1))
(countMask (if (logbitp #.*w* rex-byte)
#x3F
#x1F))
(shift/rotate-by (logand countMask shift/rotate-by))
((mv flg (the (signed-byte #.*max-linear-address-size+1*) temp-rip))
(if (or (equal opcode #xC0)
(equal opcode #xC1))
(add-to-*ip proc-mode temp-rip 1 x86)
(mv nil temp-rip)))
((when flg) (!!ms-fresh :rip-increment-error flg))
(badlength? (check-instruction-length start-rip temp-rip 0))
((when badlength?)
(!!fault-fresh :gp 0 :instruction-length badlength?)) ;; #GP(0)
;; Computing the flags and the result:
(input-rflags (the (unsigned-byte 32) (rflags x86)))
((mv result
(the (unsigned-byte 32) output-rflags)
(the (unsigned-byte 32) undefined-flags))
(case reg
(0
;; ROL
(rol-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
(1
;; ROR
(ror-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
(2
;; RCL
(rcl-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
(3
;; RCR
(rcr-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
(4
;; SAL/SHL
(sal/shl-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
(5
;; SHR
(shr-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
(7
;; SAR
(sar-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
;; The guard for this function will ensure that we don't
;; reach here.
(otherwise
(mv 0 0 0))))
;; Update the x86 state:
(x86 (write-user-rflags output-rflags undefined-flags x86))
((mv flg2 x86)
(x86-operand-to-reg/mem proc-mode reg/mem-size
inst-ac?
nil ;; Not a memory pointer operand
;; TO-DO@Shilpi: Remove this trunc.
(trunc reg/mem-size result)
seg-reg
addr
rex-byte
r/m
mod
x86))
;; Note: If flg2 is non-nil, we bail out without changing the x86 state.
((when flg2)
(!!ms-fresh :x86-operand-to-reg/mem flg2))
(x86 (write-*ip proc-mode temp-rip x86)))
x86))
;; ======================================================================
;; INSTRUCTION: SHLD/SHRD
;; ======================================================================
(def-inst x86-shld/shrd
:returns (x86 x86p :hyp (x86p x86))
:parents (one-byte-opcodes)
:short "Double-precision shift left or right."
:long
"<p>
Op/En: MRI<br/>
0F A4: SHLD r/m16, r16, imm8<br/>
0F A4: SHLD r/m32, r32, imm8<br/>
0F A4: SHLD r/m64, r64, imm8<br/>
</p>
<p>
Op/En: MRC<br/>
0F A5: SHLD r/m16, r16, CL<br/>
0F A5: SHLD r/m32, r32, CL<br/>
0F A5: SHLD r/m64, r64, CL<br/>
</p>
<p>
Op/En: MRI<br/>
0F AC: SHRD r/m16, r16, imm8<br/>
0F AC: SHRD r/m32, r32, imm8<br/>
0F AC: SHRD r/m64, r64, imm8<br/>
</p>
<p>
Op/En: MRC<br/>
0F AD: SHRD r/m16, r16, CL<br/>
0F AD: SHRD r/m32, r32, CL<br/>
0F AD: SHRD r/m64, r64, CL<br/>
</p>"
:modr/m t
:body
(b* ((p2 (prefixes->seg prefixes))
(p4? (equal #.*addr-size-override* (prefixes->adr prefixes)))
((the (integer 2 8) operand-size)
(select-operand-size proc-mode
nil ; not a byte operand
rex-byte
nil ; not an immediate operand
prefixes
nil ; no 64-bit default in 64-bit mode
nil ; don't ignore REX in 64-bit mode
nil ; don't ignore P3 in 64-bit mode
x86))
(seg-reg (select-segment-register proc-mode p2 p4? mod r/m sib x86))
;; read destination operand:
(inst-ac? t)
((mv flg dst-value increment-rip-by dst-addr x86)
(x86-operand-from-modr/m-and-sib-bytes proc-mode
#.*gpr-access*
operand-size
inst-ac?
nil ; not memory pointer operand
seg-reg
p4?
temp-rip
rex-byte
r/m
mod sib
1 ; imm8
x86))
((when flg) (!!ms-fresh :x86-operand-from-modr/m-and-sib-bytes flg))
((mv flg (the (signed-byte #.*max-linear-address-size*) temp-rip))
(add-to-*ip proc-mode temp-rip increment-rip-by x86))
((when flg) (!!ms-fresh :rip-increment-error flg))
;; read source operand:
(src-value (rgfi-size operand-size
(reg-index reg rex-byte #.*r*)
rex-byte
x86))
;; read count operand:
((mv flg count x86)
(case opcode
((#xA4 #xAC) (rme-size-opt proc-mode 1 temp-rip #.*cs* :x nil x86))
((#xA5 #xAD) (mv nil (rr08 *rcx* rex-byte x86) x86))
(otherwise (mv nil 0 x86)))) ; unreachable
((when flg) (!!ms-fresh :rme-size-error flg))
((mv flg (the (signed-byte #.*max-linear-address-size*) temp-rip))
(case opcode
((#xA4 #xAC) (add-to-*ip proc-mode temp-rip 1 x86))
((#xA5 #xAD) (mv nil temp-rip))
(otherwise (mv nil 0)))) ; unreachable
((when flg) (!!ms-fresh :rip-increment-error flg))
;; check instruction length now that we have read all of it:
(badlength? (check-instruction-length start-rip temp-rip 0))
((when badlength?)
(!!fault-fresh :gp 0 :instruction-length badlength?)) ;; #GP(0)
;; mask count according to pseudocode (the text only mentions masking
;; when CL is used, but the pseudocode masks also if imm8 is used):
(count-mask (if (logbitp #.*w* rex-byte)
#x3f
#x1f))
(count (logand count-mask count))
;; compute result and flags:
(input-rflags (the (unsigned-byte 32) (rflags x86)))
((mv result
result-undefined?
(the (unsigned-byte 32) output-rflags)
(the (unsigned-byte 32) undefined-flags))
(case opcode
((#xA4 #xA5) (shld-spec
operand-size dst-value src-value count input-rflags))
((#xAC #xAD) (shrd-spec
operand-size dst-value src-value count input-rflags))
(otherwise (mv 0 nil 0 0)))) ; unreachable
((mv result x86)
(if result-undefined?
(undef-read x86)
(mv result x86)))
;; update the state:
(x86 (write-user-rflags output-rflags undefined-flags x86))
((mv flg x86)
(x86-operand-to-reg/mem proc-mode
operand-size
inst-ac?
nil ;; not memory pointer operand
(trunc operand-size result) ; TODO: remove trunc
seg-reg
dst-addr
rex-byte
r/m
mod
x86))
((when flg) (!!ms-fresh :x86-operand-to-reg/mem flg))
(x86 (write-*ip proc-mode temp-rip x86)))
x86))
;; ======================================================================
| true |
; X86ISA Library
; Note: The license below is based on the template at:
; http://opensource.org/licenses/BSD-3-Clause
; Copyright (C) 2015, Regents of the University of Texas
; Copyright (C) 2018, Kestrel Technology, LLC
; All rights reserved.
; 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 copyright holders 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.
; Original Author(s):
; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
; Contributing Author(s):
; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
(in-package "X86ISA")
;; ======================================================================
(include-book "shifts-spec"
:ttags (:include-raw :syscall-exec :other-non-det :undef-flg))
(include-book "rotates-spec"
:ttags (:include-raw :syscall-exec :other-non-det :undef-flg))
(include-book "../decoding-and-spec-utils"
:ttags (:include-raw :syscall-exec :other-non-det :undef-flg))
(local (include-book "centaur/bitops/ihs-extensions" :dir :system))
;; ======================================================================
;; INSTRUCTION: SAL/SAR/SHL/SHR/RCL/RCR/ROL/ROR
;; ======================================================================
(local
(defrule add-to-*ip-integerp-type
(implies (and (integerp *ip)
(integerp delta))
(integerp (mv-nth 1 (add-to-*ip proc-mode *ip delta x86))))
:in-theory (e/d (add-to-*ip) ())
:rule-classes (:rewrite :type-prescription)))
(def-inst x86-sal/sar/shl/shr/rcl/rcr/rol/ror
:guard (not (equal (modr/m->reg modr/m) 6))
:guard-hints (("Goal"
:in-theory (e/d ()
(unsigned-byte-p
not force (force)))))
:parents (one-byte-opcodes)
:returns (x86 x86p :hyp (x86p x86)
:hints (("Goal" :in-theory
(e/d ()
(trunc
select-operand-size
mv-nth-0-of-add-to-*ip-when-64-bit-modep
mv-nth-1-of-add-to-*ip-when-64-bit-modep
signed-byte-p
unsigned-byte-p
not force (force))))))
:long
"<p>
Op/En: MI<br/>
C0/0: ROL r/m8, imm8<br/>
C0/1: ROR r/m8, imm8<br/>
C0/2: RCL r/m8, imm8<br/>
C0/3: RCR r/m8, imm8<br/>
C0/4: SAL/SHL r/m8, imm8<br/>
C0/5: SHR r/m8, imm8<br/>
C0/7: SAR r/m8, imm8<br/>
C1/0: ROL r/m16/32/64, imm8<br/>
C1/1: ROR r/m16/32/64, imm8<br/>
C1/2: RCL r/m16/32/64, imm8<br/>
C1/3: RCR r/m16/32/64, imm8<br/>
C1/4: SAL/SHL r/m16/32/64, imm8<br/>
C1/5: SHR r/m16/32/64, imm8<br/>
C1/7: SAR r/m16/32/64. imm8<br/>
</p>
<p>
Op/En: M1<br/>
D0/0: ROL r/m8, 1<br/>
D0/1: ROR r/m8, 1<br/>
D0/2: RCL r/m8, 1<br/>
D0/3: RCR r/m8, 1<br/>
D0/4: SAL/SHL r/m8, 1<br/>
D0/5: SHR r/m8, 1<br/>
D0/7: SAR r/m8, 1<br/>
D1/0: ROL r/m16/32/64, 1<br/>
D1/1: ROR r/m16/32/64, 1<br/>
D1/2: RCL r/m16/32/64, 1<br/>
D1/3: RCR r/m16/32/64, 1<br/>
D1/4: SAL/SHL r/m16/32/64, 1<br/>
D1/5: SHR r/m16/32/64, 1<br/>
D1/7: SAR r/m16/32/64, 1<br/>
</p>
<p>
Op/En: MC<br/>
D2/0: ROL r/m8, CL<br/>
D2/1: ROR r/m8, CL<br/>
D2/2: RCL r/m8, CL<br/>
D2/3: RCR r/m8, CL<br/>
D2/4: SAL/SHL r/m8, CL<br/>
D2/5: SHR r/m8, CL<br/>
D2/7: SAR r/m8, CL<br/>
D3/0: ROL r/m16/32/64, CL<br/>
D3/1: ROR r/m16/32/64, CL<br/>
D3/2: RCL r/m16/32/64, CL<br/>
D3/3: RCR r/m16/32/64, CL<br/>
D3/4: SAL/SHL r/m16/32/64, CL<br/>
D3/5: SHR r/m16/32/64, CL<br/>
D3/7: SAR r/m16/32/64, CL<br/>
</p>"
:modr/m t
:body
(b* ((p2 (prefixes->seg prefixes))
(p4? (equal #.*addr-size-override* (prefixes->adr prefixes)))
(byte-operand? (or (equal opcode #xC0)
(equal opcode #xD0)
(equal opcode #xD2)))
((the (integer 0 8) ?reg/mem-size)
(select-operand-size
proc-mode byte-operand? rex-byte nil prefixes nil nil nil x86))
(seg-reg (select-segment-register proc-mode p2 p4? mod r/m sib x86))
(inst-ac? t)
((mv flg0 ?reg/mem (the (unsigned-byte 3) increment-RIP-by) addr x86)
(x86-operand-from-modr/m-and-sib-bytes
proc-mode #.*gpr-access* reg/mem-size inst-ac?
nil ;; Not a memory pointer operand
seg-reg p4? temp-rip rex-byte r/m mod sib
;; Bytes of immediate data (only relevant when RIP-relative
;; addressing is done to get ?reg/mem operand)
(if (or (equal opcode #xC0)
(equal opcode #xC1))
1
0)
x86))
((when flg0)
(!!ms-fresh :x86-operand-from-modr/m-and-sib-bytes flg0))
((mv flg (the (signed-byte #.*max-linear-address-size*) temp-rip))
(add-to-*ip proc-mode temp-rip increment-RIP-by x86))
((when flg) (!!ms-fresh :rip-increment-error flg))
((mv flg1 shift/rotate-by x86)
(case opcode
((#xD0 #xD1)
(mv nil 1 x86))
((#xD2 #xD3)
(mv nil (rr08 *rcx* rex-byte x86) x86))
((#xC0 #xC1)
(rme-size-opt proc-mode 1 temp-rip #.*cs* :x nil x86))
(otherwise ;; will not be reached
(mv nil 0 x86))))
((when flg1)
(!!ms-fresh :rme-size-error flg1))
(countMask (if (logbitp #.*w* rex-byte)
#x3F
#x1F))
(shift/rotate-by (logand countMask shift/rotate-by))
((mv flg (the (signed-byte #.*max-linear-address-size+1*) temp-rip))
(if (or (equal opcode #xC0)
(equal opcode #xC1))
(add-to-*ip proc-mode temp-rip 1 x86)
(mv nil temp-rip)))
((when flg) (!!ms-fresh :rip-increment-error flg))
(badlength? (check-instruction-length start-rip temp-rip 0))
((when badlength?)
(!!fault-fresh :gp 0 :instruction-length badlength?)) ;; #GP(0)
;; Computing the flags and the result:
(input-rflags (the (unsigned-byte 32) (rflags x86)))
((mv result
(the (unsigned-byte 32) output-rflags)
(the (unsigned-byte 32) undefined-flags))
(case reg
(0
;; ROL
(rol-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
(1
;; ROR
(ror-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
(2
;; RCL
(rcl-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
(3
;; RCR
(rcr-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
(4
;; SAL/SHL
(sal/shl-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
(5
;; SHR
(shr-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
(7
;; SAR
(sar-spec reg/mem-size reg/mem shift/rotate-by input-rflags))
;; The guard for this function will ensure that we don't
;; reach here.
(otherwise
(mv 0 0 0))))
;; Update the x86 state:
(x86 (write-user-rflags output-rflags undefined-flags x86))
((mv flg2 x86)
(x86-operand-to-reg/mem proc-mode reg/mem-size
inst-ac?
nil ;; Not a memory pointer operand
;; TO-DO@Shilpi: Remove this trunc.
(trunc reg/mem-size result)
seg-reg
addr
rex-byte
r/m
mod
x86))
;; Note: If flg2 is non-nil, we bail out without changing the x86 state.
((when flg2)
(!!ms-fresh :x86-operand-to-reg/mem flg2))
(x86 (write-*ip proc-mode temp-rip x86)))
x86))
;; ======================================================================
;; INSTRUCTION: SHLD/SHRD
;; ======================================================================
(def-inst x86-shld/shrd
:returns (x86 x86p :hyp (x86p x86))
:parents (one-byte-opcodes)
:short "Double-precision shift left or right."
:long
"<p>
Op/En: MRI<br/>
0F A4: SHLD r/m16, r16, imm8<br/>
0F A4: SHLD r/m32, r32, imm8<br/>
0F A4: SHLD r/m64, r64, imm8<br/>
</p>
<p>
Op/En: MRC<br/>
0F A5: SHLD r/m16, r16, CL<br/>
0F A5: SHLD r/m32, r32, CL<br/>
0F A5: SHLD r/m64, r64, CL<br/>
</p>
<p>
Op/En: MRI<br/>
0F AC: SHRD r/m16, r16, imm8<br/>
0F AC: SHRD r/m32, r32, imm8<br/>
0F AC: SHRD r/m64, r64, imm8<br/>
</p>
<p>
Op/En: MRC<br/>
0F AD: SHRD r/m16, r16, CL<br/>
0F AD: SHRD r/m32, r32, CL<br/>
0F AD: SHRD r/m64, r64, CL<br/>
</p>"
:modr/m t
:body
(b* ((p2 (prefixes->seg prefixes))
(p4? (equal #.*addr-size-override* (prefixes->adr prefixes)))
((the (integer 2 8) operand-size)
(select-operand-size proc-mode
nil ; not a byte operand
rex-byte
nil ; not an immediate operand
prefixes
nil ; no 64-bit default in 64-bit mode
nil ; don't ignore REX in 64-bit mode
nil ; don't ignore P3 in 64-bit mode
x86))
(seg-reg (select-segment-register proc-mode p2 p4? mod r/m sib x86))
;; read destination operand:
(inst-ac? t)
((mv flg dst-value increment-rip-by dst-addr x86)
(x86-operand-from-modr/m-and-sib-bytes proc-mode
#.*gpr-access*
operand-size
inst-ac?
nil ; not memory pointer operand
seg-reg
p4?
temp-rip
rex-byte
r/m
mod sib
1 ; imm8
x86))
((when flg) (!!ms-fresh :x86-operand-from-modr/m-and-sib-bytes flg))
((mv flg (the (signed-byte #.*max-linear-address-size*) temp-rip))
(add-to-*ip proc-mode temp-rip increment-rip-by x86))
((when flg) (!!ms-fresh :rip-increment-error flg))
;; read source operand:
(src-value (rgfi-size operand-size
(reg-index reg rex-byte #.*r*)
rex-byte
x86))
;; read count operand:
((mv flg count x86)
(case opcode
((#xA4 #xAC) (rme-size-opt proc-mode 1 temp-rip #.*cs* :x nil x86))
((#xA5 #xAD) (mv nil (rr08 *rcx* rex-byte x86) x86))
(otherwise (mv nil 0 x86)))) ; unreachable
((when flg) (!!ms-fresh :rme-size-error flg))
((mv flg (the (signed-byte #.*max-linear-address-size*) temp-rip))
(case opcode
((#xA4 #xAC) (add-to-*ip proc-mode temp-rip 1 x86))
((#xA5 #xAD) (mv nil temp-rip))
(otherwise (mv nil 0)))) ; unreachable
((when flg) (!!ms-fresh :rip-increment-error flg))
;; check instruction length now that we have read all of it:
(badlength? (check-instruction-length start-rip temp-rip 0))
((when badlength?)
(!!fault-fresh :gp 0 :instruction-length badlength?)) ;; #GP(0)
;; mask count according to pseudocode (the text only mentions masking
;; when CL is used, but the pseudocode masks also if imm8 is used):
(count-mask (if (logbitp #.*w* rex-byte)
#x3f
#x1f))
(count (logand count-mask count))
;; compute result and flags:
(input-rflags (the (unsigned-byte 32) (rflags x86)))
((mv result
result-undefined?
(the (unsigned-byte 32) output-rflags)
(the (unsigned-byte 32) undefined-flags))
(case opcode
((#xA4 #xA5) (shld-spec
operand-size dst-value src-value count input-rflags))
((#xAC #xAD) (shrd-spec
operand-size dst-value src-value count input-rflags))
(otherwise (mv 0 nil 0 0)))) ; unreachable
((mv result x86)
(if result-undefined?
(undef-read x86)
(mv result x86)))
;; update the state:
(x86 (write-user-rflags output-rflags undefined-flags x86))
((mv flg x86)
(x86-operand-to-reg/mem proc-mode
operand-size
inst-ac?
nil ;; not memory pointer operand
(trunc operand-size result) ; TODO: remove trunc
seg-reg
dst-addr
rex-byte
r/m
mod
x86))
((when flg) (!!ms-fresh :x86-operand-to-reg/mem flg))
(x86 (write-*ip proc-mode temp-rip x86)))
x86))
;; ======================================================================
|
[
{
"context": ";;;; mpz.lisp\n;;;;\n;;;; Copyright (c) 2019 Robert Smith\n\n(in-package #:hypergeometrica)\n\n(deftype storage",
"end": 55,
"score": 0.9997714757919312,
"start": 43,
"tag": "NAME",
"value": "Robert Smith"
}
] |
src/mpz.lisp
|
jwg4/hypergeometrica
| 21 |
;;;; mpz.lisp
;;;;
;;;; Copyright (c) 2019 Robert Smith
(in-package #:hypergeometrica)
(deftype storage ()
`(or ram-vec disk-vec))
(defun make-storage (n)
(check-type n alexandria:array-length)
(cond
((<= 0 n (floor (* 8 *maximum-vector-size*) $digit-bits))
(make-ram-vec n))
(t
(when *verbose*
(format t "~&Making DISK-VEC of ~D digit~:P~%" n))
(make-disk-vec n))))
(deftype sign ()
"The sign of an integer."
'(member 1 -1))
(defstruct (mpz (:conc-name nil)
(:predicate mpz?)
(:copier nil)
(:constructor make-mpz (sign storage)))
(sign 1 :type sign)
(storage (make-storage 0) :type storage :read-only t))
#+sbcl (declaim (sb-ext:freeze-type mpz))
(defmethod vec-digit-length ((mpz mpz)) ; Convenient hack
(vec-digit-length (storage mpz)))
(defmethod vec-digit-pointer ((mpz mpz)) ; Convenient hack
(vec-digit-pointer (storage mpz)))
;;; Conversion functions
(defun mpz-integer (mpz)
(declare (type mpz mpz))
(with-vec (mpz mpz_)
(* (sign mpz)
(loop :for i :below (vec-digit-length mpz)
:for digit := (mpz_ i)
:for b := 1 :then (* b $base)
:sum (* digit b)))))
(defun integer-mpz (n)
(declare (type integer n))
(cond
((zerop n)
(make-mpz 1 (make-storage 1)))
((= 1 (abs n))
(make-mpz n (let ((s (make-storage 1)))
(with-vec (s s_)
(setf (s_ 0) 1))
s)))
(t
(let ((sign (signum n)))
(setf n (abs n))
(loop :until (zerop n)
:collect (multiple-value-bind (quo rem) (floor n $base)
(setf n quo)
rem)
:into digits
:finally (return
(let ((len (length digits))
(vec (make-storage (length digits))))
(with-vec (vec vec_)
(dotimes (i len (make-mpz sign vec))
(setf (vec_ i) (pop digits)))))))))))
;;; Size, Length, etc.
(declaim (ftype (function (mpz) alexandria:array-length) mpz-size))
(defun mpz-size (mpz)
"How many digits does the MPZ have?
If MPZ is equal to 0, then this is 0."
(declare #.*optimize-dangerously-fast*)
(vec-digit-length* (storage mpz)))
(defun mpz-uses-minimal-storage-p (mpz)
(= (vec-digit-length mpz) (mpz-size mpz)))
(defun optimize-mpz (mpz)
(declare (type mpz mpz))
(optimize-storage (storage mpz))
mpz)
(defun optimize-storage (vec)
(declare (type storage vec))
(let ((size (vec-digit-length* vec))
(length (vec-digit-length vec)))
(resize-vec-by vec (- size length))
vec))
(defun mpz-set-zero! (mpz)
(setf (sign mpz) 1)
(resize-vec-by (storage mpz) (- (vec-digit-length mpz)))
nil)
(defun mpz-integer-length (mpz)
"How many bits are needed to represent MPZ in two's complement?"
(let ((size (mpz-size mpz)))
(if (zerop size)
0
(with-vec (mpz mpz_)
(+ (* $digit-bits (1- size))
(integer-length (mpz_ (1- size)))
(/ (1- (sign mpz)) 2))))))
(defmethod print-object ((mpz mpz) stream)
(print-unreadable-object (mpz stream :type t :identity t)
(format stream "~D bit~:P~:[~;*~]"
(mpz-integer-length mpz)
(mpz-uses-minimal-storage-p mpz))))
;;; Comparison functions
(defun mpz-zerop (mpz)
(do-digits (i digit mpz t)
(declare (ignore i))
(unless (zerop digit)
(return-from mpz-zerop nil))))
(defun mpz-plusp (mpz)
(and (= 1 (sign mpz))
(not (mpz-zerop mpz))))
(defun mpz-minusp (mpz)
(and (= -1 (sign mpz))
(not (mpz-zerop mpz))))
(defun mpz-abs (mpz)
(make-mpz 1 (storage mpz)))
(defun mpz-negate (mpz)
(make-mpz (- (sign mpz)) (storage mpz)))
(defun mpz-negate! (mpz)
(setf (sign mpz) (- (sign mpz)))
nil)
(defun mpz-= (a b)
(with-vecs (a a_ b b_)
(and (= (sign a) (sign b))
(= (mpz-size a) (mpz-size b))
(vec= (storage a) (storage b)))))
(defun mpz-/= (a b)
(not (mpz-= a b)))
(defun %mpz-> (a b)
(assert (= 1 (sign a) (sign b)))
(let ((size-a (mpz-size a))
(size-b (mpz-size b)))
(if (/= size-a size-b)
(> size-a size-b)
(with-vecs (a a_ b b_)
(loop :for i :from (1- size-a) :downto 0
:for ai := (a_ i)
:for bi := (b_ i)
:do (cond
((> ai bi) (return t))
((< ai bi) (return nil)))
:finally (return nil))))))
(defun mpz-> (a b)
(cond
((> (sign a) (sign b)) t)
((< (sign a) (sign b)) nil)
;; Now we know they have the same sign. If they're both negative,
;; then reverse.
((= -1 (sign a))
(%mpz-> (mpz-abs b) (mpz-abs a)))
;; They have the same sign and they're positive.
(t
(%mpz-> a b))))
(defun mpz->= (a b)
(or (mpz-= a b)
(mpz-> a b)))
(defun mpz-< (a b)
(not (mpz->= a b)))
(defun mpz-<= (a b)
(not (mpz-> a b)))
(defun %add-storages/unsafe (r a size-a b size-b)
(declare (type storage r a b)
(type alexandria:array-length size-a size-b))
#+hypergeometrica-safe
(assert (>= size-a size-b))
#+hypergeometrica-safe
(assert (>= (vec-digit-length r) size-a))
;; size-a >= size-b
(with-vecs (a a_ b b_ r r_)
(let ((carry 0))
(declare (type digit carry))
(dotimes (i size-b)
;; AI + BI + CARRY
(multiple-value-bind (sum c) (add64 (a_ i) (b_ i))
;; XXX: Using MULTIPLE-VALUE-SETQ is buggy here in SBCL
;; 2.1.3.
(multiple-value-bind (sum new-carry) (add64 sum carry)
(setf carry (+ new-carry c))
(setf (r_ i) sum))))
(do-range (i size-b size-a)
(multiple-value-bind (sum new-carry) (add64 (a_ i) carry)
(setf carry new-carry
(r_ i) sum)))
;; Account for the carry.
(unless (zerop carry)
;; Do we have enough storage? If not, make some.
(assert (< size-a (vec-digit-length r)))
(setf (r_ size-a) carry))
;; Return the storage
r)))
(defun %mpz-+ (a b)
(assert (= 1 (sign a) (sign b)))
(let* ((size-a (mpz-size a))
(size-b (mpz-size b))
(r (make-storage (1+ (max size-a size-b)))))
(if (>= size-a size-b)
(make-mpz 1 (%add-storages/unsafe r
(storage a) size-a
(storage b) size-b))
(make-mpz 1 (%add-storages/unsafe r
(storage b) size-b
(storage a) size-a)))))
(defun %subtract-storages/unsafe (a size-a b size-b)
(declare (type storage a b)
(type alexandria:array-length size-a size-b))
;; a > b > 0
(assert (>= size-a size-b))
(let* ((r (make-storage size-a))
(carry 1))
(declare (type bit carry))
(with-vecs (a a_ b b_ r r_)
(dotimes (i size-b)
(let ((ai (a_ i))
(neg-bi (complement-digit (b_ i))))
;; AI + CARRY - BI
(multiple-value-bind (sum c) (add64 ai carry)
(cond
((= 1 c)
(setf (r_ i) neg-bi
carry 1))
(t
;; XXX: Using MULTIPLE-VALUE-SETQ is buggy here in SBCL
;; 2.1.3.
(multiple-value-bind (sum new-carry) (add64 sum neg-bi)
(setf carry new-carry)
(setf (r_ i) sum)))))))
(do-range (i size-b size-a)
(let ((ai (a_ i)))
(multiple-value-bind (sum c) (add64 ai carry)
(cond
((= 1 c)
(setf (r_ i) $max-digit
carry 1))
(t
;; XXX: Using MULTIPLE-VALUE-SETQ is buggy here in SBCL
;; 2.1.3.
(multiple-value-bind (sum new-carry) (add64 sum $max-digit)
(setf carry new-carry)
(setf (r_ i) sum))))))))
#+hypergeometrica-safe
(assert (= 1 carry))
r))
(defun %mpz-- (a b)
(assert (= 1 (sign a) (sign b)))
(cond
((mpz-= a b)
(integer-mpz 0))
((mpz-> a b)
(make-mpz 1 (optimize-storage
(%subtract-storages/unsafe (storage a) (mpz-size a)
(storage b) (mpz-size b)))))
(t
(make-mpz -1 (optimize-storage
(%subtract-storages/unsafe (storage b) (mpz-size b)
(storage a) (mpz-size a)))))))
(defun mpz-+ (a b)
(declare (type mpz a b))
(cond
((mpz-zerop a) b)
((mpz-zerop b) a)
((= 1 (sign a) (sign b))
(%mpz-+ a b))
((= -1 (sign a) (sign b))
(mpz-negate (%mpz-+ (mpz-abs a) (mpz-abs b))))
;; a > 0, b < 0
((= -1 (sign b))
(%mpz-- a (mpz-abs b)))
;; a < 0, b > 0
(t
(%mpz-- b (mpz-abs a)))))
(defun mpz-- (a b)
(mpz-+ a (mpz-negate b)))
(defun mpz-multiply-by-digit! (d mpz)
(declare (type digit d)
(type mpz mpz))
(cond
((zerop d)
(mpz-set-zero! mpz)
nil)
((= 1 d)
;; Do absolutely nothin'!
nil)
(t
(let ((d (abs d))
(size (mpz-size mpz))
(carry 0))
(declare (type (unsigned-byte 64) d)
(type alexandria:array-length size)
(type (unsigned-byte 64) carry))
(with-vec (mpz mpz_)
(dotimes (i size)
(multiple-value-bind (lo hi) (mul128 d (mpz_ i))
(multiple-value-bind (lo sub-carry) (add64 lo carry)
(setf (mpz_ i) lo)
(setf carry (fx+ hi sub-carry))))))
(when (plusp carry)
(when (mpz-uses-minimal-storage-p mpz)
(resize-vec-by (storage mpz) 1))
(with-vec (mpz mpz_)
(setf (mpz_ size) carry)))
nil))))
(defun mpz-multiply-by-s64! (d mpz)
(declare (type (signed-byte 64) d)
(type mpz mpz))
(mpz-multiply-by-digit! (abs d) mpz)
(when (minusp d)
(mpz-negate! mpz))
nil)
(defun %multiply-storage/schoolboy (a a-size b b-size)
#+hypergeometrica-safe
(assert (>= a-size b-size))
(let* ((length (+ 1 a-size b-size))
(r (make-storage length)))
(with-vecs (a a_ b b_ r r_)
(let ((temp (make-mpz 1 (make-storage length))))
(dotimes (i b-size r)
(let ((bi (b_ i)))
(unless (zerop bi)
;; We re-use TEMP. Clear dirty info. (XXX: We could
;; probably optimize START and END.)
;;
;; TEMP := 0
(vec-fill temp 0)
;; :START1 i should be interpreted as a left shift of A by I
;; digits.
;;
;; TEMP := A * 2^(64 * I).
(vec-replace/unsafe temp a :start1 i)
;; TEMP := B[i] * TEMP
(mpz-multiply-by-digit! bi temp)
;; R := R + TEMP
(%add-storages/unsafe r
r length
(storage temp) length))))))))
;;;
(defun mpz-debug (mpz &optional (stream *standard-output*))
(print-unreadable-object (mpz stream :type t :identity nil)
(format stream "(~D) ~:[-1~;+1~] *"
(mpz-size mpz)
(= 1 (sign mpz)))
(do-digits (i digit mpz)
(declare (ignore i))
(format stream " ~16,'0X" digit))
(terpri stream)
(format stream "~D" (mpz-integer mpz))))
|
52048
|
;;;; mpz.lisp
;;;;
;;;; Copyright (c) 2019 <NAME>
(in-package #:hypergeometrica)
(deftype storage ()
`(or ram-vec disk-vec))
(defun make-storage (n)
(check-type n alexandria:array-length)
(cond
((<= 0 n (floor (* 8 *maximum-vector-size*) $digit-bits))
(make-ram-vec n))
(t
(when *verbose*
(format t "~&Making DISK-VEC of ~D digit~:P~%" n))
(make-disk-vec n))))
(deftype sign ()
"The sign of an integer."
'(member 1 -1))
(defstruct (mpz (:conc-name nil)
(:predicate mpz?)
(:copier nil)
(:constructor make-mpz (sign storage)))
(sign 1 :type sign)
(storage (make-storage 0) :type storage :read-only t))
#+sbcl (declaim (sb-ext:freeze-type mpz))
(defmethod vec-digit-length ((mpz mpz)) ; Convenient hack
(vec-digit-length (storage mpz)))
(defmethod vec-digit-pointer ((mpz mpz)) ; Convenient hack
(vec-digit-pointer (storage mpz)))
;;; Conversion functions
(defun mpz-integer (mpz)
(declare (type mpz mpz))
(with-vec (mpz mpz_)
(* (sign mpz)
(loop :for i :below (vec-digit-length mpz)
:for digit := (mpz_ i)
:for b := 1 :then (* b $base)
:sum (* digit b)))))
(defun integer-mpz (n)
(declare (type integer n))
(cond
((zerop n)
(make-mpz 1 (make-storage 1)))
((= 1 (abs n))
(make-mpz n (let ((s (make-storage 1)))
(with-vec (s s_)
(setf (s_ 0) 1))
s)))
(t
(let ((sign (signum n)))
(setf n (abs n))
(loop :until (zerop n)
:collect (multiple-value-bind (quo rem) (floor n $base)
(setf n quo)
rem)
:into digits
:finally (return
(let ((len (length digits))
(vec (make-storage (length digits))))
(with-vec (vec vec_)
(dotimes (i len (make-mpz sign vec))
(setf (vec_ i) (pop digits)))))))))))
;;; Size, Length, etc.
(declaim (ftype (function (mpz) alexandria:array-length) mpz-size))
(defun mpz-size (mpz)
"How many digits does the MPZ have?
If MPZ is equal to 0, then this is 0."
(declare #.*optimize-dangerously-fast*)
(vec-digit-length* (storage mpz)))
(defun mpz-uses-minimal-storage-p (mpz)
(= (vec-digit-length mpz) (mpz-size mpz)))
(defun optimize-mpz (mpz)
(declare (type mpz mpz))
(optimize-storage (storage mpz))
mpz)
(defun optimize-storage (vec)
(declare (type storage vec))
(let ((size (vec-digit-length* vec))
(length (vec-digit-length vec)))
(resize-vec-by vec (- size length))
vec))
(defun mpz-set-zero! (mpz)
(setf (sign mpz) 1)
(resize-vec-by (storage mpz) (- (vec-digit-length mpz)))
nil)
(defun mpz-integer-length (mpz)
"How many bits are needed to represent MPZ in two's complement?"
(let ((size (mpz-size mpz)))
(if (zerop size)
0
(with-vec (mpz mpz_)
(+ (* $digit-bits (1- size))
(integer-length (mpz_ (1- size)))
(/ (1- (sign mpz)) 2))))))
(defmethod print-object ((mpz mpz) stream)
(print-unreadable-object (mpz stream :type t :identity t)
(format stream "~D bit~:P~:[~;*~]"
(mpz-integer-length mpz)
(mpz-uses-minimal-storage-p mpz))))
;;; Comparison functions
(defun mpz-zerop (mpz)
(do-digits (i digit mpz t)
(declare (ignore i))
(unless (zerop digit)
(return-from mpz-zerop nil))))
(defun mpz-plusp (mpz)
(and (= 1 (sign mpz))
(not (mpz-zerop mpz))))
(defun mpz-minusp (mpz)
(and (= -1 (sign mpz))
(not (mpz-zerop mpz))))
(defun mpz-abs (mpz)
(make-mpz 1 (storage mpz)))
(defun mpz-negate (mpz)
(make-mpz (- (sign mpz)) (storage mpz)))
(defun mpz-negate! (mpz)
(setf (sign mpz) (- (sign mpz)))
nil)
(defun mpz-= (a b)
(with-vecs (a a_ b b_)
(and (= (sign a) (sign b))
(= (mpz-size a) (mpz-size b))
(vec= (storage a) (storage b)))))
(defun mpz-/= (a b)
(not (mpz-= a b)))
(defun %mpz-> (a b)
(assert (= 1 (sign a) (sign b)))
(let ((size-a (mpz-size a))
(size-b (mpz-size b)))
(if (/= size-a size-b)
(> size-a size-b)
(with-vecs (a a_ b b_)
(loop :for i :from (1- size-a) :downto 0
:for ai := (a_ i)
:for bi := (b_ i)
:do (cond
((> ai bi) (return t))
((< ai bi) (return nil)))
:finally (return nil))))))
(defun mpz-> (a b)
(cond
((> (sign a) (sign b)) t)
((< (sign a) (sign b)) nil)
;; Now we know they have the same sign. If they're both negative,
;; then reverse.
((= -1 (sign a))
(%mpz-> (mpz-abs b) (mpz-abs a)))
;; They have the same sign and they're positive.
(t
(%mpz-> a b))))
(defun mpz->= (a b)
(or (mpz-= a b)
(mpz-> a b)))
(defun mpz-< (a b)
(not (mpz->= a b)))
(defun mpz-<= (a b)
(not (mpz-> a b)))
(defun %add-storages/unsafe (r a size-a b size-b)
(declare (type storage r a b)
(type alexandria:array-length size-a size-b))
#+hypergeometrica-safe
(assert (>= size-a size-b))
#+hypergeometrica-safe
(assert (>= (vec-digit-length r) size-a))
;; size-a >= size-b
(with-vecs (a a_ b b_ r r_)
(let ((carry 0))
(declare (type digit carry))
(dotimes (i size-b)
;; AI + BI + CARRY
(multiple-value-bind (sum c) (add64 (a_ i) (b_ i))
;; XXX: Using MULTIPLE-VALUE-SETQ is buggy here in SBCL
;; 2.1.3.
(multiple-value-bind (sum new-carry) (add64 sum carry)
(setf carry (+ new-carry c))
(setf (r_ i) sum))))
(do-range (i size-b size-a)
(multiple-value-bind (sum new-carry) (add64 (a_ i) carry)
(setf carry new-carry
(r_ i) sum)))
;; Account for the carry.
(unless (zerop carry)
;; Do we have enough storage? If not, make some.
(assert (< size-a (vec-digit-length r)))
(setf (r_ size-a) carry))
;; Return the storage
r)))
(defun %mpz-+ (a b)
(assert (= 1 (sign a) (sign b)))
(let* ((size-a (mpz-size a))
(size-b (mpz-size b))
(r (make-storage (1+ (max size-a size-b)))))
(if (>= size-a size-b)
(make-mpz 1 (%add-storages/unsafe r
(storage a) size-a
(storage b) size-b))
(make-mpz 1 (%add-storages/unsafe r
(storage b) size-b
(storage a) size-a)))))
(defun %subtract-storages/unsafe (a size-a b size-b)
(declare (type storage a b)
(type alexandria:array-length size-a size-b))
;; a > b > 0
(assert (>= size-a size-b))
(let* ((r (make-storage size-a))
(carry 1))
(declare (type bit carry))
(with-vecs (a a_ b b_ r r_)
(dotimes (i size-b)
(let ((ai (a_ i))
(neg-bi (complement-digit (b_ i))))
;; AI + CARRY - BI
(multiple-value-bind (sum c) (add64 ai carry)
(cond
((= 1 c)
(setf (r_ i) neg-bi
carry 1))
(t
;; XXX: Using MULTIPLE-VALUE-SETQ is buggy here in SBCL
;; 2.1.3.
(multiple-value-bind (sum new-carry) (add64 sum neg-bi)
(setf carry new-carry)
(setf (r_ i) sum)))))))
(do-range (i size-b size-a)
(let ((ai (a_ i)))
(multiple-value-bind (sum c) (add64 ai carry)
(cond
((= 1 c)
(setf (r_ i) $max-digit
carry 1))
(t
;; XXX: Using MULTIPLE-VALUE-SETQ is buggy here in SBCL
;; 2.1.3.
(multiple-value-bind (sum new-carry) (add64 sum $max-digit)
(setf carry new-carry)
(setf (r_ i) sum))))))))
#+hypergeometrica-safe
(assert (= 1 carry))
r))
(defun %mpz-- (a b)
(assert (= 1 (sign a) (sign b)))
(cond
((mpz-= a b)
(integer-mpz 0))
((mpz-> a b)
(make-mpz 1 (optimize-storage
(%subtract-storages/unsafe (storage a) (mpz-size a)
(storage b) (mpz-size b)))))
(t
(make-mpz -1 (optimize-storage
(%subtract-storages/unsafe (storage b) (mpz-size b)
(storage a) (mpz-size a)))))))
(defun mpz-+ (a b)
(declare (type mpz a b))
(cond
((mpz-zerop a) b)
((mpz-zerop b) a)
((= 1 (sign a) (sign b))
(%mpz-+ a b))
((= -1 (sign a) (sign b))
(mpz-negate (%mpz-+ (mpz-abs a) (mpz-abs b))))
;; a > 0, b < 0
((= -1 (sign b))
(%mpz-- a (mpz-abs b)))
;; a < 0, b > 0
(t
(%mpz-- b (mpz-abs a)))))
(defun mpz-- (a b)
(mpz-+ a (mpz-negate b)))
(defun mpz-multiply-by-digit! (d mpz)
(declare (type digit d)
(type mpz mpz))
(cond
((zerop d)
(mpz-set-zero! mpz)
nil)
((= 1 d)
;; Do absolutely nothin'!
nil)
(t
(let ((d (abs d))
(size (mpz-size mpz))
(carry 0))
(declare (type (unsigned-byte 64) d)
(type alexandria:array-length size)
(type (unsigned-byte 64) carry))
(with-vec (mpz mpz_)
(dotimes (i size)
(multiple-value-bind (lo hi) (mul128 d (mpz_ i))
(multiple-value-bind (lo sub-carry) (add64 lo carry)
(setf (mpz_ i) lo)
(setf carry (fx+ hi sub-carry))))))
(when (plusp carry)
(when (mpz-uses-minimal-storage-p mpz)
(resize-vec-by (storage mpz) 1))
(with-vec (mpz mpz_)
(setf (mpz_ size) carry)))
nil))))
(defun mpz-multiply-by-s64! (d mpz)
(declare (type (signed-byte 64) d)
(type mpz mpz))
(mpz-multiply-by-digit! (abs d) mpz)
(when (minusp d)
(mpz-negate! mpz))
nil)
(defun %multiply-storage/schoolboy (a a-size b b-size)
#+hypergeometrica-safe
(assert (>= a-size b-size))
(let* ((length (+ 1 a-size b-size))
(r (make-storage length)))
(with-vecs (a a_ b b_ r r_)
(let ((temp (make-mpz 1 (make-storage length))))
(dotimes (i b-size r)
(let ((bi (b_ i)))
(unless (zerop bi)
;; We re-use TEMP. Clear dirty info. (XXX: We could
;; probably optimize START and END.)
;;
;; TEMP := 0
(vec-fill temp 0)
;; :START1 i should be interpreted as a left shift of A by I
;; digits.
;;
;; TEMP := A * 2^(64 * I).
(vec-replace/unsafe temp a :start1 i)
;; TEMP := B[i] * TEMP
(mpz-multiply-by-digit! bi temp)
;; R := R + TEMP
(%add-storages/unsafe r
r length
(storage temp) length))))))))
;;;
(defun mpz-debug (mpz &optional (stream *standard-output*))
(print-unreadable-object (mpz stream :type t :identity nil)
(format stream "(~D) ~:[-1~;+1~] *"
(mpz-size mpz)
(= 1 (sign mpz)))
(do-digits (i digit mpz)
(declare (ignore i))
(format stream " ~16,'0X" digit))
(terpri stream)
(format stream "~D" (mpz-integer mpz))))
| true |
;;;; mpz.lisp
;;;;
;;;; Copyright (c) 2019 PI:NAME:<NAME>END_PI
(in-package #:hypergeometrica)
(deftype storage ()
`(or ram-vec disk-vec))
(defun make-storage (n)
(check-type n alexandria:array-length)
(cond
((<= 0 n (floor (* 8 *maximum-vector-size*) $digit-bits))
(make-ram-vec n))
(t
(when *verbose*
(format t "~&Making DISK-VEC of ~D digit~:P~%" n))
(make-disk-vec n))))
(deftype sign ()
"The sign of an integer."
'(member 1 -1))
(defstruct (mpz (:conc-name nil)
(:predicate mpz?)
(:copier nil)
(:constructor make-mpz (sign storage)))
(sign 1 :type sign)
(storage (make-storage 0) :type storage :read-only t))
#+sbcl (declaim (sb-ext:freeze-type mpz))
(defmethod vec-digit-length ((mpz mpz)) ; Convenient hack
(vec-digit-length (storage mpz)))
(defmethod vec-digit-pointer ((mpz mpz)) ; Convenient hack
(vec-digit-pointer (storage mpz)))
;;; Conversion functions
(defun mpz-integer (mpz)
(declare (type mpz mpz))
(with-vec (mpz mpz_)
(* (sign mpz)
(loop :for i :below (vec-digit-length mpz)
:for digit := (mpz_ i)
:for b := 1 :then (* b $base)
:sum (* digit b)))))
(defun integer-mpz (n)
(declare (type integer n))
(cond
((zerop n)
(make-mpz 1 (make-storage 1)))
((= 1 (abs n))
(make-mpz n (let ((s (make-storage 1)))
(with-vec (s s_)
(setf (s_ 0) 1))
s)))
(t
(let ((sign (signum n)))
(setf n (abs n))
(loop :until (zerop n)
:collect (multiple-value-bind (quo rem) (floor n $base)
(setf n quo)
rem)
:into digits
:finally (return
(let ((len (length digits))
(vec (make-storage (length digits))))
(with-vec (vec vec_)
(dotimes (i len (make-mpz sign vec))
(setf (vec_ i) (pop digits)))))))))))
;;; Size, Length, etc.
(declaim (ftype (function (mpz) alexandria:array-length) mpz-size))
(defun mpz-size (mpz)
"How many digits does the MPZ have?
If MPZ is equal to 0, then this is 0."
(declare #.*optimize-dangerously-fast*)
(vec-digit-length* (storage mpz)))
(defun mpz-uses-minimal-storage-p (mpz)
(= (vec-digit-length mpz) (mpz-size mpz)))
(defun optimize-mpz (mpz)
(declare (type mpz mpz))
(optimize-storage (storage mpz))
mpz)
(defun optimize-storage (vec)
(declare (type storage vec))
(let ((size (vec-digit-length* vec))
(length (vec-digit-length vec)))
(resize-vec-by vec (- size length))
vec))
(defun mpz-set-zero! (mpz)
(setf (sign mpz) 1)
(resize-vec-by (storage mpz) (- (vec-digit-length mpz)))
nil)
(defun mpz-integer-length (mpz)
"How many bits are needed to represent MPZ in two's complement?"
(let ((size (mpz-size mpz)))
(if (zerop size)
0
(with-vec (mpz mpz_)
(+ (* $digit-bits (1- size))
(integer-length (mpz_ (1- size)))
(/ (1- (sign mpz)) 2))))))
(defmethod print-object ((mpz mpz) stream)
(print-unreadable-object (mpz stream :type t :identity t)
(format stream "~D bit~:P~:[~;*~]"
(mpz-integer-length mpz)
(mpz-uses-minimal-storage-p mpz))))
;;; Comparison functions
(defun mpz-zerop (mpz)
(do-digits (i digit mpz t)
(declare (ignore i))
(unless (zerop digit)
(return-from mpz-zerop nil))))
(defun mpz-plusp (mpz)
(and (= 1 (sign mpz))
(not (mpz-zerop mpz))))
(defun mpz-minusp (mpz)
(and (= -1 (sign mpz))
(not (mpz-zerop mpz))))
(defun mpz-abs (mpz)
(make-mpz 1 (storage mpz)))
(defun mpz-negate (mpz)
(make-mpz (- (sign mpz)) (storage mpz)))
(defun mpz-negate! (mpz)
(setf (sign mpz) (- (sign mpz)))
nil)
(defun mpz-= (a b)
(with-vecs (a a_ b b_)
(and (= (sign a) (sign b))
(= (mpz-size a) (mpz-size b))
(vec= (storage a) (storage b)))))
(defun mpz-/= (a b)
(not (mpz-= a b)))
(defun %mpz-> (a b)
(assert (= 1 (sign a) (sign b)))
(let ((size-a (mpz-size a))
(size-b (mpz-size b)))
(if (/= size-a size-b)
(> size-a size-b)
(with-vecs (a a_ b b_)
(loop :for i :from (1- size-a) :downto 0
:for ai := (a_ i)
:for bi := (b_ i)
:do (cond
((> ai bi) (return t))
((< ai bi) (return nil)))
:finally (return nil))))))
(defun mpz-> (a b)
(cond
((> (sign a) (sign b)) t)
((< (sign a) (sign b)) nil)
;; Now we know they have the same sign. If they're both negative,
;; then reverse.
((= -1 (sign a))
(%mpz-> (mpz-abs b) (mpz-abs a)))
;; They have the same sign and they're positive.
(t
(%mpz-> a b))))
(defun mpz->= (a b)
(or (mpz-= a b)
(mpz-> a b)))
(defun mpz-< (a b)
(not (mpz->= a b)))
(defun mpz-<= (a b)
(not (mpz-> a b)))
(defun %add-storages/unsafe (r a size-a b size-b)
(declare (type storage r a b)
(type alexandria:array-length size-a size-b))
#+hypergeometrica-safe
(assert (>= size-a size-b))
#+hypergeometrica-safe
(assert (>= (vec-digit-length r) size-a))
;; size-a >= size-b
(with-vecs (a a_ b b_ r r_)
(let ((carry 0))
(declare (type digit carry))
(dotimes (i size-b)
;; AI + BI + CARRY
(multiple-value-bind (sum c) (add64 (a_ i) (b_ i))
;; XXX: Using MULTIPLE-VALUE-SETQ is buggy here in SBCL
;; 2.1.3.
(multiple-value-bind (sum new-carry) (add64 sum carry)
(setf carry (+ new-carry c))
(setf (r_ i) sum))))
(do-range (i size-b size-a)
(multiple-value-bind (sum new-carry) (add64 (a_ i) carry)
(setf carry new-carry
(r_ i) sum)))
;; Account for the carry.
(unless (zerop carry)
;; Do we have enough storage? If not, make some.
(assert (< size-a (vec-digit-length r)))
(setf (r_ size-a) carry))
;; Return the storage
r)))
(defun %mpz-+ (a b)
(assert (= 1 (sign a) (sign b)))
(let* ((size-a (mpz-size a))
(size-b (mpz-size b))
(r (make-storage (1+ (max size-a size-b)))))
(if (>= size-a size-b)
(make-mpz 1 (%add-storages/unsafe r
(storage a) size-a
(storage b) size-b))
(make-mpz 1 (%add-storages/unsafe r
(storage b) size-b
(storage a) size-a)))))
(defun %subtract-storages/unsafe (a size-a b size-b)
(declare (type storage a b)
(type alexandria:array-length size-a size-b))
;; a > b > 0
(assert (>= size-a size-b))
(let* ((r (make-storage size-a))
(carry 1))
(declare (type bit carry))
(with-vecs (a a_ b b_ r r_)
(dotimes (i size-b)
(let ((ai (a_ i))
(neg-bi (complement-digit (b_ i))))
;; AI + CARRY - BI
(multiple-value-bind (sum c) (add64 ai carry)
(cond
((= 1 c)
(setf (r_ i) neg-bi
carry 1))
(t
;; XXX: Using MULTIPLE-VALUE-SETQ is buggy here in SBCL
;; 2.1.3.
(multiple-value-bind (sum new-carry) (add64 sum neg-bi)
(setf carry new-carry)
(setf (r_ i) sum)))))))
(do-range (i size-b size-a)
(let ((ai (a_ i)))
(multiple-value-bind (sum c) (add64 ai carry)
(cond
((= 1 c)
(setf (r_ i) $max-digit
carry 1))
(t
;; XXX: Using MULTIPLE-VALUE-SETQ is buggy here in SBCL
;; 2.1.3.
(multiple-value-bind (sum new-carry) (add64 sum $max-digit)
(setf carry new-carry)
(setf (r_ i) sum))))))))
#+hypergeometrica-safe
(assert (= 1 carry))
r))
(defun %mpz-- (a b)
(assert (= 1 (sign a) (sign b)))
(cond
((mpz-= a b)
(integer-mpz 0))
((mpz-> a b)
(make-mpz 1 (optimize-storage
(%subtract-storages/unsafe (storage a) (mpz-size a)
(storage b) (mpz-size b)))))
(t
(make-mpz -1 (optimize-storage
(%subtract-storages/unsafe (storage b) (mpz-size b)
(storage a) (mpz-size a)))))))
(defun mpz-+ (a b)
(declare (type mpz a b))
(cond
((mpz-zerop a) b)
((mpz-zerop b) a)
((= 1 (sign a) (sign b))
(%mpz-+ a b))
((= -1 (sign a) (sign b))
(mpz-negate (%mpz-+ (mpz-abs a) (mpz-abs b))))
;; a > 0, b < 0
((= -1 (sign b))
(%mpz-- a (mpz-abs b)))
;; a < 0, b > 0
(t
(%mpz-- b (mpz-abs a)))))
(defun mpz-- (a b)
(mpz-+ a (mpz-negate b)))
(defun mpz-multiply-by-digit! (d mpz)
(declare (type digit d)
(type mpz mpz))
(cond
((zerop d)
(mpz-set-zero! mpz)
nil)
((= 1 d)
;; Do absolutely nothin'!
nil)
(t
(let ((d (abs d))
(size (mpz-size mpz))
(carry 0))
(declare (type (unsigned-byte 64) d)
(type alexandria:array-length size)
(type (unsigned-byte 64) carry))
(with-vec (mpz mpz_)
(dotimes (i size)
(multiple-value-bind (lo hi) (mul128 d (mpz_ i))
(multiple-value-bind (lo sub-carry) (add64 lo carry)
(setf (mpz_ i) lo)
(setf carry (fx+ hi sub-carry))))))
(when (plusp carry)
(when (mpz-uses-minimal-storage-p mpz)
(resize-vec-by (storage mpz) 1))
(with-vec (mpz mpz_)
(setf (mpz_ size) carry)))
nil))))
(defun mpz-multiply-by-s64! (d mpz)
(declare (type (signed-byte 64) d)
(type mpz mpz))
(mpz-multiply-by-digit! (abs d) mpz)
(when (minusp d)
(mpz-negate! mpz))
nil)
(defun %multiply-storage/schoolboy (a a-size b b-size)
#+hypergeometrica-safe
(assert (>= a-size b-size))
(let* ((length (+ 1 a-size b-size))
(r (make-storage length)))
(with-vecs (a a_ b b_ r r_)
(let ((temp (make-mpz 1 (make-storage length))))
(dotimes (i b-size r)
(let ((bi (b_ i)))
(unless (zerop bi)
;; We re-use TEMP. Clear dirty info. (XXX: We could
;; probably optimize START and END.)
;;
;; TEMP := 0
(vec-fill temp 0)
;; :START1 i should be interpreted as a left shift of A by I
;; digits.
;;
;; TEMP := A * 2^(64 * I).
(vec-replace/unsafe temp a :start1 i)
;; TEMP := B[i] * TEMP
(mpz-multiply-by-digit! bi temp)
;; R := R + TEMP
(%add-storages/unsafe r
r length
(storage temp) length))))))))
;;;
(defun mpz-debug (mpz &optional (stream *standard-output*))
(print-unreadable-object (mpz stream :type t :identity nil)
(format stream "(~D) ~:[-1~;+1~] *"
(mpz-size mpz)
(= 1 (sign mpz)))
(do-digits (i digit mpz)
(declare (ignore i))
(format stream " ~16,'0X" digit))
(terpri stream)
(format stream "~D" (mpz-integer mpz))))
|
[
{
"context": ";-*- Mode: Lisp -*-\n;;;; Author: Paul Dietz\n;;;; Created: Tue Jan 13 19:38:10 2004\n;;;; Cont",
"end": 49,
"score": 0.999847412109375,
"start": 39,
"tag": "NAME",
"value": "Paul Dietz"
}
] |
ansi-tests/load-streams.lsp
|
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD
| 10 |
;-*- Mode: Lisp -*-
;;;; Author: Paul Dietz
;;;; Created: Tue Jan 13 19:38:10 2004
;;;; Contains: Load files containing tests for section 21 (streams)
(in-package :cl-test)
(load "input-stream-p.lsp")
(load "output-stream-p.lsp")
(load "interactive-stream-p.lsp")
(load "open-stream-p.lsp")
(load "stream-element-type.lsp")
(load "streamp.lsp")
(load "read-byte.lsp")
(load "peek-char.lsp")
(load "read-char.lsp")
(load "read-char-no-hang.lsp")
(load "terpri.lsp")
(load "fresh-line.lsp")
(load "unread-char.lsp")
(load "write-char.lsp")
(load "read-line.lsp")
(load "write-string.lsp")
(load "write-line.lsp")
(load "read-sequence.lsp")
(load "write-sequence.lsp")
(load "file-length.lsp")
(load "file-position.lsp")
(load "file-string-length.lsp")
(load "open.lsp")
(load "stream-external-format.lsp")
(load "with-open-file.lsp")
(load "with-open-stream.lsp")
(load "listen.lsp")
(load "clear-input.lsp")
(load "finish-output.lsp")
(load "force-output.lsp")
(load "clear-output.lsp")
(load "make-synonym-stream.lsp")
(load "synonym-stream-symbol.lsp")
(load "make-broadcast-stream.lsp")
(load "broadcast-stream-streams.lsp")
(load "make-two-way-stream.lsp")
(load "two-way-stream-input-stream.lsp")
(load "two-way-stream-output-stream.lsp")
(load "echo-stream-input-stream.lsp")
(load "echo-stream-output-stream.lsp")
(load "make-echo-stream.lsp")
(load "concatenated-stream-streams.lsp")
(load "make-concatenated-stream.lsp")
(load "get-output-stream-string.lsp")
(load "make-string-input-stream.lsp")
(load "make-string-output-stream.lsp")
(load "with-input-from-string.lsp")
(load "with-output-to-string.lsp")
(load "stream-error-stream.lsp")
|
88894
|
;-*- Mode: Lisp -*-
;;;; Author: <NAME>
;;;; Created: Tue Jan 13 19:38:10 2004
;;;; Contains: Load files containing tests for section 21 (streams)
(in-package :cl-test)
(load "input-stream-p.lsp")
(load "output-stream-p.lsp")
(load "interactive-stream-p.lsp")
(load "open-stream-p.lsp")
(load "stream-element-type.lsp")
(load "streamp.lsp")
(load "read-byte.lsp")
(load "peek-char.lsp")
(load "read-char.lsp")
(load "read-char-no-hang.lsp")
(load "terpri.lsp")
(load "fresh-line.lsp")
(load "unread-char.lsp")
(load "write-char.lsp")
(load "read-line.lsp")
(load "write-string.lsp")
(load "write-line.lsp")
(load "read-sequence.lsp")
(load "write-sequence.lsp")
(load "file-length.lsp")
(load "file-position.lsp")
(load "file-string-length.lsp")
(load "open.lsp")
(load "stream-external-format.lsp")
(load "with-open-file.lsp")
(load "with-open-stream.lsp")
(load "listen.lsp")
(load "clear-input.lsp")
(load "finish-output.lsp")
(load "force-output.lsp")
(load "clear-output.lsp")
(load "make-synonym-stream.lsp")
(load "synonym-stream-symbol.lsp")
(load "make-broadcast-stream.lsp")
(load "broadcast-stream-streams.lsp")
(load "make-two-way-stream.lsp")
(load "two-way-stream-input-stream.lsp")
(load "two-way-stream-output-stream.lsp")
(load "echo-stream-input-stream.lsp")
(load "echo-stream-output-stream.lsp")
(load "make-echo-stream.lsp")
(load "concatenated-stream-streams.lsp")
(load "make-concatenated-stream.lsp")
(load "get-output-stream-string.lsp")
(load "make-string-input-stream.lsp")
(load "make-string-output-stream.lsp")
(load "with-input-from-string.lsp")
(load "with-output-to-string.lsp")
(load "stream-error-stream.lsp")
| true |
;-*- Mode: Lisp -*-
;;;; Author: PI:NAME:<NAME>END_PI
;;;; Created: Tue Jan 13 19:38:10 2004
;;;; Contains: Load files containing tests for section 21 (streams)
(in-package :cl-test)
(load "input-stream-p.lsp")
(load "output-stream-p.lsp")
(load "interactive-stream-p.lsp")
(load "open-stream-p.lsp")
(load "stream-element-type.lsp")
(load "streamp.lsp")
(load "read-byte.lsp")
(load "peek-char.lsp")
(load "read-char.lsp")
(load "read-char-no-hang.lsp")
(load "terpri.lsp")
(load "fresh-line.lsp")
(load "unread-char.lsp")
(load "write-char.lsp")
(load "read-line.lsp")
(load "write-string.lsp")
(load "write-line.lsp")
(load "read-sequence.lsp")
(load "write-sequence.lsp")
(load "file-length.lsp")
(load "file-position.lsp")
(load "file-string-length.lsp")
(load "open.lsp")
(load "stream-external-format.lsp")
(load "with-open-file.lsp")
(load "with-open-stream.lsp")
(load "listen.lsp")
(load "clear-input.lsp")
(load "finish-output.lsp")
(load "force-output.lsp")
(load "clear-output.lsp")
(load "make-synonym-stream.lsp")
(load "synonym-stream-symbol.lsp")
(load "make-broadcast-stream.lsp")
(load "broadcast-stream-streams.lsp")
(load "make-two-way-stream.lsp")
(load "two-way-stream-input-stream.lsp")
(load "two-way-stream-output-stream.lsp")
(load "echo-stream-input-stream.lsp")
(load "echo-stream-output-stream.lsp")
(load "make-echo-stream.lsp")
(load "concatenated-stream-streams.lsp")
(load "make-concatenated-stream.lsp")
(load "get-output-stream-string.lsp")
(load "make-string-input-stream.lsp")
(load "make-string-output-stream.lsp")
(load "with-input-from-string.lsp")
(load "with-output-to-string.lsp")
(load "stream-error-stream.lsp")
|
[
{
"context": "ee the\n; LICENSE for more details.\n\n; Written by: Matt Kaufmann and J Strother Moore\n; email: ",
"end": 665,
"score": 0.9998738765716553,
"start": 652,
"tag": "NAME",
"value": "Matt Kaufmann"
},
{
"context": "s.\n\n; Written by: Matt Kaufmann and J Strother Moore\n; email: [email protected] and Mo",
"end": 700,
"score": 0.9998859167098999,
"start": 684,
"tag": "NAME",
"value": "J Strother Moore"
},
{
"context": " and J Strother Moore\n; email: [email protected] and [email protected]\n; Department of Comp",
"end": 738,
"score": 0.9999279975891113,
"start": 716,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "ore\n; email: [email protected] and [email protected]\n; Department of Computer Science\n; University of ",
"end": 767,
"score": 0.9999279379844666,
"start": 748,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
proof-builder-pkg.lisp
|
TheBeaNerd/acl2
| 1 |
; ACL2 Version 8.3 -- A Computational Logic for Applicative Common Lisp
; Copyright (C) 2021, Regents of the University of Texas
; This version of ACL2 is a descendent of ACL2 Version 1.9, Copyright
; (C) 1997 Computational Logic, Inc. See the documentation topic NOTE-2-0.
; This program is free software; you can redistribute it and/or modify
; it under the terms of the LICENSE file distributed with ACL2.
; 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
; LICENSE for more details.
; Written by: Matt Kaufmann and J Strother Moore
; email: [email protected] and [email protected]
; Department of Computer Science
; University of Texas at Austin
; Austin, TX 78712 U.S.A.
(in-package "ACL2")
; The "PC" in the package name, "ACL2-PC", stands for "proof-checker", which is
; the former name of the proof-builder. We use the legacy package name for
; backward compatibility.
(defpkg "ACL2-PC" nil)
|
80490
|
; ACL2 Version 8.3 -- A Computational Logic for Applicative Common Lisp
; Copyright (C) 2021, Regents of the University of Texas
; This version of ACL2 is a descendent of ACL2 Version 1.9, Copyright
; (C) 1997 Computational Logic, Inc. See the documentation topic NOTE-2-0.
; This program is free software; you can redistribute it and/or modify
; it under the terms of the LICENSE file distributed with ACL2.
; 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
; LICENSE for more details.
; Written by: <NAME> and <NAME>
; email: <EMAIL> and <EMAIL>
; Department of Computer Science
; University of Texas at Austin
; Austin, TX 78712 U.S.A.
(in-package "ACL2")
; The "PC" in the package name, "ACL2-PC", stands for "proof-checker", which is
; the former name of the proof-builder. We use the legacy package name for
; backward compatibility.
(defpkg "ACL2-PC" nil)
| true |
; ACL2 Version 8.3 -- A Computational Logic for Applicative Common Lisp
; Copyright (C) 2021, Regents of the University of Texas
; This version of ACL2 is a descendent of ACL2 Version 1.9, Copyright
; (C) 1997 Computational Logic, Inc. See the documentation topic NOTE-2-0.
; This program is free software; you can redistribute it and/or modify
; it under the terms of the LICENSE file distributed with ACL2.
; 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
; LICENSE for more details.
; Written by: PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI
; email: PI:EMAIL:<EMAIL>END_PI and PI:EMAIL:<EMAIL>END_PI
; Department of Computer Science
; University of Texas at Austin
; Austin, TX 78712 U.S.A.
(in-package "ACL2")
; The "PC" in the package name, "ACL2-PC", stands for "proof-checker", which is
; the former name of the proof-builder. We use the legacy package name for
; backward compatibility.
(defpkg "ACL2-PC" nil)
|
[
{
"context": "; DEALINGS IN THE SOFTWARE.\n;\n; Original author: Jared Davis <[email protected]>\n\n(in-package \"ACL2\")\n(inclu",
"end": 1354,
"score": 0.9996964335441589,
"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(include-book \"utf8-decode\"",
"end": 1375,
"score": 0.999934732913971,
"start": 1356,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/unicode/read-utf8.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 "utf8-decode")
(include-book "std/io/take-bytes" :dir :system)
(local (include-book "std/io/base" :dir :system))
(local (include-book "tools/mv-nth" :dir :system))
(local (include-book "centaur/bitops/ihsext-basics" :dir :system))
(local (include-book "centaur/bitops/signed-byte-p" :dir :system))
(local (include-book "std/lists/take" :dir :system))
(set-state-ok t)
(local (in-theory (disable signed-byte-p)))
(local (in-theory (disable take)))
(local (defthm signed-byte-p-resolver
(implies (and (integerp n)
(<= 1 n)
(integerp x)
(<= (- (expt 2 (1- n))) x)
(< x (expt 2 (1- n))))
(signed-byte-p n x))
:hints(("Goal" :in-theory (enable signed-byte-p)))))
;; We now want to recreate our utf8=>ustring function but directly using the
;; file reading operations. We begin by writing equivalents of "take" and
;; "nthcdr" that operate on byte streams. We will use (read-byte$-all ...)
;; effectively as the file's contents, and relate all of these operations to
;; it.
(defund read-utf8-fast (channel state acc)
(declare (xargs :guard (and (state-p state)
(symbolp channel)
(open-input-channel-p channel :byte state)
(ustring? acc))
:measure (file-measure channel state)
:verify-guards nil))
(mbe
:logic
(if (and (state-p state)
(symbolp channel)
(open-input-channel-p channel :byte state))
(mv-let (x1 state)
(read-byte$ channel state)
(if (not x1)
(mv (reverse acc) state)
(let ((len1 (utf8-table36-expected-length x1)))
(if (not len1)
(mv 'fail state)
(mv-let (x2-x4 state)
(take-bytes (1- len1) channel state)
(let* ((x1-x4 (cons x1 x2-x4))
(first (utf8-char=>uchar x1-x4)))
(if (not first)
(mv 'fail state)
(read-utf8-fast channel state (cons first acc)))))))))
(mv 'fail state))
:exec
(mv-let
(x1 state)
(read-byte$ channel state)
(if (not x1)
(mv (reverse acc) state)
(cond
((<= (the-fixnum x1) 127)
;; Expected length 1. We don't need to do any further checking; we can
;; just recur very quickly. Note that this will give us very good
;; performance for English text, where characters are typically only a
;; single byte.
(read-utf8-fast channel state (cons x1 acc)))
((in-range? (the-fixnum x1) 194 223)
;; Expected length 2. (We excluded 192,193 because they are not
;; permitted under Table 3-7.)
(mv-let (x2 state) (read-byte$ channel state)
(if (and x2 (in-range? (the-fixnum x2) 128 191))
;; Manually-inlined utf8-combine2 operation.
(read-utf8-fast
channel state
(cons
(the-fixnum
(logior
(the-fixnum (ash (the-fixnum (logand (the-fixnum x1) 31)) 6))
(the-fixnum (logand (the-fixnum x2) 63))))
acc))
(mv 'fail state))))
((in-range? (the-fixnum x1) 224 239)
;; Expected length 3. (We cover all options here.)
(mv-let (x2 state) (read-byte$ channel state)
(mv-let (x3 state) (read-byte$ channel state)
(if (and x2 x3
(cond ((= (the-fixnum x1) 224)
(in-range? (the-fixnum x2) 160 191))
((= (the-fixnum x1) 237)
(in-range? (the-fixnum x2) 128 159))
(t
(in-range? (the-fixnum x2) 128 191)))
(in-range? (the-fixnum x3) 128 191))
(read-utf8-fast
channel state
(cons
(the-fixnum
(logior
(the-fixnum
(ash (the-fixnum (logand (the-fixnum x1) 15)) 12))
(the-fixnum
(logior
(the-fixnum
(ash (the-fixnum (logand (the-fixnum x2) 63)) 6))
(the-fixnum (logand (the-fixnum x3) 63))))))
acc))
(mv 'fail state)))))
((in-range? (the-fixnum x1) 240 244)
;; Expected length 4. (We only accept 240-244 because of Table 3-7;
;; i.e., we exclude 245, 246, and 247.
(mv-let (x2 state) (read-byte$ channel state)
(mv-let (x3 state) (read-byte$ channel state)
(mv-let (x4 state) (read-byte$ channel state)
(if (and x2 x3 x4
(cond ((= (the-fixnum x1) 240)
(in-range? (the-fixnum x2) 144 191))
((= (the-fixnum x1) 244)
(in-range? (the-fixnum x2) 128 143))
(t
(in-range? (the-fixnum x2) 128 191)))
(in-range? (the-fixnum x3) 128 191)
(in-range? (the-fixnum x4) 128 191))
(read-utf8-fast
channel state
(cons
(the-fixnum
(logior
(the-fixnum
(ash (the-fixnum (logand (the-fixnum x1) 7)) 18))
(the-fixnum
(logior
(the-fixnum
(ash (the-fixnum (logand (the-fixnum x2) 63)) 12))
(the-fixnum
(logior
(the-fixnum
(ash (the-fixnum (logand (the-fixnum x3) 63)) 6))
(the-fixnum
(logand (the-fixnum x4) 63))))))))
acc))
(mv 'fail state))))))
;; This is a little obscure. As an optimization above, we did not
;; consider cases for first byte = 192, 193, 245, 246, and 247, because
;; these are not allowed under Table 3-7.
;;
;; However, utf8-table36-expected-length predics the lengths of these
;; as 2, 2, 4, 4, and 4, respectively. So, for our MBE equivalence, we
;; need to make sure to advance the stream just like we do in the
;; :logic mode.
((or (= (the-fixnum x1) 192)
(= (the-fixnum x1) 193))
(mv-let (x2 state)
(read-byte$ channel state)
(declare (ignore x2))
(mv 'fail state)))
((or (= (the-fixnum x1) 245)
(= (the-fixnum x1) 246)
(= (the-fixnum x1) 247))
(mv-let (x2 state)
(read-byte$ channel state)
(declare (ignore x2))
(mv-let (x3 state)
(read-byte$ channel state)
(declare (ignore x3))
(mv-let (x4 state)
(read-byte$ channel state)
(declare (ignore x4))
(mv 'fail state)))))
(t
(mv 'fail state)))))))
(defthm state-p1-of-mv-nth-1-of-read-utf8-fast
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel)))
(state-p1 (mv-nth 1 (read-utf8-fast channel state acc))))
:hints(("Goal" :in-theory (enable read-utf8-fast))))
(defthm open-input-channel-p1-of-mv-nth-1-of-read-utf8-fast
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel)))
(open-input-channel-p1 channel :byte
(mv-nth 1 (read-utf8-fast channel state acc))))
:hints(("Goal" :in-theory (enable read-utf8-fast))))
;; Correctness of read-utf8-fast
;;
;; We think of (read-byte$-all channel state) as returning the file's contents.
;; We will show that under the appropriate hypotheses, the data returned by
;; (read-utf8-fast channel state acc) is exactly the same as what we would get
;; if we were to first read the entire file's contents, and then apply our UTF8
;; decoding function, utf8=>ustring, to the result.
;;
;; The proof is sort of cute. We rewrite everything to be in terms of
;; read-byte$-all. For example, we first show that read-byte$ is nothing more
;; than the car of read-byte$-all. Similarly, in take-bytes.lisp, we have
;; shown that take-bytes is just the take of read-byte$-all.
(local (defthm car-of-read-byte$
(implies (and (force (state-p state))
(force (symbolp channel))
(force (open-input-channel-p channel :byte state)))
(equal (mv-nth 0 (read-byte$ channel state))
(car (mv-nth 0 (read-byte$-all channel state)))))
:hints(("Goal" :in-theory (enable read-byte$-all)))))
(local (theory-invariant
(incompatible (:rewrite car-of-read-byte$)
(:definition read-byte$-all))))
(local (defthm read-byte$-all-of-mv-nth-1-of-read-byte$
(implies (and (force (state-p state))
(force (symbolp channel))
(force (open-input-channel-p channel :byte state)))
(equal
(mv-nth 0 (read-byte$-all channel (mv-nth 1 (read-byte$ channel state))))
(cdr (mv-nth 0 (read-byte$-all channel state)))))
:hints(("Goal" :in-theory (e/d (read-byte$-all)
(car-of-read-byte$))))))
(local (defthm car-of-read-byte$-all-when-not-caar
(implies (and (state-p1 state)
(symbolp channel)
(open-input-channel-p1 channel :byte state)
(not (car (mv-nth 0 (read-byte$-all channel state)))))
(equal (mv-nth 0 (read-byte$-all channel state))
nil))
:hints(("goal" :in-theory (e/d (read-byte$-all)
(car-of-read-byte$
read-byte$-all-of-mv-nth-1-of-read-byte$
))))))
(defthm car-of-read-utf8-fast-is-utf8=>ustring-fast-of-read-byte$-all
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel))
(true-listp acc))
(equal (mv-nth 0 (read-utf8-fast channel state acc))
(utf8=>ustring-fast (mv-nth 0 (read-byte$-all channel state))
acc)))
:hints(("Goal"
:in-theory (e/d (read-utf8-fast utf8=>ustring-fast
take)
(nthcdr-bytes-2
nthcdr-bytes-3
nthcdr-bytes-4))
:induct (read-utf8-fast channel state acc))))
;; Guard verification for read-utf8-fast.
;;
;; This is really messy, because the MBE equivalence is so dramatic. Note that
;; a lot of this is the same as what we needed for utf8=>ustring-fast.
(encapsulate
()
(local (in-theory (enable take)))
(local (defthm terrible-lemma-1
(implies (and (integerp x)
(<= 0 x)
(<= x 127))
(uchar? x))
:hints(("Goal" :in-theory (enable uchar?)))))
(local (defthm terrible-lemma-2
(IMPLIES (AND (force (integerp x1))
(force (integerp x2))
(< 127 X1)
(<= 194 X1)
(<= X1 223)
(<= 128 X2)
(<= X2 191))
(UCHAR? (LOGIOR (ASH (LOGAND X1 31) 6)
(LOGAND X2 63))))
:hints(("Goal"
:in-theory (enable utf8-combine2-guard
utf8-combine2
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine2))))))
(local (defthm terrible-lemma-3
(IMPLIES (AND (force (integerp x2))
(force (integerp x3))
(<= 160 X2)
(<= X2 191)
(<= 128 X3)
(<= X3 191))
(UCHAR? (LOGIOR 0 (ASH (LOGAND X2 63) 6)
(LOGAND X3 63))))
:hints(("Goal"
:in-theory (enable utf8-combine3-guard
utf8-combine3
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine3
(x1 224)))))))
(local (defthm terrible-lemma-4
(IMPLIES (AND (force (integerp X1))
(force (integerp X2))
(force (integerp X3))
(<= 224 X1)
(<= X1 239)
(NOT (EQUAL X1 224))
(NOT (EQUAL X1 237))
(<= 128 X2)
(<= X2 191)
(<= 128 X3)
(<= X3 191))
(UCHAR? (LOGIOR (ASH (LOGAND X1 15) 12)
(ASH (LOGAND X2 63) 6)
(LOGAND X3 63))))
:hints(("Goal"
:in-theory (enable utf8-combine3-guard
utf8-combine3
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine3))))))
(local (defthm terrible-lemma-5
(IMPLIES (AND (force (integerp x2))
(force (integerp x3))
(<= 128 X2)
(<= X2 159)
(<= 128 X3)
(<= X3 191))
(UCHAR? (LOGIOR 53248 (ASH (LOGAND X2 63) 6)
(LOGAND X3 63))))
:hints(("Goal"
:in-theory (enable utf8-combine3-guard
utf8-combine3
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine3
(x1 237)))))))
(local (defthm terrible-lemma-6
(IMPLIES (AND (force (integerp x2))
(force (integerp x3))
(force (integerp x4))
(<= 144 X2)
(<= X2 191)
(<= 128 X3)
(<= X3 191)
(<= 128 X4)
(<= X4 191))
(UCHAR? (LOGIOR 0 (ASH (LOGAND X2 63) 12)
(ASH (LOGAND X3 63) 6)
(LOGAND X4 63))))
:hints(("Goal"
:in-theory (enable utf8-combine4-guard
utf8-combine4
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine4
(x1 240)))))))
(local (defthm terrible-lemma-7
(IMPLIES (AND (force (integerp x1))
(force (integerp x2))
(force (integerp x3))
(force (integerp x4))
(<= 240 X1)
(<= X1 244)
(NOT (EQUAL X1 240))
(NOT (EQUAL X1 244))
(<= 128 X2)
(<= X2 191)
(<= 128 X3)
(<= X3 191)
(<= 128 X4)
(<= X4 191))
(UCHAR? (LOGIOR (ASH (LOGAND X1 7) 18)
(ASH (LOGAND X2 63) 12)
(ASH (LOGAND X3 63) 6)
(LOGAND X4 63))))
:hints(("Goal"
:in-theory (enable utf8-combine4-guard
utf8-combine4
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine4))))))
(local (defthm terrible-lemma-8
(IMPLIES (AND (force (integerp x2))
(force (integerp x3))
(force (integerp x4))
(<= 128 x2)
(<= x2 143)
(<= 128 x3)
(<= x3 191)
(<= 128 x4)
(<= x4 191))
(UCHAR? (LOGIOR 1048576 (ASH (LOGAND x2 63) 12)
(ASH (LOGAND x3 63) 6)
(LOGAND x4 63))))
:hints(("Goal"
:in-theory (enable utf8-combine4-guard
utf8-combine4
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine4
(x1 244)))))))
(local (include-book "std/typed-lists/signed-byte-listp" :dir :system))
(local (defthm unsigned-byte-listp-8-of-car-of-read-byte$-all-forward
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel)))
(unsigned-byte-listp 8 (mv-nth 0 (read-byte$-all channel state))))
:rule-classes ((:forward-chaining :trigger-terms ((read-byte$-all channel state))))))
(local (defthm unsigned-byte-listp-8-of-cdr-when-unsigned-byte-listp-8
(implies (unsigned-byte-listp 8 x)
(unsigned-byte-listp 8 (cdr x)))
:rule-classes ((:forward-chaining))))
(local (defthm crock
(implies (unsigned-byte-listp bytes x)
(iff (consp x)
x))))
(local (defthm hideous-lemma-1
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel))
(mv-nth 0 (read-byte$-all channel state)))
(unsigned-byte-p 8 (car (mv-nth 0 (read-byte$-all channel state)))))
:rule-classes ((:rewrite)
(:forward-chaining
:trigger-terms ((mv-nth 0 (read-byte$-all channel state)))))))
(local (defthm hideous-lemma-2
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel))
(cdr (mv-nth 0 (read-byte$-all channel state))))
(unsigned-byte-p 8 (cadr (mv-nth 0 (read-byte$-all channel state)))))
:rule-classes ((:rewrite)
(:forward-chaining
:trigger-terms ((cdr (mv-nth 0 (read-byte$-all channel state))))))))
(local (defthm hideous-lemma-3
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel))
(cddr (mv-nth 0 (read-byte$-all channel state))))
(unsigned-byte-p 8 (caddr (mv-nth 0 (read-byte$-all channel state)))))
:rule-classes ((:rewrite)
(:forward-chaining
:trigger-terms ((cddr (mv-nth 0 (read-byte$-all channel state))))))
:hints(("Goal"
:in-theory (e/d (read-byte$-all)
(car-of-read-byte$))
:expand ((read-byte$-all channel state)
(read-byte$-all channel (mv-nth 1 (read-byte$ channel state)))
(read-byte$-all
channel
(mv-nth 1 (read-byte$ channel
(mv-nth 1 (read-byte$ channel
state))))))))))
(local (defthm hideous-lemma-4
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel))
(cdddr (mv-nth 0 (read-byte$-all channel state))))
(unsigned-byte-p 8 (car (cdddr (mv-nth 0 (read-byte$-all channel state))))))
:rule-classes ((:rewrite)
(:forward-chaining
:trigger-terms ((cdddr (mv-nth 0 (read-byte$-all channel state))))))
:hints(("Goal"
:in-theory (e/d (read-byte$-all)
(car-of-read-byte$))
:expand ((read-byte$-all channel state)
(read-byte$-all channel
(mv-nth 1 (read-byte$ channel state)))
(read-byte$-all
channel
(mv-nth 1 (read-byte$ channel
(mv-nth 1 (read-byte$ channel state)))))
(read-byte$-all
channel
(mv-nth 1 (read-byte$
channel
(mv-nth 1 (read-byte$
channel
(mv-nth 1 (read-byte$ channel
state))))))))))))
(local (defthm integerp-when-unsigned-byte-p-8
(implies (unsigned-byte-p 8 x)
(integerp x))))
(local (defthm signed-byte-p-from-unsigned-byte-p-8
(implies (and (unsigned-byte-p 8 x)
(< 8 (nfix n)))
(signed-byte-p n x))))
(local (defthm len-zero-when-true-listp
(implies (true-listp x)
(equal (equal (len x) 0)
(not x)))))
(local (defthm integer-squeeze-lemma
(implies (and (syntaxp (quotep n))
(integerp n)
(< (1- n) x)
(< x (1+ n)))
(equal (equal x n)
(integerp x)))
:rule-classes ((:rewrite :backchain-limit-lst 1))))
(local (defthm unsigned-byte-p-8-when-valid-integer
(implies (and (<= 0 x)
(< x 255))
(equal (unsigned-byte-p 8 x)
(integerp x)))
:rule-classes ((:rewrite :backchain-limit-lst 1))
:hints(("Goal" :in-theory (enable unsigned-byte-p)))))
(local (include-book "arithmetic-3/bind-free/top" :dir :system))
(local (defthm nthcdr-bytes-hack
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel))
(force (natp n)))
(equal (nthcdr-bytes n channel (mv-nth 1 (read-byte$ channel state)))
(nthcdr-bytes (+ 1 n) channel state)))
:hints(("Goal"
:expand (nthcdr-bytes (+ 1 n) channel state)
:in-theory (enable nthcdr-bytes)
:do-not-induct t))))
(local (in-theory (e/d (unsigned-byte-listp
utf8-char=>uchar
utf8-table36-bytes
utf8-table37-bytes
utf8-combine2
utf8-combine3
utf8-combine4
utf8-combine2-guard
utf8-combine3-guard
utf8-combine4-guard)
(
;; BOZO the above "terrible lemmas" were developed before
;; including bitops, so they're targeting the wrong normal
;; forms...
bitops::LOGAND-WITH-BITMASK
simplify-logior
commutativity-of-logior
commutativity-of-logand
UTF8-PARTITION-SUCCESSFUL-WHEN-ANY-VALID-PARTITIONING-EXISTS
))))
(verify-guards read-utf8-fast
:hints(("Goal"
:do-not-induct t
:do-not '(generalize fertilize))))
)
(defun read-utf8 (filename state)
(declare (xargs :guard (and (state-p state)
(stringp filename))
:stobjs state))
(mv-let (channel state)
(open-input-channel filename :byte state)
(if channel
(mv-let (data state)
(read-utf8-fast channel state nil)
(let ((state (close-input-channel channel state)))
(mv data state)))
(mv "Error opening file." state))))
(defthm state-p1-of-mv-nth-1-of-read-utf8
(implies (and (force (state-p1 state))
(force (stringp filename)))
(state-p1 (mv-nth 1 (read-utf8 filename state))))
:hints(("Goal" :in-theory (enable read-utf8))))
#|| No longer true, given change to read-file-bytes in
std/io/read-file-bytes.lisp, svn 1477.
(defthm car-of-read-utf8-when-file-cannot-be-opened
(implies (and (stringp (mv-nth 0 (read-file-bytes filename state)))
(force (state-p1 state))
(force (stringp filename)))
(equal (mv-nth 0 (read-utf8 filename state))
(mv-nth 0 (read-file-bytes filename state))))
:hints(("Goal" :in-theory (enable read-file-bytes read-utf8))))
||#
(defthm car-of-read-utf8-when-file-can-be-opened
(implies (and (not (stringp (mv-nth 0 (read-file-bytes filename state))))
(force (state-p1 state))
(force (stringp filename)))
(equal (mv-nth 0 (read-utf8 filename state))
(utf8=>ustring (mv-nth 0 (read-file-bytes filename state)))))
:hints(("Goal" :in-theory (enable read-utf8 read-file-bytes))))
|
30179
|
; 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 "utf8-decode")
(include-book "std/io/take-bytes" :dir :system)
(local (include-book "std/io/base" :dir :system))
(local (include-book "tools/mv-nth" :dir :system))
(local (include-book "centaur/bitops/ihsext-basics" :dir :system))
(local (include-book "centaur/bitops/signed-byte-p" :dir :system))
(local (include-book "std/lists/take" :dir :system))
(set-state-ok t)
(local (in-theory (disable signed-byte-p)))
(local (in-theory (disable take)))
(local (defthm signed-byte-p-resolver
(implies (and (integerp n)
(<= 1 n)
(integerp x)
(<= (- (expt 2 (1- n))) x)
(< x (expt 2 (1- n))))
(signed-byte-p n x))
:hints(("Goal" :in-theory (enable signed-byte-p)))))
;; We now want to recreate our utf8=>ustring function but directly using the
;; file reading operations. We begin by writing equivalents of "take" and
;; "nthcdr" that operate on byte streams. We will use (read-byte$-all ...)
;; effectively as the file's contents, and relate all of these operations to
;; it.
(defund read-utf8-fast (channel state acc)
(declare (xargs :guard (and (state-p state)
(symbolp channel)
(open-input-channel-p channel :byte state)
(ustring? acc))
:measure (file-measure channel state)
:verify-guards nil))
(mbe
:logic
(if (and (state-p state)
(symbolp channel)
(open-input-channel-p channel :byte state))
(mv-let (x1 state)
(read-byte$ channel state)
(if (not x1)
(mv (reverse acc) state)
(let ((len1 (utf8-table36-expected-length x1)))
(if (not len1)
(mv 'fail state)
(mv-let (x2-x4 state)
(take-bytes (1- len1) channel state)
(let* ((x1-x4 (cons x1 x2-x4))
(first (utf8-char=>uchar x1-x4)))
(if (not first)
(mv 'fail state)
(read-utf8-fast channel state (cons first acc)))))))))
(mv 'fail state))
:exec
(mv-let
(x1 state)
(read-byte$ channel state)
(if (not x1)
(mv (reverse acc) state)
(cond
((<= (the-fixnum x1) 127)
;; Expected length 1. We don't need to do any further checking; we can
;; just recur very quickly. Note that this will give us very good
;; performance for English text, where characters are typically only a
;; single byte.
(read-utf8-fast channel state (cons x1 acc)))
((in-range? (the-fixnum x1) 194 223)
;; Expected length 2. (We excluded 192,193 because they are not
;; permitted under Table 3-7.)
(mv-let (x2 state) (read-byte$ channel state)
(if (and x2 (in-range? (the-fixnum x2) 128 191))
;; Manually-inlined utf8-combine2 operation.
(read-utf8-fast
channel state
(cons
(the-fixnum
(logior
(the-fixnum (ash (the-fixnum (logand (the-fixnum x1) 31)) 6))
(the-fixnum (logand (the-fixnum x2) 63))))
acc))
(mv 'fail state))))
((in-range? (the-fixnum x1) 224 239)
;; Expected length 3. (We cover all options here.)
(mv-let (x2 state) (read-byte$ channel state)
(mv-let (x3 state) (read-byte$ channel state)
(if (and x2 x3
(cond ((= (the-fixnum x1) 224)
(in-range? (the-fixnum x2) 160 191))
((= (the-fixnum x1) 237)
(in-range? (the-fixnum x2) 128 159))
(t
(in-range? (the-fixnum x2) 128 191)))
(in-range? (the-fixnum x3) 128 191))
(read-utf8-fast
channel state
(cons
(the-fixnum
(logior
(the-fixnum
(ash (the-fixnum (logand (the-fixnum x1) 15)) 12))
(the-fixnum
(logior
(the-fixnum
(ash (the-fixnum (logand (the-fixnum x2) 63)) 6))
(the-fixnum (logand (the-fixnum x3) 63))))))
acc))
(mv 'fail state)))))
((in-range? (the-fixnum x1) 240 244)
;; Expected length 4. (We only accept 240-244 because of Table 3-7;
;; i.e., we exclude 245, 246, and 247.
(mv-let (x2 state) (read-byte$ channel state)
(mv-let (x3 state) (read-byte$ channel state)
(mv-let (x4 state) (read-byte$ channel state)
(if (and x2 x3 x4
(cond ((= (the-fixnum x1) 240)
(in-range? (the-fixnum x2) 144 191))
((= (the-fixnum x1) 244)
(in-range? (the-fixnum x2) 128 143))
(t
(in-range? (the-fixnum x2) 128 191)))
(in-range? (the-fixnum x3) 128 191)
(in-range? (the-fixnum x4) 128 191))
(read-utf8-fast
channel state
(cons
(the-fixnum
(logior
(the-fixnum
(ash (the-fixnum (logand (the-fixnum x1) 7)) 18))
(the-fixnum
(logior
(the-fixnum
(ash (the-fixnum (logand (the-fixnum x2) 63)) 12))
(the-fixnum
(logior
(the-fixnum
(ash (the-fixnum (logand (the-fixnum x3) 63)) 6))
(the-fixnum
(logand (the-fixnum x4) 63))))))))
acc))
(mv 'fail state))))))
;; This is a little obscure. As an optimization above, we did not
;; consider cases for first byte = 192, 193, 245, 246, and 247, because
;; these are not allowed under Table 3-7.
;;
;; However, utf8-table36-expected-length predics the lengths of these
;; as 2, 2, 4, 4, and 4, respectively. So, for our MBE equivalence, we
;; need to make sure to advance the stream just like we do in the
;; :logic mode.
((or (= (the-fixnum x1) 192)
(= (the-fixnum x1) 193))
(mv-let (x2 state)
(read-byte$ channel state)
(declare (ignore x2))
(mv 'fail state)))
((or (= (the-fixnum x1) 245)
(= (the-fixnum x1) 246)
(= (the-fixnum x1) 247))
(mv-let (x2 state)
(read-byte$ channel state)
(declare (ignore x2))
(mv-let (x3 state)
(read-byte$ channel state)
(declare (ignore x3))
(mv-let (x4 state)
(read-byte$ channel state)
(declare (ignore x4))
(mv 'fail state)))))
(t
(mv 'fail state)))))))
(defthm state-p1-of-mv-nth-1-of-read-utf8-fast
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel)))
(state-p1 (mv-nth 1 (read-utf8-fast channel state acc))))
:hints(("Goal" :in-theory (enable read-utf8-fast))))
(defthm open-input-channel-p1-of-mv-nth-1-of-read-utf8-fast
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel)))
(open-input-channel-p1 channel :byte
(mv-nth 1 (read-utf8-fast channel state acc))))
:hints(("Goal" :in-theory (enable read-utf8-fast))))
;; Correctness of read-utf8-fast
;;
;; We think of (read-byte$-all channel state) as returning the file's contents.
;; We will show that under the appropriate hypotheses, the data returned by
;; (read-utf8-fast channel state acc) is exactly the same as what we would get
;; if we were to first read the entire file's contents, and then apply our UTF8
;; decoding function, utf8=>ustring, to the result.
;;
;; The proof is sort of cute. We rewrite everything to be in terms of
;; read-byte$-all. For example, we first show that read-byte$ is nothing more
;; than the car of read-byte$-all. Similarly, in take-bytes.lisp, we have
;; shown that take-bytes is just the take of read-byte$-all.
(local (defthm car-of-read-byte$
(implies (and (force (state-p state))
(force (symbolp channel))
(force (open-input-channel-p channel :byte state)))
(equal (mv-nth 0 (read-byte$ channel state))
(car (mv-nth 0 (read-byte$-all channel state)))))
:hints(("Goal" :in-theory (enable read-byte$-all)))))
(local (theory-invariant
(incompatible (:rewrite car-of-read-byte$)
(:definition read-byte$-all))))
(local (defthm read-byte$-all-of-mv-nth-1-of-read-byte$
(implies (and (force (state-p state))
(force (symbolp channel))
(force (open-input-channel-p channel :byte state)))
(equal
(mv-nth 0 (read-byte$-all channel (mv-nth 1 (read-byte$ channel state))))
(cdr (mv-nth 0 (read-byte$-all channel state)))))
:hints(("Goal" :in-theory (e/d (read-byte$-all)
(car-of-read-byte$))))))
(local (defthm car-of-read-byte$-all-when-not-caar
(implies (and (state-p1 state)
(symbolp channel)
(open-input-channel-p1 channel :byte state)
(not (car (mv-nth 0 (read-byte$-all channel state)))))
(equal (mv-nth 0 (read-byte$-all channel state))
nil))
:hints(("goal" :in-theory (e/d (read-byte$-all)
(car-of-read-byte$
read-byte$-all-of-mv-nth-1-of-read-byte$
))))))
(defthm car-of-read-utf8-fast-is-utf8=>ustring-fast-of-read-byte$-all
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel))
(true-listp acc))
(equal (mv-nth 0 (read-utf8-fast channel state acc))
(utf8=>ustring-fast (mv-nth 0 (read-byte$-all channel state))
acc)))
:hints(("Goal"
:in-theory (e/d (read-utf8-fast utf8=>ustring-fast
take)
(nthcdr-bytes-2
nthcdr-bytes-3
nthcdr-bytes-4))
:induct (read-utf8-fast channel state acc))))
;; Guard verification for read-utf8-fast.
;;
;; This is really messy, because the MBE equivalence is so dramatic. Note that
;; a lot of this is the same as what we needed for utf8=>ustring-fast.
(encapsulate
()
(local (in-theory (enable take)))
(local (defthm terrible-lemma-1
(implies (and (integerp x)
(<= 0 x)
(<= x 127))
(uchar? x))
:hints(("Goal" :in-theory (enable uchar?)))))
(local (defthm terrible-lemma-2
(IMPLIES (AND (force (integerp x1))
(force (integerp x2))
(< 127 X1)
(<= 194 X1)
(<= X1 223)
(<= 128 X2)
(<= X2 191))
(UCHAR? (LOGIOR (ASH (LOGAND X1 31) 6)
(LOGAND X2 63))))
:hints(("Goal"
:in-theory (enable utf8-combine2-guard
utf8-combine2
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine2))))))
(local (defthm terrible-lemma-3
(IMPLIES (AND (force (integerp x2))
(force (integerp x3))
(<= 160 X2)
(<= X2 191)
(<= 128 X3)
(<= X3 191))
(UCHAR? (LOGIOR 0 (ASH (LOGAND X2 63) 6)
(LOGAND X3 63))))
:hints(("Goal"
:in-theory (enable utf8-combine3-guard
utf8-combine3
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine3
(x1 224)))))))
(local (defthm terrible-lemma-4
(IMPLIES (AND (force (integerp X1))
(force (integerp X2))
(force (integerp X3))
(<= 224 X1)
(<= X1 239)
(NOT (EQUAL X1 224))
(NOT (EQUAL X1 237))
(<= 128 X2)
(<= X2 191)
(<= 128 X3)
(<= X3 191))
(UCHAR? (LOGIOR (ASH (LOGAND X1 15) 12)
(ASH (LOGAND X2 63) 6)
(LOGAND X3 63))))
:hints(("Goal"
:in-theory (enable utf8-combine3-guard
utf8-combine3
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine3))))))
(local (defthm terrible-lemma-5
(IMPLIES (AND (force (integerp x2))
(force (integerp x3))
(<= 128 X2)
(<= X2 159)
(<= 128 X3)
(<= X3 191))
(UCHAR? (LOGIOR 53248 (ASH (LOGAND X2 63) 6)
(LOGAND X3 63))))
:hints(("Goal"
:in-theory (enable utf8-combine3-guard
utf8-combine3
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine3
(x1 237)))))))
(local (defthm terrible-lemma-6
(IMPLIES (AND (force (integerp x2))
(force (integerp x3))
(force (integerp x4))
(<= 144 X2)
(<= X2 191)
(<= 128 X3)
(<= X3 191)
(<= 128 X4)
(<= X4 191))
(UCHAR? (LOGIOR 0 (ASH (LOGAND X2 63) 12)
(ASH (LOGAND X3 63) 6)
(LOGAND X4 63))))
:hints(("Goal"
:in-theory (enable utf8-combine4-guard
utf8-combine4
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine4
(x1 240)))))))
(local (defthm terrible-lemma-7
(IMPLIES (AND (force (integerp x1))
(force (integerp x2))
(force (integerp x3))
(force (integerp x4))
(<= 240 X1)
(<= X1 244)
(NOT (EQUAL X1 240))
(NOT (EQUAL X1 244))
(<= 128 X2)
(<= X2 191)
(<= 128 X3)
(<= X3 191)
(<= 128 X4)
(<= X4 191))
(UCHAR? (LOGIOR (ASH (LOGAND X1 7) 18)
(ASH (LOGAND X2 63) 12)
(ASH (LOGAND X3 63) 6)
(LOGAND X4 63))))
:hints(("Goal"
:in-theory (enable utf8-combine4-guard
utf8-combine4
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine4))))))
(local (defthm terrible-lemma-8
(IMPLIES (AND (force (integerp x2))
(force (integerp x3))
(force (integerp x4))
(<= 128 x2)
(<= x2 143)
(<= 128 x3)
(<= x3 191)
(<= 128 x4)
(<= x4 191))
(UCHAR? (LOGIOR 1048576 (ASH (LOGAND x2 63) 12)
(ASH (LOGAND x3 63) 6)
(LOGAND x4 63))))
:hints(("Goal"
:in-theory (enable utf8-combine4-guard
utf8-combine4
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine4
(x1 244)))))))
(local (include-book "std/typed-lists/signed-byte-listp" :dir :system))
(local (defthm unsigned-byte-listp-8-of-car-of-read-byte$-all-forward
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel)))
(unsigned-byte-listp 8 (mv-nth 0 (read-byte$-all channel state))))
:rule-classes ((:forward-chaining :trigger-terms ((read-byte$-all channel state))))))
(local (defthm unsigned-byte-listp-8-of-cdr-when-unsigned-byte-listp-8
(implies (unsigned-byte-listp 8 x)
(unsigned-byte-listp 8 (cdr x)))
:rule-classes ((:forward-chaining))))
(local (defthm crock
(implies (unsigned-byte-listp bytes x)
(iff (consp x)
x))))
(local (defthm hideous-lemma-1
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel))
(mv-nth 0 (read-byte$-all channel state)))
(unsigned-byte-p 8 (car (mv-nth 0 (read-byte$-all channel state)))))
:rule-classes ((:rewrite)
(:forward-chaining
:trigger-terms ((mv-nth 0 (read-byte$-all channel state)))))))
(local (defthm hideous-lemma-2
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel))
(cdr (mv-nth 0 (read-byte$-all channel state))))
(unsigned-byte-p 8 (cadr (mv-nth 0 (read-byte$-all channel state)))))
:rule-classes ((:rewrite)
(:forward-chaining
:trigger-terms ((cdr (mv-nth 0 (read-byte$-all channel state))))))))
(local (defthm hideous-lemma-3
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel))
(cddr (mv-nth 0 (read-byte$-all channel state))))
(unsigned-byte-p 8 (caddr (mv-nth 0 (read-byte$-all channel state)))))
:rule-classes ((:rewrite)
(:forward-chaining
:trigger-terms ((cddr (mv-nth 0 (read-byte$-all channel state))))))
:hints(("Goal"
:in-theory (e/d (read-byte$-all)
(car-of-read-byte$))
:expand ((read-byte$-all channel state)
(read-byte$-all channel (mv-nth 1 (read-byte$ channel state)))
(read-byte$-all
channel
(mv-nth 1 (read-byte$ channel
(mv-nth 1 (read-byte$ channel
state))))))))))
(local (defthm hideous-lemma-4
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel))
(cdddr (mv-nth 0 (read-byte$-all channel state))))
(unsigned-byte-p 8 (car (cdddr (mv-nth 0 (read-byte$-all channel state))))))
:rule-classes ((:rewrite)
(:forward-chaining
:trigger-terms ((cdddr (mv-nth 0 (read-byte$-all channel state))))))
:hints(("Goal"
:in-theory (e/d (read-byte$-all)
(car-of-read-byte$))
:expand ((read-byte$-all channel state)
(read-byte$-all channel
(mv-nth 1 (read-byte$ channel state)))
(read-byte$-all
channel
(mv-nth 1 (read-byte$ channel
(mv-nth 1 (read-byte$ channel state)))))
(read-byte$-all
channel
(mv-nth 1 (read-byte$
channel
(mv-nth 1 (read-byte$
channel
(mv-nth 1 (read-byte$ channel
state))))))))))))
(local (defthm integerp-when-unsigned-byte-p-8
(implies (unsigned-byte-p 8 x)
(integerp x))))
(local (defthm signed-byte-p-from-unsigned-byte-p-8
(implies (and (unsigned-byte-p 8 x)
(< 8 (nfix n)))
(signed-byte-p n x))))
(local (defthm len-zero-when-true-listp
(implies (true-listp x)
(equal (equal (len x) 0)
(not x)))))
(local (defthm integer-squeeze-lemma
(implies (and (syntaxp (quotep n))
(integerp n)
(< (1- n) x)
(< x (1+ n)))
(equal (equal x n)
(integerp x)))
:rule-classes ((:rewrite :backchain-limit-lst 1))))
(local (defthm unsigned-byte-p-8-when-valid-integer
(implies (and (<= 0 x)
(< x 255))
(equal (unsigned-byte-p 8 x)
(integerp x)))
:rule-classes ((:rewrite :backchain-limit-lst 1))
:hints(("Goal" :in-theory (enable unsigned-byte-p)))))
(local (include-book "arithmetic-3/bind-free/top" :dir :system))
(local (defthm nthcdr-bytes-hack
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel))
(force (natp n)))
(equal (nthcdr-bytes n channel (mv-nth 1 (read-byte$ channel state)))
(nthcdr-bytes (+ 1 n) channel state)))
:hints(("Goal"
:expand (nthcdr-bytes (+ 1 n) channel state)
:in-theory (enable nthcdr-bytes)
:do-not-induct t))))
(local (in-theory (e/d (unsigned-byte-listp
utf8-char=>uchar
utf8-table36-bytes
utf8-table37-bytes
utf8-combine2
utf8-combine3
utf8-combine4
utf8-combine2-guard
utf8-combine3-guard
utf8-combine4-guard)
(
;; BOZO the above "terrible lemmas" were developed before
;; including bitops, so they're targeting the wrong normal
;; forms...
bitops::LOGAND-WITH-BITMASK
simplify-logior
commutativity-of-logior
commutativity-of-logand
UTF8-PARTITION-SUCCESSFUL-WHEN-ANY-VALID-PARTITIONING-EXISTS
))))
(verify-guards read-utf8-fast
:hints(("Goal"
:do-not-induct t
:do-not '(generalize fertilize))))
)
(defun read-utf8 (filename state)
(declare (xargs :guard (and (state-p state)
(stringp filename))
:stobjs state))
(mv-let (channel state)
(open-input-channel filename :byte state)
(if channel
(mv-let (data state)
(read-utf8-fast channel state nil)
(let ((state (close-input-channel channel state)))
(mv data state)))
(mv "Error opening file." state))))
(defthm state-p1-of-mv-nth-1-of-read-utf8
(implies (and (force (state-p1 state))
(force (stringp filename)))
(state-p1 (mv-nth 1 (read-utf8 filename state))))
:hints(("Goal" :in-theory (enable read-utf8))))
#|| No longer true, given change to read-file-bytes in
std/io/read-file-bytes.lisp, svn 1477.
(defthm car-of-read-utf8-when-file-cannot-be-opened
(implies (and (stringp (mv-nth 0 (read-file-bytes filename state)))
(force (state-p1 state))
(force (stringp filename)))
(equal (mv-nth 0 (read-utf8 filename state))
(mv-nth 0 (read-file-bytes filename state))))
:hints(("Goal" :in-theory (enable read-file-bytes read-utf8))))
||#
(defthm car-of-read-utf8-when-file-can-be-opened
(implies (and (not (stringp (mv-nth 0 (read-file-bytes filename state))))
(force (state-p1 state))
(force (stringp filename)))
(equal (mv-nth 0 (read-utf8 filename state))
(utf8=>ustring (mv-nth 0 (read-file-bytes filename state)))))
:hints(("Goal" :in-theory (enable read-utf8 read-file-bytes))))
| 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 "utf8-decode")
(include-book "std/io/take-bytes" :dir :system)
(local (include-book "std/io/base" :dir :system))
(local (include-book "tools/mv-nth" :dir :system))
(local (include-book "centaur/bitops/ihsext-basics" :dir :system))
(local (include-book "centaur/bitops/signed-byte-p" :dir :system))
(local (include-book "std/lists/take" :dir :system))
(set-state-ok t)
(local (in-theory (disable signed-byte-p)))
(local (in-theory (disable take)))
(local (defthm signed-byte-p-resolver
(implies (and (integerp n)
(<= 1 n)
(integerp x)
(<= (- (expt 2 (1- n))) x)
(< x (expt 2 (1- n))))
(signed-byte-p n x))
:hints(("Goal" :in-theory (enable signed-byte-p)))))
;; We now want to recreate our utf8=>ustring function but directly using the
;; file reading operations. We begin by writing equivalents of "take" and
;; "nthcdr" that operate on byte streams. We will use (read-byte$-all ...)
;; effectively as the file's contents, and relate all of these operations to
;; it.
(defund read-utf8-fast (channel state acc)
(declare (xargs :guard (and (state-p state)
(symbolp channel)
(open-input-channel-p channel :byte state)
(ustring? acc))
:measure (file-measure channel state)
:verify-guards nil))
(mbe
:logic
(if (and (state-p state)
(symbolp channel)
(open-input-channel-p channel :byte state))
(mv-let (x1 state)
(read-byte$ channel state)
(if (not x1)
(mv (reverse acc) state)
(let ((len1 (utf8-table36-expected-length x1)))
(if (not len1)
(mv 'fail state)
(mv-let (x2-x4 state)
(take-bytes (1- len1) channel state)
(let* ((x1-x4 (cons x1 x2-x4))
(first (utf8-char=>uchar x1-x4)))
(if (not first)
(mv 'fail state)
(read-utf8-fast channel state (cons first acc)))))))))
(mv 'fail state))
:exec
(mv-let
(x1 state)
(read-byte$ channel state)
(if (not x1)
(mv (reverse acc) state)
(cond
((<= (the-fixnum x1) 127)
;; Expected length 1. We don't need to do any further checking; we can
;; just recur very quickly. Note that this will give us very good
;; performance for English text, where characters are typically only a
;; single byte.
(read-utf8-fast channel state (cons x1 acc)))
((in-range? (the-fixnum x1) 194 223)
;; Expected length 2. (We excluded 192,193 because they are not
;; permitted under Table 3-7.)
(mv-let (x2 state) (read-byte$ channel state)
(if (and x2 (in-range? (the-fixnum x2) 128 191))
;; Manually-inlined utf8-combine2 operation.
(read-utf8-fast
channel state
(cons
(the-fixnum
(logior
(the-fixnum (ash (the-fixnum (logand (the-fixnum x1) 31)) 6))
(the-fixnum (logand (the-fixnum x2) 63))))
acc))
(mv 'fail state))))
((in-range? (the-fixnum x1) 224 239)
;; Expected length 3. (We cover all options here.)
(mv-let (x2 state) (read-byte$ channel state)
(mv-let (x3 state) (read-byte$ channel state)
(if (and x2 x3
(cond ((= (the-fixnum x1) 224)
(in-range? (the-fixnum x2) 160 191))
((= (the-fixnum x1) 237)
(in-range? (the-fixnum x2) 128 159))
(t
(in-range? (the-fixnum x2) 128 191)))
(in-range? (the-fixnum x3) 128 191))
(read-utf8-fast
channel state
(cons
(the-fixnum
(logior
(the-fixnum
(ash (the-fixnum (logand (the-fixnum x1) 15)) 12))
(the-fixnum
(logior
(the-fixnum
(ash (the-fixnum (logand (the-fixnum x2) 63)) 6))
(the-fixnum (logand (the-fixnum x3) 63))))))
acc))
(mv 'fail state)))))
((in-range? (the-fixnum x1) 240 244)
;; Expected length 4. (We only accept 240-244 because of Table 3-7;
;; i.e., we exclude 245, 246, and 247.
(mv-let (x2 state) (read-byte$ channel state)
(mv-let (x3 state) (read-byte$ channel state)
(mv-let (x4 state) (read-byte$ channel state)
(if (and x2 x3 x4
(cond ((= (the-fixnum x1) 240)
(in-range? (the-fixnum x2) 144 191))
((= (the-fixnum x1) 244)
(in-range? (the-fixnum x2) 128 143))
(t
(in-range? (the-fixnum x2) 128 191)))
(in-range? (the-fixnum x3) 128 191)
(in-range? (the-fixnum x4) 128 191))
(read-utf8-fast
channel state
(cons
(the-fixnum
(logior
(the-fixnum
(ash (the-fixnum (logand (the-fixnum x1) 7)) 18))
(the-fixnum
(logior
(the-fixnum
(ash (the-fixnum (logand (the-fixnum x2) 63)) 12))
(the-fixnum
(logior
(the-fixnum
(ash (the-fixnum (logand (the-fixnum x3) 63)) 6))
(the-fixnum
(logand (the-fixnum x4) 63))))))))
acc))
(mv 'fail state))))))
;; This is a little obscure. As an optimization above, we did not
;; consider cases for first byte = 192, 193, 245, 246, and 247, because
;; these are not allowed under Table 3-7.
;;
;; However, utf8-table36-expected-length predics the lengths of these
;; as 2, 2, 4, 4, and 4, respectively. So, for our MBE equivalence, we
;; need to make sure to advance the stream just like we do in the
;; :logic mode.
((or (= (the-fixnum x1) 192)
(= (the-fixnum x1) 193))
(mv-let (x2 state)
(read-byte$ channel state)
(declare (ignore x2))
(mv 'fail state)))
((or (= (the-fixnum x1) 245)
(= (the-fixnum x1) 246)
(= (the-fixnum x1) 247))
(mv-let (x2 state)
(read-byte$ channel state)
(declare (ignore x2))
(mv-let (x3 state)
(read-byte$ channel state)
(declare (ignore x3))
(mv-let (x4 state)
(read-byte$ channel state)
(declare (ignore x4))
(mv 'fail state)))))
(t
(mv 'fail state)))))))
(defthm state-p1-of-mv-nth-1-of-read-utf8-fast
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel)))
(state-p1 (mv-nth 1 (read-utf8-fast channel state acc))))
:hints(("Goal" :in-theory (enable read-utf8-fast))))
(defthm open-input-channel-p1-of-mv-nth-1-of-read-utf8-fast
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel)))
(open-input-channel-p1 channel :byte
(mv-nth 1 (read-utf8-fast channel state acc))))
:hints(("Goal" :in-theory (enable read-utf8-fast))))
;; Correctness of read-utf8-fast
;;
;; We think of (read-byte$-all channel state) as returning the file's contents.
;; We will show that under the appropriate hypotheses, the data returned by
;; (read-utf8-fast channel state acc) is exactly the same as what we would get
;; if we were to first read the entire file's contents, and then apply our UTF8
;; decoding function, utf8=>ustring, to the result.
;;
;; The proof is sort of cute. We rewrite everything to be in terms of
;; read-byte$-all. For example, we first show that read-byte$ is nothing more
;; than the car of read-byte$-all. Similarly, in take-bytes.lisp, we have
;; shown that take-bytes is just the take of read-byte$-all.
(local (defthm car-of-read-byte$
(implies (and (force (state-p state))
(force (symbolp channel))
(force (open-input-channel-p channel :byte state)))
(equal (mv-nth 0 (read-byte$ channel state))
(car (mv-nth 0 (read-byte$-all channel state)))))
:hints(("Goal" :in-theory (enable read-byte$-all)))))
(local (theory-invariant
(incompatible (:rewrite car-of-read-byte$)
(:definition read-byte$-all))))
(local (defthm read-byte$-all-of-mv-nth-1-of-read-byte$
(implies (and (force (state-p state))
(force (symbolp channel))
(force (open-input-channel-p channel :byte state)))
(equal
(mv-nth 0 (read-byte$-all channel (mv-nth 1 (read-byte$ channel state))))
(cdr (mv-nth 0 (read-byte$-all channel state)))))
:hints(("Goal" :in-theory (e/d (read-byte$-all)
(car-of-read-byte$))))))
(local (defthm car-of-read-byte$-all-when-not-caar
(implies (and (state-p1 state)
(symbolp channel)
(open-input-channel-p1 channel :byte state)
(not (car (mv-nth 0 (read-byte$-all channel state)))))
(equal (mv-nth 0 (read-byte$-all channel state))
nil))
:hints(("goal" :in-theory (e/d (read-byte$-all)
(car-of-read-byte$
read-byte$-all-of-mv-nth-1-of-read-byte$
))))))
(defthm car-of-read-utf8-fast-is-utf8=>ustring-fast-of-read-byte$-all
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel))
(true-listp acc))
(equal (mv-nth 0 (read-utf8-fast channel state acc))
(utf8=>ustring-fast (mv-nth 0 (read-byte$-all channel state))
acc)))
:hints(("Goal"
:in-theory (e/d (read-utf8-fast utf8=>ustring-fast
take)
(nthcdr-bytes-2
nthcdr-bytes-3
nthcdr-bytes-4))
:induct (read-utf8-fast channel state acc))))
;; Guard verification for read-utf8-fast.
;;
;; This is really messy, because the MBE equivalence is so dramatic. Note that
;; a lot of this is the same as what we needed for utf8=>ustring-fast.
(encapsulate
()
(local (in-theory (enable take)))
(local (defthm terrible-lemma-1
(implies (and (integerp x)
(<= 0 x)
(<= x 127))
(uchar? x))
:hints(("Goal" :in-theory (enable uchar?)))))
(local (defthm terrible-lemma-2
(IMPLIES (AND (force (integerp x1))
(force (integerp x2))
(< 127 X1)
(<= 194 X1)
(<= X1 223)
(<= 128 X2)
(<= X2 191))
(UCHAR? (LOGIOR (ASH (LOGAND X1 31) 6)
(LOGAND X2 63))))
:hints(("Goal"
:in-theory (enable utf8-combine2-guard
utf8-combine2
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine2))))))
(local (defthm terrible-lemma-3
(IMPLIES (AND (force (integerp x2))
(force (integerp x3))
(<= 160 X2)
(<= X2 191)
(<= 128 X3)
(<= X3 191))
(UCHAR? (LOGIOR 0 (ASH (LOGAND X2 63) 6)
(LOGAND X3 63))))
:hints(("Goal"
:in-theory (enable utf8-combine3-guard
utf8-combine3
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine3
(x1 224)))))))
(local (defthm terrible-lemma-4
(IMPLIES (AND (force (integerp X1))
(force (integerp X2))
(force (integerp X3))
(<= 224 X1)
(<= X1 239)
(NOT (EQUAL X1 224))
(NOT (EQUAL X1 237))
(<= 128 X2)
(<= X2 191)
(<= 128 X3)
(<= X3 191))
(UCHAR? (LOGIOR (ASH (LOGAND X1 15) 12)
(ASH (LOGAND X2 63) 6)
(LOGAND X3 63))))
:hints(("Goal"
:in-theory (enable utf8-combine3-guard
utf8-combine3
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine3))))))
(local (defthm terrible-lemma-5
(IMPLIES (AND (force (integerp x2))
(force (integerp x3))
(<= 128 X2)
(<= X2 159)
(<= 128 X3)
(<= X3 191))
(UCHAR? (LOGIOR 53248 (ASH (LOGAND X2 63) 6)
(LOGAND X3 63))))
:hints(("Goal"
:in-theory (enable utf8-combine3-guard
utf8-combine3
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine3
(x1 237)))))))
(local (defthm terrible-lemma-6
(IMPLIES (AND (force (integerp x2))
(force (integerp x3))
(force (integerp x4))
(<= 144 X2)
(<= X2 191)
(<= 128 X3)
(<= X3 191)
(<= 128 X4)
(<= X4 191))
(UCHAR? (LOGIOR 0 (ASH (LOGAND X2 63) 12)
(ASH (LOGAND X3 63) 6)
(LOGAND X4 63))))
:hints(("Goal"
:in-theory (enable utf8-combine4-guard
utf8-combine4
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine4
(x1 240)))))))
(local (defthm terrible-lemma-7
(IMPLIES (AND (force (integerp x1))
(force (integerp x2))
(force (integerp x3))
(force (integerp x4))
(<= 240 X1)
(<= X1 244)
(NOT (EQUAL X1 240))
(NOT (EQUAL X1 244))
(<= 128 X2)
(<= X2 191)
(<= 128 X3)
(<= X3 191)
(<= 128 X4)
(<= X4 191))
(UCHAR? (LOGIOR (ASH (LOGAND X1 7) 18)
(ASH (LOGAND X2 63) 12)
(ASH (LOGAND X3 63) 6)
(LOGAND X4 63))))
:hints(("Goal"
:in-theory (enable utf8-combine4-guard
utf8-combine4
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine4))))))
(local (defthm terrible-lemma-8
(IMPLIES (AND (force (integerp x2))
(force (integerp x3))
(force (integerp x4))
(<= 128 x2)
(<= x2 143)
(<= 128 x3)
(<= x3 191)
(<= 128 x4)
(<= x4 191))
(UCHAR? (LOGIOR 1048576 (ASH (LOGAND x2 63) 12)
(ASH (LOGAND x3 63) 6)
(LOGAND x4 63))))
:hints(("Goal"
:in-theory (enable utf8-combine4-guard
utf8-combine4
utf8-table36-bytes
utf8-table37-bytes)
:use ((:instance uchar?-of-utf8-combine4
(x1 244)))))))
(local (include-book "std/typed-lists/signed-byte-listp" :dir :system))
(local (defthm unsigned-byte-listp-8-of-car-of-read-byte$-all-forward
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel)))
(unsigned-byte-listp 8 (mv-nth 0 (read-byte$-all channel state))))
:rule-classes ((:forward-chaining :trigger-terms ((read-byte$-all channel state))))))
(local (defthm unsigned-byte-listp-8-of-cdr-when-unsigned-byte-listp-8
(implies (unsigned-byte-listp 8 x)
(unsigned-byte-listp 8 (cdr x)))
:rule-classes ((:forward-chaining))))
(local (defthm crock
(implies (unsigned-byte-listp bytes x)
(iff (consp x)
x))))
(local (defthm hideous-lemma-1
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel))
(mv-nth 0 (read-byte$-all channel state)))
(unsigned-byte-p 8 (car (mv-nth 0 (read-byte$-all channel state)))))
:rule-classes ((:rewrite)
(:forward-chaining
:trigger-terms ((mv-nth 0 (read-byte$-all channel state)))))))
(local (defthm hideous-lemma-2
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel))
(cdr (mv-nth 0 (read-byte$-all channel state))))
(unsigned-byte-p 8 (cadr (mv-nth 0 (read-byte$-all channel state)))))
:rule-classes ((:rewrite)
(:forward-chaining
:trigger-terms ((cdr (mv-nth 0 (read-byte$-all channel state))))))))
(local (defthm hideous-lemma-3
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel))
(cddr (mv-nth 0 (read-byte$-all channel state))))
(unsigned-byte-p 8 (caddr (mv-nth 0 (read-byte$-all channel state)))))
:rule-classes ((:rewrite)
(:forward-chaining
:trigger-terms ((cddr (mv-nth 0 (read-byte$-all channel state))))))
:hints(("Goal"
:in-theory (e/d (read-byte$-all)
(car-of-read-byte$))
:expand ((read-byte$-all channel state)
(read-byte$-all channel (mv-nth 1 (read-byte$ channel state)))
(read-byte$-all
channel
(mv-nth 1 (read-byte$ channel
(mv-nth 1 (read-byte$ channel
state))))))))))
(local (defthm hideous-lemma-4
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel))
(cdddr (mv-nth 0 (read-byte$-all channel state))))
(unsigned-byte-p 8 (car (cdddr (mv-nth 0 (read-byte$-all channel state))))))
:rule-classes ((:rewrite)
(:forward-chaining
:trigger-terms ((cdddr (mv-nth 0 (read-byte$-all channel state))))))
:hints(("Goal"
:in-theory (e/d (read-byte$-all)
(car-of-read-byte$))
:expand ((read-byte$-all channel state)
(read-byte$-all channel
(mv-nth 1 (read-byte$ channel state)))
(read-byte$-all
channel
(mv-nth 1 (read-byte$ channel
(mv-nth 1 (read-byte$ channel state)))))
(read-byte$-all
channel
(mv-nth 1 (read-byte$
channel
(mv-nth 1 (read-byte$
channel
(mv-nth 1 (read-byte$ channel
state))))))))))))
(local (defthm integerp-when-unsigned-byte-p-8
(implies (unsigned-byte-p 8 x)
(integerp x))))
(local (defthm signed-byte-p-from-unsigned-byte-p-8
(implies (and (unsigned-byte-p 8 x)
(< 8 (nfix n)))
(signed-byte-p n x))))
(local (defthm len-zero-when-true-listp
(implies (true-listp x)
(equal (equal (len x) 0)
(not x)))))
(local (defthm integer-squeeze-lemma
(implies (and (syntaxp (quotep n))
(integerp n)
(< (1- n) x)
(< x (1+ n)))
(equal (equal x n)
(integerp x)))
:rule-classes ((:rewrite :backchain-limit-lst 1))))
(local (defthm unsigned-byte-p-8-when-valid-integer
(implies (and (<= 0 x)
(< x 255))
(equal (unsigned-byte-p 8 x)
(integerp x)))
:rule-classes ((:rewrite :backchain-limit-lst 1))
:hints(("Goal" :in-theory (enable unsigned-byte-p)))))
(local (include-book "arithmetic-3/bind-free/top" :dir :system))
(local (defthm nthcdr-bytes-hack
(implies (and (force (state-p1 state))
(force (open-input-channel-p1 channel :byte state))
(force (symbolp channel))
(force (natp n)))
(equal (nthcdr-bytes n channel (mv-nth 1 (read-byte$ channel state)))
(nthcdr-bytes (+ 1 n) channel state)))
:hints(("Goal"
:expand (nthcdr-bytes (+ 1 n) channel state)
:in-theory (enable nthcdr-bytes)
:do-not-induct t))))
(local (in-theory (e/d (unsigned-byte-listp
utf8-char=>uchar
utf8-table36-bytes
utf8-table37-bytes
utf8-combine2
utf8-combine3
utf8-combine4
utf8-combine2-guard
utf8-combine3-guard
utf8-combine4-guard)
(
;; BOZO the above "terrible lemmas" were developed before
;; including bitops, so they're targeting the wrong normal
;; forms...
bitops::LOGAND-WITH-BITMASK
simplify-logior
commutativity-of-logior
commutativity-of-logand
UTF8-PARTITION-SUCCESSFUL-WHEN-ANY-VALID-PARTITIONING-EXISTS
))))
(verify-guards read-utf8-fast
:hints(("Goal"
:do-not-induct t
:do-not '(generalize fertilize))))
)
(defun read-utf8 (filename state)
(declare (xargs :guard (and (state-p state)
(stringp filename))
:stobjs state))
(mv-let (channel state)
(open-input-channel filename :byte state)
(if channel
(mv-let (data state)
(read-utf8-fast channel state nil)
(let ((state (close-input-channel channel state)))
(mv data state)))
(mv "Error opening file." state))))
(defthm state-p1-of-mv-nth-1-of-read-utf8
(implies (and (force (state-p1 state))
(force (stringp filename)))
(state-p1 (mv-nth 1 (read-utf8 filename state))))
:hints(("Goal" :in-theory (enable read-utf8))))
#|| No longer true, given change to read-file-bytes in
std/io/read-file-bytes.lisp, svn 1477.
(defthm car-of-read-utf8-when-file-cannot-be-opened
(implies (and (stringp (mv-nth 0 (read-file-bytes filename state)))
(force (state-p1 state))
(force (stringp filename)))
(equal (mv-nth 0 (read-utf8 filename state))
(mv-nth 0 (read-file-bytes filename state))))
:hints(("Goal" :in-theory (enable read-file-bytes read-utf8))))
||#
(defthm car-of-read-utf8-when-file-can-be-opened
(implies (and (not (stringp (mv-nth 0 (read-file-bytes filename state))))
(force (state-p1 state))
(force (stringp filename)))
(equal (mv-nth 0 (read-utf8 filename state))
(utf8=>ustring (mv-nth 0 (read-file-bytes filename state)))))
:hints(("Goal" :in-theory (enable read-utf8 read-file-bytes))))
|
[
{
"context": "; DEALINGS IN THE SOFTWARE.\n;\n; Original author: Jared Davis <[email protected]>\n\n(in-package \"VL\")\n(include-",
"end": 1390,
"score": 0.9996312856674194,
"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 \"fmt\")\n(include",
"end": 1410,
"score": 0.9999340772628784,
"start": 1392,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/centaur/vl/mlib/json.lisp
|
jueqingsizhe66/acl2
| 1 |
; 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 "fmt")
(include-book "find-module")
(include-book "centaur/bridge/to-json" :dir :system)
(local (include-book "../util/arithmetic"))
(defsection json-printing
:parents (printer)
:short "Routines for encoding various ACL2 structures into <a
href='http://www.json.org/'>JSON</a> format."
:long "<p>This is a collection of printing routines for translating ACL2
structures into JSON format. These routines are mainly meant to make it easy
to convert @(see vl) @(see syntax) into nice JSON data, but are somewhat
flexible and may be useful for other applications.</p>")
(defsection json-encoders
:parents (json-printing)
:short "A table of JSON encoders to use for for different kinds of data."
:long "<p>A JSON encoder is a function of the following signature:</p>
@({ encode-foo : foo * ps --> ps })
<p>Where @('foo') is expected to be an object of some type @('foop'), and
@('ps') is the @(see vl) @(see printer) state stobj, @(see ps). Each such
routine is responsible for printing a JSON encoding of its @('foop') argument.
Each such function may assume that @(see ps) is set to text mode.</p>
<p>The encoder table is a simple association of @('foop') to @('encode-foo')
functions. We can use it to automatically generate encoders for, e.g., @(see
defaggregate) structures.</p>"
(table vl-json)
(table vl-json 'encoders
;; Alist binding each recognizer foop to its JSON encoder, vl-jp-foo
)
(defun get-json-encoders (world)
"Look up the current alist of json encoders."
(declare (xargs :mode :program))
(cdr (assoc 'encoders (table-alist 'vl-json world))))
(defmacro add-json-encoder (foop encoder-fn)
(declare (xargs :guard (and (symbolp foop)
(symbolp encoder-fn))))
`(table vl-json 'encoders
(cons (cons ',foop ',encoder-fn)
(get-json-encoders world))))
(defun get-json-encoder (foop world)
(declare (xargs :mode :program))
(let ((entry (assoc foop (get-json-encoders world))))
(if entry
(cdr entry)
(er hard? 'get-json-encoder
"No json encoder defined for ~x0.~%" foop)))))
#||
(get-json-encoders (w state))
(add-json-encoder barp vl-enc-bar)
(get-json-encoders (w state))
(get-json-encoder 'barp (w state)) ;; vl-enc-bar
(get-json-encoder 'foop (w state)) ;; fail, no encoder defined
||#
(define jp-bool ((x booleanp) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a @(see booleanp) into JSON as @('true') or @('false')."
(if x
(vl-print-str "true")
(vl-print-str "false")))
(add-json-encoder booleanp jp-bool)
(add-json-encoder not jp-bool)
(define jp-col-after-printing-string-aux
((col natp "Current column we're at.")
(x stringp "String we're about to print, not yet reversed.")
(n natp "Current position in X.")
(xl natp "Pre-computed length of X."))
:returns (new-col natp :rule-classes :type-prescription)
:parents (jp-str)
:short "Fast way to figure out the new column after printing a JSON string
with proper encoding."
:guard (and (<= n xl)
(= xl (length x)))
:measure (nfix (- (nfix xl) (nfix n)))
(declare (type (integer 0 *) col n xl)
(type string x))
(b* (((when (mbe :logic (zp (- (nfix xl) (nfix n)))
:exec (= n xl)))
(lnfix col))
((the (unsigned-byte 8) code) (char-code (char x n)))
((when (or (<= code 31)
(>= code 127)))
;; This is a "json weird char." Our encoder will turn it into
;; \uXXXX. The length of \uXXXX is 6.
(jp-col-after-printing-string-aux (+ 6 col) x (+ 1 (lnfix n)) xl)))
;; Else there is only one character.
(jp-col-after-printing-string-aux (+ 1 col) x (+ 1 (lnfix n)) xl)))
(define jp-str ((x :type string) &key (ps 'ps))
:parents (json-encoders)
:short "Print the JSON encoding of a string, handling all escaping correctly
and including the surrounding quotes."
:long "<p>We go to some effort to make this fast.</p>"
(b* ((rchars (vl-ps->rchars))
(col (vl-ps->col))
(xl (length x))
(rchars (cons #\" (bridge::json-encode-str-aux x 0 xl (cons #\" rchars))))
(col (+ 2 (jp-col-after-printing-string-aux col x 0 xl))))
(vl-ps-seq
(vl-ps-update-rchars rchars)
(vl-ps-update-col col)))
:prepwork
((local (defthm l0
(implies (and (vl-printedlist-p acc)
(character-listp x))
(vl-printedlist-p (bridge::json-encode-chars x acc)))
:hints(("Goal"
:in-theory (e/d (bridge::json-encode-chars
bridge::json-encode-char
bridge::json-encode-weird-char)
(digit-to-char))))))))
(add-json-encoder stringp jp-str)
(define jp-maybe-string ((x maybe-stringp) &key (ps 'ps))
:parents (json-encoders)
(if x
(jp-str x)
(vl-print "null")))
(add-json-encoder maybe-stringp jp-maybe-string)
(define jp-bignat ((x natp) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a potentially large natural number as a JSON string."
(vl-print-str (str::natstr x)))
(define jp-nat ((x natp) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a probably small natural number as a JSON number."
:long "<p>We require that the integer is at most 2^31, which we think is the
minimum reasonable size for a JSON implementation to support.</p>"
(b* (((unless (<= x (expt 2 31)))
(raise "Scarily trying to JSON-encode large natural: ~x0." x)
ps))
(vl-print-nat x)))
(define jp-maybe-nat ((x maybe-natp) &key (ps 'ps))
:parents (json-encoders)
(if x
(jp-nat x)
(vl-print-str "null")))
(add-json-encoder natp jp-nat)
(add-json-encoder posp jp-nat)
(add-json-encoder maybe-natp jp-maybe-nat)
(add-json-encoder maybe-posp jp-maybe-nat)
(define jp-sym-main ((x symbolp) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a simple symbol as a JSON string, including the surrounding
quotes."
:long "<p>We assume that @('x') has a simple enough name to print without any
encoding. This is generally true for keyword constants used as tags and in
basic enumerations like @(see vl-exprtype-p). We print only the symbol name,
in lower-case.</p>"
(vl-ps-seq (vl-print "\"")
(vl-print-str (str::downcase-string (symbol-name x)))
(vl-print "\"")))
(defsection jp-sym
:parents (json-encoders)
:short "Optimized version of @(see jp-sym-main)."
:long "<p>This is a simple macro that is meant to be the same as @(see
jp-sym-main). The only difference is that if we are given a literal symbol,
e.g., @(':foo'), we can do the string manipulation at compile time.</p>"
(defmacro jp-sym (x &key (ps 'ps))
(if (or (keywordp x)
(booleanp x)
(and (quotep x)
(symbolp (acl2::unquote x))))
;; Yes, want to optimize.
(let* ((guts (if (quotep x) (acl2::unquote x) x))
(ans (str::cat "\""
(str::downcase-string (symbol-name guts))
"\"")))
`(vl-print-str ,ans :ps ,ps))
`(jp-sym-main ,x :ps ,ps))))
#||
(top-level (vl-cw-ps-seq (jp-sym :foo))) ;; "foo"
(top-level (vl-cw-ps-seq (jp-sym t))) ;; "t"
(top-level (vl-cw-ps-seq (jp-sym nil))) ;; "nil"
(top-level (vl-cw-ps-seq (jp-sym 'bar))) ;; "bar"
(top-level (let ((x 'baz))
(vl-cw-ps-seq (jp-sym x)))) ;; "baz"
||#
(defsection jp-object
:parents (json-encoders)
:short "Utility for printing JSON <i>objects</i>, which in some other
languages might be called alists, dictionaries, hashes, records, etc."
:long "<p>Syntax Example:</p>
@({
(jp-object :tag (vl-print \"loc\")
:file (vl-print x.filename)
:line (vl-print x.line)
:col (vl-print x.col))
--->
{ \"tag\": \"loc\", \"file\": ... }
})
<p>The arguments to @('jp-object') should be an alternating list of literal
keywords, which (for better performance) we assume are so simple they do not
need to be encoded, and printing expressions which should handle any necessary
encoding.</p>"
:autodoc nil
(defun jp-object-aux (forms)
(declare (xargs :guard t))
(b* (((when (atom forms))
nil)
((unless (keywordp (car forms)))
(er hard? 'jp-object "Expected alternating keywords and values."))
((unless (consp (cdr forms)))
(er hard? 'jp-object "No argument found after ~x0." (car forms)))
;; Suppose the keyword is :foo.
;; We create the string: "foo":
;; We can create this at macroexpansion time.
(name1 (str::downcase-string (symbol-name (car forms))))
(name1-colon (str::cat "\"" name1 "\": ")))
(list* `(vl-print-str ,name1-colon)
(second forms)
(if (atom (cddr forms))
nil
(cons `(vl-println? ", ")
(jp-object-aux (cddr forms)))))))
(defmacro jp-object (&rest forms)
`(vl-ps-seq (vl-print "{")
,@(jp-object-aux forms)
(vl-println? "}"))))
; Fancy automatic json encoding of std structures
(program)
(define make-json-encoder-alist
(efields ;; A proper std::formallist-p for this structure's fields
omit ;; A list of any fields to omit from the encoded output
overrides ;; An alist of (fieldname . encoder-to-use-instead-of-default)
world ;; For looking up default encoders
)
;; Returns an alist of the form (fieldname . encoder-to-use)
(b* (((when (atom efields))
nil)
((std::formal e1) (car efields))
(- (cw "Determining encoder for ~x0... " e1.name))
;; Are we supposed to omit it?
((when (member e1.name omit))
(cw "omitting it.~%")
(make-json-encoder-alist (cdr efields) omit overrides world))
;; Are we supposed to override it?
(look (assoc e1.name overrides))
((when look)
(cw "overriding with ~x0.~%" (cdr look))
(cons (cons e1.name (cdr look))
(make-json-encoder-alist (cdr efields) omit overrides world)))
((unless (and (tuplep 2 e1.guard)
(equal (second e1.guard) e1.name)))
(raise "Guard ~x0 too complex.~%" e1.guard))
(predicate (first e1.guard))
(encoder (get-json-encoder predicate world)))
(cw "defaulting to ~x0~%" encoder)
(cons (cons e1.name encoder)
(make-json-encoder-alist (cdr efields) omit overrides world))))
(define encoder-alist-main-actions
(basename ;; base name for aggregate, e.g., 'vl-location
alist ;; alist of fields->encoder to use
newlines ;; NIL means don't auto-newline between elements; any number means
;; newline and indent to that many places between lines
)
(b* (((when (atom alist))
nil)
((cons fieldname encoder) (car alist))
(foo->bar (std::da-accessor-name basename fieldname))
;; Suppose the fieldname is foo. We create the string ["foo":]. We can
;; create this at macroexpansion time.
(name1 (str::downcase-string (symbol-name fieldname)))
(name1-colon (str::cat "\"" name1 "\": ")))
(list* `(vl-print-str ,name1-colon)
`(,encoder (,foo->bar x))
(if (atom (cdr alist))
nil
(cons (if newlines
`(vl-ps-seq (vl-println ", ")
(vl-indent ,newlines))
`(vl-println? ", "))
(encoder-alist-main-actions basename (cdr alist) newlines))))))
(define convert-flexprod-fields-into-eformals ((x "list of fty::flexprod-fields"))
(b* (((when (atom x))
nil)
((fty::flexprod-field x1) (car x)))
(cons (std::make-formal :name x1.name
:guard (list x1.type x1.name))
(convert-flexprod-fields-into-eformals (cdr x)))))
(define def-vl-jp-aggregate-fn (type omit overrides long newlines world)
(b* ((mksym-package-symbol 'vl::foo)
(elem-print (mksym 'vl-jp- type))
(elem (mksym 'vl- type))
(elem-p (mksym 'vl- type '-p))
(elem-p-str (symbol-name elem-p))
((mv tag efields)
(b* ((agginfo (std::get-aggregate elem world))
((when agginfo)
(cw "Found info for defaggregate ~x0.~%" type)
(mv (std::agginfo->tag agginfo)
(std::agginfo->efields agginfo)))
(prodinfo (fty::get-flexprod-info elem world))
((unless prodinfo)
(mv (raise "Type ~x0 doesn't look like a known defaggregate/defprod?~%" type)
nil))
((fty::prodinfo prodinfo) prodinfo)
(efields (convert-flexprod-fields-into-eformals
(fty::flexprod->fields prodinfo.prod)))
(tag (fty::prodinfo->tag prodinfo)))
(mv tag efields)))
(- (cw "Inferred tag ~x0.~%" tag))
(- (cw "Inferred fields ~x0.~%" efields))
((unless (std::formallist-p efields))
(raise "Expected :efields for ~x0 to be a valid formallist, found ~x1."
elem efields))
(enc-alist (make-json-encoder-alist efields omit overrides world))
((unless (consp enc-alist))
(raise "Expected at least one field to encode."))
(main (encoder-alist-main-actions elem enc-alist newlines)))
`(define ,elem-print ((x ,elem-p) &key (ps 'ps))
:parents (json-encoders)
:short ,(cat "Print the JSON encoding of a @(see " elem-p-str
") to @(see ps).")
:long ,long
(vl-ps-seq
(vl-print "{\"tag\": ")
(jp-sym ',tag)
,(if newlines
`(vl-ps-seq (vl-println ", ")
(vl-indent ,newlines))
`(vl-print ", "))
,@main
(vl-println? "}"))
///
(add-json-encoder ,elem-p ,elem-print))))
#|
(def-vl-jp-aggregate-fn
'location
'(col)
'((filename . blah))
"long"
(w state))
|#
(defmacro def-vl-jp-aggregate (type &key omit override newlines
(long '""))
(declare (xargs :guard (maybe-natp newlines)))
`(make-event
(let ((form (def-vl-jp-aggregate-fn ',type ',omit ',override ',long ',newlines
(w state))))
(value form))))
(logic)
(defmacro def-vl-jp-list (type &key newlines)
(declare (xargs :guard (maybe-natp newlines)))
(b* ((mksym-package-symbol 'vl::foo)
(list-p (mksym 'vl- type 'list-p))
(elem-print (mksym 'vl-jp- type))
(list-print-aux (mksym 'vl-jp- type 'list-aux))
(list-print (mksym 'vl-jp- type 'list))
(list-p-str (symbol-name list-p)))
`(encapsulate ()
(define ,list-print-aux ((x ,list-p) &key (ps 'ps))
:parents (,list-print)
:short ,(cat "Prints out the elements of a @(see " list-p-str
") without the enclosing brackets.")
(if (atom x)
ps
(vl-ps-seq (,elem-print (car x))
(if (atom (cdr x))
ps
,(if newlines
`(vl-ps-seq (vl-println ",")
(vl-indent ,newlines))
`(vl-println? ", ")))
(,list-print-aux (cdr x)))))
(define ,list-print ((x ,list-p) &key (ps 'ps))
:parents (json-encoders)
:short ,(cat "Prints out the elements of a @(see " list-p-str
") with the enclosing brackets.")
(vl-ps-seq (vl-print "[")
(,list-print-aux x)
(vl-println? "]")))
(add-json-encoder ,list-p ,list-print))))
;; Real Verilog JSON Encoding
(define vl-jp-exprtype ((x vl-exprtype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-cstrength ((x vl-cstrength-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-dstrength ((x vl-dstrength-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-direction ((x vl-direction-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-gatetype ((x vl-gatetype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-evatomtype ((x vl-evatomtype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-assign-type ((x vl-assign-type-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-deassign-type ((x vl-deassign-type-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-casecheck ((x vl-casecheck-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-casetype ((x vl-casetype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-taskporttype ((x vl-taskporttype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-alwaystype ((x vl-alwaystype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(add-json-encoder vl-exprtype-p vl-jp-exprtype)
(add-json-encoder vl-cstrength-p vl-jp-cstrength)
(add-json-encoder vl-dstrength-p vl-jp-dstrength)
(add-json-encoder vl-direction-p vl-jp-direction)
(add-json-encoder vl-gatetype-p vl-jp-gatetype)
(add-json-encoder vl-evatomtype-p vl-jp-evatomtype)
(add-json-encoder vl-assign-type-p vl-jp-assign-type)
(add-json-encoder vl-deassign-type-p vl-jp-deassign-type)
(add-json-encoder vl-casetype-p vl-jp-casetype)
(add-json-encoder vl-casecheck-p vl-jp-casecheck)
(add-json-encoder vl-taskporttype-p vl-jp-taskporttype)
(add-json-encoder vl-alwaystype-p vl-jp-alwaystype)
(define vl-jp-maybe-exprtype ((x vl-maybe-exprtype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(if x
(vl-jp-exprtype x)
(vl-print "null")))
(define vl-jp-maybe-cstrength ((x vl-maybe-cstrength-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(if x
(vl-jp-cstrength x)
(vl-print "null")))
(define vl-jp-maybe-direction ((x vl-maybe-direction-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(if x
(vl-jp-direction x)
(vl-print "null")))
(add-json-encoder vl-maybe-exprtype-p vl-jp-maybe-exprtype)
(add-json-encoder vl-maybe-cstrength-p vl-jp-maybe-cstrength)
(add-json-encoder vl-maybe-direction-p vl-jp-maybe-direction)
(def-vl-jp-aggregate location)
#||
(top-level
(vl-cw-ps-seq (vl-jp-location *vl-fakeloc*)))
||#
(def-vl-jp-aggregate constint
:override ((value . jp-bignat))
:long "<p>Note that we always encode the value as a string. This is
because it is quite common for Verilog constants to run into the hundreds
of bits, but the JSON standard doesn't really ever say how big of numbers
must be supported and JSON implementations often use machine integers
which could not hold such large values.</p>")
(define jp-bit ((x vl-bit-p) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a @(see vl-bit-p) as a JSON string."
(jp-str (implode (list (vl-bit->char x)))))
(add-json-encoder vl-bit-p jp-bit)
(define jp-bitlist ((x vl-bitlist-p) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a @(see vl-bitlist-p) as a JSON string."
(jp-str (vl-bitlist->string x)))
(add-json-encoder vl-bitlist-p jp-bitlist)
(define jp-timeunit ((x vl-timeunit-p) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a @(see vl-timeunit-p) as a JSON string."
(jp-str (vl-timeunit->string x)))
(add-json-encoder vl-timeunit-p jp-timeunit)
(define jp-keygutstype ((x vl-keygutstype-p) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a @(see vl-keygutstype-p) as a JSON string."
(jp-str (vl-keygutstype->string x)))
(add-json-encoder vl-keygutstype-p jp-keygutstype)
(define jp-basictypekind ((x vl-basictypekind-p) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a @(see vl-basictypekind-p) as a JSON string."
(jp-str (vl-basictypekind->string x)))
(add-json-encoder vl-basictypekind-p jp-basictypekind)
(def-vl-jp-aggregate weirdint)
(def-vl-jp-aggregate string)
(def-vl-jp-aggregate real)
(def-vl-jp-aggregate id)
(def-vl-jp-aggregate hidpiece)
(def-vl-jp-aggregate sysfunname)
(def-vl-jp-aggregate tagname)
(def-vl-jp-aggregate funname)
(def-vl-jp-aggregate keyguts)
(def-vl-jp-aggregate extint)
(def-vl-jp-aggregate time)
(def-vl-jp-aggregate basictype)
(define vl-jp-atomguts ((x vl-atomguts-p) &key (ps 'ps))
:parents (vl-jp-expr vl-atomguts-p)
:guard-hints (("Goal" :in-theory (enable vl-atomguts-p)))
(case (tag x)
(:vl-id (vl-jp-id x))
(:vl-constint (vl-jp-constint x))
(:vl-weirdint (vl-jp-weirdint x))
(:vl-string (vl-jp-string x))
(:vl-real (vl-jp-real x))
(:vl-hidpiece (vl-jp-hidpiece x))
(:vl-funname (vl-jp-funname x))
(:vl-keyguts (vl-jp-keyguts x))
(:vl-extint (vl-jp-extint x))
(:vl-time (vl-jp-time x))
(:vl-basictype (vl-jp-basictype x))
(:vl-tagname (vl-jp-tagname x))
(otherwise (vl-jp-sysfunname x))))
(add-json-encoder vl-atomguts-p vl-jp-atomguts)
(defines vl-jp-expr
:parents (json-encoders)
(define vl-jp-expr ((x vl-expr-p) &key (ps 'ps))
:measure (two-nats-measure (vl-expr-count x) 0)
(vl-expr-case x
:atom
(jp-object :tag (jp-sym :atom)
:guts (vl-jp-atomguts x.guts)
:finalwidth (jp-maybe-nat x.finalwidth)
:finaltype (vl-jp-maybe-exprtype x.finaltype))
:nonatom
(jp-object :tag (jp-sym :nonatom)
:atts (vl-jp-atts x.atts)
:args (vl-jp-exprlist x.args)
:finalwidth (jp-maybe-nat x.finalwidth)
:finaltype (vl-jp-maybe-exprtype x.finaltype))))
(define vl-jp-atts ((x vl-atts-p) &key (ps 'ps))
:measure (two-nats-measure (vl-atts-count x) 1)
;; Atts are a string->maybe-expr alist, so turn them into a JSON object
;; binding keys to values...
(vl-ps-seq (vl-print "{")
(vl-jp-atts-aux x)
(vl-println? "}")))
(define vl-jp-atts-aux ((x vl-atts-p) &key (ps 'ps))
:measure (two-nats-measure (vl-atts-count x) 0)
(b* ((x (vl-atts-fix x))
((when (atom x))
ps)
((cons name1 val1) (car x)))
(vl-ps-seq (jp-str name1)
(vl-print ": ")
(if val1
(vl-jp-expr val1)
(vl-print "null"))
(if (atom (cdr x))
ps
(vl-println? ", "))
(vl-jp-atts-aux (cdr x)))))
(define vl-jp-exprlist ((x vl-exprlist-p) &key (ps 'ps))
;; Print the expressions as a JSON array with brackets.
:measure (two-nats-measure (vl-exprlist-count x) 1)
(vl-ps-seq (vl-print "[")
(vl-jp-exprlist-aux x)
(vl-println? "]")))
(define vl-jp-exprlist-aux ((x vl-exprlist-p) &key (ps 'ps))
:measure (two-nats-measure (vl-exprlist-count x) 0)
(b* (((when (atom x))
ps))
(vl-ps-seq (vl-jp-expr (car x))
(if (atom (cdr x))
ps
(vl-println? ", "))
(vl-jp-exprlist-aux (cdr x))))))
(define vl-jp-maybe-expr ((x vl-maybe-expr-p) &key (ps 'ps))
(if x
(vl-jp-expr x)
(vl-print "null")))
(add-json-encoder vl-expr-p vl-jp-expr)
(add-json-encoder vl-exprlist-p vl-jp-exprlist)
(add-json-encoder vl-atts-p vl-jp-atts)
(add-json-encoder vl-maybe-expr-p vl-jp-maybe-expr)
(def-vl-jp-aggregate range)
(def-vl-jp-list range)
(define vl-jp-maybe-range ((x vl-maybe-range-p) &key (ps 'ps))
(if x
(vl-jp-range x)
(vl-print "null")))
(add-json-encoder vl-maybe-range-p vl-jp-maybe-range)
(def-vl-jp-aggregate port)
(def-vl-jp-list port :newlines 4)
(def-vl-jp-aggregate gatedelay)
(define vl-jp-maybe-gatedelay ((x vl-maybe-gatedelay-p) &key (ps 'ps))
:parents (json-encoders vl-maybe-gatedelay-p)
(if x
(vl-jp-gatedelay x)
(vl-print "null")))
(add-json-encoder vl-maybe-gatedelay-p vl-jp-maybe-gatedelay)
(def-vl-jp-aggregate plainarg)
(def-vl-jp-list plainarg :newlines 4)
(def-vl-jp-aggregate namedarg)
(def-vl-jp-list namedarg :newlines 4)
(define vl-jp-lifetime ((x vl-lifetime-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-randomqualifier ((x vl-randomqualifier-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-nettypename ((x vl-nettypename-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-coretypename ((x vl-coretypename-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(add-json-encoder vl-lifetime-p vl-jp-lifetime)
(add-json-encoder vl-randomqualifier-p vl-jp-randomqualifier)
(add-json-encoder vl-nettypename-p vl-jp-nettypename)
(add-json-encoder vl-coretypename-p vl-jp-coretypename)
(define vl-jp-packeddimension ((x vl-packeddimension-p) &key (ps 'ps))
:parents (json-encoders)
(if (eq x :vl-unsized-dimension)
(jp-sym x)
(vl-jp-range x)))
(add-json-encoder vl-packeddimension-p vl-jp-packeddimension)
(def-vl-jp-list packeddimension)
(define vl-jp-maybe-packeddimension ((x vl-maybe-packeddimension-p) &key (ps 'ps))
:parents (json-encoders)
(if x
(vl-jp-packeddimension x)
(vl-print "null")))
(add-json-encoder vl-maybe-packeddimension-p vl-jp-maybe-packeddimension)
(define vl-jp-enumbasekind ((x vl-enumbasekind-p) &key (ps 'ps))
:guard-hints(("Goal" :in-theory (enable vl-enumbasekind-p)))
(if (stringp x)
(jp-object :tag (jp-sym :user-defined-type)
:name (jp-str x))
(jp-sym x)))
(add-json-encoder vl-enumbasekind-p vl-jp-enumbasekind)
(def-vl-jp-aggregate enumbasetype)
(def-vl-jp-aggregate enumitem)
(def-vl-jp-list enumitem)
(defines vl-jp-datatype
(define vl-jp-datatype ((x vl-datatype-p) &key (ps 'ps))
:measure (two-nats-measure (vl-datatype-count x) 0)
(vl-datatype-case x
:vl-nettype
(jp-object :tag (jp-sym :vl-nettype)
:name (vl-jp-nettypename x.name)
:signedp (jp-bool x.signedp)
:range (vl-jp-maybe-range x.range))
:vl-coretype
(jp-object :tag (jp-sym :vl-coretype)
:name (vl-jp-coretypename x.name)
:signedp (jp-bool x.signedp)
:dism (vl-jp-packeddimensionlist x.dims))
:vl-struct
(jp-object :tag (jp-sym :vl-struct)
:packedp (jp-bool x.packedp)
:signedp (jp-bool x.signedp)
:dims (vl-jp-packeddimensionlist x.dims)
:members (vl-jp-structmemberlist x.members))
:vl-union
(jp-object :tag (jp-sym :vl-union)
:packedp (jp-bool x.packedp)
:signedp (jp-bool x.signedp)
:taggedp (jp-bool x.taggedp)
:dims (vl-jp-packeddimensionlist x.dims)
:members (vl-jp-structmemberlist x.members))
:vl-enum
(jp-object :tag (jp-sym :vl-enum)
:basetype (vl-jp-enumbasetype x.basetype)
:items (vl-jp-enumitemlist x.items)
:dims (vl-jp-packeddimensionlist x.dims))
:vl-usertype
(jp-object :tag (jp-sym :vl-usertype)
:kind (vl-jp-expr x.kind)
:dims (vl-jp-packeddimensionlist x.dims))))
(define vl-jp-structmemberlist ((x vl-structmemberlist-p) &key (ps 'ps))
;; Print the stmtessions as a JSON array with brackets.
:measure (two-nats-measure (vl-structmemberlist-count x) 1)
(vl-ps-seq (vl-print "[")
(vl-jp-structmemberlist-aux x)
(vl-println? "]")))
(define vl-jp-structmemberlist-aux ((x vl-structmemberlist-p) &key (ps 'ps))
:measure (two-nats-measure (vl-structmemberlist-count x) 0)
(if (atom x)
ps
(vl-ps-seq (vl-jp-structmember (car x))
(if (atom (cdr x))
ps
(vl-println? ", "))
(vl-jp-structmemberlist-aux (cdr x)))))
(define vl-jp-structmember ((x vl-structmember-p) &key (ps 'ps))
:measure (two-nats-measure (vl-structmember-count x) 0)
(b* (((vl-structmember x) x))
(jp-object :tag (jp-sym :vl-structmember)
:atts (vl-jp-atts x.atts)
:rand (vl-jp-randomqualifier x.rand)
:dims (vl-jp-packeddimensionlist x.dims)
:rhs (vl-jp-maybe-expr x.rhs)
:type (vl-jp-datatype x.type)))))
(add-json-encoder vl-datatype-p vl-jp-datatype)
(add-json-encoder vl-structmember-p vl-jp-structmember)
(add-json-encoder vl-structmemberlist-p vl-jp-structmemberlist)
(define vl-jp-maybe-datatype ((x vl-maybe-datatype-p) &key (ps 'ps))
(if x
(vl-jp-datatype x)
(vl-print "null")))
(add-json-encoder vl-maybe-datatype-p vl-jp-maybe-datatype)
(def-vl-jp-aggregate vardecl)
(def-vl-jp-list vardecl :newlines 4)
(define vl-jp-paramtype ((x vl-paramtype-p) &key (ps 'ps))
(vl-paramtype-case x
(:vl-implicitvalueparam
(jp-object :tag (jp-sym :vl-implicitvalueparam)
:sign (jp-sym x.sign)
:range (vl-jp-maybe-range x.range)
:default (vl-jp-maybe-expr x.default)))
(:vl-explicitvalueparam
(jp-object :tag (jp-sym :vl-explicitvalueparam)
:type (vl-jp-datatype x.type)
:default (vl-jp-maybe-expr x.default)))
(:vl-typeparam
(jp-object :tag (jp-sym :vl-typeparam)
:default (vl-jp-maybe-datatype x.default)))))
(add-json-encoder vl-paramtype-p vl-jp-paramtype)
(def-vl-jp-aggregate paramdecl)
(def-vl-jp-list paramdecl :newlines 4)
(define vl-jp-blockitem ((x vl-blockitem-p) &key (ps 'ps))
:guard-hints (("Goal" :in-theory (enable vl-blockitem-p)))
(mbe :logic
(cond ((vl-vardecl-p x) (vl-jp-vardecl x))
(t (vl-jp-paramdecl x)))
:exec
(case (tag x)
(:vl-vardecl (vl-jp-vardecl x))
(otherwise (vl-jp-paramdecl x)))))
(add-json-encoder vl-blockitem-p vl-jp-blockitem)
(def-vl-jp-list blockitem)
(define vl-jp-arguments ((x vl-arguments-p) &key (ps 'ps))
:parents (json-encoders vl-arguments-p)
(vl-arguments-case x
:vl-arguments-named
(jp-object :tag (jp-sym :vl-arguments)
:namedp (jp-bool t)
:starp (jp-bool x.starp)
:args (vl-jp-namedarglist x.args))
:vl-arguments-plain
(jp-object :tag (jp-sym :vl-arguments)
:namedp (jp-bool nil)
:args (vl-jp-plainarglist x.args))))
(add-json-encoder vl-arguments-p vl-jp-arguments)
(def-vl-jp-aggregate gatestrength)
(define vl-jp-maybe-gatestrength ((x vl-maybe-gatestrength-p) &key (ps 'ps))
(if x
(vl-jp-gatestrength x)
(vl-print "null")))
(add-json-encoder vl-maybe-gatestrength-p vl-jp-maybe-gatestrength)
(define vl-jp-paramvalue ((x vl-paramvalue-p) &key (ps 'ps))
:parents (json-encoders vl-paramvalue-p)
(b* ((x (vl-paramvalue-fix x)))
(vl-paramvalue-case x
:expr (vl-jp-expr x)
:datatype (vl-jp-datatype x))))
(add-json-encoder vl-paramvalue-p vl-jp-paramvalue)
(def-vl-jp-list paramvalue)
(define vl-jp-maybe-paramvalue ((x vl-maybe-paramvalue-p) &key (ps 'ps))
(if x
(vl-jp-paramvalue x)
(vl-print "null")))
(add-json-encoder vl-maybe-paramvalue-p vl-jp-maybe-paramvalue)
(def-vl-jp-aggregate namedparamvalue)
(def-vl-jp-list namedparamvalue)
(define vl-jp-paramargs ((x vl-paramargs-p) &key (ps 'ps))
(vl-paramargs-case x
:vl-paramargs-named
(jp-object :tag (jp-sym :vl-paramargs)
:namedp (jp-bool t)
:args (vl-jp-namedparamvaluelist x.args))
:vl-paramargs-plain
(jp-object :tag (jp-sym :vl-paramargs)
:namedp (jp-bool nil)
:args (vl-jp-paramvaluelist x.args))))
(add-json-encoder vl-paramargs-p vl-jp-paramargs)
(def-vl-jp-aggregate modinst)
(def-vl-jp-list modinst)
(def-vl-jp-aggregate gateinst)
(def-vl-jp-list gateinst)
(def-vl-jp-aggregate delaycontrol)
(def-vl-jp-aggregate evatom)
(def-vl-jp-list evatom)
(def-vl-jp-aggregate eventcontrol)
(def-vl-jp-aggregate repeateventcontrol)
(define vl-jp-delayoreventcontrol ((x vl-delayoreventcontrol-p) &key (ps 'ps))
:guard-hints (("Goal" :in-theory (enable vl-delayoreventcontrol-p)))
(cond ((vl-delaycontrol-p x) (vl-jp-delaycontrol x))
((vl-eventcontrol-p x) (vl-jp-eventcontrol x))
(t (vl-jp-repeateventcontrol x))))
(add-json-encoder vl-delayoreventcontrol-p vl-jp-delayoreventcontrol)
(define vl-jp-maybe-delayoreventcontrol ((x vl-maybe-delayoreventcontrol-p)
&key (ps 'ps))
(if x
(vl-jp-delayoreventcontrol x)
(vl-print "null")))
(add-json-encoder vl-maybe-delayoreventcontrol-p vl-jp-maybe-delayoreventcontrol)
(defines vl-jp-stmt
(define vl-jp-stmt ((x vl-stmt-p) &key (ps 'ps))
:measure (two-nats-measure (vl-stmt-count x) 0)
(b* ((kind (vl-stmt-kind x)))
(vl-stmt-case x
:vl-nullstmt
(jp-object :tag (jp-sym kind)
:atts (vl-jp-atts x.atts))
:vl-assignstmt
(jp-object :tag (jp-sym kind)
:lvalue (vl-jp-expr x.lvalue)
:expr (vl-jp-expr x.expr)
:ctrl (vl-jp-maybe-delayoreventcontrol x.ctrl)
:atts (vl-jp-atts x.atts))
:vl-deassignstmt
(jp-object :tag (jp-sym kind)
:lvalue (vl-jp-expr x.lvalue)
:atts (vl-jp-atts x.atts))
:vl-enablestmt
(jp-object :tag (jp-sym kind)
:id (vl-jp-expr x.id)
:args (vl-jp-exprlist x.args)
:atts (vl-jp-atts x.atts))
:vl-disablestmt
(jp-object :tag (jp-sym kind)
:id (vl-jp-expr x.id)
:atts (vl-jp-atts x.atts))
:vl-eventtriggerstmt
(jp-object :tag (jp-sym kind)
:id (vl-jp-expr x.id)
:atts (vl-jp-atts x.atts))
:vl-casestmt
(jp-object :tag (jp-sym kind)
:casetype (vl-jp-casetype x.casetype)
:check (vl-jp-casecheck x.check)
:test (vl-jp-expr x.test)
:default (vl-jp-stmt x.default)
:caselist (vl-jp-cases x.caselist)
:atts (vl-jp-atts x.atts))
:vl-ifstmt
(jp-object :tag (jp-sym kind)
:condition (vl-jp-expr x.condition)
:truebranch (vl-jp-stmt x.truebranch)
:falsebranch (vl-jp-stmt x.falsebranch)
:atts (vl-jp-atts x.atts))
:vl-foreverstmt
(jp-object :tag (jp-sym kind)
:body (vl-jp-stmt x.body)
:atts (vl-jp-atts x.atts))
:vl-waitstmt
(jp-object :tag (jp-sym kind)
:condition (vl-jp-expr x.condition)
:body (vl-jp-stmt x.body)
:atts (vl-jp-atts x.atts))
:vl-whilestmt
(jp-object :tag (jp-sym kind)
:condition (vl-jp-expr x.condition)
:body (vl-jp-stmt x.body)
:atts (vl-jp-atts x.atts))
:vl-forstmt
(jp-object :tag (jp-sym kind)
:initlhs (vl-jp-expr x.initlhs)
:initrhs (vl-jp-expr x.initrhs)
:test (vl-jp-expr x.test)
:nextlhs (vl-jp-expr x.nextlhs)
:nextrhs (vl-jp-expr x.nextrhs)
:body (vl-jp-stmt x.body)
:atts (vl-jp-atts x.atts))
:vl-blockstmt
(jp-object :tag (jp-sym kind)
:sequential (jp-bool x.sequentialp)
:name (jp-maybe-string x.name)
:decls (vl-jp-blockitemlist x.decls)
:stmts (vl-jp-stmtlist x.stmts)
:atts (vl-jp-atts x.atts))
:vl-repeatstmt
(jp-object :tag (jp-sym kind)
:condition (vl-jp-expr x.condition)
:body (vl-jp-stmt x.body)
:atts (vl-jp-atts x.atts))
:vl-timingstmt
(jp-object :tag (jp-sym kind)
:ctrl (vl-jp-delayoreventcontrol x.ctrl)
:body (vl-jp-stmt x.body)
:atts (vl-jp-atts x.atts))
)))
(define vl-jp-stmtlist ((x vl-stmtlist-p) &key (ps 'ps))
;; Print the stmtessions as a JSON array with brackets.
:measure (two-nats-measure (vl-stmtlist-count x) 1)
(vl-ps-seq (vl-print "[")
(vl-jp-stmtlist-aux x)
(vl-println? "]")))
(define vl-jp-stmtlist-aux ((x vl-stmtlist-p) &key (ps 'ps))
:measure (two-nats-measure (vl-stmtlist-count x) 0)
(b* (((when (atom x))
ps))
(vl-ps-seq (vl-jp-stmt (car x))
(if (atom (cdr x))
ps
(vl-println? ", "))
(vl-jp-stmtlist-aux (cdr x)))))
(define vl-jp-cases ((x vl-caselist-p) &key (ps 'ps))
;; Print the stmtessions as a JSON array with brackets.
:measure (two-nats-measure (vl-caselist-count x) 1)
(vl-ps-seq (vl-print "[")
(vl-jp-cases-aux x)
(vl-println? "]")))
(define vl-jp-cases-aux ((x vl-caselist-p) &key (ps 'ps))
;; Print the stmtessions as a JSON array with brackets.
:measure (two-nats-measure (vl-caselist-count x) 0)
(b* ((x (vl-caselist-fix x))
((when (atom x))
ps)
((cons exprs stmt1) (car x)))
(vl-ps-seq (vl-print "[")
(vl-jp-exprlist exprs)
(vl-println? ",")
(vl-jp-stmt stmt1)
(vl-println? "]")
(if (atom (cdr x))
ps
(vl-println? ", "))
(vl-jp-cases-aux (cdr x))))))
(add-json-encoder vl-stmt-p vl-jp-stmt)
(add-json-encoder vl-stmtlist-p vl-jp-stmtlist)
(add-json-encoder vl-caselist-p vl-jp-cases)
(def-vl-jp-aggregate always)
(def-vl-jp-list always :newlines 4)
(def-vl-jp-aggregate initial)
(def-vl-jp-list initial :newlines 4)
(def-vl-jp-aggregate taskport)
(def-vl-jp-list taskport :newlines 4)
(def-vl-jp-aggregate fundecl)
(def-vl-jp-list fundecl :newlines 4)
(def-vl-jp-aggregate taskdecl)
(def-vl-jp-list taskdecl :newlines 4)
(def-vl-jp-aggregate portdecl)
(def-vl-jp-list portdecl :newlines 4)
(def-vl-jp-aggregate assign)
(def-vl-jp-list assign :newlines 4)
(define vl-jp-warning ((x vl-warning-p) &key (ps 'ps))
:parents (json-encoders)
:short "Special, custom JSON encoder for warnings."
:long "<p>We probably don't want to use the ordinary aggregate-encoding stuff
to print @(see vl-warning-p) objects, since the types in the @(':args') field
are dynamic and, besides, who wants to reimplement @(see vl-cw) in other
languages. Instead, it's probably more convenient to just go ahead and convert
the warning into a printed message here. We'll include both HTML and plain
TEXT versions of the message.</p>"
(b* (((vl-warning x) x)
(text (with-local-ps (vl-cw-obj x.msg x.args)))
(html (with-local-ps (vl-ps-update-htmlp t)
(vl-cw-obj x.msg x.args))))
(jp-object :tag (vl-print "\"warning\"")
:fatalp (jp-bool x.fatalp)
:type (jp-str (symbol-name x.type))
:fn (jp-str (symbol-name x.fn))
:text (jp-str text)
:html (jp-str html))))
(add-json-encoder vl-warning-p jp-warning)
(def-vl-jp-list warning :newlines 4)
(define vl-jp-commentmap-aux ((x vl-commentmap-p) &key (ps 'ps))
(b* (((when (atom x))
ps))
(vl-ps-seq (vl-print "{\"loc\": ")
(vl-jp-location (caar x))
(vl-println? ", \"comment\": ")
(jp-str (cdar x))
(vl-print "}")
(if (atom (cdr x))
ps
(vl-println? ", "))
(vl-jp-commentmap-aux (cdr x)))))
(define vl-jp-commentmap ((x vl-commentmap-p) &key (ps 'ps))
(vl-ps-seq (vl-print "[")
(vl-jp-commentmap-aux x)
(vl-println? "]")))
(add-json-encoder vl-commentmap-p vl-jp-commentmap)
(def-vl-jp-aggregate modport-port)
(def-vl-jp-list modport-port)
(def-vl-jp-aggregate modport)
(def-vl-jp-aggregate alias)
(define vl-jp-fwdtypedefkind ((x vl-fwdtypedefkind-p) &key (ps 'ps))
(jp-str (case x
(:vl-enum "enum")
(:vl-struct "struct")
(:vl-union "union")
(:vl-class "class")
(:vl-interfaceclass "interfaceclass")))
///
(add-json-encoder vl-fwdtypedefkind-p vl-jp-fwdtypedefkind))
(def-vl-jp-aggregate fwdtypedef)
(define vl-jp-modelement ((x vl-modelement-p) &key (ps 'ps))
:guard-hints (("goal" :in-theory (enable vl-modelement-p)))
(case (tag x)
(:VL-PORT (VL-jp-PORT X))
(:VL-PORTDECL (VL-jp-PORTDECL X))
(:VL-ASSIGN (VL-jp-ASSIGN X))
(:VL-ALIAS (VL-jp-ALIAS X))
(:VL-VARDECL (VL-jp-VARDECL X))
(:VL-PARAMDECL (VL-jp-PARAMDECL X))
(:VL-FUNDECL (VL-jp-FUNDECL X))
(:VL-TASKDECL (VL-jp-TASKDECL X))
(:VL-MODINST (VL-jp-MODINST X))
(:VL-GATEINST (VL-jp-GATEINST X))
(:VL-ALWAYS (VL-jp-ALWAYS X))
(:VL-INITIAL (VL-jp-INITIAL X))
;; BOZO implement typedef
(:VL-TYPEDEF ps)
(:VL-FWDTYPEDEF (VL-jp-FWDTYPEDEF X))
(OTHERWISE (VL-jp-MODPORT X))))
(def-vl-jp-list modelement)
(define vl-jp-genelement ((x vl-genelement-p) &key (ps 'ps))
(vl-genelement-case x
:vl-genbase (vl-jp-modelement x.item)
;; BOZO implement generates
:otherwise ps)
///
(add-json-encoder vl-genelement-p vl-jp-genelement))
(def-vl-jp-list genelement)
(def-vl-jp-aggregate module
:omit (params esim)
:newlines 2)
(def-vl-jp-list module
:newlines 1)
(define vl-jp-modalist-aux ((x vl-modalist-p) &key (ps 'ps))
(b* (((when (atom x))
ps))
(vl-ps-seq (jp-str (caar x))
(vl-print ": ")
(vl-jp-module (cdar x))
(if (atom (cdr x))
ps
(vl-println ", "))
(vl-jp-modalist-aux (cdr x)))))
(define vl-jp-modalist ((x vl-modalist-p) &key (ps 'ps))
(vl-ps-seq (vl-print "{")
(vl-jp-modalist-aux x)
(vl-println "}")))
(define vl-jp-individual-modules ((x vl-modulelist-p) &key (ps 'ps))
;; This doesn't print a single valid JSON object. Instead, it prints a whole
;; list of JSON objects separated by newlines.
(if (atom x)
ps
(vl-ps-seq (vl-jp-module (car x))
(vl-print "
")
(vl-jp-individual-modules (cdr x)))))
|
69094
|
; 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 "fmt")
(include-book "find-module")
(include-book "centaur/bridge/to-json" :dir :system)
(local (include-book "../util/arithmetic"))
(defsection json-printing
:parents (printer)
:short "Routines for encoding various ACL2 structures into <a
href='http://www.json.org/'>JSON</a> format."
:long "<p>This is a collection of printing routines for translating ACL2
structures into JSON format. These routines are mainly meant to make it easy
to convert @(see vl) @(see syntax) into nice JSON data, but are somewhat
flexible and may be useful for other applications.</p>")
(defsection json-encoders
:parents (json-printing)
:short "A table of JSON encoders to use for for different kinds of data."
:long "<p>A JSON encoder is a function of the following signature:</p>
@({ encode-foo : foo * ps --> ps })
<p>Where @('foo') is expected to be an object of some type @('foop'), and
@('ps') is the @(see vl) @(see printer) state stobj, @(see ps). Each such
routine is responsible for printing a JSON encoding of its @('foop') argument.
Each such function may assume that @(see ps) is set to text mode.</p>
<p>The encoder table is a simple association of @('foop') to @('encode-foo')
functions. We can use it to automatically generate encoders for, e.g., @(see
defaggregate) structures.</p>"
(table vl-json)
(table vl-json 'encoders
;; Alist binding each recognizer foop to its JSON encoder, vl-jp-foo
)
(defun get-json-encoders (world)
"Look up the current alist of json encoders."
(declare (xargs :mode :program))
(cdr (assoc 'encoders (table-alist 'vl-json world))))
(defmacro add-json-encoder (foop encoder-fn)
(declare (xargs :guard (and (symbolp foop)
(symbolp encoder-fn))))
`(table vl-json 'encoders
(cons (cons ',foop ',encoder-fn)
(get-json-encoders world))))
(defun get-json-encoder (foop world)
(declare (xargs :mode :program))
(let ((entry (assoc foop (get-json-encoders world))))
(if entry
(cdr entry)
(er hard? 'get-json-encoder
"No json encoder defined for ~x0.~%" foop)))))
#||
(get-json-encoders (w state))
(add-json-encoder barp vl-enc-bar)
(get-json-encoders (w state))
(get-json-encoder 'barp (w state)) ;; vl-enc-bar
(get-json-encoder 'foop (w state)) ;; fail, no encoder defined
||#
(define jp-bool ((x booleanp) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a @(see booleanp) into JSON as @('true') or @('false')."
(if x
(vl-print-str "true")
(vl-print-str "false")))
(add-json-encoder booleanp jp-bool)
(add-json-encoder not jp-bool)
(define jp-col-after-printing-string-aux
((col natp "Current column we're at.")
(x stringp "String we're about to print, not yet reversed.")
(n natp "Current position in X.")
(xl natp "Pre-computed length of X."))
:returns (new-col natp :rule-classes :type-prescription)
:parents (jp-str)
:short "Fast way to figure out the new column after printing a JSON string
with proper encoding."
:guard (and (<= n xl)
(= xl (length x)))
:measure (nfix (- (nfix xl) (nfix n)))
(declare (type (integer 0 *) col n xl)
(type string x))
(b* (((when (mbe :logic (zp (- (nfix xl) (nfix n)))
:exec (= n xl)))
(lnfix col))
((the (unsigned-byte 8) code) (char-code (char x n)))
((when (or (<= code 31)
(>= code 127)))
;; This is a "json weird char." Our encoder will turn it into
;; \uXXXX. The length of \uXXXX is 6.
(jp-col-after-printing-string-aux (+ 6 col) x (+ 1 (lnfix n)) xl)))
;; Else there is only one character.
(jp-col-after-printing-string-aux (+ 1 col) x (+ 1 (lnfix n)) xl)))
(define jp-str ((x :type string) &key (ps 'ps))
:parents (json-encoders)
:short "Print the JSON encoding of a string, handling all escaping correctly
and including the surrounding quotes."
:long "<p>We go to some effort to make this fast.</p>"
(b* ((rchars (vl-ps->rchars))
(col (vl-ps->col))
(xl (length x))
(rchars (cons #\" (bridge::json-encode-str-aux x 0 xl (cons #\" rchars))))
(col (+ 2 (jp-col-after-printing-string-aux col x 0 xl))))
(vl-ps-seq
(vl-ps-update-rchars rchars)
(vl-ps-update-col col)))
:prepwork
((local (defthm l0
(implies (and (vl-printedlist-p acc)
(character-listp x))
(vl-printedlist-p (bridge::json-encode-chars x acc)))
:hints(("Goal"
:in-theory (e/d (bridge::json-encode-chars
bridge::json-encode-char
bridge::json-encode-weird-char)
(digit-to-char))))))))
(add-json-encoder stringp jp-str)
(define jp-maybe-string ((x maybe-stringp) &key (ps 'ps))
:parents (json-encoders)
(if x
(jp-str x)
(vl-print "null")))
(add-json-encoder maybe-stringp jp-maybe-string)
(define jp-bignat ((x natp) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a potentially large natural number as a JSON string."
(vl-print-str (str::natstr x)))
(define jp-nat ((x natp) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a probably small natural number as a JSON number."
:long "<p>We require that the integer is at most 2^31, which we think is the
minimum reasonable size for a JSON implementation to support.</p>"
(b* (((unless (<= x (expt 2 31)))
(raise "Scarily trying to JSON-encode large natural: ~x0." x)
ps))
(vl-print-nat x)))
(define jp-maybe-nat ((x maybe-natp) &key (ps 'ps))
:parents (json-encoders)
(if x
(jp-nat x)
(vl-print-str "null")))
(add-json-encoder natp jp-nat)
(add-json-encoder posp jp-nat)
(add-json-encoder maybe-natp jp-maybe-nat)
(add-json-encoder maybe-posp jp-maybe-nat)
(define jp-sym-main ((x symbolp) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a simple symbol as a JSON string, including the surrounding
quotes."
:long "<p>We assume that @('x') has a simple enough name to print without any
encoding. This is generally true for keyword constants used as tags and in
basic enumerations like @(see vl-exprtype-p). We print only the symbol name,
in lower-case.</p>"
(vl-ps-seq (vl-print "\"")
(vl-print-str (str::downcase-string (symbol-name x)))
(vl-print "\"")))
(defsection jp-sym
:parents (json-encoders)
:short "Optimized version of @(see jp-sym-main)."
:long "<p>This is a simple macro that is meant to be the same as @(see
jp-sym-main). The only difference is that if we are given a literal symbol,
e.g., @(':foo'), we can do the string manipulation at compile time.</p>"
(defmacro jp-sym (x &key (ps 'ps))
(if (or (keywordp x)
(booleanp x)
(and (quotep x)
(symbolp (acl2::unquote x))))
;; Yes, want to optimize.
(let* ((guts (if (quotep x) (acl2::unquote x) x))
(ans (str::cat "\""
(str::downcase-string (symbol-name guts))
"\"")))
`(vl-print-str ,ans :ps ,ps))
`(jp-sym-main ,x :ps ,ps))))
#||
(top-level (vl-cw-ps-seq (jp-sym :foo))) ;; "foo"
(top-level (vl-cw-ps-seq (jp-sym t))) ;; "t"
(top-level (vl-cw-ps-seq (jp-sym nil))) ;; "nil"
(top-level (vl-cw-ps-seq (jp-sym 'bar))) ;; "bar"
(top-level (let ((x 'baz))
(vl-cw-ps-seq (jp-sym x)))) ;; "baz"
||#
(defsection jp-object
:parents (json-encoders)
:short "Utility for printing JSON <i>objects</i>, which in some other
languages might be called alists, dictionaries, hashes, records, etc."
:long "<p>Syntax Example:</p>
@({
(jp-object :tag (vl-print \"loc\")
:file (vl-print x.filename)
:line (vl-print x.line)
:col (vl-print x.col))
--->
{ \"tag\": \"loc\", \"file\": ... }
})
<p>The arguments to @('jp-object') should be an alternating list of literal
keywords, which (for better performance) we assume are so simple they do not
need to be encoded, and printing expressions which should handle any necessary
encoding.</p>"
:autodoc nil
(defun jp-object-aux (forms)
(declare (xargs :guard t))
(b* (((when (atom forms))
nil)
((unless (keywordp (car forms)))
(er hard? 'jp-object "Expected alternating keywords and values."))
((unless (consp (cdr forms)))
(er hard? 'jp-object "No argument found after ~x0." (car forms)))
;; Suppose the keyword is :foo.
;; We create the string: "foo":
;; We can create this at macroexpansion time.
(name1 (str::downcase-string (symbol-name (car forms))))
(name1-colon (str::cat "\"" name1 "\": ")))
(list* `(vl-print-str ,name1-colon)
(second forms)
(if (atom (cddr forms))
nil
(cons `(vl-println? ", ")
(jp-object-aux (cddr forms)))))))
(defmacro jp-object (&rest forms)
`(vl-ps-seq (vl-print "{")
,@(jp-object-aux forms)
(vl-println? "}"))))
; Fancy automatic json encoding of std structures
(program)
(define make-json-encoder-alist
(efields ;; A proper std::formallist-p for this structure's fields
omit ;; A list of any fields to omit from the encoded output
overrides ;; An alist of (fieldname . encoder-to-use-instead-of-default)
world ;; For looking up default encoders
)
;; Returns an alist of the form (fieldname . encoder-to-use)
(b* (((when (atom efields))
nil)
((std::formal e1) (car efields))
(- (cw "Determining encoder for ~x0... " e1.name))
;; Are we supposed to omit it?
((when (member e1.name omit))
(cw "omitting it.~%")
(make-json-encoder-alist (cdr efields) omit overrides world))
;; Are we supposed to override it?
(look (assoc e1.name overrides))
((when look)
(cw "overriding with ~x0.~%" (cdr look))
(cons (cons e1.name (cdr look))
(make-json-encoder-alist (cdr efields) omit overrides world)))
((unless (and (tuplep 2 e1.guard)
(equal (second e1.guard) e1.name)))
(raise "Guard ~x0 too complex.~%" e1.guard))
(predicate (first e1.guard))
(encoder (get-json-encoder predicate world)))
(cw "defaulting to ~x0~%" encoder)
(cons (cons e1.name encoder)
(make-json-encoder-alist (cdr efields) omit overrides world))))
(define encoder-alist-main-actions
(basename ;; base name for aggregate, e.g., 'vl-location
alist ;; alist of fields->encoder to use
newlines ;; NIL means don't auto-newline between elements; any number means
;; newline and indent to that many places between lines
)
(b* (((when (atom alist))
nil)
((cons fieldname encoder) (car alist))
(foo->bar (std::da-accessor-name basename fieldname))
;; Suppose the fieldname is foo. We create the string ["foo":]. We can
;; create this at macroexpansion time.
(name1 (str::downcase-string (symbol-name fieldname)))
(name1-colon (str::cat "\"" name1 "\": ")))
(list* `(vl-print-str ,name1-colon)
`(,encoder (,foo->bar x))
(if (atom (cdr alist))
nil
(cons (if newlines
`(vl-ps-seq (vl-println ", ")
(vl-indent ,newlines))
`(vl-println? ", "))
(encoder-alist-main-actions basename (cdr alist) newlines))))))
(define convert-flexprod-fields-into-eformals ((x "list of fty::flexprod-fields"))
(b* (((when (atom x))
nil)
((fty::flexprod-field x1) (car x)))
(cons (std::make-formal :name x1.name
:guard (list x1.type x1.name))
(convert-flexprod-fields-into-eformals (cdr x)))))
(define def-vl-jp-aggregate-fn (type omit overrides long newlines world)
(b* ((mksym-package-symbol 'vl::foo)
(elem-print (mksym 'vl-jp- type))
(elem (mksym 'vl- type))
(elem-p (mksym 'vl- type '-p))
(elem-p-str (symbol-name elem-p))
((mv tag efields)
(b* ((agginfo (std::get-aggregate elem world))
((when agginfo)
(cw "Found info for defaggregate ~x0.~%" type)
(mv (std::agginfo->tag agginfo)
(std::agginfo->efields agginfo)))
(prodinfo (fty::get-flexprod-info elem world))
((unless prodinfo)
(mv (raise "Type ~x0 doesn't look like a known defaggregate/defprod?~%" type)
nil))
((fty::prodinfo prodinfo) prodinfo)
(efields (convert-flexprod-fields-into-eformals
(fty::flexprod->fields prodinfo.prod)))
(tag (fty::prodinfo->tag prodinfo)))
(mv tag efields)))
(- (cw "Inferred tag ~x0.~%" tag))
(- (cw "Inferred fields ~x0.~%" efields))
((unless (std::formallist-p efields))
(raise "Expected :efields for ~x0 to be a valid formallist, found ~x1."
elem efields))
(enc-alist (make-json-encoder-alist efields omit overrides world))
((unless (consp enc-alist))
(raise "Expected at least one field to encode."))
(main (encoder-alist-main-actions elem enc-alist newlines)))
`(define ,elem-print ((x ,elem-p) &key (ps 'ps))
:parents (json-encoders)
:short ,(cat "Print the JSON encoding of a @(see " elem-p-str
") to @(see ps).")
:long ,long
(vl-ps-seq
(vl-print "{\"tag\": ")
(jp-sym ',tag)
,(if newlines
`(vl-ps-seq (vl-println ", ")
(vl-indent ,newlines))
`(vl-print ", "))
,@main
(vl-println? "}"))
///
(add-json-encoder ,elem-p ,elem-print))))
#|
(def-vl-jp-aggregate-fn
'location
'(col)
'((filename . blah))
"long"
(w state))
|#
(defmacro def-vl-jp-aggregate (type &key omit override newlines
(long '""))
(declare (xargs :guard (maybe-natp newlines)))
`(make-event
(let ((form (def-vl-jp-aggregate-fn ',type ',omit ',override ',long ',newlines
(w state))))
(value form))))
(logic)
(defmacro def-vl-jp-list (type &key newlines)
(declare (xargs :guard (maybe-natp newlines)))
(b* ((mksym-package-symbol 'vl::foo)
(list-p (mksym 'vl- type 'list-p))
(elem-print (mksym 'vl-jp- type))
(list-print-aux (mksym 'vl-jp- type 'list-aux))
(list-print (mksym 'vl-jp- type 'list))
(list-p-str (symbol-name list-p)))
`(encapsulate ()
(define ,list-print-aux ((x ,list-p) &key (ps 'ps))
:parents (,list-print)
:short ,(cat "Prints out the elements of a @(see " list-p-str
") without the enclosing brackets.")
(if (atom x)
ps
(vl-ps-seq (,elem-print (car x))
(if (atom (cdr x))
ps
,(if newlines
`(vl-ps-seq (vl-println ",")
(vl-indent ,newlines))
`(vl-println? ", ")))
(,list-print-aux (cdr x)))))
(define ,list-print ((x ,list-p) &key (ps 'ps))
:parents (json-encoders)
:short ,(cat "Prints out the elements of a @(see " list-p-str
") with the enclosing brackets.")
(vl-ps-seq (vl-print "[")
(,list-print-aux x)
(vl-println? "]")))
(add-json-encoder ,list-p ,list-print))))
;; Real Verilog JSON Encoding
(define vl-jp-exprtype ((x vl-exprtype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-cstrength ((x vl-cstrength-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-dstrength ((x vl-dstrength-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-direction ((x vl-direction-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-gatetype ((x vl-gatetype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-evatomtype ((x vl-evatomtype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-assign-type ((x vl-assign-type-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-deassign-type ((x vl-deassign-type-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-casecheck ((x vl-casecheck-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-casetype ((x vl-casetype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-taskporttype ((x vl-taskporttype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-alwaystype ((x vl-alwaystype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(add-json-encoder vl-exprtype-p vl-jp-exprtype)
(add-json-encoder vl-cstrength-p vl-jp-cstrength)
(add-json-encoder vl-dstrength-p vl-jp-dstrength)
(add-json-encoder vl-direction-p vl-jp-direction)
(add-json-encoder vl-gatetype-p vl-jp-gatetype)
(add-json-encoder vl-evatomtype-p vl-jp-evatomtype)
(add-json-encoder vl-assign-type-p vl-jp-assign-type)
(add-json-encoder vl-deassign-type-p vl-jp-deassign-type)
(add-json-encoder vl-casetype-p vl-jp-casetype)
(add-json-encoder vl-casecheck-p vl-jp-casecheck)
(add-json-encoder vl-taskporttype-p vl-jp-taskporttype)
(add-json-encoder vl-alwaystype-p vl-jp-alwaystype)
(define vl-jp-maybe-exprtype ((x vl-maybe-exprtype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(if x
(vl-jp-exprtype x)
(vl-print "null")))
(define vl-jp-maybe-cstrength ((x vl-maybe-cstrength-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(if x
(vl-jp-cstrength x)
(vl-print "null")))
(define vl-jp-maybe-direction ((x vl-maybe-direction-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(if x
(vl-jp-direction x)
(vl-print "null")))
(add-json-encoder vl-maybe-exprtype-p vl-jp-maybe-exprtype)
(add-json-encoder vl-maybe-cstrength-p vl-jp-maybe-cstrength)
(add-json-encoder vl-maybe-direction-p vl-jp-maybe-direction)
(def-vl-jp-aggregate location)
#||
(top-level
(vl-cw-ps-seq (vl-jp-location *vl-fakeloc*)))
||#
(def-vl-jp-aggregate constint
:override ((value . jp-bignat))
:long "<p>Note that we always encode the value as a string. This is
because it is quite common for Verilog constants to run into the hundreds
of bits, but the JSON standard doesn't really ever say how big of numbers
must be supported and JSON implementations often use machine integers
which could not hold such large values.</p>")
(define jp-bit ((x vl-bit-p) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a @(see vl-bit-p) as a JSON string."
(jp-str (implode (list (vl-bit->char x)))))
(add-json-encoder vl-bit-p jp-bit)
(define jp-bitlist ((x vl-bitlist-p) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a @(see vl-bitlist-p) as a JSON string."
(jp-str (vl-bitlist->string x)))
(add-json-encoder vl-bitlist-p jp-bitlist)
(define jp-timeunit ((x vl-timeunit-p) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a @(see vl-timeunit-p) as a JSON string."
(jp-str (vl-timeunit->string x)))
(add-json-encoder vl-timeunit-p jp-timeunit)
(define jp-keygutstype ((x vl-keygutstype-p) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a @(see vl-keygutstype-p) as a JSON string."
(jp-str (vl-keygutstype->string x)))
(add-json-encoder vl-keygutstype-p jp-keygutstype)
(define jp-basictypekind ((x vl-basictypekind-p) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a @(see vl-basictypekind-p) as a JSON string."
(jp-str (vl-basictypekind->string x)))
(add-json-encoder vl-basictypekind-p jp-basictypekind)
(def-vl-jp-aggregate weirdint)
(def-vl-jp-aggregate string)
(def-vl-jp-aggregate real)
(def-vl-jp-aggregate id)
(def-vl-jp-aggregate hidpiece)
(def-vl-jp-aggregate sysfunname)
(def-vl-jp-aggregate tagname)
(def-vl-jp-aggregate funname)
(def-vl-jp-aggregate keyguts)
(def-vl-jp-aggregate extint)
(def-vl-jp-aggregate time)
(def-vl-jp-aggregate basictype)
(define vl-jp-atomguts ((x vl-atomguts-p) &key (ps 'ps))
:parents (vl-jp-expr vl-atomguts-p)
:guard-hints (("Goal" :in-theory (enable vl-atomguts-p)))
(case (tag x)
(:vl-id (vl-jp-id x))
(:vl-constint (vl-jp-constint x))
(:vl-weirdint (vl-jp-weirdint x))
(:vl-string (vl-jp-string x))
(:vl-real (vl-jp-real x))
(:vl-hidpiece (vl-jp-hidpiece x))
(:vl-funname (vl-jp-funname x))
(:vl-keyguts (vl-jp-keyguts x))
(:vl-extint (vl-jp-extint x))
(:vl-time (vl-jp-time x))
(:vl-basictype (vl-jp-basictype x))
(:vl-tagname (vl-jp-tagname x))
(otherwise (vl-jp-sysfunname x))))
(add-json-encoder vl-atomguts-p vl-jp-atomguts)
(defines vl-jp-expr
:parents (json-encoders)
(define vl-jp-expr ((x vl-expr-p) &key (ps 'ps))
:measure (two-nats-measure (vl-expr-count x) 0)
(vl-expr-case x
:atom
(jp-object :tag (jp-sym :atom)
:guts (vl-jp-atomguts x.guts)
:finalwidth (jp-maybe-nat x.finalwidth)
:finaltype (vl-jp-maybe-exprtype x.finaltype))
:nonatom
(jp-object :tag (jp-sym :nonatom)
:atts (vl-jp-atts x.atts)
:args (vl-jp-exprlist x.args)
:finalwidth (jp-maybe-nat x.finalwidth)
:finaltype (vl-jp-maybe-exprtype x.finaltype))))
(define vl-jp-atts ((x vl-atts-p) &key (ps 'ps))
:measure (two-nats-measure (vl-atts-count x) 1)
;; Atts are a string->maybe-expr alist, so turn them into a JSON object
;; binding keys to values...
(vl-ps-seq (vl-print "{")
(vl-jp-atts-aux x)
(vl-println? "}")))
(define vl-jp-atts-aux ((x vl-atts-p) &key (ps 'ps))
:measure (two-nats-measure (vl-atts-count x) 0)
(b* ((x (vl-atts-fix x))
((when (atom x))
ps)
((cons name1 val1) (car x)))
(vl-ps-seq (jp-str name1)
(vl-print ": ")
(if val1
(vl-jp-expr val1)
(vl-print "null"))
(if (atom (cdr x))
ps
(vl-println? ", "))
(vl-jp-atts-aux (cdr x)))))
(define vl-jp-exprlist ((x vl-exprlist-p) &key (ps 'ps))
;; Print the expressions as a JSON array with brackets.
:measure (two-nats-measure (vl-exprlist-count x) 1)
(vl-ps-seq (vl-print "[")
(vl-jp-exprlist-aux x)
(vl-println? "]")))
(define vl-jp-exprlist-aux ((x vl-exprlist-p) &key (ps 'ps))
:measure (two-nats-measure (vl-exprlist-count x) 0)
(b* (((when (atom x))
ps))
(vl-ps-seq (vl-jp-expr (car x))
(if (atom (cdr x))
ps
(vl-println? ", "))
(vl-jp-exprlist-aux (cdr x))))))
(define vl-jp-maybe-expr ((x vl-maybe-expr-p) &key (ps 'ps))
(if x
(vl-jp-expr x)
(vl-print "null")))
(add-json-encoder vl-expr-p vl-jp-expr)
(add-json-encoder vl-exprlist-p vl-jp-exprlist)
(add-json-encoder vl-atts-p vl-jp-atts)
(add-json-encoder vl-maybe-expr-p vl-jp-maybe-expr)
(def-vl-jp-aggregate range)
(def-vl-jp-list range)
(define vl-jp-maybe-range ((x vl-maybe-range-p) &key (ps 'ps))
(if x
(vl-jp-range x)
(vl-print "null")))
(add-json-encoder vl-maybe-range-p vl-jp-maybe-range)
(def-vl-jp-aggregate port)
(def-vl-jp-list port :newlines 4)
(def-vl-jp-aggregate gatedelay)
(define vl-jp-maybe-gatedelay ((x vl-maybe-gatedelay-p) &key (ps 'ps))
:parents (json-encoders vl-maybe-gatedelay-p)
(if x
(vl-jp-gatedelay x)
(vl-print "null")))
(add-json-encoder vl-maybe-gatedelay-p vl-jp-maybe-gatedelay)
(def-vl-jp-aggregate plainarg)
(def-vl-jp-list plainarg :newlines 4)
(def-vl-jp-aggregate namedarg)
(def-vl-jp-list namedarg :newlines 4)
(define vl-jp-lifetime ((x vl-lifetime-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-randomqualifier ((x vl-randomqualifier-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-nettypename ((x vl-nettypename-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-coretypename ((x vl-coretypename-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(add-json-encoder vl-lifetime-p vl-jp-lifetime)
(add-json-encoder vl-randomqualifier-p vl-jp-randomqualifier)
(add-json-encoder vl-nettypename-p vl-jp-nettypename)
(add-json-encoder vl-coretypename-p vl-jp-coretypename)
(define vl-jp-packeddimension ((x vl-packeddimension-p) &key (ps 'ps))
:parents (json-encoders)
(if (eq x :vl-unsized-dimension)
(jp-sym x)
(vl-jp-range x)))
(add-json-encoder vl-packeddimension-p vl-jp-packeddimension)
(def-vl-jp-list packeddimension)
(define vl-jp-maybe-packeddimension ((x vl-maybe-packeddimension-p) &key (ps 'ps))
:parents (json-encoders)
(if x
(vl-jp-packeddimension x)
(vl-print "null")))
(add-json-encoder vl-maybe-packeddimension-p vl-jp-maybe-packeddimension)
(define vl-jp-enumbasekind ((x vl-enumbasekind-p) &key (ps 'ps))
:guard-hints(("Goal" :in-theory (enable vl-enumbasekind-p)))
(if (stringp x)
(jp-object :tag (jp-sym :user-defined-type)
:name (jp-str x))
(jp-sym x)))
(add-json-encoder vl-enumbasekind-p vl-jp-enumbasekind)
(def-vl-jp-aggregate enumbasetype)
(def-vl-jp-aggregate enumitem)
(def-vl-jp-list enumitem)
(defines vl-jp-datatype
(define vl-jp-datatype ((x vl-datatype-p) &key (ps 'ps))
:measure (two-nats-measure (vl-datatype-count x) 0)
(vl-datatype-case x
:vl-nettype
(jp-object :tag (jp-sym :vl-nettype)
:name (vl-jp-nettypename x.name)
:signedp (jp-bool x.signedp)
:range (vl-jp-maybe-range x.range))
:vl-coretype
(jp-object :tag (jp-sym :vl-coretype)
:name (vl-jp-coretypename x.name)
:signedp (jp-bool x.signedp)
:dism (vl-jp-packeddimensionlist x.dims))
:vl-struct
(jp-object :tag (jp-sym :vl-struct)
:packedp (jp-bool x.packedp)
:signedp (jp-bool x.signedp)
:dims (vl-jp-packeddimensionlist x.dims)
:members (vl-jp-structmemberlist x.members))
:vl-union
(jp-object :tag (jp-sym :vl-union)
:packedp (jp-bool x.packedp)
:signedp (jp-bool x.signedp)
:taggedp (jp-bool x.taggedp)
:dims (vl-jp-packeddimensionlist x.dims)
:members (vl-jp-structmemberlist x.members))
:vl-enum
(jp-object :tag (jp-sym :vl-enum)
:basetype (vl-jp-enumbasetype x.basetype)
:items (vl-jp-enumitemlist x.items)
:dims (vl-jp-packeddimensionlist x.dims))
:vl-usertype
(jp-object :tag (jp-sym :vl-usertype)
:kind (vl-jp-expr x.kind)
:dims (vl-jp-packeddimensionlist x.dims))))
(define vl-jp-structmemberlist ((x vl-structmemberlist-p) &key (ps 'ps))
;; Print the stmtessions as a JSON array with brackets.
:measure (two-nats-measure (vl-structmemberlist-count x) 1)
(vl-ps-seq (vl-print "[")
(vl-jp-structmemberlist-aux x)
(vl-println? "]")))
(define vl-jp-structmemberlist-aux ((x vl-structmemberlist-p) &key (ps 'ps))
:measure (two-nats-measure (vl-structmemberlist-count x) 0)
(if (atom x)
ps
(vl-ps-seq (vl-jp-structmember (car x))
(if (atom (cdr x))
ps
(vl-println? ", "))
(vl-jp-structmemberlist-aux (cdr x)))))
(define vl-jp-structmember ((x vl-structmember-p) &key (ps 'ps))
:measure (two-nats-measure (vl-structmember-count x) 0)
(b* (((vl-structmember x) x))
(jp-object :tag (jp-sym :vl-structmember)
:atts (vl-jp-atts x.atts)
:rand (vl-jp-randomqualifier x.rand)
:dims (vl-jp-packeddimensionlist x.dims)
:rhs (vl-jp-maybe-expr x.rhs)
:type (vl-jp-datatype x.type)))))
(add-json-encoder vl-datatype-p vl-jp-datatype)
(add-json-encoder vl-structmember-p vl-jp-structmember)
(add-json-encoder vl-structmemberlist-p vl-jp-structmemberlist)
(define vl-jp-maybe-datatype ((x vl-maybe-datatype-p) &key (ps 'ps))
(if x
(vl-jp-datatype x)
(vl-print "null")))
(add-json-encoder vl-maybe-datatype-p vl-jp-maybe-datatype)
(def-vl-jp-aggregate vardecl)
(def-vl-jp-list vardecl :newlines 4)
(define vl-jp-paramtype ((x vl-paramtype-p) &key (ps 'ps))
(vl-paramtype-case x
(:vl-implicitvalueparam
(jp-object :tag (jp-sym :vl-implicitvalueparam)
:sign (jp-sym x.sign)
:range (vl-jp-maybe-range x.range)
:default (vl-jp-maybe-expr x.default)))
(:vl-explicitvalueparam
(jp-object :tag (jp-sym :vl-explicitvalueparam)
:type (vl-jp-datatype x.type)
:default (vl-jp-maybe-expr x.default)))
(:vl-typeparam
(jp-object :tag (jp-sym :vl-typeparam)
:default (vl-jp-maybe-datatype x.default)))))
(add-json-encoder vl-paramtype-p vl-jp-paramtype)
(def-vl-jp-aggregate paramdecl)
(def-vl-jp-list paramdecl :newlines 4)
(define vl-jp-blockitem ((x vl-blockitem-p) &key (ps 'ps))
:guard-hints (("Goal" :in-theory (enable vl-blockitem-p)))
(mbe :logic
(cond ((vl-vardecl-p x) (vl-jp-vardecl x))
(t (vl-jp-paramdecl x)))
:exec
(case (tag x)
(:vl-vardecl (vl-jp-vardecl x))
(otherwise (vl-jp-paramdecl x)))))
(add-json-encoder vl-blockitem-p vl-jp-blockitem)
(def-vl-jp-list blockitem)
(define vl-jp-arguments ((x vl-arguments-p) &key (ps 'ps))
:parents (json-encoders vl-arguments-p)
(vl-arguments-case x
:vl-arguments-named
(jp-object :tag (jp-sym :vl-arguments)
:namedp (jp-bool t)
:starp (jp-bool x.starp)
:args (vl-jp-namedarglist x.args))
:vl-arguments-plain
(jp-object :tag (jp-sym :vl-arguments)
:namedp (jp-bool nil)
:args (vl-jp-plainarglist x.args))))
(add-json-encoder vl-arguments-p vl-jp-arguments)
(def-vl-jp-aggregate gatestrength)
(define vl-jp-maybe-gatestrength ((x vl-maybe-gatestrength-p) &key (ps 'ps))
(if x
(vl-jp-gatestrength x)
(vl-print "null")))
(add-json-encoder vl-maybe-gatestrength-p vl-jp-maybe-gatestrength)
(define vl-jp-paramvalue ((x vl-paramvalue-p) &key (ps 'ps))
:parents (json-encoders vl-paramvalue-p)
(b* ((x (vl-paramvalue-fix x)))
(vl-paramvalue-case x
:expr (vl-jp-expr x)
:datatype (vl-jp-datatype x))))
(add-json-encoder vl-paramvalue-p vl-jp-paramvalue)
(def-vl-jp-list paramvalue)
(define vl-jp-maybe-paramvalue ((x vl-maybe-paramvalue-p) &key (ps 'ps))
(if x
(vl-jp-paramvalue x)
(vl-print "null")))
(add-json-encoder vl-maybe-paramvalue-p vl-jp-maybe-paramvalue)
(def-vl-jp-aggregate namedparamvalue)
(def-vl-jp-list namedparamvalue)
(define vl-jp-paramargs ((x vl-paramargs-p) &key (ps 'ps))
(vl-paramargs-case x
:vl-paramargs-named
(jp-object :tag (jp-sym :vl-paramargs)
:namedp (jp-bool t)
:args (vl-jp-namedparamvaluelist x.args))
:vl-paramargs-plain
(jp-object :tag (jp-sym :vl-paramargs)
:namedp (jp-bool nil)
:args (vl-jp-paramvaluelist x.args))))
(add-json-encoder vl-paramargs-p vl-jp-paramargs)
(def-vl-jp-aggregate modinst)
(def-vl-jp-list modinst)
(def-vl-jp-aggregate gateinst)
(def-vl-jp-list gateinst)
(def-vl-jp-aggregate delaycontrol)
(def-vl-jp-aggregate evatom)
(def-vl-jp-list evatom)
(def-vl-jp-aggregate eventcontrol)
(def-vl-jp-aggregate repeateventcontrol)
(define vl-jp-delayoreventcontrol ((x vl-delayoreventcontrol-p) &key (ps 'ps))
:guard-hints (("Goal" :in-theory (enable vl-delayoreventcontrol-p)))
(cond ((vl-delaycontrol-p x) (vl-jp-delaycontrol x))
((vl-eventcontrol-p x) (vl-jp-eventcontrol x))
(t (vl-jp-repeateventcontrol x))))
(add-json-encoder vl-delayoreventcontrol-p vl-jp-delayoreventcontrol)
(define vl-jp-maybe-delayoreventcontrol ((x vl-maybe-delayoreventcontrol-p)
&key (ps 'ps))
(if x
(vl-jp-delayoreventcontrol x)
(vl-print "null")))
(add-json-encoder vl-maybe-delayoreventcontrol-p vl-jp-maybe-delayoreventcontrol)
(defines vl-jp-stmt
(define vl-jp-stmt ((x vl-stmt-p) &key (ps 'ps))
:measure (two-nats-measure (vl-stmt-count x) 0)
(b* ((kind (vl-stmt-kind x)))
(vl-stmt-case x
:vl-nullstmt
(jp-object :tag (jp-sym kind)
:atts (vl-jp-atts x.atts))
:vl-assignstmt
(jp-object :tag (jp-sym kind)
:lvalue (vl-jp-expr x.lvalue)
:expr (vl-jp-expr x.expr)
:ctrl (vl-jp-maybe-delayoreventcontrol x.ctrl)
:atts (vl-jp-atts x.atts))
:vl-deassignstmt
(jp-object :tag (jp-sym kind)
:lvalue (vl-jp-expr x.lvalue)
:atts (vl-jp-atts x.atts))
:vl-enablestmt
(jp-object :tag (jp-sym kind)
:id (vl-jp-expr x.id)
:args (vl-jp-exprlist x.args)
:atts (vl-jp-atts x.atts))
:vl-disablestmt
(jp-object :tag (jp-sym kind)
:id (vl-jp-expr x.id)
:atts (vl-jp-atts x.atts))
:vl-eventtriggerstmt
(jp-object :tag (jp-sym kind)
:id (vl-jp-expr x.id)
:atts (vl-jp-atts x.atts))
:vl-casestmt
(jp-object :tag (jp-sym kind)
:casetype (vl-jp-casetype x.casetype)
:check (vl-jp-casecheck x.check)
:test (vl-jp-expr x.test)
:default (vl-jp-stmt x.default)
:caselist (vl-jp-cases x.caselist)
:atts (vl-jp-atts x.atts))
:vl-ifstmt
(jp-object :tag (jp-sym kind)
:condition (vl-jp-expr x.condition)
:truebranch (vl-jp-stmt x.truebranch)
:falsebranch (vl-jp-stmt x.falsebranch)
:atts (vl-jp-atts x.atts))
:vl-foreverstmt
(jp-object :tag (jp-sym kind)
:body (vl-jp-stmt x.body)
:atts (vl-jp-atts x.atts))
:vl-waitstmt
(jp-object :tag (jp-sym kind)
:condition (vl-jp-expr x.condition)
:body (vl-jp-stmt x.body)
:atts (vl-jp-atts x.atts))
:vl-whilestmt
(jp-object :tag (jp-sym kind)
:condition (vl-jp-expr x.condition)
:body (vl-jp-stmt x.body)
:atts (vl-jp-atts x.atts))
:vl-forstmt
(jp-object :tag (jp-sym kind)
:initlhs (vl-jp-expr x.initlhs)
:initrhs (vl-jp-expr x.initrhs)
:test (vl-jp-expr x.test)
:nextlhs (vl-jp-expr x.nextlhs)
:nextrhs (vl-jp-expr x.nextrhs)
:body (vl-jp-stmt x.body)
:atts (vl-jp-atts x.atts))
:vl-blockstmt
(jp-object :tag (jp-sym kind)
:sequential (jp-bool x.sequentialp)
:name (jp-maybe-string x.name)
:decls (vl-jp-blockitemlist x.decls)
:stmts (vl-jp-stmtlist x.stmts)
:atts (vl-jp-atts x.atts))
:vl-repeatstmt
(jp-object :tag (jp-sym kind)
:condition (vl-jp-expr x.condition)
:body (vl-jp-stmt x.body)
:atts (vl-jp-atts x.atts))
:vl-timingstmt
(jp-object :tag (jp-sym kind)
:ctrl (vl-jp-delayoreventcontrol x.ctrl)
:body (vl-jp-stmt x.body)
:atts (vl-jp-atts x.atts))
)))
(define vl-jp-stmtlist ((x vl-stmtlist-p) &key (ps 'ps))
;; Print the stmtessions as a JSON array with brackets.
:measure (two-nats-measure (vl-stmtlist-count x) 1)
(vl-ps-seq (vl-print "[")
(vl-jp-stmtlist-aux x)
(vl-println? "]")))
(define vl-jp-stmtlist-aux ((x vl-stmtlist-p) &key (ps 'ps))
:measure (two-nats-measure (vl-stmtlist-count x) 0)
(b* (((when (atom x))
ps))
(vl-ps-seq (vl-jp-stmt (car x))
(if (atom (cdr x))
ps
(vl-println? ", "))
(vl-jp-stmtlist-aux (cdr x)))))
(define vl-jp-cases ((x vl-caselist-p) &key (ps 'ps))
;; Print the stmtessions as a JSON array with brackets.
:measure (two-nats-measure (vl-caselist-count x) 1)
(vl-ps-seq (vl-print "[")
(vl-jp-cases-aux x)
(vl-println? "]")))
(define vl-jp-cases-aux ((x vl-caselist-p) &key (ps 'ps))
;; Print the stmtessions as a JSON array with brackets.
:measure (two-nats-measure (vl-caselist-count x) 0)
(b* ((x (vl-caselist-fix x))
((when (atom x))
ps)
((cons exprs stmt1) (car x)))
(vl-ps-seq (vl-print "[")
(vl-jp-exprlist exprs)
(vl-println? ",")
(vl-jp-stmt stmt1)
(vl-println? "]")
(if (atom (cdr x))
ps
(vl-println? ", "))
(vl-jp-cases-aux (cdr x))))))
(add-json-encoder vl-stmt-p vl-jp-stmt)
(add-json-encoder vl-stmtlist-p vl-jp-stmtlist)
(add-json-encoder vl-caselist-p vl-jp-cases)
(def-vl-jp-aggregate always)
(def-vl-jp-list always :newlines 4)
(def-vl-jp-aggregate initial)
(def-vl-jp-list initial :newlines 4)
(def-vl-jp-aggregate taskport)
(def-vl-jp-list taskport :newlines 4)
(def-vl-jp-aggregate fundecl)
(def-vl-jp-list fundecl :newlines 4)
(def-vl-jp-aggregate taskdecl)
(def-vl-jp-list taskdecl :newlines 4)
(def-vl-jp-aggregate portdecl)
(def-vl-jp-list portdecl :newlines 4)
(def-vl-jp-aggregate assign)
(def-vl-jp-list assign :newlines 4)
(define vl-jp-warning ((x vl-warning-p) &key (ps 'ps))
:parents (json-encoders)
:short "Special, custom JSON encoder for warnings."
:long "<p>We probably don't want to use the ordinary aggregate-encoding stuff
to print @(see vl-warning-p) objects, since the types in the @(':args') field
are dynamic and, besides, who wants to reimplement @(see vl-cw) in other
languages. Instead, it's probably more convenient to just go ahead and convert
the warning into a printed message here. We'll include both HTML and plain
TEXT versions of the message.</p>"
(b* (((vl-warning x) x)
(text (with-local-ps (vl-cw-obj x.msg x.args)))
(html (with-local-ps (vl-ps-update-htmlp t)
(vl-cw-obj x.msg x.args))))
(jp-object :tag (vl-print "\"warning\"")
:fatalp (jp-bool x.fatalp)
:type (jp-str (symbol-name x.type))
:fn (jp-str (symbol-name x.fn))
:text (jp-str text)
:html (jp-str html))))
(add-json-encoder vl-warning-p jp-warning)
(def-vl-jp-list warning :newlines 4)
(define vl-jp-commentmap-aux ((x vl-commentmap-p) &key (ps 'ps))
(b* (((when (atom x))
ps))
(vl-ps-seq (vl-print "{\"loc\": ")
(vl-jp-location (caar x))
(vl-println? ", \"comment\": ")
(jp-str (cdar x))
(vl-print "}")
(if (atom (cdr x))
ps
(vl-println? ", "))
(vl-jp-commentmap-aux (cdr x)))))
(define vl-jp-commentmap ((x vl-commentmap-p) &key (ps 'ps))
(vl-ps-seq (vl-print "[")
(vl-jp-commentmap-aux x)
(vl-println? "]")))
(add-json-encoder vl-commentmap-p vl-jp-commentmap)
(def-vl-jp-aggregate modport-port)
(def-vl-jp-list modport-port)
(def-vl-jp-aggregate modport)
(def-vl-jp-aggregate alias)
(define vl-jp-fwdtypedefkind ((x vl-fwdtypedefkind-p) &key (ps 'ps))
(jp-str (case x
(:vl-enum "enum")
(:vl-struct "struct")
(:vl-union "union")
(:vl-class "class")
(:vl-interfaceclass "interfaceclass")))
///
(add-json-encoder vl-fwdtypedefkind-p vl-jp-fwdtypedefkind))
(def-vl-jp-aggregate fwdtypedef)
(define vl-jp-modelement ((x vl-modelement-p) &key (ps 'ps))
:guard-hints (("goal" :in-theory (enable vl-modelement-p)))
(case (tag x)
(:VL-PORT (VL-jp-PORT X))
(:VL-PORTDECL (VL-jp-PORTDECL X))
(:VL-ASSIGN (VL-jp-ASSIGN X))
(:VL-ALIAS (VL-jp-ALIAS X))
(:VL-VARDECL (VL-jp-VARDECL X))
(:VL-PARAMDECL (VL-jp-PARAMDECL X))
(:VL-FUNDECL (VL-jp-FUNDECL X))
(:VL-TASKDECL (VL-jp-TASKDECL X))
(:VL-MODINST (VL-jp-MODINST X))
(:VL-GATEINST (VL-jp-GATEINST X))
(:VL-ALWAYS (VL-jp-ALWAYS X))
(:VL-INITIAL (VL-jp-INITIAL X))
;; BOZO implement typedef
(:VL-TYPEDEF ps)
(:VL-FWDTYPEDEF (VL-jp-FWDTYPEDEF X))
(OTHERWISE (VL-jp-MODPORT X))))
(def-vl-jp-list modelement)
(define vl-jp-genelement ((x vl-genelement-p) &key (ps 'ps))
(vl-genelement-case x
:vl-genbase (vl-jp-modelement x.item)
;; BOZO implement generates
:otherwise ps)
///
(add-json-encoder vl-genelement-p vl-jp-genelement))
(def-vl-jp-list genelement)
(def-vl-jp-aggregate module
:omit (params esim)
:newlines 2)
(def-vl-jp-list module
:newlines 1)
(define vl-jp-modalist-aux ((x vl-modalist-p) &key (ps 'ps))
(b* (((when (atom x))
ps))
(vl-ps-seq (jp-str (caar x))
(vl-print ": ")
(vl-jp-module (cdar x))
(if (atom (cdr x))
ps
(vl-println ", "))
(vl-jp-modalist-aux (cdr x)))))
(define vl-jp-modalist ((x vl-modalist-p) &key (ps 'ps))
(vl-ps-seq (vl-print "{")
(vl-jp-modalist-aux x)
(vl-println "}")))
(define vl-jp-individual-modules ((x vl-modulelist-p) &key (ps 'ps))
;; This doesn't print a single valid JSON object. Instead, it prints a whole
;; list of JSON objects separated by newlines.
(if (atom x)
ps
(vl-ps-seq (vl-jp-module (car x))
(vl-print "
")
(vl-jp-individual-modules (cdr x)))))
| 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 "fmt")
(include-book "find-module")
(include-book "centaur/bridge/to-json" :dir :system)
(local (include-book "../util/arithmetic"))
(defsection json-printing
:parents (printer)
:short "Routines for encoding various ACL2 structures into <a
href='http://www.json.org/'>JSON</a> format."
:long "<p>This is a collection of printing routines for translating ACL2
structures into JSON format. These routines are mainly meant to make it easy
to convert @(see vl) @(see syntax) into nice JSON data, but are somewhat
flexible and may be useful for other applications.</p>")
(defsection json-encoders
:parents (json-printing)
:short "A table of JSON encoders to use for for different kinds of data."
:long "<p>A JSON encoder is a function of the following signature:</p>
@({ encode-foo : foo * ps --> ps })
<p>Where @('foo') is expected to be an object of some type @('foop'), and
@('ps') is the @(see vl) @(see printer) state stobj, @(see ps). Each such
routine is responsible for printing a JSON encoding of its @('foop') argument.
Each such function may assume that @(see ps) is set to text mode.</p>
<p>The encoder table is a simple association of @('foop') to @('encode-foo')
functions. We can use it to automatically generate encoders for, e.g., @(see
defaggregate) structures.</p>"
(table vl-json)
(table vl-json 'encoders
;; Alist binding each recognizer foop to its JSON encoder, vl-jp-foo
)
(defun get-json-encoders (world)
"Look up the current alist of json encoders."
(declare (xargs :mode :program))
(cdr (assoc 'encoders (table-alist 'vl-json world))))
(defmacro add-json-encoder (foop encoder-fn)
(declare (xargs :guard (and (symbolp foop)
(symbolp encoder-fn))))
`(table vl-json 'encoders
(cons (cons ',foop ',encoder-fn)
(get-json-encoders world))))
(defun get-json-encoder (foop world)
(declare (xargs :mode :program))
(let ((entry (assoc foop (get-json-encoders world))))
(if entry
(cdr entry)
(er hard? 'get-json-encoder
"No json encoder defined for ~x0.~%" foop)))))
#||
(get-json-encoders (w state))
(add-json-encoder barp vl-enc-bar)
(get-json-encoders (w state))
(get-json-encoder 'barp (w state)) ;; vl-enc-bar
(get-json-encoder 'foop (w state)) ;; fail, no encoder defined
||#
(define jp-bool ((x booleanp) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a @(see booleanp) into JSON as @('true') or @('false')."
(if x
(vl-print-str "true")
(vl-print-str "false")))
(add-json-encoder booleanp jp-bool)
(add-json-encoder not jp-bool)
(define jp-col-after-printing-string-aux
((col natp "Current column we're at.")
(x stringp "String we're about to print, not yet reversed.")
(n natp "Current position in X.")
(xl natp "Pre-computed length of X."))
:returns (new-col natp :rule-classes :type-prescription)
:parents (jp-str)
:short "Fast way to figure out the new column after printing a JSON string
with proper encoding."
:guard (and (<= n xl)
(= xl (length x)))
:measure (nfix (- (nfix xl) (nfix n)))
(declare (type (integer 0 *) col n xl)
(type string x))
(b* (((when (mbe :logic (zp (- (nfix xl) (nfix n)))
:exec (= n xl)))
(lnfix col))
((the (unsigned-byte 8) code) (char-code (char x n)))
((when (or (<= code 31)
(>= code 127)))
;; This is a "json weird char." Our encoder will turn it into
;; \uXXXX. The length of \uXXXX is 6.
(jp-col-after-printing-string-aux (+ 6 col) x (+ 1 (lnfix n)) xl)))
;; Else there is only one character.
(jp-col-after-printing-string-aux (+ 1 col) x (+ 1 (lnfix n)) xl)))
(define jp-str ((x :type string) &key (ps 'ps))
:parents (json-encoders)
:short "Print the JSON encoding of a string, handling all escaping correctly
and including the surrounding quotes."
:long "<p>We go to some effort to make this fast.</p>"
(b* ((rchars (vl-ps->rchars))
(col (vl-ps->col))
(xl (length x))
(rchars (cons #\" (bridge::json-encode-str-aux x 0 xl (cons #\" rchars))))
(col (+ 2 (jp-col-after-printing-string-aux col x 0 xl))))
(vl-ps-seq
(vl-ps-update-rchars rchars)
(vl-ps-update-col col)))
:prepwork
((local (defthm l0
(implies (and (vl-printedlist-p acc)
(character-listp x))
(vl-printedlist-p (bridge::json-encode-chars x acc)))
:hints(("Goal"
:in-theory (e/d (bridge::json-encode-chars
bridge::json-encode-char
bridge::json-encode-weird-char)
(digit-to-char))))))))
(add-json-encoder stringp jp-str)
(define jp-maybe-string ((x maybe-stringp) &key (ps 'ps))
:parents (json-encoders)
(if x
(jp-str x)
(vl-print "null")))
(add-json-encoder maybe-stringp jp-maybe-string)
(define jp-bignat ((x natp) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a potentially large natural number as a JSON string."
(vl-print-str (str::natstr x)))
(define jp-nat ((x natp) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a probably small natural number as a JSON number."
:long "<p>We require that the integer is at most 2^31, which we think is the
minimum reasonable size for a JSON implementation to support.</p>"
(b* (((unless (<= x (expt 2 31)))
(raise "Scarily trying to JSON-encode large natural: ~x0." x)
ps))
(vl-print-nat x)))
(define jp-maybe-nat ((x maybe-natp) &key (ps 'ps))
:parents (json-encoders)
(if x
(jp-nat x)
(vl-print-str "null")))
(add-json-encoder natp jp-nat)
(add-json-encoder posp jp-nat)
(add-json-encoder maybe-natp jp-maybe-nat)
(add-json-encoder maybe-posp jp-maybe-nat)
(define jp-sym-main ((x symbolp) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a simple symbol as a JSON string, including the surrounding
quotes."
:long "<p>We assume that @('x') has a simple enough name to print without any
encoding. This is generally true for keyword constants used as tags and in
basic enumerations like @(see vl-exprtype-p). We print only the symbol name,
in lower-case.</p>"
(vl-ps-seq (vl-print "\"")
(vl-print-str (str::downcase-string (symbol-name x)))
(vl-print "\"")))
(defsection jp-sym
:parents (json-encoders)
:short "Optimized version of @(see jp-sym-main)."
:long "<p>This is a simple macro that is meant to be the same as @(see
jp-sym-main). The only difference is that if we are given a literal symbol,
e.g., @(':foo'), we can do the string manipulation at compile time.</p>"
(defmacro jp-sym (x &key (ps 'ps))
(if (or (keywordp x)
(booleanp x)
(and (quotep x)
(symbolp (acl2::unquote x))))
;; Yes, want to optimize.
(let* ((guts (if (quotep x) (acl2::unquote x) x))
(ans (str::cat "\""
(str::downcase-string (symbol-name guts))
"\"")))
`(vl-print-str ,ans :ps ,ps))
`(jp-sym-main ,x :ps ,ps))))
#||
(top-level (vl-cw-ps-seq (jp-sym :foo))) ;; "foo"
(top-level (vl-cw-ps-seq (jp-sym t))) ;; "t"
(top-level (vl-cw-ps-seq (jp-sym nil))) ;; "nil"
(top-level (vl-cw-ps-seq (jp-sym 'bar))) ;; "bar"
(top-level (let ((x 'baz))
(vl-cw-ps-seq (jp-sym x)))) ;; "baz"
||#
(defsection jp-object
:parents (json-encoders)
:short "Utility for printing JSON <i>objects</i>, which in some other
languages might be called alists, dictionaries, hashes, records, etc."
:long "<p>Syntax Example:</p>
@({
(jp-object :tag (vl-print \"loc\")
:file (vl-print x.filename)
:line (vl-print x.line)
:col (vl-print x.col))
--->
{ \"tag\": \"loc\", \"file\": ... }
})
<p>The arguments to @('jp-object') should be an alternating list of literal
keywords, which (for better performance) we assume are so simple they do not
need to be encoded, and printing expressions which should handle any necessary
encoding.</p>"
:autodoc nil
(defun jp-object-aux (forms)
(declare (xargs :guard t))
(b* (((when (atom forms))
nil)
((unless (keywordp (car forms)))
(er hard? 'jp-object "Expected alternating keywords and values."))
((unless (consp (cdr forms)))
(er hard? 'jp-object "No argument found after ~x0." (car forms)))
;; Suppose the keyword is :foo.
;; We create the string: "foo":
;; We can create this at macroexpansion time.
(name1 (str::downcase-string (symbol-name (car forms))))
(name1-colon (str::cat "\"" name1 "\": ")))
(list* `(vl-print-str ,name1-colon)
(second forms)
(if (atom (cddr forms))
nil
(cons `(vl-println? ", ")
(jp-object-aux (cddr forms)))))))
(defmacro jp-object (&rest forms)
`(vl-ps-seq (vl-print "{")
,@(jp-object-aux forms)
(vl-println? "}"))))
; Fancy automatic json encoding of std structures
(program)
(define make-json-encoder-alist
(efields ;; A proper std::formallist-p for this structure's fields
omit ;; A list of any fields to omit from the encoded output
overrides ;; An alist of (fieldname . encoder-to-use-instead-of-default)
world ;; For looking up default encoders
)
;; Returns an alist of the form (fieldname . encoder-to-use)
(b* (((when (atom efields))
nil)
((std::formal e1) (car efields))
(- (cw "Determining encoder for ~x0... " e1.name))
;; Are we supposed to omit it?
((when (member e1.name omit))
(cw "omitting it.~%")
(make-json-encoder-alist (cdr efields) omit overrides world))
;; Are we supposed to override it?
(look (assoc e1.name overrides))
((when look)
(cw "overriding with ~x0.~%" (cdr look))
(cons (cons e1.name (cdr look))
(make-json-encoder-alist (cdr efields) omit overrides world)))
((unless (and (tuplep 2 e1.guard)
(equal (second e1.guard) e1.name)))
(raise "Guard ~x0 too complex.~%" e1.guard))
(predicate (first e1.guard))
(encoder (get-json-encoder predicate world)))
(cw "defaulting to ~x0~%" encoder)
(cons (cons e1.name encoder)
(make-json-encoder-alist (cdr efields) omit overrides world))))
(define encoder-alist-main-actions
(basename ;; base name for aggregate, e.g., 'vl-location
alist ;; alist of fields->encoder to use
newlines ;; NIL means don't auto-newline between elements; any number means
;; newline and indent to that many places between lines
)
(b* (((when (atom alist))
nil)
((cons fieldname encoder) (car alist))
(foo->bar (std::da-accessor-name basename fieldname))
;; Suppose the fieldname is foo. We create the string ["foo":]. We can
;; create this at macroexpansion time.
(name1 (str::downcase-string (symbol-name fieldname)))
(name1-colon (str::cat "\"" name1 "\": ")))
(list* `(vl-print-str ,name1-colon)
`(,encoder (,foo->bar x))
(if (atom (cdr alist))
nil
(cons (if newlines
`(vl-ps-seq (vl-println ", ")
(vl-indent ,newlines))
`(vl-println? ", "))
(encoder-alist-main-actions basename (cdr alist) newlines))))))
(define convert-flexprod-fields-into-eformals ((x "list of fty::flexprod-fields"))
(b* (((when (atom x))
nil)
((fty::flexprod-field x1) (car x)))
(cons (std::make-formal :name x1.name
:guard (list x1.type x1.name))
(convert-flexprod-fields-into-eformals (cdr x)))))
(define def-vl-jp-aggregate-fn (type omit overrides long newlines world)
(b* ((mksym-package-symbol 'vl::foo)
(elem-print (mksym 'vl-jp- type))
(elem (mksym 'vl- type))
(elem-p (mksym 'vl- type '-p))
(elem-p-str (symbol-name elem-p))
((mv tag efields)
(b* ((agginfo (std::get-aggregate elem world))
((when agginfo)
(cw "Found info for defaggregate ~x0.~%" type)
(mv (std::agginfo->tag agginfo)
(std::agginfo->efields agginfo)))
(prodinfo (fty::get-flexprod-info elem world))
((unless prodinfo)
(mv (raise "Type ~x0 doesn't look like a known defaggregate/defprod?~%" type)
nil))
((fty::prodinfo prodinfo) prodinfo)
(efields (convert-flexprod-fields-into-eformals
(fty::flexprod->fields prodinfo.prod)))
(tag (fty::prodinfo->tag prodinfo)))
(mv tag efields)))
(- (cw "Inferred tag ~x0.~%" tag))
(- (cw "Inferred fields ~x0.~%" efields))
((unless (std::formallist-p efields))
(raise "Expected :efields for ~x0 to be a valid formallist, found ~x1."
elem efields))
(enc-alist (make-json-encoder-alist efields omit overrides world))
((unless (consp enc-alist))
(raise "Expected at least one field to encode."))
(main (encoder-alist-main-actions elem enc-alist newlines)))
`(define ,elem-print ((x ,elem-p) &key (ps 'ps))
:parents (json-encoders)
:short ,(cat "Print the JSON encoding of a @(see " elem-p-str
") to @(see ps).")
:long ,long
(vl-ps-seq
(vl-print "{\"tag\": ")
(jp-sym ',tag)
,(if newlines
`(vl-ps-seq (vl-println ", ")
(vl-indent ,newlines))
`(vl-print ", "))
,@main
(vl-println? "}"))
///
(add-json-encoder ,elem-p ,elem-print))))
#|
(def-vl-jp-aggregate-fn
'location
'(col)
'((filename . blah))
"long"
(w state))
|#
(defmacro def-vl-jp-aggregate (type &key omit override newlines
(long '""))
(declare (xargs :guard (maybe-natp newlines)))
`(make-event
(let ((form (def-vl-jp-aggregate-fn ',type ',omit ',override ',long ',newlines
(w state))))
(value form))))
(logic)
(defmacro def-vl-jp-list (type &key newlines)
(declare (xargs :guard (maybe-natp newlines)))
(b* ((mksym-package-symbol 'vl::foo)
(list-p (mksym 'vl- type 'list-p))
(elem-print (mksym 'vl-jp- type))
(list-print-aux (mksym 'vl-jp- type 'list-aux))
(list-print (mksym 'vl-jp- type 'list))
(list-p-str (symbol-name list-p)))
`(encapsulate ()
(define ,list-print-aux ((x ,list-p) &key (ps 'ps))
:parents (,list-print)
:short ,(cat "Prints out the elements of a @(see " list-p-str
") without the enclosing brackets.")
(if (atom x)
ps
(vl-ps-seq (,elem-print (car x))
(if (atom (cdr x))
ps
,(if newlines
`(vl-ps-seq (vl-println ",")
(vl-indent ,newlines))
`(vl-println? ", ")))
(,list-print-aux (cdr x)))))
(define ,list-print ((x ,list-p) &key (ps 'ps))
:parents (json-encoders)
:short ,(cat "Prints out the elements of a @(see " list-p-str
") with the enclosing brackets.")
(vl-ps-seq (vl-print "[")
(,list-print-aux x)
(vl-println? "]")))
(add-json-encoder ,list-p ,list-print))))
;; Real Verilog JSON Encoding
(define vl-jp-exprtype ((x vl-exprtype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-cstrength ((x vl-cstrength-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-dstrength ((x vl-dstrength-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-direction ((x vl-direction-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-gatetype ((x vl-gatetype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-evatomtype ((x vl-evatomtype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-assign-type ((x vl-assign-type-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-deassign-type ((x vl-deassign-type-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-casecheck ((x vl-casecheck-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-casetype ((x vl-casetype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-taskporttype ((x vl-taskporttype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-alwaystype ((x vl-alwaystype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(add-json-encoder vl-exprtype-p vl-jp-exprtype)
(add-json-encoder vl-cstrength-p vl-jp-cstrength)
(add-json-encoder vl-dstrength-p vl-jp-dstrength)
(add-json-encoder vl-direction-p vl-jp-direction)
(add-json-encoder vl-gatetype-p vl-jp-gatetype)
(add-json-encoder vl-evatomtype-p vl-jp-evatomtype)
(add-json-encoder vl-assign-type-p vl-jp-assign-type)
(add-json-encoder vl-deassign-type-p vl-jp-deassign-type)
(add-json-encoder vl-casetype-p vl-jp-casetype)
(add-json-encoder vl-casecheck-p vl-jp-casecheck)
(add-json-encoder vl-taskporttype-p vl-jp-taskporttype)
(add-json-encoder vl-alwaystype-p vl-jp-alwaystype)
(define vl-jp-maybe-exprtype ((x vl-maybe-exprtype-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(if x
(vl-jp-exprtype x)
(vl-print "null")))
(define vl-jp-maybe-cstrength ((x vl-maybe-cstrength-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(if x
(vl-jp-cstrength x)
(vl-print "null")))
(define vl-jp-maybe-direction ((x vl-maybe-direction-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(if x
(vl-jp-direction x)
(vl-print "null")))
(add-json-encoder vl-maybe-exprtype-p vl-jp-maybe-exprtype)
(add-json-encoder vl-maybe-cstrength-p vl-jp-maybe-cstrength)
(add-json-encoder vl-maybe-direction-p vl-jp-maybe-direction)
(def-vl-jp-aggregate location)
#||
(top-level
(vl-cw-ps-seq (vl-jp-location *vl-fakeloc*)))
||#
(def-vl-jp-aggregate constint
:override ((value . jp-bignat))
:long "<p>Note that we always encode the value as a string. This is
because it is quite common for Verilog constants to run into the hundreds
of bits, but the JSON standard doesn't really ever say how big of numbers
must be supported and JSON implementations often use machine integers
which could not hold such large values.</p>")
(define jp-bit ((x vl-bit-p) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a @(see vl-bit-p) as a JSON string."
(jp-str (implode (list (vl-bit->char x)))))
(add-json-encoder vl-bit-p jp-bit)
(define jp-bitlist ((x vl-bitlist-p) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a @(see vl-bitlist-p) as a JSON string."
(jp-str (vl-bitlist->string x)))
(add-json-encoder vl-bitlist-p jp-bitlist)
(define jp-timeunit ((x vl-timeunit-p) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a @(see vl-timeunit-p) as a JSON string."
(jp-str (vl-timeunit->string x)))
(add-json-encoder vl-timeunit-p jp-timeunit)
(define jp-keygutstype ((x vl-keygutstype-p) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a @(see vl-keygutstype-p) as a JSON string."
(jp-str (vl-keygutstype->string x)))
(add-json-encoder vl-keygutstype-p jp-keygutstype)
(define jp-basictypekind ((x vl-basictypekind-p) &key (ps 'ps))
:parents (json-encoders)
:short "Encode a @(see vl-basictypekind-p) as a JSON string."
(jp-str (vl-basictypekind->string x)))
(add-json-encoder vl-basictypekind-p jp-basictypekind)
(def-vl-jp-aggregate weirdint)
(def-vl-jp-aggregate string)
(def-vl-jp-aggregate real)
(def-vl-jp-aggregate id)
(def-vl-jp-aggregate hidpiece)
(def-vl-jp-aggregate sysfunname)
(def-vl-jp-aggregate tagname)
(def-vl-jp-aggregate funname)
(def-vl-jp-aggregate keyguts)
(def-vl-jp-aggregate extint)
(def-vl-jp-aggregate time)
(def-vl-jp-aggregate basictype)
(define vl-jp-atomguts ((x vl-atomguts-p) &key (ps 'ps))
:parents (vl-jp-expr vl-atomguts-p)
:guard-hints (("Goal" :in-theory (enable vl-atomguts-p)))
(case (tag x)
(:vl-id (vl-jp-id x))
(:vl-constint (vl-jp-constint x))
(:vl-weirdint (vl-jp-weirdint x))
(:vl-string (vl-jp-string x))
(:vl-real (vl-jp-real x))
(:vl-hidpiece (vl-jp-hidpiece x))
(:vl-funname (vl-jp-funname x))
(:vl-keyguts (vl-jp-keyguts x))
(:vl-extint (vl-jp-extint x))
(:vl-time (vl-jp-time x))
(:vl-basictype (vl-jp-basictype x))
(:vl-tagname (vl-jp-tagname x))
(otherwise (vl-jp-sysfunname x))))
(add-json-encoder vl-atomguts-p vl-jp-atomguts)
(defines vl-jp-expr
:parents (json-encoders)
(define vl-jp-expr ((x vl-expr-p) &key (ps 'ps))
:measure (two-nats-measure (vl-expr-count x) 0)
(vl-expr-case x
:atom
(jp-object :tag (jp-sym :atom)
:guts (vl-jp-atomguts x.guts)
:finalwidth (jp-maybe-nat x.finalwidth)
:finaltype (vl-jp-maybe-exprtype x.finaltype))
:nonatom
(jp-object :tag (jp-sym :nonatom)
:atts (vl-jp-atts x.atts)
:args (vl-jp-exprlist x.args)
:finalwidth (jp-maybe-nat x.finalwidth)
:finaltype (vl-jp-maybe-exprtype x.finaltype))))
(define vl-jp-atts ((x vl-atts-p) &key (ps 'ps))
:measure (two-nats-measure (vl-atts-count x) 1)
;; Atts are a string->maybe-expr alist, so turn them into a JSON object
;; binding keys to values...
(vl-ps-seq (vl-print "{")
(vl-jp-atts-aux x)
(vl-println? "}")))
(define vl-jp-atts-aux ((x vl-atts-p) &key (ps 'ps))
:measure (two-nats-measure (vl-atts-count x) 0)
(b* ((x (vl-atts-fix x))
((when (atom x))
ps)
((cons name1 val1) (car x)))
(vl-ps-seq (jp-str name1)
(vl-print ": ")
(if val1
(vl-jp-expr val1)
(vl-print "null"))
(if (atom (cdr x))
ps
(vl-println? ", "))
(vl-jp-atts-aux (cdr x)))))
(define vl-jp-exprlist ((x vl-exprlist-p) &key (ps 'ps))
;; Print the expressions as a JSON array with brackets.
:measure (two-nats-measure (vl-exprlist-count x) 1)
(vl-ps-seq (vl-print "[")
(vl-jp-exprlist-aux x)
(vl-println? "]")))
(define vl-jp-exprlist-aux ((x vl-exprlist-p) &key (ps 'ps))
:measure (two-nats-measure (vl-exprlist-count x) 0)
(b* (((when (atom x))
ps))
(vl-ps-seq (vl-jp-expr (car x))
(if (atom (cdr x))
ps
(vl-println? ", "))
(vl-jp-exprlist-aux (cdr x))))))
(define vl-jp-maybe-expr ((x vl-maybe-expr-p) &key (ps 'ps))
(if x
(vl-jp-expr x)
(vl-print "null")))
(add-json-encoder vl-expr-p vl-jp-expr)
(add-json-encoder vl-exprlist-p vl-jp-exprlist)
(add-json-encoder vl-atts-p vl-jp-atts)
(add-json-encoder vl-maybe-expr-p vl-jp-maybe-expr)
(def-vl-jp-aggregate range)
(def-vl-jp-list range)
(define vl-jp-maybe-range ((x vl-maybe-range-p) &key (ps 'ps))
(if x
(vl-jp-range x)
(vl-print "null")))
(add-json-encoder vl-maybe-range-p vl-jp-maybe-range)
(def-vl-jp-aggregate port)
(def-vl-jp-list port :newlines 4)
(def-vl-jp-aggregate gatedelay)
(define vl-jp-maybe-gatedelay ((x vl-maybe-gatedelay-p) &key (ps 'ps))
:parents (json-encoders vl-maybe-gatedelay-p)
(if x
(vl-jp-gatedelay x)
(vl-print "null")))
(add-json-encoder vl-maybe-gatedelay-p vl-jp-maybe-gatedelay)
(def-vl-jp-aggregate plainarg)
(def-vl-jp-list plainarg :newlines 4)
(def-vl-jp-aggregate namedarg)
(def-vl-jp-list namedarg :newlines 4)
(define vl-jp-lifetime ((x vl-lifetime-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-randomqualifier ((x vl-randomqualifier-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-nettypename ((x vl-nettypename-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(define vl-jp-coretypename ((x vl-coretypename-p) &key (ps 'ps))
:parents (json-encoders)
:inline t
(jp-sym x))
(add-json-encoder vl-lifetime-p vl-jp-lifetime)
(add-json-encoder vl-randomqualifier-p vl-jp-randomqualifier)
(add-json-encoder vl-nettypename-p vl-jp-nettypename)
(add-json-encoder vl-coretypename-p vl-jp-coretypename)
(define vl-jp-packeddimension ((x vl-packeddimension-p) &key (ps 'ps))
:parents (json-encoders)
(if (eq x :vl-unsized-dimension)
(jp-sym x)
(vl-jp-range x)))
(add-json-encoder vl-packeddimension-p vl-jp-packeddimension)
(def-vl-jp-list packeddimension)
(define vl-jp-maybe-packeddimension ((x vl-maybe-packeddimension-p) &key (ps 'ps))
:parents (json-encoders)
(if x
(vl-jp-packeddimension x)
(vl-print "null")))
(add-json-encoder vl-maybe-packeddimension-p vl-jp-maybe-packeddimension)
(define vl-jp-enumbasekind ((x vl-enumbasekind-p) &key (ps 'ps))
:guard-hints(("Goal" :in-theory (enable vl-enumbasekind-p)))
(if (stringp x)
(jp-object :tag (jp-sym :user-defined-type)
:name (jp-str x))
(jp-sym x)))
(add-json-encoder vl-enumbasekind-p vl-jp-enumbasekind)
(def-vl-jp-aggregate enumbasetype)
(def-vl-jp-aggregate enumitem)
(def-vl-jp-list enumitem)
(defines vl-jp-datatype
(define vl-jp-datatype ((x vl-datatype-p) &key (ps 'ps))
:measure (two-nats-measure (vl-datatype-count x) 0)
(vl-datatype-case x
:vl-nettype
(jp-object :tag (jp-sym :vl-nettype)
:name (vl-jp-nettypename x.name)
:signedp (jp-bool x.signedp)
:range (vl-jp-maybe-range x.range))
:vl-coretype
(jp-object :tag (jp-sym :vl-coretype)
:name (vl-jp-coretypename x.name)
:signedp (jp-bool x.signedp)
:dism (vl-jp-packeddimensionlist x.dims))
:vl-struct
(jp-object :tag (jp-sym :vl-struct)
:packedp (jp-bool x.packedp)
:signedp (jp-bool x.signedp)
:dims (vl-jp-packeddimensionlist x.dims)
:members (vl-jp-structmemberlist x.members))
:vl-union
(jp-object :tag (jp-sym :vl-union)
:packedp (jp-bool x.packedp)
:signedp (jp-bool x.signedp)
:taggedp (jp-bool x.taggedp)
:dims (vl-jp-packeddimensionlist x.dims)
:members (vl-jp-structmemberlist x.members))
:vl-enum
(jp-object :tag (jp-sym :vl-enum)
:basetype (vl-jp-enumbasetype x.basetype)
:items (vl-jp-enumitemlist x.items)
:dims (vl-jp-packeddimensionlist x.dims))
:vl-usertype
(jp-object :tag (jp-sym :vl-usertype)
:kind (vl-jp-expr x.kind)
:dims (vl-jp-packeddimensionlist x.dims))))
(define vl-jp-structmemberlist ((x vl-structmemberlist-p) &key (ps 'ps))
;; Print the stmtessions as a JSON array with brackets.
:measure (two-nats-measure (vl-structmemberlist-count x) 1)
(vl-ps-seq (vl-print "[")
(vl-jp-structmemberlist-aux x)
(vl-println? "]")))
(define vl-jp-structmemberlist-aux ((x vl-structmemberlist-p) &key (ps 'ps))
:measure (two-nats-measure (vl-structmemberlist-count x) 0)
(if (atom x)
ps
(vl-ps-seq (vl-jp-structmember (car x))
(if (atom (cdr x))
ps
(vl-println? ", "))
(vl-jp-structmemberlist-aux (cdr x)))))
(define vl-jp-structmember ((x vl-structmember-p) &key (ps 'ps))
:measure (two-nats-measure (vl-structmember-count x) 0)
(b* (((vl-structmember x) x))
(jp-object :tag (jp-sym :vl-structmember)
:atts (vl-jp-atts x.atts)
:rand (vl-jp-randomqualifier x.rand)
:dims (vl-jp-packeddimensionlist x.dims)
:rhs (vl-jp-maybe-expr x.rhs)
:type (vl-jp-datatype x.type)))))
(add-json-encoder vl-datatype-p vl-jp-datatype)
(add-json-encoder vl-structmember-p vl-jp-structmember)
(add-json-encoder vl-structmemberlist-p vl-jp-structmemberlist)
(define vl-jp-maybe-datatype ((x vl-maybe-datatype-p) &key (ps 'ps))
(if x
(vl-jp-datatype x)
(vl-print "null")))
(add-json-encoder vl-maybe-datatype-p vl-jp-maybe-datatype)
(def-vl-jp-aggregate vardecl)
(def-vl-jp-list vardecl :newlines 4)
(define vl-jp-paramtype ((x vl-paramtype-p) &key (ps 'ps))
(vl-paramtype-case x
(:vl-implicitvalueparam
(jp-object :tag (jp-sym :vl-implicitvalueparam)
:sign (jp-sym x.sign)
:range (vl-jp-maybe-range x.range)
:default (vl-jp-maybe-expr x.default)))
(:vl-explicitvalueparam
(jp-object :tag (jp-sym :vl-explicitvalueparam)
:type (vl-jp-datatype x.type)
:default (vl-jp-maybe-expr x.default)))
(:vl-typeparam
(jp-object :tag (jp-sym :vl-typeparam)
:default (vl-jp-maybe-datatype x.default)))))
(add-json-encoder vl-paramtype-p vl-jp-paramtype)
(def-vl-jp-aggregate paramdecl)
(def-vl-jp-list paramdecl :newlines 4)
(define vl-jp-blockitem ((x vl-blockitem-p) &key (ps 'ps))
:guard-hints (("Goal" :in-theory (enable vl-blockitem-p)))
(mbe :logic
(cond ((vl-vardecl-p x) (vl-jp-vardecl x))
(t (vl-jp-paramdecl x)))
:exec
(case (tag x)
(:vl-vardecl (vl-jp-vardecl x))
(otherwise (vl-jp-paramdecl x)))))
(add-json-encoder vl-blockitem-p vl-jp-blockitem)
(def-vl-jp-list blockitem)
(define vl-jp-arguments ((x vl-arguments-p) &key (ps 'ps))
:parents (json-encoders vl-arguments-p)
(vl-arguments-case x
:vl-arguments-named
(jp-object :tag (jp-sym :vl-arguments)
:namedp (jp-bool t)
:starp (jp-bool x.starp)
:args (vl-jp-namedarglist x.args))
:vl-arguments-plain
(jp-object :tag (jp-sym :vl-arguments)
:namedp (jp-bool nil)
:args (vl-jp-plainarglist x.args))))
(add-json-encoder vl-arguments-p vl-jp-arguments)
(def-vl-jp-aggregate gatestrength)
(define vl-jp-maybe-gatestrength ((x vl-maybe-gatestrength-p) &key (ps 'ps))
(if x
(vl-jp-gatestrength x)
(vl-print "null")))
(add-json-encoder vl-maybe-gatestrength-p vl-jp-maybe-gatestrength)
(define vl-jp-paramvalue ((x vl-paramvalue-p) &key (ps 'ps))
:parents (json-encoders vl-paramvalue-p)
(b* ((x (vl-paramvalue-fix x)))
(vl-paramvalue-case x
:expr (vl-jp-expr x)
:datatype (vl-jp-datatype x))))
(add-json-encoder vl-paramvalue-p vl-jp-paramvalue)
(def-vl-jp-list paramvalue)
(define vl-jp-maybe-paramvalue ((x vl-maybe-paramvalue-p) &key (ps 'ps))
(if x
(vl-jp-paramvalue x)
(vl-print "null")))
(add-json-encoder vl-maybe-paramvalue-p vl-jp-maybe-paramvalue)
(def-vl-jp-aggregate namedparamvalue)
(def-vl-jp-list namedparamvalue)
(define vl-jp-paramargs ((x vl-paramargs-p) &key (ps 'ps))
(vl-paramargs-case x
:vl-paramargs-named
(jp-object :tag (jp-sym :vl-paramargs)
:namedp (jp-bool t)
:args (vl-jp-namedparamvaluelist x.args))
:vl-paramargs-plain
(jp-object :tag (jp-sym :vl-paramargs)
:namedp (jp-bool nil)
:args (vl-jp-paramvaluelist x.args))))
(add-json-encoder vl-paramargs-p vl-jp-paramargs)
(def-vl-jp-aggregate modinst)
(def-vl-jp-list modinst)
(def-vl-jp-aggregate gateinst)
(def-vl-jp-list gateinst)
(def-vl-jp-aggregate delaycontrol)
(def-vl-jp-aggregate evatom)
(def-vl-jp-list evatom)
(def-vl-jp-aggregate eventcontrol)
(def-vl-jp-aggregate repeateventcontrol)
(define vl-jp-delayoreventcontrol ((x vl-delayoreventcontrol-p) &key (ps 'ps))
:guard-hints (("Goal" :in-theory (enable vl-delayoreventcontrol-p)))
(cond ((vl-delaycontrol-p x) (vl-jp-delaycontrol x))
((vl-eventcontrol-p x) (vl-jp-eventcontrol x))
(t (vl-jp-repeateventcontrol x))))
(add-json-encoder vl-delayoreventcontrol-p vl-jp-delayoreventcontrol)
(define vl-jp-maybe-delayoreventcontrol ((x vl-maybe-delayoreventcontrol-p)
&key (ps 'ps))
(if x
(vl-jp-delayoreventcontrol x)
(vl-print "null")))
(add-json-encoder vl-maybe-delayoreventcontrol-p vl-jp-maybe-delayoreventcontrol)
(defines vl-jp-stmt
(define vl-jp-stmt ((x vl-stmt-p) &key (ps 'ps))
:measure (two-nats-measure (vl-stmt-count x) 0)
(b* ((kind (vl-stmt-kind x)))
(vl-stmt-case x
:vl-nullstmt
(jp-object :tag (jp-sym kind)
:atts (vl-jp-atts x.atts))
:vl-assignstmt
(jp-object :tag (jp-sym kind)
:lvalue (vl-jp-expr x.lvalue)
:expr (vl-jp-expr x.expr)
:ctrl (vl-jp-maybe-delayoreventcontrol x.ctrl)
:atts (vl-jp-atts x.atts))
:vl-deassignstmt
(jp-object :tag (jp-sym kind)
:lvalue (vl-jp-expr x.lvalue)
:atts (vl-jp-atts x.atts))
:vl-enablestmt
(jp-object :tag (jp-sym kind)
:id (vl-jp-expr x.id)
:args (vl-jp-exprlist x.args)
:atts (vl-jp-atts x.atts))
:vl-disablestmt
(jp-object :tag (jp-sym kind)
:id (vl-jp-expr x.id)
:atts (vl-jp-atts x.atts))
:vl-eventtriggerstmt
(jp-object :tag (jp-sym kind)
:id (vl-jp-expr x.id)
:atts (vl-jp-atts x.atts))
:vl-casestmt
(jp-object :tag (jp-sym kind)
:casetype (vl-jp-casetype x.casetype)
:check (vl-jp-casecheck x.check)
:test (vl-jp-expr x.test)
:default (vl-jp-stmt x.default)
:caselist (vl-jp-cases x.caselist)
:atts (vl-jp-atts x.atts))
:vl-ifstmt
(jp-object :tag (jp-sym kind)
:condition (vl-jp-expr x.condition)
:truebranch (vl-jp-stmt x.truebranch)
:falsebranch (vl-jp-stmt x.falsebranch)
:atts (vl-jp-atts x.atts))
:vl-foreverstmt
(jp-object :tag (jp-sym kind)
:body (vl-jp-stmt x.body)
:atts (vl-jp-atts x.atts))
:vl-waitstmt
(jp-object :tag (jp-sym kind)
:condition (vl-jp-expr x.condition)
:body (vl-jp-stmt x.body)
:atts (vl-jp-atts x.atts))
:vl-whilestmt
(jp-object :tag (jp-sym kind)
:condition (vl-jp-expr x.condition)
:body (vl-jp-stmt x.body)
:atts (vl-jp-atts x.atts))
:vl-forstmt
(jp-object :tag (jp-sym kind)
:initlhs (vl-jp-expr x.initlhs)
:initrhs (vl-jp-expr x.initrhs)
:test (vl-jp-expr x.test)
:nextlhs (vl-jp-expr x.nextlhs)
:nextrhs (vl-jp-expr x.nextrhs)
:body (vl-jp-stmt x.body)
:atts (vl-jp-atts x.atts))
:vl-blockstmt
(jp-object :tag (jp-sym kind)
:sequential (jp-bool x.sequentialp)
:name (jp-maybe-string x.name)
:decls (vl-jp-blockitemlist x.decls)
:stmts (vl-jp-stmtlist x.stmts)
:atts (vl-jp-atts x.atts))
:vl-repeatstmt
(jp-object :tag (jp-sym kind)
:condition (vl-jp-expr x.condition)
:body (vl-jp-stmt x.body)
:atts (vl-jp-atts x.atts))
:vl-timingstmt
(jp-object :tag (jp-sym kind)
:ctrl (vl-jp-delayoreventcontrol x.ctrl)
:body (vl-jp-stmt x.body)
:atts (vl-jp-atts x.atts))
)))
(define vl-jp-stmtlist ((x vl-stmtlist-p) &key (ps 'ps))
;; Print the stmtessions as a JSON array with brackets.
:measure (two-nats-measure (vl-stmtlist-count x) 1)
(vl-ps-seq (vl-print "[")
(vl-jp-stmtlist-aux x)
(vl-println? "]")))
(define vl-jp-stmtlist-aux ((x vl-stmtlist-p) &key (ps 'ps))
:measure (two-nats-measure (vl-stmtlist-count x) 0)
(b* (((when (atom x))
ps))
(vl-ps-seq (vl-jp-stmt (car x))
(if (atom (cdr x))
ps
(vl-println? ", "))
(vl-jp-stmtlist-aux (cdr x)))))
(define vl-jp-cases ((x vl-caselist-p) &key (ps 'ps))
;; Print the stmtessions as a JSON array with brackets.
:measure (two-nats-measure (vl-caselist-count x) 1)
(vl-ps-seq (vl-print "[")
(vl-jp-cases-aux x)
(vl-println? "]")))
(define vl-jp-cases-aux ((x vl-caselist-p) &key (ps 'ps))
;; Print the stmtessions as a JSON array with brackets.
:measure (two-nats-measure (vl-caselist-count x) 0)
(b* ((x (vl-caselist-fix x))
((when (atom x))
ps)
((cons exprs stmt1) (car x)))
(vl-ps-seq (vl-print "[")
(vl-jp-exprlist exprs)
(vl-println? ",")
(vl-jp-stmt stmt1)
(vl-println? "]")
(if (atom (cdr x))
ps
(vl-println? ", "))
(vl-jp-cases-aux (cdr x))))))
(add-json-encoder vl-stmt-p vl-jp-stmt)
(add-json-encoder vl-stmtlist-p vl-jp-stmtlist)
(add-json-encoder vl-caselist-p vl-jp-cases)
(def-vl-jp-aggregate always)
(def-vl-jp-list always :newlines 4)
(def-vl-jp-aggregate initial)
(def-vl-jp-list initial :newlines 4)
(def-vl-jp-aggregate taskport)
(def-vl-jp-list taskport :newlines 4)
(def-vl-jp-aggregate fundecl)
(def-vl-jp-list fundecl :newlines 4)
(def-vl-jp-aggregate taskdecl)
(def-vl-jp-list taskdecl :newlines 4)
(def-vl-jp-aggregate portdecl)
(def-vl-jp-list portdecl :newlines 4)
(def-vl-jp-aggregate assign)
(def-vl-jp-list assign :newlines 4)
(define vl-jp-warning ((x vl-warning-p) &key (ps 'ps))
:parents (json-encoders)
:short "Special, custom JSON encoder for warnings."
:long "<p>We probably don't want to use the ordinary aggregate-encoding stuff
to print @(see vl-warning-p) objects, since the types in the @(':args') field
are dynamic and, besides, who wants to reimplement @(see vl-cw) in other
languages. Instead, it's probably more convenient to just go ahead and convert
the warning into a printed message here. We'll include both HTML and plain
TEXT versions of the message.</p>"
(b* (((vl-warning x) x)
(text (with-local-ps (vl-cw-obj x.msg x.args)))
(html (with-local-ps (vl-ps-update-htmlp t)
(vl-cw-obj x.msg x.args))))
(jp-object :tag (vl-print "\"warning\"")
:fatalp (jp-bool x.fatalp)
:type (jp-str (symbol-name x.type))
:fn (jp-str (symbol-name x.fn))
:text (jp-str text)
:html (jp-str html))))
(add-json-encoder vl-warning-p jp-warning)
(def-vl-jp-list warning :newlines 4)
(define vl-jp-commentmap-aux ((x vl-commentmap-p) &key (ps 'ps))
(b* (((when (atom x))
ps))
(vl-ps-seq (vl-print "{\"loc\": ")
(vl-jp-location (caar x))
(vl-println? ", \"comment\": ")
(jp-str (cdar x))
(vl-print "}")
(if (atom (cdr x))
ps
(vl-println? ", "))
(vl-jp-commentmap-aux (cdr x)))))
(define vl-jp-commentmap ((x vl-commentmap-p) &key (ps 'ps))
(vl-ps-seq (vl-print "[")
(vl-jp-commentmap-aux x)
(vl-println? "]")))
(add-json-encoder vl-commentmap-p vl-jp-commentmap)
(def-vl-jp-aggregate modport-port)
(def-vl-jp-list modport-port)
(def-vl-jp-aggregate modport)
(def-vl-jp-aggregate alias)
(define vl-jp-fwdtypedefkind ((x vl-fwdtypedefkind-p) &key (ps 'ps))
(jp-str (case x
(:vl-enum "enum")
(:vl-struct "struct")
(:vl-union "union")
(:vl-class "class")
(:vl-interfaceclass "interfaceclass")))
///
(add-json-encoder vl-fwdtypedefkind-p vl-jp-fwdtypedefkind))
(def-vl-jp-aggregate fwdtypedef)
(define vl-jp-modelement ((x vl-modelement-p) &key (ps 'ps))
:guard-hints (("goal" :in-theory (enable vl-modelement-p)))
(case (tag x)
(:VL-PORT (VL-jp-PORT X))
(:VL-PORTDECL (VL-jp-PORTDECL X))
(:VL-ASSIGN (VL-jp-ASSIGN X))
(:VL-ALIAS (VL-jp-ALIAS X))
(:VL-VARDECL (VL-jp-VARDECL X))
(:VL-PARAMDECL (VL-jp-PARAMDECL X))
(:VL-FUNDECL (VL-jp-FUNDECL X))
(:VL-TASKDECL (VL-jp-TASKDECL X))
(:VL-MODINST (VL-jp-MODINST X))
(:VL-GATEINST (VL-jp-GATEINST X))
(:VL-ALWAYS (VL-jp-ALWAYS X))
(:VL-INITIAL (VL-jp-INITIAL X))
;; BOZO implement typedef
(:VL-TYPEDEF ps)
(:VL-FWDTYPEDEF (VL-jp-FWDTYPEDEF X))
(OTHERWISE (VL-jp-MODPORT X))))
(def-vl-jp-list modelement)
(define vl-jp-genelement ((x vl-genelement-p) &key (ps 'ps))
(vl-genelement-case x
:vl-genbase (vl-jp-modelement x.item)
;; BOZO implement generates
:otherwise ps)
///
(add-json-encoder vl-genelement-p vl-jp-genelement))
(def-vl-jp-list genelement)
(def-vl-jp-aggregate module
:omit (params esim)
:newlines 2)
(def-vl-jp-list module
:newlines 1)
(define vl-jp-modalist-aux ((x vl-modalist-p) &key (ps 'ps))
(b* (((when (atom x))
ps))
(vl-ps-seq (jp-str (caar x))
(vl-print ": ")
(vl-jp-module (cdar x))
(if (atom (cdr x))
ps
(vl-println ", "))
(vl-jp-modalist-aux (cdr x)))))
(define vl-jp-modalist ((x vl-modalist-p) &key (ps 'ps))
(vl-ps-seq (vl-print "{")
(vl-jp-modalist-aux x)
(vl-println "}")))
(define vl-jp-individual-modules ((x vl-modulelist-p) &key (ps 'ps))
;; This doesn't print a single valid JSON object. Instead, it prints a whole
;; list of JSON objects separated by newlines.
(if (atom x)
ps
(vl-ps-seq (vl-jp-module (car x))
(vl-print "
")
(vl-jp-individual-modules (cdr x)))))
|
[
{
"context": "plementation of Kildall's \"Algorithm A\":\n;;;;\n;;;; G.A. Kildall, \"A Unified Approach to Global Program\n;;;; Optim",
"end": 99,
"score": 0.9998497366905212,
"start": 87,
"tag": "NAME",
"value": "G.A. Kildall"
}
] |
Code/Cleavir/Kildall/cleavir-kildall.asd
|
gwerbin/SICL
| 842 |
(cl:in-package #:asdf-user)
;;;; Implementation of Kildall's "Algorithm A":
;;;;
;;;; G.A. Kildall, "A Unified Approach to Global Program
;;;; Optimization." Proceedings of the First ACM Symposium on
;;;; Principles of Programming Languages,194-206, 1973.
;;;;
;;;; It's a very general algorithm for optimization information on
;;;; program structures like HIR.
;;;; See liveness.lisp for an example.
(defsystem :cleavir-kildall
:depends-on (:cleavir-hir)
:serial t
:components
((:file "packages")
(:file "kildall")
(:file "pool")
(:file "dictionary")
(:file "work-list")
(:file "map-pool")
(:file "iterate")
(:file "initial-work")
(:file "alist-pool")
(:file "bitset")
(:file "interfunction")))
|
76160
|
(cl:in-package #:asdf-user)
;;;; Implementation of Kildall's "Algorithm A":
;;;;
;;;; <NAME>, "A Unified Approach to Global Program
;;;; Optimization." Proceedings of the First ACM Symposium on
;;;; Principles of Programming Languages,194-206, 1973.
;;;;
;;;; It's a very general algorithm for optimization information on
;;;; program structures like HIR.
;;;; See liveness.lisp for an example.
(defsystem :cleavir-kildall
:depends-on (:cleavir-hir)
:serial t
:components
((:file "packages")
(:file "kildall")
(:file "pool")
(:file "dictionary")
(:file "work-list")
(:file "map-pool")
(:file "iterate")
(:file "initial-work")
(:file "alist-pool")
(:file "bitset")
(:file "interfunction")))
| true |
(cl:in-package #:asdf-user)
;;;; Implementation of Kildall's "Algorithm A":
;;;;
;;;; PI:NAME:<NAME>END_PI, "A Unified Approach to Global Program
;;;; Optimization." Proceedings of the First ACM Symposium on
;;;; Principles of Programming Languages,194-206, 1973.
;;;;
;;;; It's a very general algorithm for optimization information on
;;;; program structures like HIR.
;;;; See liveness.lisp for an example.
(defsystem :cleavir-kildall
:depends-on (:cleavir-hir)
:serial t
:components
((:file "packages")
(:file "kildall")
(:file "pool")
(:file "dictionary")
(:file "work-list")
(:file "map-pool")
(:file "iterate")
(:file "initial-work")
(:file "alist-pool")
(:file "bitset")
(:file "interfunction")))
|
[
{
"context": "tq *sort-data*\n (vector (list (list \"JonL\" \"White\") \"Iteration\")\n (lis",
"end": 4520,
"score": 0.999237060546875,
"start": 4516,
"tag": "NAME",
"value": "JonL"
},
{
"context": "t-data*\n (vector (list (list \"JonL\" \"White\") \"Iteration\")\n (list (list ",
"end": 4528,
"score": 0.7934608459472656,
"start": 4523,
"tag": "NAME",
"value": "White"
},
{
"context": ") \"Iteration\")\n (list (list \"Dick\" \"Waters\") \"Iteration\")\n (li",
"end": 4583,
"score": 0.9989503026008606,
"start": 4579,
"tag": "NAME",
"value": "Dick"
},
{
"context": "ation\")\n (list (list \"Dick\" \"Waters\") \"Iteration\")\n (list (list ",
"end": 4592,
"score": 0.8935590386390686,
"start": 4586,
"tag": "NAME",
"value": "Waters"
},
{
"context": ") \"Iteration\")\n (list (list \"Dick\" \"Gabriel\") \"Objects\")\n (lis",
"end": 4647,
"score": 0.9993623495101929,
"start": 4643,
"tag": "NAME",
"value": "Dick"
},
{
"context": "ation\")\n (list (list \"Dick\" \"Gabriel\") \"Objects\")\n (list (list \"K",
"end": 4657,
"score": 0.9995339512825012,
"start": 4650,
"tag": "NAME",
"value": "Gabriel"
},
{
"context": "l\") \"Objects\")\n (list (list \"Kent\" \"Pitman\") \"Conditions\")\n (l",
"end": 4710,
"score": 0.9985640048980713,
"start": 4706,
"tag": "NAME",
"value": "Kent"
},
{
"context": "jects\")\n (list (list \"Kent\" \"Pitman\") \"Conditions\")\n (list (list",
"end": 4719,
"score": 0.9896774291992188,
"start": 4713,
"tag": "NAME",
"value": "Pitman"
},
{
"context": " \"Conditions\")\n (list (list \"Gregor\" \"Kiczales\") \"Objects\")\n (li",
"end": 4777,
"score": 0.9995594024658203,
"start": 4771,
"tag": "NAME",
"value": "Gregor"
},
{
"context": "ons\")\n (list (list \"Gregor\" \"Kiczales\") \"Objects\")\n (list (list \"D",
"end": 4788,
"score": 0.9990105032920837,
"start": 4780,
"tag": "NAME",
"value": "Kiczales"
},
{
"context": "s\") \"Objects\")\n (list (list \"David\" \"Moon\") \"Objects\")\n (list (",
"end": 4842,
"score": 0.9993230104446411,
"start": 4837,
"tag": "NAME",
"value": "David"
},
{
"context": "ects\")\n (list (list \"David\" \"Moon\") \"Objects\")\n (list (list \"K",
"end": 4849,
"score": 0.8450735807418823,
"start": 4845,
"tag": "NAME",
"value": "Moon"
},
{
"context": "n\") \"Objects\")\n (list (list \"Kathy\" \"Chapman\") \"Editorial\")\n (l",
"end": 4903,
"score": 0.9994146227836609,
"start": 4898,
"tag": "NAME",
"value": "Kathy"
},
{
"context": "ects\")\n (list (list \"Kathy\" \"Chapman\") \"Editorial\")\n (list (list ",
"end": 4913,
"score": 0.9992387294769287,
"start": 4906,
"tag": "NAME",
"value": "Chapman"
},
{
"context": ") \"Editorial\")\n (list (list \"Larry\" \"Masinter\") \"Cleanup\")\n (li",
"end": 4969,
"score": 0.9993582963943481,
"start": 4964,
"tag": "NAME",
"value": "Larry"
},
{
"context": "rial\")\n (list (list \"Larry\" \"Masinter\") \"Cleanup\")\n (list (list \"S",
"end": 4980,
"score": 0.9995184540748596,
"start": 4972,
"tag": "NAME",
"value": "Masinter"
},
{
"context": "r\") \"Cleanup\")\n (list (list \"Sandra\" \"Loosemore\") \"Compiler\")))\n #'string-less",
"end": 5035,
"score": 0.9992756247520447,
"start": 5029,
"tag": "NAME",
"value": "Sandra"
},
{
"context": "nup\")\n (list (list \"Sandra\" \"Loosemore\") \"Compiler\")))\n #'string-lessp :key #'cad",
"end": 5047,
"score": 0.9808369278907776,
"start": 5038,
"tag": "NAME",
"value": "Loosemore"
},
{
"context": "r\")))\n #'string-lessp :key #'cadar)\n #(((\"Kathy\" \"Chapman\") \"Editorial\")\n ((\"Dick\" \"Gabriel\") ",
"end": 5113,
"score": 0.9995353817939758,
"start": 5108,
"tag": "NAME",
"value": "Kathy"
},
{
"context": " #'string-lessp :key #'cadar)\n #(((\"Kathy\" \"Chapman\") \"Editorial\")\n ((\"Dick\" \"Gabriel\") \"Objects\")",
"end": 5123,
"score": 0.9993453025817871,
"start": 5116,
"tag": "NAME",
"value": "Chapman"
},
{
"context": "dar)\n #(((\"Kathy\" \"Chapman\") \"Editorial\")\n ((\"Dick\" \"Gabriel\") \"Objects\")\n ((\"Gregor\" \"Kiczales\")",
"end": 5150,
"score": 0.9994500875473022,
"start": 5146,
"tag": "NAME",
"value": "Dick"
},
{
"context": "#(((\"Kathy\" \"Chapman\") \"Editorial\")\n ((\"Dick\" \"Gabriel\") \"Objects\")\n ((\"Gregor\" \"Kiczales\") \"Objects\"",
"end": 5160,
"score": 0.999610185623169,
"start": 5153,
"tag": "NAME",
"value": "Gabriel"
},
{
"context": "orial\")\n ((\"Dick\" \"Gabriel\") \"Objects\")\n ((\"Gregor\" \"Kiczales\") \"Objects\")\n ((\"Sandra\" \"Loosemore",
"end": 5187,
"score": 0.999730110168457,
"start": 5181,
"tag": "NAME",
"value": "Gregor"
},
{
"context": " ((\"Dick\" \"Gabriel\") \"Objects\")\n ((\"Gregor\" \"Kiczales\") \"Objects\")\n ((\"Sandra\" \"Loosemore\") \"Compile",
"end": 5198,
"score": 0.999605655670166,
"start": 5190,
"tag": "NAME",
"value": "Kiczales"
},
{
"context": "ts\")\n ((\"Gregor\" \"Kiczales\") \"Objects\")\n ((\"Sandra\" \"Loosemore\") \"Compiler\")\n ((\"Larry\" \"Masinter",
"end": 5225,
"score": 0.99973064661026,
"start": 5219,
"tag": "NAME",
"value": "Sandra"
},
{
"context": "((\"Gregor\" \"Kiczales\") \"Objects\")\n ((\"Sandra\" \"Loosemore\") \"Compiler\")\n ((\"Larry\" \"Masinter\") \"Cleanup\"",
"end": 5237,
"score": 0.9981898665428162,
"start": 5228,
"tag": "NAME",
"value": "Loosemore"
},
{
"context": "\")\n ((\"Sandra\" \"Loosemore\") \"Compiler\")\n ((\"Larry\" \"Masinter\") \"Cleanup\")\n ((\"David\" \"Moon\") \"Ob",
"end": 5264,
"score": 0.9996732473373413,
"start": 5259,
"tag": "NAME",
"value": "Larry"
},
{
"context": "(\"Sandra\" \"Loosemore\") \"Compiler\")\n ((\"Larry\" \"Masinter\") \"Cleanup\")\n ((\"David\" \"Moon\") \"Objects\")\n ",
"end": 5275,
"score": 0.9989326000213623,
"start": 5267,
"tag": "NAME",
"value": "Masinter"
},
{
"context": "ler\")\n ((\"Larry\" \"Masinter\") \"Cleanup\")\n ((\"David\" \"Moon\") \"Objects\")\n ((\"Kent\" \"Pitman\") \"Condi",
"end": 5301,
"score": 0.9990705847740173,
"start": 5296,
"tag": "NAME",
"value": "David"
},
{
"context": " ((\"Larry\" \"Masinter\") \"Cleanup\")\n ((\"David\" \"Moon\") \"Objects\")\n ((\"Kent\" \"Pitman\") \"Conditions\")",
"end": 5308,
"score": 0.6694673299789429,
"start": 5304,
"tag": "NAME",
"value": "Moon"
},
{
"context": "Cleanup\")\n ((\"David\" \"Moon\") \"Objects\")\n ((\"Kent\" \"Pitman\") \"Conditions\")\n ((\"Dick\" \"Waters\") \"",
"end": 5333,
"score": 0.9995694756507874,
"start": 5329,
"tag": "NAME",
"value": "Kent"
},
{
"context": "\")\n ((\"David\" \"Moon\") \"Objects\")\n ((\"Kent\" \"Pitman\") \"Conditions\")\n ((\"Dick\" \"Waters\") \"Iteration",
"end": 5342,
"score": 0.9992263317108154,
"start": 5336,
"tag": "NAME",
"value": "Pitman"
},
{
"context": "cts\")\n ((\"Kent\" \"Pitman\") \"Conditions\")\n ((\"Dick\" \"Waters\") \"Iteration\")\n ((\"JonL\" \"White\") \"It",
"end": 5370,
"score": 0.999685525894165,
"start": 5366,
"tag": "NAME",
"value": "Dick"
},
{
"context": " ((\"Kent\" \"Pitman\") \"Conditions\")\n ((\"Dick\" \"Waters\") \"Iteration\")\n ((\"JonL\" \"White\") \"Iteration\")",
"end": 5379,
"score": 0.9968268871307373,
"start": 5373,
"tag": "NAME",
"value": "Waters"
},
{
"context": "ions\")\n ((\"Dick\" \"Waters\") \"Iteration\")\n ((\"JonL\" \"White\") \"Iteration\")))\n\n;; Note that individual",
"end": 5406,
"score": 0.9997429847717285,
"start": 5402,
"tag": "NAME",
"value": "JonL"
},
{
"context": " ((\"Dick\" \"Waters\") \"Iteration\")\n ((\"JonL\" \"White\") \"Iteration\")))\n\n;; Note that individual alphabe",
"end": 5414,
"score": 0.9879745841026306,
"start": 5409,
"tag": "NAME",
"value": "White"
},
{
"context": "t *sort-data* #'string-lessp :key #'cadr))\n #(((\"Larry\" \"Masinter\") \"Cleanup\")\n ((\"Sandra\" \"Loosemore",
"end": 5628,
"score": 0.9996858835220337,
"start": 5623,
"tag": "NAME",
"value": "Larry"
},
{
"context": "data* #'string-lessp :key #'cadr))\n #(((\"Larry\" \"Masinter\") \"Cleanup\")\n ((\"Sandra\" \"Loosemore\") \"Compile",
"end": 5639,
"score": 0.9995052218437195,
"start": 5631,
"tag": "NAME",
"value": "Masinter"
},
{
"context": "adr))\n #(((\"Larry\" \"Masinter\") \"Cleanup\")\n ((\"Sandra\" \"Loosemore\") \"Compiler\")\n ((\"Kent\" \"Pitman\") ",
"end": 5666,
"score": 0.9997165203094482,
"start": 5660,
"tag": "NAME",
"value": "Sandra"
},
{
"context": "(((\"Larry\" \"Masinter\") \"Cleanup\")\n ((\"Sandra\" \"Loosemore\") \"Compiler\")\n ((\"Kent\" \"Pitman\") \"Conditions\"",
"end": 5678,
"score": 0.9976682662963867,
"start": 5669,
"tag": "NAME",
"value": "Loosemore"
},
{
"context": "\")\n ((\"Sandra\" \"Loosemore\") \"Compiler\")\n ((\"Kent\" \"Pitman\") \"Conditions\")\n ((\"Kathy\" \"Chapman\")",
"end": 5704,
"score": 0.9996082186698914,
"start": 5700,
"tag": "NAME",
"value": "Kent"
},
{
"context": "((\"Sandra\" \"Loosemore\") \"Compiler\")\n ((\"Kent\" \"Pitman\") \"Conditions\")\n ((\"Kathy\" \"Chapman\") \"Editori",
"end": 5713,
"score": 0.9993088841438293,
"start": 5707,
"tag": "NAME",
"value": "Pitman"
},
{
"context": "ler\")\n ((\"Kent\" \"Pitman\") \"Conditions\")\n ((\"Kathy\" \"Chapman\") \"Editorial\")\n ((\"Dick\" \"Waters\") \"",
"end": 5742,
"score": 0.999699056148529,
"start": 5737,
"tag": "NAME",
"value": "Kathy"
},
{
"context": " ((\"Kent\" \"Pitman\") \"Conditions\")\n ((\"Kathy\" \"Chapman\") \"Editorial\")\n ((\"Dick\" \"Waters\") \"Iteration\"",
"end": 5752,
"score": 0.9993109107017517,
"start": 5745,
"tag": "NAME",
"value": "Chapman"
},
{
"context": "ns\")\n ((\"Kathy\" \"Chapman\") \"Editorial\")\n ((\"Dick\" \"Waters\") \"Iteration\")\n ((\"JonL\" \"White\") \"It",
"end": 5779,
"score": 0.9996459484100342,
"start": 5775,
"tag": "NAME",
"value": "Dick"
},
{
"context": " ((\"Kathy\" \"Chapman\") \"Editorial\")\n ((\"Dick\" \"Waters\") \"Iteration\")\n ((\"JonL\" \"White\") \"Iteration\")",
"end": 5788,
"score": 0.9973113536834717,
"start": 5782,
"tag": "NAME",
"value": "Waters"
},
{
"context": "rial\")\n ((\"Dick\" \"Waters\") \"Iteration\")\n ((\"JonL\" \"White\") \"Iteration\")\n ((\"Dick\" \"Gabriel\") \"O",
"end": 5815,
"score": 0.999673068523407,
"start": 5811,
"tag": "NAME",
"value": "JonL"
},
{
"context": " ((\"Dick\" \"Waters\") \"Iteration\")\n ((\"JonL\" \"White\") \"Iteration\")\n ((\"Dick\" \"Gabriel\") \"Objects\")",
"end": 5823,
"score": 0.9949448108673096,
"start": 5818,
"tag": "NAME",
"value": "White"
},
{
"context": "ation\")\n ((\"JonL\" \"White\") \"Iteration\")\n ((\"Dick\" \"Gabriel\") \"Objects\")\n ((\"Gregor\" \"Kiczales\")",
"end": 5850,
"score": 0.999688982963562,
"start": 5846,
"tag": "NAME",
"value": "Dick"
},
{
"context": "\n ((\"JonL\" \"White\") \"Iteration\")\n ((\"Dick\" \"Gabriel\") \"Objects\")\n ((\"Gregor\" \"Kiczales\") \"Objects\"",
"end": 5860,
"score": 0.9996681213378906,
"start": 5853,
"tag": "NAME",
"value": "Gabriel"
},
{
"context": "ation\")\n ((\"Dick\" \"Gabriel\") \"Objects\")\n ((\"Gregor\" \"Kiczales\") \"Objects\")\n ((\"David\" \"Moon\") \"Ob",
"end": 5887,
"score": 0.9997429847717285,
"start": 5881,
"tag": "NAME",
"value": "Gregor"
},
{
"context": " ((\"Dick\" \"Gabriel\") \"Objects\")\n ((\"Gregor\" \"Kiczales\") \"Objects\")\n ((\"David\" \"Moon\") \"Objects\")))\n\n",
"end": 5898,
"score": 0.9996627569198608,
"start": 5890,
"tag": "NAME",
"value": "Kiczales"
},
{
"context": "ts\")\n ((\"Gregor\" \"Kiczales\") \"Objects\")\n ((\"David\" \"Moon\") \"Objects\")))\n\n",
"end": 5924,
"score": 0.9997008442878723,
"start": 5919,
"tag": "NAME",
"value": "David"
},
{
"context": " ((\"Gregor\" \"Kiczales\") \"Objects\")\n ((\"David\" \"Moon\") \"Objects\")))\n\n",
"end": 5931,
"score": 0.9909389019012451,
"start": 5927,
"tag": "NAME",
"value": "Moon"
}
] |
test/rtsequences-sort.lisp
|
nptcl/npt
| 37 |
;;
;; ANSI COMMON LISP: 17. Sequences
;;
;;
;; Function SIMPLE-SORT
;;
(deftest simple-sort.1
(lisp-system::simple-sort () #'<)
nil)
(deftest simple-sort.2
(lisp-system::simple-sort #() #'<)
#())
(deftest simple-sort.3
(lisp-system::simple-sort '(3 4 8 5 1 2 9 8 7) #'<)
(1 2 3 4 5 7 8 8 9))
(deftest simple-sort.4
(lisp-system::simple-sort '(3 4 8 5 1 2 9 8 7) #'>)
(9 8 8 7 5 4 3 2 1))
(deftest simple-sort.5
(lisp-system::simple-sort #(3 4 8 5 1 2 9 8 7) #'<)
#(1 2 3 4 5 7 8 8 9))
(deftest simple-sort.6
(lisp-system::simple-sort #(3 4 8 5 1 2 9 8 7) #'>)
#(9 8 8 7 5 4 3 2 1))
(deftest simple-sort.7
(lisp-system::simple-sort
'((5 3) (2 9) (8 4) (4 8))
#'< :key #'car)
((2 9) (4 8) (5 3) (8 4)))
(deftest simple-sort.8
(lisp-system::simple-sort
'((5 3) (2 9) (8 4) (4 8))
#'< :key #'cadr)
((5 3) (8 4) (4 8) (2 9)))
;;
;; Function BUBBLE-SORT
;;
(deftest bubble-sort.1
(lisp-system::bubble-sort () #'<)
nil)
(deftest bubble-sort.2
(lisp-system::bubble-sort #() #'<)
#())
(deftest bubble-sort.3
(lisp-system::bubble-sort '(3 4 8 5 1 2 9 8 7) #'<)
(1 2 3 4 5 7 8 8 9))
(deftest bubble-sort.4
(lisp-system::bubble-sort '(3 4 8 5 1 2 9 7 8) #'<)
(1 2 3 4 5 7 8 8 9))
(deftest bubble-sort.5
(lisp-system::bubble-sort '(3 4 8 5 1 2 9 8 7) #'>)
(9 8 8 7 5 4 3 2 1))
(deftest bubble-sort.6
(lisp-system::bubble-sort '(3 4 8 5 1 2 9 7 8) #'>)
(9 8 8 7 5 4 3 2 1))
(deftest bubble-sort.7
(lisp-system::bubble-sort #(3 4 8 5 1 2 9 8 7) #'<)
#(1 2 3 4 5 7 8 8 9))
(deftest bubble-sort.8
(lisp-system::bubble-sort #(3 4 8 5 1 2 9 8 7) #'>)
#(9 8 8 7 5 4 3 2 1))
(deftest bubble-sort.9
(lisp-system::bubble-sort
'((1 5) (3 6) (3 8) (9 2) (1 4) (8 4))
#'< :key #'car)
((1 5) (1 4) (3 6) (3 8) (8 4) (9 2)))
(deftest bubble-sort.10
(lisp-system::bubble-sort
#((1 5) (3 6) (3 8) (9 2) (1 4) (8 4))
#'< :key #'car)
#((1 5) (1 4) (3 6) (3 8) (8 4) (9 2)))
;;
;; Function SORT
;;
(deftest sort.1
(sort () #'<)
nil)
(deftest sort.2
(sort #() #'<)
#())
(deftest sort.3
(sort '(3 4 8 5 1 2 9 8 7) #'<)
(1 2 3 4 5 7 8 8 9))
(deftest sort.4
(sort '(3 4 8 5 1 2 9 8 7) #'>)
(9 8 8 7 5 4 3 2 1))
(deftest sort.5
(sort #(3 4 8 5 1 2 9 8 7) #'<)
#(1 2 3 4 5 7 8 8 9))
(deftest sort.6
(sort #(3 4 8 5 1 2 9 8 7) #'>)
#(9 8 8 7 5 4 3 2 1))
(deftest-error! sort-error.1
(eval '(sort 10)))
(deftest-error! sort-error.2
(eval '(sort)))
(deftest-error sort-error.3
(eval '(sort nil #'< nil)))
(deftest-error sort-error.4
(eval '(sort nil #'< :key)))
(deftest-error sort-error.5
(eval '(sort nil #'< :key 10)))
(deftest-error sort-error.6
(eval '(sort nil #'< :hello 10)))
;;
;; Function STABLE-SORT
;;
(deftest stable-sort.1
(stable-sort () #'<)
nil)
(deftest stable-sort.2
(stable-sort #() #'<)
#())
(deftest stable-sort.3
(stable-sort '(3 4 8 5 1 2 9 8 7) #'<)
(1 2 3 4 5 7 8 8 9))
(deftest stable-sort.4
(stable-sort '(3 4 8 5 1 2 9 8 7) #'>)
(9 8 8 7 5 4 3 2 1))
(deftest stable-sort.5
(stable-sort #(3 4 8 5 1 2 9 8 7) #'<)
#(1 2 3 4 5 7 8 8 9))
(deftest stable-sort.6
(stable-sort #(3 4 8 5 1 2 9 8 7) #'>)
#(9 8 8 7 5 4 3 2 1))
(deftest stable-sort.7
(stable-sort
'((1 5) (3 6) (3 8) (9 2) (1 4) (8 4))
#'< :key #'car)
((1 5) (1 4) (3 6) (3 8) (8 4) (9 2)))
(deftest stable-sort.8
(stable-sort
'((1 5) (3 6) (3 8) (9 2) (1 4) (8 4))
#'< :key #'car)
((1 5) (1 4) (3 6) (3 8) (8 4) (9 2)))
(deftest-error! stable-sort-error.1
(eval '(stable-sort 10)))
(deftest-error! stable-sort-error.2
(eval '(stable-sort)))
(deftest-error stable-sort-error.3
(eval '(stable-sort nil #'< nil)))
(deftest-error stable-sort-error.4
(eval '(stable-sort nil #'< :key)))
(deftest-error stable-sort-error.5
(eval '(stable-sort nil #'< :key 10)))
(deftest-error stable-sort-error.6
(eval '(stable-sort nil #'< :hello 10)))
;; ANSI Common Lisp
(defvar *sort-data*)
(deftest sort-test.1
(progn
(setq *sort-data* (copy-seq "lkjashd"))
(sort *sort-data* #'char-lessp))
"adhjkls")
(deftest sort-test.2
(progn
(setq *sort-data* (list '(1 2 3) '(4 5 6) '(7 8 9)))
(sort *sort-data* #'> :key #'car))
((7 8 9) (4 5 6) (1 2 3)))
(deftest sort-test.3
(progn
(setq *sort-data* (list 1 2 3 4 5 6 7 8 9 0))
(stable-sort *sort-data* #'(lambda (x y) (and (oddp x) (evenp y)))))
(1 3 5 7 9 2 4 6 8 0))
(deftest sort-test.4
(sort (setq *sort-data*
(vector (list (list "JonL" "White") "Iteration")
(list (list "Dick" "Waters") "Iteration")
(list (list "Dick" "Gabriel") "Objects")
(list (list "Kent" "Pitman") "Conditions")
(list (list "Gregor" "Kiczales") "Objects")
(list (list "David" "Moon") "Objects")
(list (list "Kathy" "Chapman") "Editorial")
(list (list "Larry" "Masinter") "Cleanup")
(list (list "Sandra" "Loosemore") "Compiler")))
#'string-lessp :key #'cadar)
#((("Kathy" "Chapman") "Editorial")
(("Dick" "Gabriel") "Objects")
(("Gregor" "Kiczales") "Objects")
(("Sandra" "Loosemore") "Compiler")
(("Larry" "Masinter") "Cleanup")
(("David" "Moon") "Objects")
(("Kent" "Pitman") "Conditions")
(("Dick" "Waters") "Iteration")
(("JonL" "White") "Iteration")))
;; Note that individual alphabetical order within `committees'
;; is preserved.
(deftest sort-test.5
(setq *sort-data*
(stable-sort *sort-data* #'string-lessp :key #'cadr))
#((("Larry" "Masinter") "Cleanup")
(("Sandra" "Loosemore") "Compiler")
(("Kent" "Pitman") "Conditions")
(("Kathy" "Chapman") "Editorial")
(("Dick" "Waters") "Iteration")
(("JonL" "White") "Iteration")
(("Dick" "Gabriel") "Objects")
(("Gregor" "Kiczales") "Objects")
(("David" "Moon") "Objects")))
|
22205
|
;;
;; ANSI COMMON LISP: 17. Sequences
;;
;;
;; Function SIMPLE-SORT
;;
(deftest simple-sort.1
(lisp-system::simple-sort () #'<)
nil)
(deftest simple-sort.2
(lisp-system::simple-sort #() #'<)
#())
(deftest simple-sort.3
(lisp-system::simple-sort '(3 4 8 5 1 2 9 8 7) #'<)
(1 2 3 4 5 7 8 8 9))
(deftest simple-sort.4
(lisp-system::simple-sort '(3 4 8 5 1 2 9 8 7) #'>)
(9 8 8 7 5 4 3 2 1))
(deftest simple-sort.5
(lisp-system::simple-sort #(3 4 8 5 1 2 9 8 7) #'<)
#(1 2 3 4 5 7 8 8 9))
(deftest simple-sort.6
(lisp-system::simple-sort #(3 4 8 5 1 2 9 8 7) #'>)
#(9 8 8 7 5 4 3 2 1))
(deftest simple-sort.7
(lisp-system::simple-sort
'((5 3) (2 9) (8 4) (4 8))
#'< :key #'car)
((2 9) (4 8) (5 3) (8 4)))
(deftest simple-sort.8
(lisp-system::simple-sort
'((5 3) (2 9) (8 4) (4 8))
#'< :key #'cadr)
((5 3) (8 4) (4 8) (2 9)))
;;
;; Function BUBBLE-SORT
;;
(deftest bubble-sort.1
(lisp-system::bubble-sort () #'<)
nil)
(deftest bubble-sort.2
(lisp-system::bubble-sort #() #'<)
#())
(deftest bubble-sort.3
(lisp-system::bubble-sort '(3 4 8 5 1 2 9 8 7) #'<)
(1 2 3 4 5 7 8 8 9))
(deftest bubble-sort.4
(lisp-system::bubble-sort '(3 4 8 5 1 2 9 7 8) #'<)
(1 2 3 4 5 7 8 8 9))
(deftest bubble-sort.5
(lisp-system::bubble-sort '(3 4 8 5 1 2 9 8 7) #'>)
(9 8 8 7 5 4 3 2 1))
(deftest bubble-sort.6
(lisp-system::bubble-sort '(3 4 8 5 1 2 9 7 8) #'>)
(9 8 8 7 5 4 3 2 1))
(deftest bubble-sort.7
(lisp-system::bubble-sort #(3 4 8 5 1 2 9 8 7) #'<)
#(1 2 3 4 5 7 8 8 9))
(deftest bubble-sort.8
(lisp-system::bubble-sort #(3 4 8 5 1 2 9 8 7) #'>)
#(9 8 8 7 5 4 3 2 1))
(deftest bubble-sort.9
(lisp-system::bubble-sort
'((1 5) (3 6) (3 8) (9 2) (1 4) (8 4))
#'< :key #'car)
((1 5) (1 4) (3 6) (3 8) (8 4) (9 2)))
(deftest bubble-sort.10
(lisp-system::bubble-sort
#((1 5) (3 6) (3 8) (9 2) (1 4) (8 4))
#'< :key #'car)
#((1 5) (1 4) (3 6) (3 8) (8 4) (9 2)))
;;
;; Function SORT
;;
(deftest sort.1
(sort () #'<)
nil)
(deftest sort.2
(sort #() #'<)
#())
(deftest sort.3
(sort '(3 4 8 5 1 2 9 8 7) #'<)
(1 2 3 4 5 7 8 8 9))
(deftest sort.4
(sort '(3 4 8 5 1 2 9 8 7) #'>)
(9 8 8 7 5 4 3 2 1))
(deftest sort.5
(sort #(3 4 8 5 1 2 9 8 7) #'<)
#(1 2 3 4 5 7 8 8 9))
(deftest sort.6
(sort #(3 4 8 5 1 2 9 8 7) #'>)
#(9 8 8 7 5 4 3 2 1))
(deftest-error! sort-error.1
(eval '(sort 10)))
(deftest-error! sort-error.2
(eval '(sort)))
(deftest-error sort-error.3
(eval '(sort nil #'< nil)))
(deftest-error sort-error.4
(eval '(sort nil #'< :key)))
(deftest-error sort-error.5
(eval '(sort nil #'< :key 10)))
(deftest-error sort-error.6
(eval '(sort nil #'< :hello 10)))
;;
;; Function STABLE-SORT
;;
(deftest stable-sort.1
(stable-sort () #'<)
nil)
(deftest stable-sort.2
(stable-sort #() #'<)
#())
(deftest stable-sort.3
(stable-sort '(3 4 8 5 1 2 9 8 7) #'<)
(1 2 3 4 5 7 8 8 9))
(deftest stable-sort.4
(stable-sort '(3 4 8 5 1 2 9 8 7) #'>)
(9 8 8 7 5 4 3 2 1))
(deftest stable-sort.5
(stable-sort #(3 4 8 5 1 2 9 8 7) #'<)
#(1 2 3 4 5 7 8 8 9))
(deftest stable-sort.6
(stable-sort #(3 4 8 5 1 2 9 8 7) #'>)
#(9 8 8 7 5 4 3 2 1))
(deftest stable-sort.7
(stable-sort
'((1 5) (3 6) (3 8) (9 2) (1 4) (8 4))
#'< :key #'car)
((1 5) (1 4) (3 6) (3 8) (8 4) (9 2)))
(deftest stable-sort.8
(stable-sort
'((1 5) (3 6) (3 8) (9 2) (1 4) (8 4))
#'< :key #'car)
((1 5) (1 4) (3 6) (3 8) (8 4) (9 2)))
(deftest-error! stable-sort-error.1
(eval '(stable-sort 10)))
(deftest-error! stable-sort-error.2
(eval '(stable-sort)))
(deftest-error stable-sort-error.3
(eval '(stable-sort nil #'< nil)))
(deftest-error stable-sort-error.4
(eval '(stable-sort nil #'< :key)))
(deftest-error stable-sort-error.5
(eval '(stable-sort nil #'< :key 10)))
(deftest-error stable-sort-error.6
(eval '(stable-sort nil #'< :hello 10)))
;; ANSI Common Lisp
(defvar *sort-data*)
(deftest sort-test.1
(progn
(setq *sort-data* (copy-seq "lkjashd"))
(sort *sort-data* #'char-lessp))
"adhjkls")
(deftest sort-test.2
(progn
(setq *sort-data* (list '(1 2 3) '(4 5 6) '(7 8 9)))
(sort *sort-data* #'> :key #'car))
((7 8 9) (4 5 6) (1 2 3)))
(deftest sort-test.3
(progn
(setq *sort-data* (list 1 2 3 4 5 6 7 8 9 0))
(stable-sort *sort-data* #'(lambda (x y) (and (oddp x) (evenp y)))))
(1 3 5 7 9 2 4 6 8 0))
(deftest sort-test.4
(sort (setq *sort-data*
(vector (list (list "<NAME>" "<NAME>") "Iteration")
(list (list "<NAME>" "<NAME>") "Iteration")
(list (list "<NAME>" "<NAME>") "Objects")
(list (list "<NAME>" "<NAME>") "Conditions")
(list (list "<NAME>" "<NAME>") "Objects")
(list (list "<NAME>" "<NAME>") "Objects")
(list (list "<NAME>" "<NAME>") "Editorial")
(list (list "<NAME>" "<NAME>") "Cleanup")
(list (list "<NAME>" "<NAME>") "Compiler")))
#'string-lessp :key #'cadar)
#((("<NAME>" "<NAME>") "Editorial")
(("<NAME>" "<NAME>") "Objects")
(("<NAME>" "<NAME>") "Objects")
(("<NAME>" "<NAME>") "Compiler")
(("<NAME>" "<NAME>") "Cleanup")
(("<NAME>" "<NAME>") "Objects")
(("<NAME>" "<NAME>") "Conditions")
(("<NAME>" "<NAME>") "Iteration")
(("<NAME>" "<NAME>") "Iteration")))
;; Note that individual alphabetical order within `committees'
;; is preserved.
(deftest sort-test.5
(setq *sort-data*
(stable-sort *sort-data* #'string-lessp :key #'cadr))
#((("<NAME>" "<NAME>") "Cleanup")
(("<NAME>" "<NAME>") "Compiler")
(("<NAME>" "<NAME>") "Conditions")
(("<NAME>" "<NAME>") "Editorial")
(("<NAME>" "<NAME>") "Iteration")
(("<NAME>" "<NAME>") "Iteration")
(("<NAME>" "<NAME>") "Objects")
(("<NAME>" "<NAME>") "Objects")
(("<NAME>" "<NAME>") "Objects")))
| true |
;;
;; ANSI COMMON LISP: 17. Sequences
;;
;;
;; Function SIMPLE-SORT
;;
(deftest simple-sort.1
(lisp-system::simple-sort () #'<)
nil)
(deftest simple-sort.2
(lisp-system::simple-sort #() #'<)
#())
(deftest simple-sort.3
(lisp-system::simple-sort '(3 4 8 5 1 2 9 8 7) #'<)
(1 2 3 4 5 7 8 8 9))
(deftest simple-sort.4
(lisp-system::simple-sort '(3 4 8 5 1 2 9 8 7) #'>)
(9 8 8 7 5 4 3 2 1))
(deftest simple-sort.5
(lisp-system::simple-sort #(3 4 8 5 1 2 9 8 7) #'<)
#(1 2 3 4 5 7 8 8 9))
(deftest simple-sort.6
(lisp-system::simple-sort #(3 4 8 5 1 2 9 8 7) #'>)
#(9 8 8 7 5 4 3 2 1))
(deftest simple-sort.7
(lisp-system::simple-sort
'((5 3) (2 9) (8 4) (4 8))
#'< :key #'car)
((2 9) (4 8) (5 3) (8 4)))
(deftest simple-sort.8
(lisp-system::simple-sort
'((5 3) (2 9) (8 4) (4 8))
#'< :key #'cadr)
((5 3) (8 4) (4 8) (2 9)))
;;
;; Function BUBBLE-SORT
;;
(deftest bubble-sort.1
(lisp-system::bubble-sort () #'<)
nil)
(deftest bubble-sort.2
(lisp-system::bubble-sort #() #'<)
#())
(deftest bubble-sort.3
(lisp-system::bubble-sort '(3 4 8 5 1 2 9 8 7) #'<)
(1 2 3 4 5 7 8 8 9))
(deftest bubble-sort.4
(lisp-system::bubble-sort '(3 4 8 5 1 2 9 7 8) #'<)
(1 2 3 4 5 7 8 8 9))
(deftest bubble-sort.5
(lisp-system::bubble-sort '(3 4 8 5 1 2 9 8 7) #'>)
(9 8 8 7 5 4 3 2 1))
(deftest bubble-sort.6
(lisp-system::bubble-sort '(3 4 8 5 1 2 9 7 8) #'>)
(9 8 8 7 5 4 3 2 1))
(deftest bubble-sort.7
(lisp-system::bubble-sort #(3 4 8 5 1 2 9 8 7) #'<)
#(1 2 3 4 5 7 8 8 9))
(deftest bubble-sort.8
(lisp-system::bubble-sort #(3 4 8 5 1 2 9 8 7) #'>)
#(9 8 8 7 5 4 3 2 1))
(deftest bubble-sort.9
(lisp-system::bubble-sort
'((1 5) (3 6) (3 8) (9 2) (1 4) (8 4))
#'< :key #'car)
((1 5) (1 4) (3 6) (3 8) (8 4) (9 2)))
(deftest bubble-sort.10
(lisp-system::bubble-sort
#((1 5) (3 6) (3 8) (9 2) (1 4) (8 4))
#'< :key #'car)
#((1 5) (1 4) (3 6) (3 8) (8 4) (9 2)))
;;
;; Function SORT
;;
(deftest sort.1
(sort () #'<)
nil)
(deftest sort.2
(sort #() #'<)
#())
(deftest sort.3
(sort '(3 4 8 5 1 2 9 8 7) #'<)
(1 2 3 4 5 7 8 8 9))
(deftest sort.4
(sort '(3 4 8 5 1 2 9 8 7) #'>)
(9 8 8 7 5 4 3 2 1))
(deftest sort.5
(sort #(3 4 8 5 1 2 9 8 7) #'<)
#(1 2 3 4 5 7 8 8 9))
(deftest sort.6
(sort #(3 4 8 5 1 2 9 8 7) #'>)
#(9 8 8 7 5 4 3 2 1))
(deftest-error! sort-error.1
(eval '(sort 10)))
(deftest-error! sort-error.2
(eval '(sort)))
(deftest-error sort-error.3
(eval '(sort nil #'< nil)))
(deftest-error sort-error.4
(eval '(sort nil #'< :key)))
(deftest-error sort-error.5
(eval '(sort nil #'< :key 10)))
(deftest-error sort-error.6
(eval '(sort nil #'< :hello 10)))
;;
;; Function STABLE-SORT
;;
(deftest stable-sort.1
(stable-sort () #'<)
nil)
(deftest stable-sort.2
(stable-sort #() #'<)
#())
(deftest stable-sort.3
(stable-sort '(3 4 8 5 1 2 9 8 7) #'<)
(1 2 3 4 5 7 8 8 9))
(deftest stable-sort.4
(stable-sort '(3 4 8 5 1 2 9 8 7) #'>)
(9 8 8 7 5 4 3 2 1))
(deftest stable-sort.5
(stable-sort #(3 4 8 5 1 2 9 8 7) #'<)
#(1 2 3 4 5 7 8 8 9))
(deftest stable-sort.6
(stable-sort #(3 4 8 5 1 2 9 8 7) #'>)
#(9 8 8 7 5 4 3 2 1))
(deftest stable-sort.7
(stable-sort
'((1 5) (3 6) (3 8) (9 2) (1 4) (8 4))
#'< :key #'car)
((1 5) (1 4) (3 6) (3 8) (8 4) (9 2)))
(deftest stable-sort.8
(stable-sort
'((1 5) (3 6) (3 8) (9 2) (1 4) (8 4))
#'< :key #'car)
((1 5) (1 4) (3 6) (3 8) (8 4) (9 2)))
(deftest-error! stable-sort-error.1
(eval '(stable-sort 10)))
(deftest-error! stable-sort-error.2
(eval '(stable-sort)))
(deftest-error stable-sort-error.3
(eval '(stable-sort nil #'< nil)))
(deftest-error stable-sort-error.4
(eval '(stable-sort nil #'< :key)))
(deftest-error stable-sort-error.5
(eval '(stable-sort nil #'< :key 10)))
(deftest-error stable-sort-error.6
(eval '(stable-sort nil #'< :hello 10)))
;; ANSI Common Lisp
(defvar *sort-data*)
(deftest sort-test.1
(progn
(setq *sort-data* (copy-seq "lkjashd"))
(sort *sort-data* #'char-lessp))
"adhjkls")
(deftest sort-test.2
(progn
(setq *sort-data* (list '(1 2 3) '(4 5 6) '(7 8 9)))
(sort *sort-data* #'> :key #'car))
((7 8 9) (4 5 6) (1 2 3)))
(deftest sort-test.3
(progn
(setq *sort-data* (list 1 2 3 4 5 6 7 8 9 0))
(stable-sort *sort-data* #'(lambda (x y) (and (oddp x) (evenp y)))))
(1 3 5 7 9 2 4 6 8 0))
(deftest sort-test.4
(sort (setq *sort-data*
(vector (list (list "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Iteration")
(list (list "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Iteration")
(list (list "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Objects")
(list (list "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Conditions")
(list (list "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Objects")
(list (list "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Objects")
(list (list "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Editorial")
(list (list "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Cleanup")
(list (list "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Compiler")))
#'string-lessp :key #'cadar)
#((("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Editorial")
(("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Objects")
(("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Objects")
(("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Compiler")
(("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Cleanup")
(("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Objects")
(("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Conditions")
(("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Iteration")
(("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Iteration")))
;; Note that individual alphabetical order within `committees'
;; is preserved.
(deftest sort-test.5
(setq *sort-data*
(stable-sort *sort-data* #'string-lessp :key #'cadr))
#((("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Cleanup")
(("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Compiler")
(("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Conditions")
(("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Editorial")
(("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Iteration")
(("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Iteration")
(("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Objects")
(("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Objects")
(("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") "Objects")))
|
[
{
"context": "ckage definition\n;;;;\n;;;; Copyright (C) 2006,2007 Sven Van Caekenberghe, Beta Nine BVBA.\n;;;;\n;;;; You are granted the ri",
"end": 118,
"score": 0.9998819828033447,
"start": 97,
"tag": "NAME",
"value": "Sven Van Caekenberghe"
}
] |
cl-s3-package.lisp
|
svenvc/cl-s3
| 3 |
;;;; -*- Mode: LISP -*-
;;;;
;;;; The CL-S3 package definition
;;;;
;;;; Copyright (C) 2006,2007 Sven Van Caekenberghe, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(defpackage :cl-s3
(:use common-lisp)
(:export
#:*access-key-id*
#:*secret-access-key*
#:request-date
#:unix-time->lisp-time
#:lisp-time->unix-time
#:make-authorization
#:amazon-s3-api-error
#:get-service
#:get-bucket
#:put-bucket
#:delete-bucket
#:get-object
#:put-object
#:head-object
#:delete-object
#:list-buckets
#:list-objects
#:upload-file
#:download-file)
(:documentation "A Common Lisp Amazon S3 client interface package"))
;;; eof
|
45562
|
;;;; -*- Mode: LISP -*-
;;;;
;;;; The CL-S3 package definition
;;;;
;;;; Copyright (C) 2006,2007 <NAME>, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(defpackage :cl-s3
(:use common-lisp)
(:export
#:*access-key-id*
#:*secret-access-key*
#:request-date
#:unix-time->lisp-time
#:lisp-time->unix-time
#:make-authorization
#:amazon-s3-api-error
#:get-service
#:get-bucket
#:put-bucket
#:delete-bucket
#:get-object
#:put-object
#:head-object
#:delete-object
#:list-buckets
#:list-objects
#:upload-file
#:download-file)
(:documentation "A Common Lisp Amazon S3 client interface package"))
;;; eof
| true |
;;;; -*- Mode: LISP -*-
;;;;
;;;; The CL-S3 package definition
;;;;
;;;; Copyright (C) 2006,2007 PI:NAME:<NAME>END_PI, Beta Nine BVBA.
;;;;
;;;; You are granted the rights to distribute and use this software
;;;; as governed by the terms of the Lisp Lesser General Public License
;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
(defpackage :cl-s3
(:use common-lisp)
(:export
#:*access-key-id*
#:*secret-access-key*
#:request-date
#:unix-time->lisp-time
#:lisp-time->unix-time
#:make-authorization
#:amazon-s3-api-error
#:get-service
#:get-bucket
#:put-bucket
#:delete-bucket
#:get-object
#:put-object
#:head-object
#:delete-object
#:list-buckets
#:list-objects
#:upload-file
#:download-file)
(:documentation "A Common Lisp Amazon S3 client interface package"))
;;; eof
|
[
{
"context": "ense. See the file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;",
"end": 161,
"score": 0.9991880059242249,
"start": 151,
"tag": "NAME",
"value": "Eric Smith"
},
{
"context": " file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 185,
"score": 0.999930202960968,
"start": 163,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/kestrel/prime-fields/prime-fields.lisp
|
mayankmanj/acl2
| 305 |
; Prime fields library
;
; Copyright (C) 2019-2021 Kestrel Institute
;
; License: A 3-clause BSD license. See the file books/3BSD-mod.txt.
;
; Author: Eric Smith ([email protected])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "PFIELD")
;; This book defines operations on the finite field consisting of the integers
;; modulo some prime p.
;; The rules in the book generally each deal with a single function. For
;; reasoning about these operations, consider including the book
;; prime-fields-rules.
;; In this version of the formalization, the prime is passed explicitly to all
;; of the operations. See also prime-fields-alt.lisp, which uses a constrained
;; function for the prime.
;(include-book "../../projects/quadratic-reciprocity/euclid") ;brings in rtl::primep
(include-book "../utilities/pos-fix")
(include-book "fep")
(include-book "minus1")
(include-book "neg")
(include-book "add")
(include-book "sub")
(include-book "mul")
(include-book "pow")
(include-book "inv")
(include-book "div")
(local (include-book "support"))
(local (include-book "../arithmetic-light/times"))
(local (include-book "../arithmetic-light/expt"))
(local (include-book "../arithmetic-light/mod"))
(in-theory (disable (:e rtl::primep)))
(defmacro primep (x) `(rtl::primep ,x))
|
8582
|
; Prime fields library
;
; Copyright (C) 2019-2021 Kestrel Institute
;
; License: A 3-clause BSD license. See the file books/3BSD-mod.txt.
;
; Author: <NAME> (<EMAIL>)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "PFIELD")
;; This book defines operations on the finite field consisting of the integers
;; modulo some prime p.
;; The rules in the book generally each deal with a single function. For
;; reasoning about these operations, consider including the book
;; prime-fields-rules.
;; In this version of the formalization, the prime is passed explicitly to all
;; of the operations. See also prime-fields-alt.lisp, which uses a constrained
;; function for the prime.
;(include-book "../../projects/quadratic-reciprocity/euclid") ;brings in rtl::primep
(include-book "../utilities/pos-fix")
(include-book "fep")
(include-book "minus1")
(include-book "neg")
(include-book "add")
(include-book "sub")
(include-book "mul")
(include-book "pow")
(include-book "inv")
(include-book "div")
(local (include-book "support"))
(local (include-book "../arithmetic-light/times"))
(local (include-book "../arithmetic-light/expt"))
(local (include-book "../arithmetic-light/mod"))
(in-theory (disable (:e rtl::primep)))
(defmacro primep (x) `(rtl::primep ,x))
| true |
; Prime fields library
;
; Copyright (C) 2019-2021 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 "PFIELD")
;; This book defines operations on the finite field consisting of the integers
;; modulo some prime p.
;; The rules in the book generally each deal with a single function. For
;; reasoning about these operations, consider including the book
;; prime-fields-rules.
;; In this version of the formalization, the prime is passed explicitly to all
;; of the operations. See also prime-fields-alt.lisp, which uses a constrained
;; function for the prime.
;(include-book "../../projects/quadratic-reciprocity/euclid") ;brings in rtl::primep
(include-book "../utilities/pos-fix")
(include-book "fep")
(include-book "minus1")
(include-book "neg")
(include-book "add")
(include-book "sub")
(include-book "mul")
(include-book "pow")
(include-book "inv")
(include-book "div")
(local (include-book "support"))
(local (include-book "../arithmetic-light/times"))
(local (include-book "../arithmetic-light/expt"))
(local (include-book "../arithmetic-light/mod"))
(in-theory (disable (:e rtl::primep)))
(defmacro primep (x) `(rtl::primep ,x))
|
[
{
"context": ")\n\n(defsystem papyrus\n :version \"0.1\"\n :author \"TANIGUCHI Masaya\"\n :license \"MIT\"\n :depends-on (:named-readtable",
"end": 156,
"score": 0.999823272228241,
"start": 140,
"tag": "NAME",
"value": "TANIGUCHI Masaya"
}
] |
papyrus.asd
|
nzt/papyrus
| 15 |
(in-package :cl-user)
(defpackage papyrus-asd
(:use :cl :asdf))
(in-package :papyrus-asd)
(defsystem papyrus
:version "0.1"
:author "TANIGUCHI Masaya"
:license "MIT"
:depends-on (:named-readtables)
:components ((:file "papyrus"))
:description "A Literate Programming Tool")
|
2284
|
(in-package :cl-user)
(defpackage papyrus-asd
(:use :cl :asdf))
(in-package :papyrus-asd)
(defsystem papyrus
:version "0.1"
:author "<NAME>"
:license "MIT"
:depends-on (:named-readtables)
:components ((:file "papyrus"))
:description "A Literate Programming Tool")
| true |
(in-package :cl-user)
(defpackage papyrus-asd
(:use :cl :asdf))
(in-package :papyrus-asd)
(defsystem papyrus
:version "0.1"
:author "PI:NAME:<NAME>END_PI"
:license "MIT"
:depends-on (:named-readtables)
:components ((:file "papyrus"))
:description "A Literate Programming Tool")
|
[
{
"context": " of harmony\n (c) 2017 Shirakumo http://tymoon.eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n",
"end": 91,
"score": 0.9999211430549622,
"start": 73,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "umo http://tymoon.eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(in-package #:cl-user)\n(",
"end": 116,
"score": 0.9998922348022461,
"start": 102,
"tag": "NAME",
"value": "Nicolas Hafner"
},
{
"context": ".eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(in-package #:cl-user)\n(defpackage #:harmony",
"end": 136,
"score": 0.9999253749847412,
"start": 118,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
sources/mp3.lisp
|
terminal625/harmony
| 0 |
#|
This file is a part of harmony
(c) 2017 Shirakumo http://tymoon.eu ([email protected])
Author: Nicolas Hafner <[email protected]>
|#
(in-package #:cl-user)
(defpackage #:harmony-mp3
(:nicknames #:org.shirakumo.fraf.harmony.sources.mp3)
(:use #:cl #:harmony)
(:export
#:mp3-source))
(in-package #:org.shirakumo.fraf.harmony.sources.mp3)
(define-source-type "mp3" mp3-source)
(defclass mp3-source (unpack-source file-source)
((mp3-file :initform NIL :accessor mp3-file)
(channels :initarg :channels :accessor channels))
(:default-initargs :channels 2))
(defmethod initialize-packed-audio ((source mp3-source))
(let ((file (cl-mpg123:make-file (file source)
:accepted-format (list (samplerate (context source))
(channels source)
:float))))
(cl-mpg123:connect file)
(setf (mp3-file source) file)
(multiple-value-bind (rate channels encoding) (cl-mpg123:file-format file)
(cl-mixed:make-packed-audio
NIL
0
encoding
channels
:alternating
rate))))
(defmethod seek-to-sample ((source mp3-source) position)
(cl-mpg123:seek (mp3-file source) position :mode :absolute :by :sample))
(defmethod sample-count ((source mp3-source))
(cl-mpg123:sample-count (mp3-file source)))
(defmethod process ((source mp3-source) samples)
(fill-for-unpack-source source samples #'cl-mpg123:read-directly (mp3-file source)))
|
18311
|
#|
This file is a part of harmony
(c) 2017 Shirakumo http://tymoon.eu (<EMAIL>)
Author: <NAME> <<EMAIL>>
|#
(in-package #:cl-user)
(defpackage #:harmony-mp3
(:nicknames #:org.shirakumo.fraf.harmony.sources.mp3)
(:use #:cl #:harmony)
(:export
#:mp3-source))
(in-package #:org.shirakumo.fraf.harmony.sources.mp3)
(define-source-type "mp3" mp3-source)
(defclass mp3-source (unpack-source file-source)
((mp3-file :initform NIL :accessor mp3-file)
(channels :initarg :channels :accessor channels))
(:default-initargs :channels 2))
(defmethod initialize-packed-audio ((source mp3-source))
(let ((file (cl-mpg123:make-file (file source)
:accepted-format (list (samplerate (context source))
(channels source)
:float))))
(cl-mpg123:connect file)
(setf (mp3-file source) file)
(multiple-value-bind (rate channels encoding) (cl-mpg123:file-format file)
(cl-mixed:make-packed-audio
NIL
0
encoding
channels
:alternating
rate))))
(defmethod seek-to-sample ((source mp3-source) position)
(cl-mpg123:seek (mp3-file source) position :mode :absolute :by :sample))
(defmethod sample-count ((source mp3-source))
(cl-mpg123:sample-count (mp3-file source)))
(defmethod process ((source mp3-source) samples)
(fill-for-unpack-source source samples #'cl-mpg123:read-directly (mp3-file source)))
| true |
#|
This file is a part of harmony
(c) 2017 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 #:harmony-mp3
(:nicknames #:org.shirakumo.fraf.harmony.sources.mp3)
(:use #:cl #:harmony)
(:export
#:mp3-source))
(in-package #:org.shirakumo.fraf.harmony.sources.mp3)
(define-source-type "mp3" mp3-source)
(defclass mp3-source (unpack-source file-source)
((mp3-file :initform NIL :accessor mp3-file)
(channels :initarg :channels :accessor channels))
(:default-initargs :channels 2))
(defmethod initialize-packed-audio ((source mp3-source))
(let ((file (cl-mpg123:make-file (file source)
:accepted-format (list (samplerate (context source))
(channels source)
:float))))
(cl-mpg123:connect file)
(setf (mp3-file source) file)
(multiple-value-bind (rate channels encoding) (cl-mpg123:file-format file)
(cl-mixed:make-packed-audio
NIL
0
encoding
channels
:alternating
rate))))
(defmethod seek-to-sample ((source mp3-source) position)
(cl-mpg123:seek (mp3-file source) position :mode :absolute :by :sample))
(defmethod sample-count ((source mp3-source))
(cl-mpg123:sample-count (mp3-file source)))
(defmethod process ((source mp3-source) samples)
(fill-for-unpack-source source samples #'cl-mpg123:read-directly (mp3-file source)))
|
[
{
"context": "; Winston & Horn (3rd Edition) Chapter 19 \n\n\n; First set up the ne",
"end": 16,
"score": 0.9528541564941406,
"start": 2,
"tag": "NAME",
"value": "Winston & Horn"
}
] |
lsp/search.lsp
|
blakemcbride/XLISP-PLUS
| 17 |
; Winston & Horn (3rd Edition) Chapter 19
; First set up the network
(setf (get 's 'neighbors) '(a d)
(get 'a 'neighbors) '(s b d)
(get 'b 'neighbors) '(a c e)
(get 'c 'neighbors) '(b)
(get 'd 'neighbors) '(s a e)
(get 'e 'neighbors) '(b d f)
(get 'f 'neighbors) '(e))
(setf (get 's 'coordinates) '(0 3)
(get 'a 'coordinates) '(4 6)
(get 'b 'coordinates) '(7 6)
(get 'c 'coordinates) '(11 6)
(get 'd 'coordinates) '(3 0)
(get 'e 'coordinates) '(6 0)
(get 'f 'coordinates) '(11 3))
; The extend function is used everywhere to provide a new queue
(defun extend (path)
(print (reverse path)) ; for observing what is happening
(mapcar #'(lambda (new-node) (cons new-node path))
(remove-if #'(lambda (neighbor) (member neighbor path))
(get (first path) 'neighbors))))
; depth first search
(defun depth-first (start finish &optional (queue (list (list start))))
(cond ((endp queue) nil) ; Queue empty?
((eq finish (first (first queue))) ; finish found?
(reverse (first queue)))
(t (depth-first
start
finish
(append (extend (first queue))
(rest queue))))))
; breadth first search
(defun breadth-first (start finish &optional (queue (list (list start))))
(cond ((endp queue) nil) ; Queue empty?
((eq finish (first (first queue))) ; finish found?
(reverse (first queue)))
(t (breadth-first
start
finish
(append (rest queue)
(extend (first queue)))))))
; best first search
(defun best-first (start finish &optional (queue (list (list start))))
(cond ((endp queue) nil) ; Queue empty?
((eq finish (first (first queue))) ; finish found?
(reverse (first queue)))
(t (best-first
start
finish
(sort (append (extend (first queue))
(rest queue))
#'(lambda (p1 p2) (closerp p1 p2 finish)))))))
(defun square (x) (* x x))
(defun straight-line-distance (node-1 node-2)
(let ((coord-1 (get node-1 'coordinates))
(coord-2 (get node-2 'coordinates)))
(sqrt (float (+ (square (- (first coord-1) (first coord-2)))
(square (- (second coord-1) (second coord-2))))))))
(defun closerp (path-1 path-2 target-node)
(< (straight-line-distance (first path-1) target-node)
(straight-line-distance (first path-2) target-node)))
; hill climb search
(defun hill-climb (start finish &optional (queue (list (list start))))
(cond ((endp queue) nil) ; Queue empty?
((eq finish (first (first queue))) ; finish found?
(reverse (first queue)))
(t (hill-climb
start
finish
(append (sort (extend (first queue))
#'(lambda (p1 p2)
(closerp p1 p2 finish)))
(rest queue))))))
; branch and bound search (shortest length guarenteed)
(defun branch-and-bound (start finish &optional (queue (list (list start))))
(cond ((endp queue) nil) ; Queue empty?
((eq finish (first (first queue))) ; finish found?
(reverse (first queue)))
(t (branch-and-bound
start
finish
(sort (append (extend (first queue))
(rest queue))
#'shorterp)))))
(defun shorterp (path-1 path-2)
(< (path-length path-1) (path-length path-2)))
(defun path-length (path)
(if (endp (rest path))
0
(+ (straight-line-distance (first path) (second path))
(path-length (rest path)))))
; pert chart searching (problem 19-7)
(setf (get 's 'successors) '(a d)
(get 'a 'successors) '(b d)
(get 'b 'successors) '(c e)
(get 'c 'successors) '()
(get 'd 'successors) '(e)
(get 'e 'successors) '(f)
(get 'f 'successors) '())
(setf (get 's 'time-consumed) 3
(get 'a 'time-consumed) 2
(get 'b 'time-consumed) 4
(get 'c 'time-consumed) 3
(get 'd 'time-consumed) 3
(get 'e 'time-consumed) 2
(get 'f 'time-consumed) 1)
(defun pextend (path)
(mapcar #'(lambda (new-node) (cons new-node path))
(remove-if #'(lambda (successor) (member successor path))
(get (first path) 'successors))))
(defun all-paths (start &optional (queue (list (list start))))
(let ((extended (pextend (first queue))))
(cond ((endp extended)
(mapcar #'reverse queue))
(t (all-paths
start
(sort (append extended (rest queue))
#'first-path-incomplete-p))))))
(defun first-path-incomplete-p (p1 p2)
(not (endp (pextend p1))))
; Pert chart searching (problem 19-8)
(defun time-consumed (path)
(if (endp path)
0
(+ (get (first path) 'time-consumed)
(time-consumed (rest path)))))
(defun longerp (p1 p2) (> (time-consumed p1) (time-consumed p2)))
(defun critical-path (start &optional (queue (list (list start))))
(let ((extended (pextend (first queue))))
(cond ((endp extended)
(reverse (first (sort queue #'longerp))))
(t (critical-path
start
(sort (append extended (rest queue))
#'first-path-incomplete-p))))))
|
75290
|
; <NAME> (3rd Edition) Chapter 19
; First set up the network
(setf (get 's 'neighbors) '(a d)
(get 'a 'neighbors) '(s b d)
(get 'b 'neighbors) '(a c e)
(get 'c 'neighbors) '(b)
(get 'd 'neighbors) '(s a e)
(get 'e 'neighbors) '(b d f)
(get 'f 'neighbors) '(e))
(setf (get 's 'coordinates) '(0 3)
(get 'a 'coordinates) '(4 6)
(get 'b 'coordinates) '(7 6)
(get 'c 'coordinates) '(11 6)
(get 'd 'coordinates) '(3 0)
(get 'e 'coordinates) '(6 0)
(get 'f 'coordinates) '(11 3))
; The extend function is used everywhere to provide a new queue
(defun extend (path)
(print (reverse path)) ; for observing what is happening
(mapcar #'(lambda (new-node) (cons new-node path))
(remove-if #'(lambda (neighbor) (member neighbor path))
(get (first path) 'neighbors))))
; depth first search
(defun depth-first (start finish &optional (queue (list (list start))))
(cond ((endp queue) nil) ; Queue empty?
((eq finish (first (first queue))) ; finish found?
(reverse (first queue)))
(t (depth-first
start
finish
(append (extend (first queue))
(rest queue))))))
; breadth first search
(defun breadth-first (start finish &optional (queue (list (list start))))
(cond ((endp queue) nil) ; Queue empty?
((eq finish (first (first queue))) ; finish found?
(reverse (first queue)))
(t (breadth-first
start
finish
(append (rest queue)
(extend (first queue)))))))
; best first search
(defun best-first (start finish &optional (queue (list (list start))))
(cond ((endp queue) nil) ; Queue empty?
((eq finish (first (first queue))) ; finish found?
(reverse (first queue)))
(t (best-first
start
finish
(sort (append (extend (first queue))
(rest queue))
#'(lambda (p1 p2) (closerp p1 p2 finish)))))))
(defun square (x) (* x x))
(defun straight-line-distance (node-1 node-2)
(let ((coord-1 (get node-1 'coordinates))
(coord-2 (get node-2 'coordinates)))
(sqrt (float (+ (square (- (first coord-1) (first coord-2)))
(square (- (second coord-1) (second coord-2))))))))
(defun closerp (path-1 path-2 target-node)
(< (straight-line-distance (first path-1) target-node)
(straight-line-distance (first path-2) target-node)))
; hill climb search
(defun hill-climb (start finish &optional (queue (list (list start))))
(cond ((endp queue) nil) ; Queue empty?
((eq finish (first (first queue))) ; finish found?
(reverse (first queue)))
(t (hill-climb
start
finish
(append (sort (extend (first queue))
#'(lambda (p1 p2)
(closerp p1 p2 finish)))
(rest queue))))))
; branch and bound search (shortest length guarenteed)
(defun branch-and-bound (start finish &optional (queue (list (list start))))
(cond ((endp queue) nil) ; Queue empty?
((eq finish (first (first queue))) ; finish found?
(reverse (first queue)))
(t (branch-and-bound
start
finish
(sort (append (extend (first queue))
(rest queue))
#'shorterp)))))
(defun shorterp (path-1 path-2)
(< (path-length path-1) (path-length path-2)))
(defun path-length (path)
(if (endp (rest path))
0
(+ (straight-line-distance (first path) (second path))
(path-length (rest path)))))
; pert chart searching (problem 19-7)
(setf (get 's 'successors) '(a d)
(get 'a 'successors) '(b d)
(get 'b 'successors) '(c e)
(get 'c 'successors) '()
(get 'd 'successors) '(e)
(get 'e 'successors) '(f)
(get 'f 'successors) '())
(setf (get 's 'time-consumed) 3
(get 'a 'time-consumed) 2
(get 'b 'time-consumed) 4
(get 'c 'time-consumed) 3
(get 'd 'time-consumed) 3
(get 'e 'time-consumed) 2
(get 'f 'time-consumed) 1)
(defun pextend (path)
(mapcar #'(lambda (new-node) (cons new-node path))
(remove-if #'(lambda (successor) (member successor path))
(get (first path) 'successors))))
(defun all-paths (start &optional (queue (list (list start))))
(let ((extended (pextend (first queue))))
(cond ((endp extended)
(mapcar #'reverse queue))
(t (all-paths
start
(sort (append extended (rest queue))
#'first-path-incomplete-p))))))
(defun first-path-incomplete-p (p1 p2)
(not (endp (pextend p1))))
; Pert chart searching (problem 19-8)
(defun time-consumed (path)
(if (endp path)
0
(+ (get (first path) 'time-consumed)
(time-consumed (rest path)))))
(defun longerp (p1 p2) (> (time-consumed p1) (time-consumed p2)))
(defun critical-path (start &optional (queue (list (list start))))
(let ((extended (pextend (first queue))))
(cond ((endp extended)
(reverse (first (sort queue #'longerp))))
(t (critical-path
start
(sort (append extended (rest queue))
#'first-path-incomplete-p))))))
| true |
; PI:NAME:<NAME>END_PI (3rd Edition) Chapter 19
; First set up the network
(setf (get 's 'neighbors) '(a d)
(get 'a 'neighbors) '(s b d)
(get 'b 'neighbors) '(a c e)
(get 'c 'neighbors) '(b)
(get 'd 'neighbors) '(s a e)
(get 'e 'neighbors) '(b d f)
(get 'f 'neighbors) '(e))
(setf (get 's 'coordinates) '(0 3)
(get 'a 'coordinates) '(4 6)
(get 'b 'coordinates) '(7 6)
(get 'c 'coordinates) '(11 6)
(get 'd 'coordinates) '(3 0)
(get 'e 'coordinates) '(6 0)
(get 'f 'coordinates) '(11 3))
; The extend function is used everywhere to provide a new queue
(defun extend (path)
(print (reverse path)) ; for observing what is happening
(mapcar #'(lambda (new-node) (cons new-node path))
(remove-if #'(lambda (neighbor) (member neighbor path))
(get (first path) 'neighbors))))
; depth first search
(defun depth-first (start finish &optional (queue (list (list start))))
(cond ((endp queue) nil) ; Queue empty?
((eq finish (first (first queue))) ; finish found?
(reverse (first queue)))
(t (depth-first
start
finish
(append (extend (first queue))
(rest queue))))))
; breadth first search
(defun breadth-first (start finish &optional (queue (list (list start))))
(cond ((endp queue) nil) ; Queue empty?
((eq finish (first (first queue))) ; finish found?
(reverse (first queue)))
(t (breadth-first
start
finish
(append (rest queue)
(extend (first queue)))))))
; best first search
(defun best-first (start finish &optional (queue (list (list start))))
(cond ((endp queue) nil) ; Queue empty?
((eq finish (first (first queue))) ; finish found?
(reverse (first queue)))
(t (best-first
start
finish
(sort (append (extend (first queue))
(rest queue))
#'(lambda (p1 p2) (closerp p1 p2 finish)))))))
(defun square (x) (* x x))
(defun straight-line-distance (node-1 node-2)
(let ((coord-1 (get node-1 'coordinates))
(coord-2 (get node-2 'coordinates)))
(sqrt (float (+ (square (- (first coord-1) (first coord-2)))
(square (- (second coord-1) (second coord-2))))))))
(defun closerp (path-1 path-2 target-node)
(< (straight-line-distance (first path-1) target-node)
(straight-line-distance (first path-2) target-node)))
; hill climb search
(defun hill-climb (start finish &optional (queue (list (list start))))
(cond ((endp queue) nil) ; Queue empty?
((eq finish (first (first queue))) ; finish found?
(reverse (first queue)))
(t (hill-climb
start
finish
(append (sort (extend (first queue))
#'(lambda (p1 p2)
(closerp p1 p2 finish)))
(rest queue))))))
; branch and bound search (shortest length guarenteed)
(defun branch-and-bound (start finish &optional (queue (list (list start))))
(cond ((endp queue) nil) ; Queue empty?
((eq finish (first (first queue))) ; finish found?
(reverse (first queue)))
(t (branch-and-bound
start
finish
(sort (append (extend (first queue))
(rest queue))
#'shorterp)))))
(defun shorterp (path-1 path-2)
(< (path-length path-1) (path-length path-2)))
(defun path-length (path)
(if (endp (rest path))
0
(+ (straight-line-distance (first path) (second path))
(path-length (rest path)))))
; pert chart searching (problem 19-7)
(setf (get 's 'successors) '(a d)
(get 'a 'successors) '(b d)
(get 'b 'successors) '(c e)
(get 'c 'successors) '()
(get 'd 'successors) '(e)
(get 'e 'successors) '(f)
(get 'f 'successors) '())
(setf (get 's 'time-consumed) 3
(get 'a 'time-consumed) 2
(get 'b 'time-consumed) 4
(get 'c 'time-consumed) 3
(get 'd 'time-consumed) 3
(get 'e 'time-consumed) 2
(get 'f 'time-consumed) 1)
(defun pextend (path)
(mapcar #'(lambda (new-node) (cons new-node path))
(remove-if #'(lambda (successor) (member successor path))
(get (first path) 'successors))))
(defun all-paths (start &optional (queue (list (list start))))
(let ((extended (pextend (first queue))))
(cond ((endp extended)
(mapcar #'reverse queue))
(t (all-paths
start
(sort (append extended (rest queue))
#'first-path-incomplete-p))))))
(defun first-path-incomplete-p (p1 p2)
(not (endp (pextend p1))))
; Pert chart searching (problem 19-8)
(defun time-consumed (path)
(if (endp path)
0
(+ (get (first path) 'time-consumed)
(time-consumed (rest path)))))
(defun longerp (p1 p2) (> (time-consumed p1) (time-consumed p2)))
(defun critical-path (start &optional (queue (list (list start))))
(let ((extended (pextend (first queue))))
(cond ((endp extended)
(reverse (first (sort queue #'longerp))))
(t (critical-path
start
(sort (append extended (rest queue))
#'first-path-incomplete-p))))))
|
[
{
"context": "syntax. \n;;;;; Completed: 05/07/2017\n;;;;; Author: Stanley C. Small <[email protected]>\n;;;;; Modifications: n",
"end": 353,
"score": 0.9998680353164673,
"start": 337,
"tag": "NAME",
"value": "Stanley C. Small"
},
{
"context": "leted: 05/07/2017\n;;;;; Author: Stanley C. Small <[email protected]>\n;;;;; Modifications: none\n;;;;;;;;;;;;;;;;;;;;;;",
"end": 379,
"score": 0.999935507774353,
"start": 355,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " and end). NOTE: This fucntion was inspired by Dr. Roy Turner's work. \n;;;\n\n(defmethod tspfitness ((i individua",
"end": 5701,
"score": 0.999138593673706,
"start": 5691,
"tag": "NAME",
"value": "Roy Turner"
},
{
"context": " algorithm inspired \n;;;\t\tby pseudocode written by Stuart Russell and Peter Norvig. The fucntion is\n;;;\t\tpassed a s",
"end": 9766,
"score": 0.9998263120651245,
"start": 9752,
"tag": "NAME",
"value": "Stuart Russell"
},
{
"context": " \n;;;\t\tby pseudocode written by Stuart Russell and Peter Norvig. The fucntion is\n;;;\t\tpassed a series of domain-d",
"end": 9783,
"score": 0.9998611807823181,
"start": 9771,
"tag": "NAME",
"value": "Peter Norvig"
}
] |
search.lisp
|
stansmall/LocalSearchTechniques
| 1 |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;; This file contains the code for an implementation of a genetic algorithm and a
;;;;; simulated annealing algorithm, along with two problem domains. The program is
;;;;; written in Common Lisp syntax.
;;;;; Completed: 05/07/2017
;;;;; Author: Stanley C. Small <[email protected]>
;;;;; Modifications: none
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Class: individual
;;; Slots:
;;; - state: the current state of the problem
;;; - fitness: an evaluated fitness of the current state based on a fitness-fn
;;; Description:
;;; This class holds all information necessary to represent an indidivdual in a
;;; population or a neighboring state in the simulated annealing algorithm, both
;;; candidate solutions for the given problem.
;;;
(defclass individual () (
(state :initform nil :initarg :state :accessor state)
(fitness :initform nil :initarg :fitness :accessor fitness)))
;;;
;;; Functions: getfitness, getstate
;;; Arguments:
;;; - an individual: used to retrive a state or fitness value
;;; Description:
;;; These are accessor methods for the individual class. Storing the fitness value
;;; along with the state drastically reduces computation time. NOTE: the acessor
;;; does not compute the fitness fucntion if it is not availible. It must be used
;;; at discression of the user.
;;;
(defmethod getfitness ((i individual))
(slot-value i 'fitness))
(defmethod getstate ((i individual))
(slot-value i 'state))
;;;
;;; Class: problem
;;; Slots:
;;; - fitness-fn: a problem-specific fitness function
;;; - mutate-fn: a problem-specific fucntion used for mutation
;;; - reproduce-fn: a problem-specific fucntion for reproduction in a ga
;;; - population-fn: a function used to create an initial population
;;; Description:
;;; This class holds specific functions for each problem to be used in the
;;; domain independent algorithms. Each problem must be tuned to achieve best
;;; performance during search.
;;;
(defclass problem () (
(fitness-fn :initform nil :initarg :fitness-fn :accessor fitness-fn)
(mutate-fn :initform nil :initarg :mutate-fn :accessor mutate-fn)
(reproduce-fn :initform nil :initarg :reproduce-fn :accessor reproduce-fn)
(population-fn :initform nil :initarg :population-fn :accessor population-fn)))
;;;
;;; Problem: 8queens
;;; Description:
;;; The 8-queens problem has a goal of arranging 8 queens on a chessboard in a
;;; way so that they do not attack each other. These domain-specific functions
;;; are designed to optimise perfomance of the local search algorithms.
;;;
(setq 8queens (make-instance 'problem
:fitness-fn 'queensfitness
:mutate-fn 'mutate
:reproduce-fn 'reproduce
:population-fn 'queenspop))
;;;
;;; Method: queensfitness
;;; Arguments:
;;; - i: an individual
;;; Description:
;;; This fucntion counts the number of non-attacking pairs of queens on a chessboard.
;;; A solution to the problem has 28 pairs of non-attacking queens.
;;;
(defmethod queensfitness ((i individual))
(let ((attacked 0))
(with-slots (state fitness) i
(loop for i from 0 to 6 do
(loop for j from (+ 1 i) to 7 do
(if (eql (nth i state) (nth j state))
(setq attacked (+ attacked 1)))
(if (eql (- (nth j state) (nth i state)) (or (- j i) (+ j i)))
(setq attacked (+ attacked 1)))
(if (eql (- (nth i state) (nth j state)) (or (- j i) (+ j i)))
(setq attacked (+ attacked 1)))))
(setq fitness (- 28 attacked)))))
;;;
;;; Fucntion: queenspop
;;; Arguments:
;;; - size: the size of the poplation
;;; - fitness-fn: a domain-dependent evaluation for the fitness of an individual
;;; Description:
;;; This function creates a population of a specified size for the 8queens problem.
;;;
(defun queenspop (size fitness-fn)
(let ((g nil) (p nil))
(dotimes (i size)
(dotimes (j 8)
(setf g (cons (+ (random 8) 1) g)))
(setf p (cons (make-instance 'individual :state g ) p))
(funcall fitness-fn (car p))
(setf g nil)) p))
;;;
;;; Problem: tsp
;;; Description:
;;; The traveling salesperson problem is an NP-hard problem with a goal of
;;; finding the shortest path between a number of cities with given distances.
;;; These domain-specific functions are designed to optimise perfomance of the
;;; local search algorithms.
;;;
(setq tsp (make-instance 'problem
:fitness-fn 'tspfitness
:mutate-fn 'swap
:reproduce-fn 'tspreproduce
:population-fn 'tsppop))
;;;
;;; Fucntion: generate tsp
;;; Arguments:
;;; - cityquantity: the number of cities
;;; - mindistance: the minimum number of distance units between cities
;;; - maxistance: the maximum number of distance units between cities
;;; Description:
;;; This function will generate a random TSP problem given the number of cities and
;;; min and max link costs.
;;;
(defun generatetsp (cityquantity mindistance maxdistance)
(defvar *cities* cityquantity)
(defvar *tspdist* (loop for i from 1 to (- cityquantity 1) append
(loop for j from (+ 1 i) to cityquantity collect
(list i j (+ mindistance (random (- (+ maxdistance 1) mindistance))))))))
;;;
;;; Method: tspfitness
;;; Arguments:
;;; - i: an individual
;;; Description:
;;; This fucntion calculates the cost of the current path, but returns the reciprocal so
;;; shorter paths are evaluated as more optimal than longer paths. If a path does not begin
;;; and end at the same place, then it’s penalized, as it is if a city occurs more than once
;;; (other than start and end). NOTE: This fucntion was inspired by Dr. Roy Turner's work.
;;;
(defmethod tspfitness ((i individual))
(with-slots (state fitness) i
(setq total 0)
(if (eql (first state) (car (last state))) t (setq total most-positive-fixnum))
(if (duplicates (cdr state)) (setq total most-positive-fixnum))
(loop for j from 0 to (- (length state) 2) do
(setq total (+ total
(or (third (car (member (list (nth j state) (nth (+ j 1) state)) *tspdist*
:test #'(lambda (target candidate)
(or (and (eql (car target) (car candidate))
(eql (cadr target) (cadr candidate)))
(and (eql (car target) (cadr candidate))
(eql (cadr target) (car candidate))))))))
most-positive-fixnum))))
(setq fitness (float (/ 1 total)))))
;;;
;;; Fucntion: duplicates
;;; Arguments:
;;; - state: a list
;;; Description:
;;; This function determines if a list contains duplicates.
;;;
(defun duplicates (state)
(cond ((null state) nil)
((member (car state) (cdr state)) (cons (car state) (duplicates (cdr state))))
(t (duplicates (cdr state)))))
;;;
;;; Fucntion: tsppop
;;; Arguments:
;;; - size: the size of the poplation
;;; - fitness-fn: a domain-dependent evaluation for the fitness of an individual
;;; Description:
;;; This function creates a population of a specified size for the tsp problem.
;;;
(defun tsppop (size fitness-fn)
(let ((g nil) (p nil))
(dotimes (i size)
(loop for j from 1 to *cities* do
(setf g (cons j g)))
(setf p (cons (make-instance 'individual :state (cons '1 g)) p))
(funcall fitness-fn (car p))
(setf g nil)) p))
;;;
;;; Fucntion: annealing
;;; Arguments:
;;; - p: an problem
;;; - schedule: a schedule for the temperature to cool in the function
;;; Description:
;;; The simulated annealing algorithm is similar to the hill-climbing algorithm,
;;; aside from the fact that the agorithm allows the selection of sub-optimal moves
;;; to avoid the possibility of finding a local maximum in favor of a global one.
;;; As time passes, errors are less likely to occur. When the temperature reaches 0
;;; The current individual is returned.
;;;
(defun annealing ((p problem) schedule)
(let ((current nil) (next nil) (temperature nil))
(with-slots (fitness-fn mutate-fn intital-state population-fn) p
(setf current (car (funcall population-fn 1 fitness-fn)))
(funcall fitness-fn current)
(loop for timestep from 1 to most-positive-fixnum do
(setf temperature (funcall schedule timestep))
(if (eql 0 temperature) (return current))
(setf next (getneighbor current mutate-fn))
(funcall fitness-fn next)
(setf deltaE (- (getfitness next) (print (getfitness current))))
(if (> deltaE 0) (setq current next))
(if (> (random 1.0) (exp (/ deltaE temperature))) (setf current next))))))
;;;
;;; Fucntion: getneighbor
;;; Arguments:
;;; - i: an individual
;;; - mutate-fn: a domain-specific function used to mutate an individual state
;;; Description:
;;; This function copies an inidivual, then modifies that individual using a
;;; mutate-fn, then returns that individual.
;;;
(defun getneighbor ((i individual) mutate-fn)
(let ((neighbor nil))
(with-slots (state) i
(setq neighbor (make-instance 'individual :state (copy-list state)))
(funcall mutate-fn neighbor)
neighbor)))
;;;
;;; Fucntion: schedule
;;; Description:
;;; A sample schedule function from the AIMA website.
;;;
(defun schedule (timestep)
(let ((k 20) (lam .005) (lim 100))
(if (< (* k (exp (* lam timestep))) lim) (* k (exp (* lam timestep))) 0)))
;;;
;;; Function: ga
;;; Arguments:
;;; - p: a problem (either 8queens or tsp)
;;; - popsize: the size of the population
;;; - stopfitness: the desired fitness set to stop the search
;;; - mutationchance: a mutation rate percentage (0 to 100)
;;; - weight: a factor to which fitness plays a role
;;; (i.e. a higher weight will select fit individuals more often)
;;; Description:
;;; This is a domain-independent implementation of a genetic algorithm inspired
;;; by pseudocode written by Stuart Russell and Peter Norvig. The fucntion is
;;; passed a series of domain-dependent functions as specified by the CLOS problem
;;; object. Once an initial population is created, parents are selected with a
;;; random weighted selection, where the weight factor can be adjusted. The
;;; parents undergo a crossover, producing a child which has a chance of mutation.
;;; Each child is added to the new population and the new-population replaces the
;;; old population. The search stops when an individual reaches a fitnes passed as
;;; a parameter to the function.
;;;
(defun ga ((p problem) popsize stopfitness mutationchance weight)
(let ((population nil) (new-population nil) (x nil) (y nil) (child nil))
(with-slots (fitness-fn mutate-fn reproduce-fn population-fn intital-state) p
(setf population (funcall population-fn popsize fitness-fn)) ; new pop
(loop
(setf new-population nil)
(loop for individual from 0 to (length population) do
(setf x (randomweighted population fitness-fn weight)) ; select
(setf y (randomweighted population fitness-fn weight)) ; parents
(setf child (funcall reproduce-fn x y))
(if (< (random 100) mutationchance) ; mutation
(funcall mutate-fn child))
(print (funcall fitness-fn child)) ; display
(setf new-population (cons child new-population)) ; fitness
(setf population new-population))
(when (> (getfitness child) stopfitness) (return child)))))) ; stop cond
;;;
;;; Function: randomweighted
;;; Arguments:
;;; - population: a population
;;; - fitness-fn: a domain-dependent fitness-fn
;;; - weight: a factor to which the weights will be amplified
;;; Description:
;;; This fucntion randomly selects an individual from a population with a greater
;;; preference for individuals with a higher fitness value. The factor to which
;;; the fitness of an indivudal impacts the choice can be modified by the weight
;;; argument. The fitness of each individul is summed, then a threshold value is
;;; chosen. Indivduals are then added until the threshold is reached, then that
;;; individual is returned.
;;;
(defun randomweighted (population fitness-fn weight)
(let ((fitnesssum 0) (i 0) (z 0))
(loop for i in population do
(setf fitnesssum (+ (expt (getfitness i) weight) fitnesssum)))
(setf z (random fitnesssum)) ; threshold
(loop for j in population do
(setq i (+ (expt (getfitness j) weight) i))
(if (> i z) (return j)))))
;;;
;;; Method: mutate
;;; Arguments:
;;; - i: an individual
;;; Description:
;;; This fucntion modifies the state of an indivdual by randomly replacing one
;;; value in the state by a random number up to the length of the state.
;;; NOTE: This function does not update the fitness value for the state.
;;;
(defmethod mutate ((i individual))
(with-slots (state fitness) i
(setf (nth (random (length state)) state) (+ (random (length state)) 1))
i)) ; individual
;;;
;;; Method: swap
;;; Arguments:
;;; - i: an individual
;;; Description:
;;; This fucntion modifies the state of an indivdual by swapping two values.
;;; NOTE: This function does not update the fitness value for the state.
;;;
(defmethod swap ((i individual))
(with-slots (state fitness) i
(rotatef (nth (+ (random (- (length state) 3)) 1) state)
(nth (+ (random (- (length state) 3)) 1) state))
i)) ; individual
;;;
;;; Function: reproduce
;;; Arguments:
;;; - x: a parent individual
;;; - y: a parent individual
;;; Description:
;;; This fucntion takes two indivudals as arguments and performs a crossover
;;; between the two genomes. An index is randomly chosen to cut the indivduals,
;;; the the two states are combined to form a child CLOS individual.
;;;
(defun reproduce ((x individual) (y individual))
(let ((n nil) (c nil)) ; length &
(with-slots ((x state)) x ; cut index
(with-slots ((y state)) y
(setf n (- (length x) 1)) ; end of state
(setf c (random n)) ; cut index
(make-instance 'individual :state ; new child
(append (sublist x 0 c) (sublist y (+ c 1) n)))))))
;;;
;;; Function: sublist
;;; Arguments:
;;; - state: a list describing the state of an individual
;;; - start: staring index
;;; - end: ending index
;;; Description:
;;; This fucntion takes the state of an indivudal and creates a sublist when
;;; provided the starting and ending index.
;;;
(defun sublist (state start end)
(loop for i from start to end
collect (nth i state)))
;;;
;;; Function: tspreproduce
;;; Arguments:
;;; - x: a parent individual
;;; - y: a parent individual
;;; Description:
;;; This domain-dependent fucntion takes two indivudals as arguments and performs
;;; a crossover between the two genomes. A sublist is chosen with random start
;;; and end indexes. The sublist of the x genome is inserted into the state, with
;;; values of y added in a way which ensures no cities are duplicated in the child
;;; state.
;;;
(defun tspreproduce ((x individual) (y individual))
(let ((state nil) (start nil) (end nil) (sublist nil))
(with-slots ((x state)) x
(with-slots ((y state)) y
(setf start (+ (random (- (length x) 3)) 1)) ; ensure
(setf end (+ (random (- (- (length x) 2) start)) 1 start)) ; first & last
(setf sublist (sublist x start end)) ; remain
(loop for i in y do ; unchanged
(if (not (member i sublist)) (setq state (cons i state)))
(if (eql (position i y) start) (setq state (append sublist state))))
(make-instance 'individual :state state)))))
|
27924
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;; This file contains the code for an implementation of a genetic algorithm and a
;;;;; simulated annealing algorithm, along with two problem domains. The program is
;;;;; written in Common Lisp syntax.
;;;;; Completed: 05/07/2017
;;;;; Author: <NAME> <<EMAIL>>
;;;;; Modifications: none
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Class: individual
;;; Slots:
;;; - state: the current state of the problem
;;; - fitness: an evaluated fitness of the current state based on a fitness-fn
;;; Description:
;;; This class holds all information necessary to represent an indidivdual in a
;;; population or a neighboring state in the simulated annealing algorithm, both
;;; candidate solutions for the given problem.
;;;
(defclass individual () (
(state :initform nil :initarg :state :accessor state)
(fitness :initform nil :initarg :fitness :accessor fitness)))
;;;
;;; Functions: getfitness, getstate
;;; Arguments:
;;; - an individual: used to retrive a state or fitness value
;;; Description:
;;; These are accessor methods for the individual class. Storing the fitness value
;;; along with the state drastically reduces computation time. NOTE: the acessor
;;; does not compute the fitness fucntion if it is not availible. It must be used
;;; at discression of the user.
;;;
(defmethod getfitness ((i individual))
(slot-value i 'fitness))
(defmethod getstate ((i individual))
(slot-value i 'state))
;;;
;;; Class: problem
;;; Slots:
;;; - fitness-fn: a problem-specific fitness function
;;; - mutate-fn: a problem-specific fucntion used for mutation
;;; - reproduce-fn: a problem-specific fucntion for reproduction in a ga
;;; - population-fn: a function used to create an initial population
;;; Description:
;;; This class holds specific functions for each problem to be used in the
;;; domain independent algorithms. Each problem must be tuned to achieve best
;;; performance during search.
;;;
(defclass problem () (
(fitness-fn :initform nil :initarg :fitness-fn :accessor fitness-fn)
(mutate-fn :initform nil :initarg :mutate-fn :accessor mutate-fn)
(reproduce-fn :initform nil :initarg :reproduce-fn :accessor reproduce-fn)
(population-fn :initform nil :initarg :population-fn :accessor population-fn)))
;;;
;;; Problem: 8queens
;;; Description:
;;; The 8-queens problem has a goal of arranging 8 queens on a chessboard in a
;;; way so that they do not attack each other. These domain-specific functions
;;; are designed to optimise perfomance of the local search algorithms.
;;;
(setq 8queens (make-instance 'problem
:fitness-fn 'queensfitness
:mutate-fn 'mutate
:reproduce-fn 'reproduce
:population-fn 'queenspop))
;;;
;;; Method: queensfitness
;;; Arguments:
;;; - i: an individual
;;; Description:
;;; This fucntion counts the number of non-attacking pairs of queens on a chessboard.
;;; A solution to the problem has 28 pairs of non-attacking queens.
;;;
(defmethod queensfitness ((i individual))
(let ((attacked 0))
(with-slots (state fitness) i
(loop for i from 0 to 6 do
(loop for j from (+ 1 i) to 7 do
(if (eql (nth i state) (nth j state))
(setq attacked (+ attacked 1)))
(if (eql (- (nth j state) (nth i state)) (or (- j i) (+ j i)))
(setq attacked (+ attacked 1)))
(if (eql (- (nth i state) (nth j state)) (or (- j i) (+ j i)))
(setq attacked (+ attacked 1)))))
(setq fitness (- 28 attacked)))))
;;;
;;; Fucntion: queenspop
;;; Arguments:
;;; - size: the size of the poplation
;;; - fitness-fn: a domain-dependent evaluation for the fitness of an individual
;;; Description:
;;; This function creates a population of a specified size for the 8queens problem.
;;;
(defun queenspop (size fitness-fn)
(let ((g nil) (p nil))
(dotimes (i size)
(dotimes (j 8)
(setf g (cons (+ (random 8) 1) g)))
(setf p (cons (make-instance 'individual :state g ) p))
(funcall fitness-fn (car p))
(setf g nil)) p))
;;;
;;; Problem: tsp
;;; Description:
;;; The traveling salesperson problem is an NP-hard problem with a goal of
;;; finding the shortest path between a number of cities with given distances.
;;; These domain-specific functions are designed to optimise perfomance of the
;;; local search algorithms.
;;;
(setq tsp (make-instance 'problem
:fitness-fn 'tspfitness
:mutate-fn 'swap
:reproduce-fn 'tspreproduce
:population-fn 'tsppop))
;;;
;;; Fucntion: generate tsp
;;; Arguments:
;;; - cityquantity: the number of cities
;;; - mindistance: the minimum number of distance units between cities
;;; - maxistance: the maximum number of distance units between cities
;;; Description:
;;; This function will generate a random TSP problem given the number of cities and
;;; min and max link costs.
;;;
(defun generatetsp (cityquantity mindistance maxdistance)
(defvar *cities* cityquantity)
(defvar *tspdist* (loop for i from 1 to (- cityquantity 1) append
(loop for j from (+ 1 i) to cityquantity collect
(list i j (+ mindistance (random (- (+ maxdistance 1) mindistance))))))))
;;;
;;; Method: tspfitness
;;; Arguments:
;;; - i: an individual
;;; Description:
;;; This fucntion calculates the cost of the current path, but returns the reciprocal so
;;; shorter paths are evaluated as more optimal than longer paths. If a path does not begin
;;; and end at the same place, then it’s penalized, as it is if a city occurs more than once
;;; (other than start and end). NOTE: This fucntion was inspired by Dr. <NAME>'s work.
;;;
(defmethod tspfitness ((i individual))
(with-slots (state fitness) i
(setq total 0)
(if (eql (first state) (car (last state))) t (setq total most-positive-fixnum))
(if (duplicates (cdr state)) (setq total most-positive-fixnum))
(loop for j from 0 to (- (length state) 2) do
(setq total (+ total
(or (third (car (member (list (nth j state) (nth (+ j 1) state)) *tspdist*
:test #'(lambda (target candidate)
(or (and (eql (car target) (car candidate))
(eql (cadr target) (cadr candidate)))
(and (eql (car target) (cadr candidate))
(eql (cadr target) (car candidate))))))))
most-positive-fixnum))))
(setq fitness (float (/ 1 total)))))
;;;
;;; Fucntion: duplicates
;;; Arguments:
;;; - state: a list
;;; Description:
;;; This function determines if a list contains duplicates.
;;;
(defun duplicates (state)
(cond ((null state) nil)
((member (car state) (cdr state)) (cons (car state) (duplicates (cdr state))))
(t (duplicates (cdr state)))))
;;;
;;; Fucntion: tsppop
;;; Arguments:
;;; - size: the size of the poplation
;;; - fitness-fn: a domain-dependent evaluation for the fitness of an individual
;;; Description:
;;; This function creates a population of a specified size for the tsp problem.
;;;
(defun tsppop (size fitness-fn)
(let ((g nil) (p nil))
(dotimes (i size)
(loop for j from 1 to *cities* do
(setf g (cons j g)))
(setf p (cons (make-instance 'individual :state (cons '1 g)) p))
(funcall fitness-fn (car p))
(setf g nil)) p))
;;;
;;; Fucntion: annealing
;;; Arguments:
;;; - p: an problem
;;; - schedule: a schedule for the temperature to cool in the function
;;; Description:
;;; The simulated annealing algorithm is similar to the hill-climbing algorithm,
;;; aside from the fact that the agorithm allows the selection of sub-optimal moves
;;; to avoid the possibility of finding a local maximum in favor of a global one.
;;; As time passes, errors are less likely to occur. When the temperature reaches 0
;;; The current individual is returned.
;;;
(defun annealing ((p problem) schedule)
(let ((current nil) (next nil) (temperature nil))
(with-slots (fitness-fn mutate-fn intital-state population-fn) p
(setf current (car (funcall population-fn 1 fitness-fn)))
(funcall fitness-fn current)
(loop for timestep from 1 to most-positive-fixnum do
(setf temperature (funcall schedule timestep))
(if (eql 0 temperature) (return current))
(setf next (getneighbor current mutate-fn))
(funcall fitness-fn next)
(setf deltaE (- (getfitness next) (print (getfitness current))))
(if (> deltaE 0) (setq current next))
(if (> (random 1.0) (exp (/ deltaE temperature))) (setf current next))))))
;;;
;;; Fucntion: getneighbor
;;; Arguments:
;;; - i: an individual
;;; - mutate-fn: a domain-specific function used to mutate an individual state
;;; Description:
;;; This function copies an inidivual, then modifies that individual using a
;;; mutate-fn, then returns that individual.
;;;
(defun getneighbor ((i individual) mutate-fn)
(let ((neighbor nil))
(with-slots (state) i
(setq neighbor (make-instance 'individual :state (copy-list state)))
(funcall mutate-fn neighbor)
neighbor)))
;;;
;;; Fucntion: schedule
;;; Description:
;;; A sample schedule function from the AIMA website.
;;;
(defun schedule (timestep)
(let ((k 20) (lam .005) (lim 100))
(if (< (* k (exp (* lam timestep))) lim) (* k (exp (* lam timestep))) 0)))
;;;
;;; Function: ga
;;; Arguments:
;;; - p: a problem (either 8queens or tsp)
;;; - popsize: the size of the population
;;; - stopfitness: the desired fitness set to stop the search
;;; - mutationchance: a mutation rate percentage (0 to 100)
;;; - weight: a factor to which fitness plays a role
;;; (i.e. a higher weight will select fit individuals more often)
;;; Description:
;;; This is a domain-independent implementation of a genetic algorithm inspired
;;; by pseudocode written by <NAME> and <NAME>. The fucntion is
;;; passed a series of domain-dependent functions as specified by the CLOS problem
;;; object. Once an initial population is created, parents are selected with a
;;; random weighted selection, where the weight factor can be adjusted. The
;;; parents undergo a crossover, producing a child which has a chance of mutation.
;;; Each child is added to the new population and the new-population replaces the
;;; old population. The search stops when an individual reaches a fitnes passed as
;;; a parameter to the function.
;;;
(defun ga ((p problem) popsize stopfitness mutationchance weight)
(let ((population nil) (new-population nil) (x nil) (y nil) (child nil))
(with-slots (fitness-fn mutate-fn reproduce-fn population-fn intital-state) p
(setf population (funcall population-fn popsize fitness-fn)) ; new pop
(loop
(setf new-population nil)
(loop for individual from 0 to (length population) do
(setf x (randomweighted population fitness-fn weight)) ; select
(setf y (randomweighted population fitness-fn weight)) ; parents
(setf child (funcall reproduce-fn x y))
(if (< (random 100) mutationchance) ; mutation
(funcall mutate-fn child))
(print (funcall fitness-fn child)) ; display
(setf new-population (cons child new-population)) ; fitness
(setf population new-population))
(when (> (getfitness child) stopfitness) (return child)))))) ; stop cond
;;;
;;; Function: randomweighted
;;; Arguments:
;;; - population: a population
;;; - fitness-fn: a domain-dependent fitness-fn
;;; - weight: a factor to which the weights will be amplified
;;; Description:
;;; This fucntion randomly selects an individual from a population with a greater
;;; preference for individuals with a higher fitness value. The factor to which
;;; the fitness of an indivudal impacts the choice can be modified by the weight
;;; argument. The fitness of each individul is summed, then a threshold value is
;;; chosen. Indivduals are then added until the threshold is reached, then that
;;; individual is returned.
;;;
(defun randomweighted (population fitness-fn weight)
(let ((fitnesssum 0) (i 0) (z 0))
(loop for i in population do
(setf fitnesssum (+ (expt (getfitness i) weight) fitnesssum)))
(setf z (random fitnesssum)) ; threshold
(loop for j in population do
(setq i (+ (expt (getfitness j) weight) i))
(if (> i z) (return j)))))
;;;
;;; Method: mutate
;;; Arguments:
;;; - i: an individual
;;; Description:
;;; This fucntion modifies the state of an indivdual by randomly replacing one
;;; value in the state by a random number up to the length of the state.
;;; NOTE: This function does not update the fitness value for the state.
;;;
(defmethod mutate ((i individual))
(with-slots (state fitness) i
(setf (nth (random (length state)) state) (+ (random (length state)) 1))
i)) ; individual
;;;
;;; Method: swap
;;; Arguments:
;;; - i: an individual
;;; Description:
;;; This fucntion modifies the state of an indivdual by swapping two values.
;;; NOTE: This function does not update the fitness value for the state.
;;;
(defmethod swap ((i individual))
(with-slots (state fitness) i
(rotatef (nth (+ (random (- (length state) 3)) 1) state)
(nth (+ (random (- (length state) 3)) 1) state))
i)) ; individual
;;;
;;; Function: reproduce
;;; Arguments:
;;; - x: a parent individual
;;; - y: a parent individual
;;; Description:
;;; This fucntion takes two indivudals as arguments and performs a crossover
;;; between the two genomes. An index is randomly chosen to cut the indivduals,
;;; the the two states are combined to form a child CLOS individual.
;;;
(defun reproduce ((x individual) (y individual))
(let ((n nil) (c nil)) ; length &
(with-slots ((x state)) x ; cut index
(with-slots ((y state)) y
(setf n (- (length x) 1)) ; end of state
(setf c (random n)) ; cut index
(make-instance 'individual :state ; new child
(append (sublist x 0 c) (sublist y (+ c 1) n)))))))
;;;
;;; Function: sublist
;;; Arguments:
;;; - state: a list describing the state of an individual
;;; - start: staring index
;;; - end: ending index
;;; Description:
;;; This fucntion takes the state of an indivudal and creates a sublist when
;;; provided the starting and ending index.
;;;
(defun sublist (state start end)
(loop for i from start to end
collect (nth i state)))
;;;
;;; Function: tspreproduce
;;; Arguments:
;;; - x: a parent individual
;;; - y: a parent individual
;;; Description:
;;; This domain-dependent fucntion takes two indivudals as arguments and performs
;;; a crossover between the two genomes. A sublist is chosen with random start
;;; and end indexes. The sublist of the x genome is inserted into the state, with
;;; values of y added in a way which ensures no cities are duplicated in the child
;;; state.
;;;
(defun tspreproduce ((x individual) (y individual))
(let ((state nil) (start nil) (end nil) (sublist nil))
(with-slots ((x state)) x
(with-slots ((y state)) y
(setf start (+ (random (- (length x) 3)) 1)) ; ensure
(setf end (+ (random (- (- (length x) 2) start)) 1 start)) ; first & last
(setf sublist (sublist x start end)) ; remain
(loop for i in y do ; unchanged
(if (not (member i sublist)) (setq state (cons i state)))
(if (eql (position i y) start) (setq state (append sublist state))))
(make-instance 'individual :state state)))))
| true |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;; This file contains the code for an implementation of a genetic algorithm and a
;;;;; simulated annealing algorithm, along with two problem domains. The program is
;;;;; written in Common Lisp syntax.
;;;;; Completed: 05/07/2017
;;;;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;;;; Modifications: none
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Class: individual
;;; Slots:
;;; - state: the current state of the problem
;;; - fitness: an evaluated fitness of the current state based on a fitness-fn
;;; Description:
;;; This class holds all information necessary to represent an indidivdual in a
;;; population or a neighboring state in the simulated annealing algorithm, both
;;; candidate solutions for the given problem.
;;;
(defclass individual () (
(state :initform nil :initarg :state :accessor state)
(fitness :initform nil :initarg :fitness :accessor fitness)))
;;;
;;; Functions: getfitness, getstate
;;; Arguments:
;;; - an individual: used to retrive a state or fitness value
;;; Description:
;;; These are accessor methods for the individual class. Storing the fitness value
;;; along with the state drastically reduces computation time. NOTE: the acessor
;;; does not compute the fitness fucntion if it is not availible. It must be used
;;; at discression of the user.
;;;
(defmethod getfitness ((i individual))
(slot-value i 'fitness))
(defmethod getstate ((i individual))
(slot-value i 'state))
;;;
;;; Class: problem
;;; Slots:
;;; - fitness-fn: a problem-specific fitness function
;;; - mutate-fn: a problem-specific fucntion used for mutation
;;; - reproduce-fn: a problem-specific fucntion for reproduction in a ga
;;; - population-fn: a function used to create an initial population
;;; Description:
;;; This class holds specific functions for each problem to be used in the
;;; domain independent algorithms. Each problem must be tuned to achieve best
;;; performance during search.
;;;
(defclass problem () (
(fitness-fn :initform nil :initarg :fitness-fn :accessor fitness-fn)
(mutate-fn :initform nil :initarg :mutate-fn :accessor mutate-fn)
(reproduce-fn :initform nil :initarg :reproduce-fn :accessor reproduce-fn)
(population-fn :initform nil :initarg :population-fn :accessor population-fn)))
;;;
;;; Problem: 8queens
;;; Description:
;;; The 8-queens problem has a goal of arranging 8 queens on a chessboard in a
;;; way so that they do not attack each other. These domain-specific functions
;;; are designed to optimise perfomance of the local search algorithms.
;;;
(setq 8queens (make-instance 'problem
:fitness-fn 'queensfitness
:mutate-fn 'mutate
:reproduce-fn 'reproduce
:population-fn 'queenspop))
;;;
;;; Method: queensfitness
;;; Arguments:
;;; - i: an individual
;;; Description:
;;; This fucntion counts the number of non-attacking pairs of queens on a chessboard.
;;; A solution to the problem has 28 pairs of non-attacking queens.
;;;
(defmethod queensfitness ((i individual))
(let ((attacked 0))
(with-slots (state fitness) i
(loop for i from 0 to 6 do
(loop for j from (+ 1 i) to 7 do
(if (eql (nth i state) (nth j state))
(setq attacked (+ attacked 1)))
(if (eql (- (nth j state) (nth i state)) (or (- j i) (+ j i)))
(setq attacked (+ attacked 1)))
(if (eql (- (nth i state) (nth j state)) (or (- j i) (+ j i)))
(setq attacked (+ attacked 1)))))
(setq fitness (- 28 attacked)))))
;;;
;;; Fucntion: queenspop
;;; Arguments:
;;; - size: the size of the poplation
;;; - fitness-fn: a domain-dependent evaluation for the fitness of an individual
;;; Description:
;;; This function creates a population of a specified size for the 8queens problem.
;;;
(defun queenspop (size fitness-fn)
(let ((g nil) (p nil))
(dotimes (i size)
(dotimes (j 8)
(setf g (cons (+ (random 8) 1) g)))
(setf p (cons (make-instance 'individual :state g ) p))
(funcall fitness-fn (car p))
(setf g nil)) p))
;;;
;;; Problem: tsp
;;; Description:
;;; The traveling salesperson problem is an NP-hard problem with a goal of
;;; finding the shortest path between a number of cities with given distances.
;;; These domain-specific functions are designed to optimise perfomance of the
;;; local search algorithms.
;;;
(setq tsp (make-instance 'problem
:fitness-fn 'tspfitness
:mutate-fn 'swap
:reproduce-fn 'tspreproduce
:population-fn 'tsppop))
;;;
;;; Fucntion: generate tsp
;;; Arguments:
;;; - cityquantity: the number of cities
;;; - mindistance: the minimum number of distance units between cities
;;; - maxistance: the maximum number of distance units between cities
;;; Description:
;;; This function will generate a random TSP problem given the number of cities and
;;; min and max link costs.
;;;
(defun generatetsp (cityquantity mindistance maxdistance)
(defvar *cities* cityquantity)
(defvar *tspdist* (loop for i from 1 to (- cityquantity 1) append
(loop for j from (+ 1 i) to cityquantity collect
(list i j (+ mindistance (random (- (+ maxdistance 1) mindistance))))))))
;;;
;;; Method: tspfitness
;;; Arguments:
;;; - i: an individual
;;; Description:
;;; This fucntion calculates the cost of the current path, but returns the reciprocal so
;;; shorter paths are evaluated as more optimal than longer paths. If a path does not begin
;;; and end at the same place, then it’s penalized, as it is if a city occurs more than once
;;; (other than start and end). NOTE: This fucntion was inspired by Dr. PI:NAME:<NAME>END_PI's work.
;;;
(defmethod tspfitness ((i individual))
(with-slots (state fitness) i
(setq total 0)
(if (eql (first state) (car (last state))) t (setq total most-positive-fixnum))
(if (duplicates (cdr state)) (setq total most-positive-fixnum))
(loop for j from 0 to (- (length state) 2) do
(setq total (+ total
(or (third (car (member (list (nth j state) (nth (+ j 1) state)) *tspdist*
:test #'(lambda (target candidate)
(or (and (eql (car target) (car candidate))
(eql (cadr target) (cadr candidate)))
(and (eql (car target) (cadr candidate))
(eql (cadr target) (car candidate))))))))
most-positive-fixnum))))
(setq fitness (float (/ 1 total)))))
;;;
;;; Fucntion: duplicates
;;; Arguments:
;;; - state: a list
;;; Description:
;;; This function determines if a list contains duplicates.
;;;
(defun duplicates (state)
(cond ((null state) nil)
((member (car state) (cdr state)) (cons (car state) (duplicates (cdr state))))
(t (duplicates (cdr state)))))
;;;
;;; Fucntion: tsppop
;;; Arguments:
;;; - size: the size of the poplation
;;; - fitness-fn: a domain-dependent evaluation for the fitness of an individual
;;; Description:
;;; This function creates a population of a specified size for the tsp problem.
;;;
(defun tsppop (size fitness-fn)
(let ((g nil) (p nil))
(dotimes (i size)
(loop for j from 1 to *cities* do
(setf g (cons j g)))
(setf p (cons (make-instance 'individual :state (cons '1 g)) p))
(funcall fitness-fn (car p))
(setf g nil)) p))
;;;
;;; Fucntion: annealing
;;; Arguments:
;;; - p: an problem
;;; - schedule: a schedule for the temperature to cool in the function
;;; Description:
;;; The simulated annealing algorithm is similar to the hill-climbing algorithm,
;;; aside from the fact that the agorithm allows the selection of sub-optimal moves
;;; to avoid the possibility of finding a local maximum in favor of a global one.
;;; As time passes, errors are less likely to occur. When the temperature reaches 0
;;; The current individual is returned.
;;;
(defun annealing ((p problem) schedule)
(let ((current nil) (next nil) (temperature nil))
(with-slots (fitness-fn mutate-fn intital-state population-fn) p
(setf current (car (funcall population-fn 1 fitness-fn)))
(funcall fitness-fn current)
(loop for timestep from 1 to most-positive-fixnum do
(setf temperature (funcall schedule timestep))
(if (eql 0 temperature) (return current))
(setf next (getneighbor current mutate-fn))
(funcall fitness-fn next)
(setf deltaE (- (getfitness next) (print (getfitness current))))
(if (> deltaE 0) (setq current next))
(if (> (random 1.0) (exp (/ deltaE temperature))) (setf current next))))))
;;;
;;; Fucntion: getneighbor
;;; Arguments:
;;; - i: an individual
;;; - mutate-fn: a domain-specific function used to mutate an individual state
;;; Description:
;;; This function copies an inidivual, then modifies that individual using a
;;; mutate-fn, then returns that individual.
;;;
(defun getneighbor ((i individual) mutate-fn)
(let ((neighbor nil))
(with-slots (state) i
(setq neighbor (make-instance 'individual :state (copy-list state)))
(funcall mutate-fn neighbor)
neighbor)))
;;;
;;; Fucntion: schedule
;;; Description:
;;; A sample schedule function from the AIMA website.
;;;
(defun schedule (timestep)
(let ((k 20) (lam .005) (lim 100))
(if (< (* k (exp (* lam timestep))) lim) (* k (exp (* lam timestep))) 0)))
;;;
;;; Function: ga
;;; Arguments:
;;; - p: a problem (either 8queens or tsp)
;;; - popsize: the size of the population
;;; - stopfitness: the desired fitness set to stop the search
;;; - mutationchance: a mutation rate percentage (0 to 100)
;;; - weight: a factor to which fitness plays a role
;;; (i.e. a higher weight will select fit individuals more often)
;;; Description:
;;; This is a domain-independent implementation of a genetic algorithm inspired
;;; by pseudocode written by PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI. The fucntion is
;;; passed a series of domain-dependent functions as specified by the CLOS problem
;;; object. Once an initial population is created, parents are selected with a
;;; random weighted selection, where the weight factor can be adjusted. The
;;; parents undergo a crossover, producing a child which has a chance of mutation.
;;; Each child is added to the new population and the new-population replaces the
;;; old population. The search stops when an individual reaches a fitnes passed as
;;; a parameter to the function.
;;;
(defun ga ((p problem) popsize stopfitness mutationchance weight)
(let ((population nil) (new-population nil) (x nil) (y nil) (child nil))
(with-slots (fitness-fn mutate-fn reproduce-fn population-fn intital-state) p
(setf population (funcall population-fn popsize fitness-fn)) ; new pop
(loop
(setf new-population nil)
(loop for individual from 0 to (length population) do
(setf x (randomweighted population fitness-fn weight)) ; select
(setf y (randomweighted population fitness-fn weight)) ; parents
(setf child (funcall reproduce-fn x y))
(if (< (random 100) mutationchance) ; mutation
(funcall mutate-fn child))
(print (funcall fitness-fn child)) ; display
(setf new-population (cons child new-population)) ; fitness
(setf population new-population))
(when (> (getfitness child) stopfitness) (return child)))))) ; stop cond
;;;
;;; Function: randomweighted
;;; Arguments:
;;; - population: a population
;;; - fitness-fn: a domain-dependent fitness-fn
;;; - weight: a factor to which the weights will be amplified
;;; Description:
;;; This fucntion randomly selects an individual from a population with a greater
;;; preference for individuals with a higher fitness value. The factor to which
;;; the fitness of an indivudal impacts the choice can be modified by the weight
;;; argument. The fitness of each individul is summed, then a threshold value is
;;; chosen. Indivduals are then added until the threshold is reached, then that
;;; individual is returned.
;;;
(defun randomweighted (population fitness-fn weight)
(let ((fitnesssum 0) (i 0) (z 0))
(loop for i in population do
(setf fitnesssum (+ (expt (getfitness i) weight) fitnesssum)))
(setf z (random fitnesssum)) ; threshold
(loop for j in population do
(setq i (+ (expt (getfitness j) weight) i))
(if (> i z) (return j)))))
;;;
;;; Method: mutate
;;; Arguments:
;;; - i: an individual
;;; Description:
;;; This fucntion modifies the state of an indivdual by randomly replacing one
;;; value in the state by a random number up to the length of the state.
;;; NOTE: This function does not update the fitness value for the state.
;;;
(defmethod mutate ((i individual))
(with-slots (state fitness) i
(setf (nth (random (length state)) state) (+ (random (length state)) 1))
i)) ; individual
;;;
;;; Method: swap
;;; Arguments:
;;; - i: an individual
;;; Description:
;;; This fucntion modifies the state of an indivdual by swapping two values.
;;; NOTE: This function does not update the fitness value for the state.
;;;
(defmethod swap ((i individual))
(with-slots (state fitness) i
(rotatef (nth (+ (random (- (length state) 3)) 1) state)
(nth (+ (random (- (length state) 3)) 1) state))
i)) ; individual
;;;
;;; Function: reproduce
;;; Arguments:
;;; - x: a parent individual
;;; - y: a parent individual
;;; Description:
;;; This fucntion takes two indivudals as arguments and performs a crossover
;;; between the two genomes. An index is randomly chosen to cut the indivduals,
;;; the the two states are combined to form a child CLOS individual.
;;;
(defun reproduce ((x individual) (y individual))
(let ((n nil) (c nil)) ; length &
(with-slots ((x state)) x ; cut index
(with-slots ((y state)) y
(setf n (- (length x) 1)) ; end of state
(setf c (random n)) ; cut index
(make-instance 'individual :state ; new child
(append (sublist x 0 c) (sublist y (+ c 1) n)))))))
;;;
;;; Function: sublist
;;; Arguments:
;;; - state: a list describing the state of an individual
;;; - start: staring index
;;; - end: ending index
;;; Description:
;;; This fucntion takes the state of an indivudal and creates a sublist when
;;; provided the starting and ending index.
;;;
(defun sublist (state start end)
(loop for i from start to end
collect (nth i state)))
;;;
;;; Function: tspreproduce
;;; Arguments:
;;; - x: a parent individual
;;; - y: a parent individual
;;; Description:
;;; This domain-dependent fucntion takes two indivudals as arguments and performs
;;; a crossover between the two genomes. A sublist is chosen with random start
;;; and end indexes. The sublist of the x genome is inserted into the state, with
;;; values of y added in a way which ensures no cities are duplicated in the child
;;; state.
;;;
(defun tspreproduce ((x individual) (y individual))
(let ((state nil) (start nil) (end nil) (sublist nil))
(with-slots ((x state)) x
(with-slots ((y state)) y
(setf start (+ (random (- (length x) 3)) 1)) ; ensure
(setf end (+ (random (- (- (length x) 2) start)) 1 start)) ; first & last
(setf sublist (sublist x start end)) ; remain
(loop for i in y do ; unchanged
(if (not (member i sublist)) (setq state (cons i state)))
(if (eql (position i y) start) (setq state (append sublist state))))
(make-instance 'individual :state state)))))
|
[
{
"context": "ry\nhttps://srfi.schemers.org/srfi-112\"\n :author \"CHIBA Masaomi\"\n :maintainer \"CHIBA Masaomi\"\n :serial t\n :com",
"end": 278,
"score": 0.9998166561126709,
"start": 265,
"tag": "NAME",
"value": "CHIBA Masaomi"
},
{
"context": "rfi-112\"\n :author \"CHIBA Masaomi\"\n :maintainer \"CHIBA Masaomi\"\n :serial t\n :components ((:file \"package\")\n ",
"end": 308,
"score": 0.9998525977134705,
"start": 295,
"tag": "NAME",
"value": "CHIBA Masaomi"
},
{
"context": "m :srfi-112))))\n (let ((name \"https://github.com/g000001/srfi-112\")\n (nickname :srfi-112))\n (if ",
"end": 508,
"score": 0.9946373105049133,
"start": 501,
"tag": "USERNAME",
"value": "g000001"
}
] |
srfi-112.asd
|
g000001/srfi-112
| 0 |
;;;; srfi-112.asd -*- Mode: Lisp;-*-
(cl:in-package :asdf)
(defsystem :srfi-112
:version "20200228"
:description "SRFI 112 for CL: Environment Inquiry"
:long-description "SRFI 112 for CL: Environment Inquiry
https://srfi.schemers.org/srfi-112"
:author "CHIBA Masaomi"
:maintainer "CHIBA Masaomi"
:serial t
:components ((:file "package")
(:file "srfi-112")))
(defmethod perform :after ((o load-op) (c (eql (find-system :srfi-112))))
(let ((name "https://github.com/g000001/srfi-112")
(nickname :srfi-112))
(if (and (find-package nickname)
(not (eq (find-package nickname)
(find-package name))))
(warn "~A: A package with name ~A already exists." name nickname)
(rename-package name name `(,nickname)))))
;;; *EOF*
|
63554
|
;;;; srfi-112.asd -*- Mode: Lisp;-*-
(cl:in-package :asdf)
(defsystem :srfi-112
:version "20200228"
:description "SRFI 112 for CL: Environment Inquiry"
:long-description "SRFI 112 for CL: Environment Inquiry
https://srfi.schemers.org/srfi-112"
:author "<NAME>"
:maintainer "<NAME>"
:serial t
:components ((:file "package")
(:file "srfi-112")))
(defmethod perform :after ((o load-op) (c (eql (find-system :srfi-112))))
(let ((name "https://github.com/g000001/srfi-112")
(nickname :srfi-112))
(if (and (find-package nickname)
(not (eq (find-package nickname)
(find-package name))))
(warn "~A: A package with name ~A already exists." name nickname)
(rename-package name name `(,nickname)))))
;;; *EOF*
| true |
;;;; srfi-112.asd -*- Mode: Lisp;-*-
(cl:in-package :asdf)
(defsystem :srfi-112
:version "20200228"
:description "SRFI 112 for CL: Environment Inquiry"
:long-description "SRFI 112 for CL: Environment Inquiry
https://srfi.schemers.org/srfi-112"
:author "PI:NAME:<NAME>END_PI"
:maintainer "PI:NAME:<NAME>END_PI"
:serial t
:components ((:file "package")
(:file "srfi-112")))
(defmethod perform :after ((o load-op) (c (eql (find-system :srfi-112))))
(let ((name "https://github.com/g000001/srfi-112")
(nickname :srfi-112))
(if (and (find-package nickname)
(not (eq (find-package nickname)
(find-package name))))
(warn "~A: A package with name ~A already exists." name nickname)
(rename-package name name `(,nickname)))))
;;; *EOF*
|
[
{
"context": " 8.\n\nThe Hald CLUT algorithm has been developed by Eskil Steenberg as described\nat http://www.quelsolaar.com/technol",
"end": 60071,
"score": 0.9997627139091492,
"start": 60056,
"tag": "NAME",
"value": "Eskil Steenberg"
},
{
"context": "y/clut.html, and was adapted for\nGraphicsMagick by Clément Follet with support from Cédric Lejeune of\nWorkflowers.\n",
"end": 60188,
"score": 0.9998046159744263,
"start": 60174,
"tag": "NAME",
"value": "Clément Follet"
},
{
"context": "GraphicsMagick by Clément Follet with support from Cédric Lejeune of\nWorkflowers.\n\nThe format of the HaldClutImage ",
"end": 60221,
"score": 0.9993706941604614,
"start": 60207,
"tag": "NAME",
"value": "Cédric Lejeune"
}
] |
src/cffi/magick-wand.lisp
|
muyinliu/cl-graphicsmagick
| 6 |
;;; magick_wand
(in-package :gm)
(defcfun ("InitializeMagick" %InitializeMagick)
:void
"Initialize GraphicsMagick environment. Must do this to prevent ERROR: Assertion failed: \(semaphore_info != \(SemaphoreInfo *) NULL), function LockSemaphoreInfo, file magick/semaphore.c, line 601.
InitializeMagick() initializes the GraphicsMagick environment.
InitializeMagick() MUST be invoked by the using program before making
use of GraphicsMagick functions or else the library will be unusable.
This function should be invoked in the primary \(original) thread of the
application's process, and before starting any OpenMP threads, as part
of program initialization.
The format of the InitializeMagick function is:
InitializeMagick\(const char *path)
A description of each parameter follows:
o path: The execution path of the current GraphicsMagick client.
Note: InitializeMagick is declared in file magick/magick.c
Since GraphicsMagick v1.1.0"
(path :string))
;; InitializeMagick is called by NewMagickWand NewPixelWand & NewDrawingWand,
;; but call InitializeMagick here to make sure all other functions
;; like MagickQueryFormats works immediately after loaded.
(%InitializeMagick (null-pointer))
(defcfun ("CloneMagickWand" %CloneMagickWand)
%MagickWand
"Makes an exact copy of the specified wand.
The format of the CloneMagickWand method is:
MagickWand *CloneMagickWand\( const MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand to clone.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("DestroyMagickWand" %DestroyMagickWand)
:void
"Deallocates memory associated with an MagickWand.
The format of the DestroyMagickWand method is:
void DestroyMagickWand\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickAdaptiveThresholdImage" %MagickAdaptiveThresholdImage)
%magick-status
"Selects an individual threshold for each pixel based on the range of intensity values in its local neighborhood. This allows for thresholding of an image whose global intensity histogram doesn't contain distinctive peaks.
The format of the MagickAdaptiveThresholdImage method is:
unsigned int MagickAdaptiveThresholdImage\( MagickWand *wand, const unsigned long width,
const unsigned long height, const long offset );
wand:
The magick wand.
width:
The width of the local neighborhood.
height:
The height of the local neighborhood.
offset:
The mean offset.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(width :unsigned-long)
(height :unsigned-long)
(offset :long))
(defcfun ("MagickAddImage" %MagickAddImage)
%magick-status
"Adds the specified images at the current image location.
The format of the MagickAddImage method is:
unsigned int MagickAddImage\( MagickWand *wand, const MagickWand *add_wand );
wand:
The magick wand.
insert:
The splice wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(add_wand %MagickWand))
(defcfun ("MagickAddNoiseImage" %MagickAddNoiseImage)
%magick-status
"Adds random noise to the image.
The format of the MagickAddNoiseImage method is:
unsigned int MagickAddNoiseImage\( MagickWand *wand, const NoiseType noise_type );
wand:
The magick wand.
noise_type:
The type of noise: Uniform, Gaussian, Multiplicative,
Impulse, Laplacian, Poisson, or Random.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(noise_type %NoiseType))
(defcfun ("MagickAffineTransformImage" %MagickAffineTransformImage)
%magick-status
"Transforms an image as dictated by the affine matrix of the drawing wand.
The format of the MagickAffineTransformImage method is:
unsigned int MagickAffineTransformImage\( MagickWand *wand, const DrawingWand *drawing_wand );
wand:
The magick wand.
drawing_wand:
The draw wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(drawing_wand %DrawingWand))
(defcfun ("MagickAnnotateImage" %MagickAnnotateImage)
%magick-status
"Annotates an image with text.
The format of the MagickAnnotateImage method is:
unsigned int MagickAnnotateImage\( MagickWand *wand, const DrawingWand *drawing_wand,
const double x, const double y, const double angle,
const char *text );
wand:
The magick wand.
drawing_wand:
The draw wand.
x:
x ordinate to left of text
y:
y ordinate to text baseline
angle:
rotate text relative to this angle.
text:
text to draw
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(drawing_wand %DrawingWand)
(x :double)
(y :double)
(angle :double)
(text :string))
(defcfun ("MagickAnimateImages" %MagickAnimateImages)
%magick-status
"Animates an image or image sequence.
The format of the MagickAnimateImages method is:
unsigned int MagickAnimateImages\( MagickWand *wand, const char *server_name );
wand:
The magick wand.
server_name:
The X server name.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(server_name :string))
(defcfun ("MagickAppendImages" %MagickAppendImages)
%MagickWand
"Append a set of images.
The format of the MagickAppendImages method is:
MagickWand *MagickAppendImages\( MagickWand *wand, const unsigned int stack );
wand:
The magick wand.
stack:
By default, images are stacked left-to-right. Set stack to True
to stack them top-to-bottom.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(stack :unsigned-int))
(defcfun ("MagickAutoOrientImage" %MagickAutoOrientImage)
%magick-status
"Adjusts the current image so that its orientation is suitable for viewing \(i.e. top-left orientation).
The format of the MagickAutoOrientImage method is:
unsigned int MagickAutoOrientImage\( MagickWand *wand,
const OrientationType current_orientation,
ExceptionInfo *exception );
wand:
The magick wand.
current_orientation:
Current image orientation. May be one of: TopLeftOrientation Left to right and Top to bottom TopRightOrientation Right to left and Top to bottom BottomRightOrientation Right to left and Bottom to top BottomLeftOrientation Left to right and Bottom to top LeftTopOrientation Top to bottom and Left to right RightTopOrientation Top to bottom and Right to left RightBottomOrientation Bottom to top and Right to left LeftBottomOrientation Bottom to top and Left to right UndefinedOrientation Current orientation is not known. Use orientation defined by the current image if any. Equivalent to MagickGetImageOrientation\().
Returns True on success, False otherwise.
Note that after successful auto-orientation the internal orientation will be set to TopLeftOrientation. However this internal value is only written to TIFF files. For JPEG files, there is currently no support for resetting the EXIF orientation tag to TopLeft so the JPEG should be stripped or EXIF profile removed if present to prevent saved auto-oriented images from being incorrectly rotated a second time by follow-on viewers that understand the EXIF orientation tag.
Since GraphicsMagick v1.3.26"
(wand %MagickWand)
(current_orientation %OrientationType)
(exception %ExceptionInfo))
(defcfun ("MagickAverageImages" %MagickAverageImages)
%MagickWand
"Average a set of images.
The format of the MagickAverageImages method is:
MagickWand *MagickAverageImages\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickBlackThresholdImage" %MagickBlackThresholdImage)
%magick-status
"Is like MagickThresholdImage\() but forces all pixels below the threshold into black while leaving all pixels above the threshold unchanged.
The format of the MagickBlackThresholdImage method is:
unsigned int MagickBlackThresholdImage\( MagickWand *wand, const PixelWand *threshold );
wand:
The magick wand.
threshold:
The pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(threshold %PixelWand))
(defcfun ("MagickBlurImage" %MagickBlurImage)
%magick-status
"Blurs an image. We convolve the image with a Gaussian operator of the given radius and standard deviation \(sigma). For reasonable results, the radius should be larger than sigma. Use a radius of 0 and BlurImage\() selects a suitable radius for you.
The format of the MagickBlurImage method is:
unsigned int MagickBlurImage\( MagickWand *wand, const double radius, const double sigma );
wand:
The magick wand.
radius:
The radius of the Gaussian, in pixels, not counting the center
pixel.
sigma:
The standard deviation of the Gaussian, in pixels.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double)
(sigma :double))
(defcfun ("MagickBorderImage" %MagickBorderImage)
%magick-status
"Surrounds the image with a border of the color defined by the bordercolor pixel wand.
The format of the MagickBorderImage method is:
unsigned int MagickBorderImage\( MagickWand *wand, const PixelWand *bordercolor,
const unsigned long width, const unsigned long height );
wand:
The magick wand.
bordercolor:
The border color pixel wand.
width:
The border width.
height:
The border height.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(bordercolor %PixelWand)
(width :unsigned-long)
(height :unsigned-long))
(defcfun ("MagickCdlImage" %MagickCdlImage)
%MagickPassFail
"The MagickCdlImage\() method applies \(\"bakes in\") the ASC-CDL which is a format for the exchange of basic primary color grading information between equipment and software from different manufacturers. The format defines the math for three functions: slope, offset and power. Each function uses a number for the red, green, and blue color channels for a total of nine numbers comprising a single color decision. A tenth number for chrominance \(saturation) has been proposed but is not yet standardized.
The cdl argument string is comma delimited and is in the form \(but
without invervening spaces or line breaks):
redslope, redoffset, redpower :
greenslope, greenoffset, greenpower :
blueslope, blueoffset, bluepower :
saturation
with the unity \(no change) specification being:
\"1.0,0.0,1.0:1.0,0.0,1.0:1.0,0.0,1.0:0.0\"
See http://en.wikipedia.org/wiki/ASC_CDL for more information.
The format of the MagickCdlImage method is:
MagickPassFail MagickCdlImage\( MagickWand *wand, const char *cdl );
A description of each parameter follows:
wand:
The image wand.
cdl:
Define the coefficients for slope offset and power in the
red green and blue channels, plus saturation.
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(cdl :string))
(defcfun ("MagickCharcoalImage" %MagickCharcoalImage)
%magick-status
"Simulates a charcoal drawing.
The format of the MagickCharcoalImage method is:
unsigned int MagickCharcoalImage\( MagickWand *wand, const double radius, const double sigma );
wand:
The magick wand.
radius:
The radius of the Gaussian, in pixels, not counting the center
pixel.
sigma:
The standard deviation of the Gaussian, in pixels.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double)
(sigma :double))
(defcfun ("MagickChopImage" %MagickChopImage)
%magick-status
"Removes a region of an image and collapses the image to occupy the removed portion
The format of the MagickChopImage method is:
unsigned int MagickChopImage\( MagickWand *wand, const unsigned long width,
const unsigned long height, const long x, const long y );
wand:
The magick wand.
width:
The region width.
height:
The region height.
x:
The region x offset.
y:
The region y offset.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(width :unsigned-long)
(height :unsigned-long)
(x :long)
(y :long))
(defcfun ("MagickClearException" %MagickClearException)
:void
"Clears the last wand exception.
The format of the MagickClearException method is:
void MagickClearException\( MagickWand *wand );
wand:
The magick wand.
Since GraphicsMagick v1.3.26"
(wand %MagickWand))
(defcfun ("MagickClipImage" %MagickClipImage)
%magick-status
"Clips along the first path from the 8BIM profile, if present.
The format of the MagickClipImage method is:
unsigned int MagickClipImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickClipPathImage" %MagickClipPathImage)
%magick-status
"Clips along the named paths from the 8BIM profile, if present. Later operations take effect inside the path. Id may be a number if preceded with #, to work on a numbered path, e.g., \"#1\" to use the first path.
The format of the MagickClipPathImage method is:
unsigned int MagickClipPathImage\( MagickWand *wand, const char *pathname,
const unsigned int inside );
wand:
The magick wand.
pathname:
name of clipping path resource. If name is preceded by #, use
clipping path numbered by name.
inside:
if non-zero, later operations take effect inside clipping path.
Otherwise later operations take effect outside clipping path.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(pathname :string)
(inside :unsigned-int))
(defcfun ("MagickCoalesceImages" %MagickCoalesceImages)
%MagickWand
"Composites a set of images while respecting any page offsets and disposal methods. GIF, MIFF, and MNG animation sequences typically start with an image background and each subsequent image varies in size and offset. MagickCoalesceImages\() returns a new sequence where each image in the sequence is the same size as the first and composited with the next image in the sequence.
The format of the MagickCoalesceImages method is:
MagickWand *MagickCoalesceImages\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickColorFloodfillImage" %MagickColorFloodfillImage)
%magick-status
"Changes the color value of any pixel that matches target and is an immediate neighbor. If the method FillToBorderMethod is specified, the color value is changed for any neighbor pixel that does not match the bordercolor member of image.
The format of the MagickColorFloodfillImage method is:
unsigned int MagickColorFloodfillImage\( MagickWand *wand, const PixelWand *fill,
const double fuzz, const PixelWand *bordercolor,
const long x, const long y );
wand:
The magick wand.
fill:
The floodfill color pixel wand.
fuzz:
By default target must match a particular pixel color
exactly. However, in many cases two colors may differ by a small amount.
The fuzz member of image defines how much tolerance is acceptable to
consider two colors as the same. For example, set fuzz to 10 and the
color red at intensities of 100 and 102 respectively are now interpreted
as the same color for the purposes of the floodfill.
bordercolor:
The border color pixel wand.
x,y:
The starting location of the operation.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(fill %PixelWand)
(fuzz :double)
(bordercolor %PixelWand)
(x :long)
(y :long))
(defcfun ("MagickColorizeImage" %MagickColorizeImage)
%magick-status
"Blends the fill color with each pixel in the image.
The format of the MagickColorizeImage method is:
unsigned int MagickColorizeImage\( MagickWand *wand, const PixelWand *colorize,
const PixelWand *opacity );
wand:
The magick wand.
colorize:
The colorize pixel wand.
opacity:
The opacity pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(colorize %PixelWand)
(opacity %PixelWand))
(defcfun ("MagickCommentImage" %MagickCommentImage)
%magick-status
"Adds a comment to your image.
The format of the MagickCommentImage method is:
unsigned int MagickCommentImage\( MagickWand *wand, const char *comment );
A description of each parameter follows:
wand:
The magick wand.
comment:
The image comment.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(comment :string))
(defcfun ("MagickCompareImageChannels" %MagickCompareImageChannels)
%MagickWand
"Compares one or more image channels and returns the specified distortion metric.
The format of the MagickCompareImageChannels method is:
MagickWand *MagickCompareImageChannels\( MagickWand *wand, const MagickWand *reference,
const ChannelType channel, const MetricType metric,
double *distortion );
wand:
The magick wand.
reference:
The reference wand.
channel:
The channel.
metric:
The metric.
distortion:
The computed distortion between the images.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(reference %MagickWand)
(channel %ChannelType)
(metric %MetricType)
(distortion :pointer))
(defcfun ("MagickCompareImages" %MagickCompareImages)
%MagickWand
"Compares one or more images and returns the specified distortion metric.
The format of the MagickCompareImages method is:
MagickWand *MagickCompareImages\( MagickWand *wand, const MagickWand *reference,
const MetricType metric, double *distortion );
wand:
The magick wand.
reference:
The reference wand.
metric:
The metric.
distortion:
The computed distortion between the images.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(reference %MagickWand)
(metric %MetricType)
(distortion :pointer))
(defcfun ("MagickCompositeImage" %MagickCompositeImage)
%magick-status
"Composite one image onto another at the specified offset.
The format of the MagickCompositeImage method is:
unsigned int MagickCompositeImage\( MagickWand *wand, const MagickWand *composite_wand,
const CompositeOperator compose, const long x,
const long y );
wand:
The magick wand.
composite_image:
The composite image.
compose:
This operator affects how the composite is applied to the
image. The default is Over. Choose from these operators:
OverCompositeOp InCompositeOp OutCompositeOP
AtopCompositeOP XorCompositeOP PlusCompositeOP
MinusCompositeOP AddCompositeOP SubtractCompositeOP
DifferenceCompositeOP BumpmapCompositeOP CopyCompositeOP
DisplaceCompositeOP
x_offset:
The column offset of the composited image.
y_offset:
The row offset of the composited image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(composite_wand %MagickWand)
(compose %CompositeOperator)
(x :long)
(y :long))
(defcfun ("MagickContrastImage" %MagickContrastImage)
%magick-status
"Enhances the intensity differences between the lighter and darker elements of the image. Set sharpen to a value other than 0 to increase the image contrast otherwise the contrast is reduced.
The format of the MagickContrastImage method is:
unsigned int MagickContrastImage\( MagickWand *wand, const unsigned int sharpen );
wand:
The magick wand.
sharpen:
Increase or decrease image contrast.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(sharpen :unsigned-int))
(defcfun ("MagickConvolveImage" %MagickConvolveImage)
%magick-status
"Applies a custom convolution kernel to the image.
The format of the MagickConvolveImage method is:
unsigned int MagickConvolveImage\( MagickWand *wand, const unsigned long order,
const double *kernel );
wand:
The magick wand.
order:
The number of columns and rows in the filter kernel.
kernel:
An array of doubles representing the convolution kernel.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(order :unsigned-long)
(kernel :pointer))
(defcfun ("MagickCropImage" %MagickCropImage)
%magick-status
"Extracts a region of the image.
The format of the MagickCropImage method is:
unsigned int MagickCropImage\( MagickWand *wand, const unsigned long width,
const unsigned long height, const long x, const long y );
wand:
The magick wand.
width:
The region width.
height:
The region height.
x:
The region x offset.
y:
The region y offset.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(width :unsigned-long)
(height :unsigned-long)
(x :long)
(y :long))
(defcfun ("MagickCycleColormapImage" %MagickCycleColormapImage)
%magick-status
"Displaces an image's colormap by a given number of positions. If you cycle the colormap a number of times you can produce a psychodelic effect.
The format of the MagickCycleColormapImage method is:
unsigned int MagickCycleColormapImage\( MagickWand *wand, const long displace );
wand:
The magick wand.
pixel_wand:
The pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(displace :long))
(defcfun ("MagickDeconstructImages" %MagickDeconstructImages)
%MagickWand
"Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers.
The format of the MagickDeconstructImages method is:
MagickWand *MagickDeconstructImages\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickDescribeImage" %MagickDescribeImage)
:string
"Describes an image by formatting its attributes to an allocated string which must be freed by the user. Attributes include the image width, height, size, and others. The string is similar to the output of 'identify -verbose'.
The format of the MagickDescribeImage method is:
const char *MagickDescribeImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickDespeckleImage" %MagickDespeckleImage)
%magick-status
"Reduces the speckle noise in an image while perserving the edges of the original image.
The format of the MagickDespeckleImage method is:
unsigned int MagickDespeckleImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickDisplayImage" %MagickDisplayImage)
%magick-status
"Displays an image.
The format of the MagickDisplayImage method is:
unsigned int MagickDisplayImage\( MagickWand *wand, const char *server_name );
A description of each parameter follows:
wand:
The magick wand.
server_name:
The X server name.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(server_name :string))
(defcfun ("MagickDisplayImages" %MagickDisplayImages)
%magick-status
"Displays an image or image sequence.
The format of the MagickDisplayImages method is:
unsigned int MagickDisplayImages\( MagickWand *wand, const char *server_name );
wand:
The magick wand.
server_name:
The X server name.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(server_name :string))
(defcfun ("MagickDrawImage" %MagickDrawImage)
%magick-status
"Draws vectors on the image as described by DrawingWand.
The format of the MagickDrawImage method is:
unsigned int MagickDrawImage\( MagickWand *wand, const DrawingWand *drawing_wand );
wand:
The magick wand.
drawing_wand:
The draw wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(drawing_wand %DrawingWand))
(defcfun ("MagickEdgeImage" %MagickEdgeImage)
%magick-status
"Enhance edges within the image with a convolution filter of the given radius. Use a radius of 0 and Edge\() selects a suitable radius for you.
The format of the MagickEdgeImage method is:
unsigned int MagickEdgeImage\( MagickWand *wand, const double radius );
A description of each parameter follows:
wand:
The magick wand.
radius:
the radius of the pixel neighborhood.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double))
(defcfun ("MagickEmbossImage" %MagickEmbossImage)
%magick-status
"Returns a grayscale image with a three-dimensional effect. We convolve the image with a Gaussian operator of the given radius and standard deviation \(sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and Emboss\() selects a suitable radius for you.
The format of the MagickEmbossImage method is:
unsigned int MagickEmbossImage\( MagickWand *wand, const double radius, const double sigma );
wand:
The magick wand.
radius:
The radius of the Gaussian, in pixels, not counting the center
pixel.
sigma:
The standard deviation of the Gaussian, in pixels.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double)
(sigma :double))
(defcfun ("MagickEnhanceImage" %MagickEnhanceImage)
%magick-status
"Applies a digital filter that improves the quality of a noisy image.
The format of the MagickEnhanceImage method is:
unsigned int MagickEnhanceImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickEqualizeImage" %MagickEqualizeImage)
%magick-status
"Equalizes the image histogram.
The format of the MagickEqualizeImage method is:
unsigned int MagickEqualizeImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickExtentImage" %MagickExtentImage)
%magick-status
"Use MagickExtentImage\() to change the image dimensions as specified by geometry width and height. The existing image content is composited at the position specified by geometry x and y using the image compose method. Existing image content which falls outside the bounds of the new image dimensions is discarded.
The format of the MagickExtentImage method is:
unsigned int MagickExtentImage\( MagickWand *wand, const size_t width, const size_t height,
const ssize_t x, const ssize_t y );
wand:
The magick wand.
width:
New image width
height:
New image height
x, y:
Top left composition coordinate to place existing image content
on the new image.
Since GraphicsMagick v1.3.14"
(wand %MagickWand)
(width %size_t)
(height %size_t)
(x %ssize_t)
(y %ssize_t))
(defcfun ("MagickFlattenImages" %MagickFlattenImages)
%MagickWand
"Merges a sequence of images. This is useful for combining Photoshop layers into a single image.
The format of the MagickFlattenImages method is:
MagickWand *MagickFlattenImages\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickFlipImage" %MagickFlipImage)
%magick-status
"Creates a vertical mirror image by reflecting the pixels around the central x-axis\(swap up/down).
The format of the MagickFlipImage method is:
unsigned int MagickFlipImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickFlopImage" %MagickFlopImage)
%magick-status
"Creates a horizontal mirror image by reflecting the pixels around the central y-axis\(swap left/right).
The format of the MagickFlopImage method is:
unsigned int MagickFlopImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickFrameImage" %MagickFrameImage)
%magick-status
"Adds a simulated three-dimensional border around the image. The width and height specify the border width of the vertical and horizontal sides of the frame. The inner and outer bevels indicate the width of the inner and outer shadows of the frame.
The format of the MagickFrameImage method is:
unsigned int MagickFrameImage\( MagickWand *wand, const PixelWand *matte_color,
const unsigned long width, const unsigned long height,
const long inner_bevel, const long outer_bevel );
wand:
The magick wand.
matte_color:
The frame color pixel wand.
width:
The border width.
height:
The border height.
inner_bevel:
The inner bevel width.
outer_bevel:
The outer bevel width.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(matte_color %PixelWand)
(width :unsigned-long)
(height :unsigned-long)
(inner_bevel :long)
(outer_bevel :long))
(defcfun ("MagickFxImage" %MagickFxImage)
%MagickWand
"Evaluate expression for each pixel in the image.
The format of the MagickFxImage method is:
MagickWand *MagickFxImage\( MagickWand *wand, const char *expression );
A description of each parameter follows:
wand:
The magick wand.
expression:
The expression.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(expression :string))
(defcfun ("MagickFxImageChannel" %MagickFxImageChannel)
%MagickWand
"Evaluate expression for each pixel in the specified channel.
The format of the MagickFxImageChannel method is:
MagickWand *MagickFxImageChannel\( MagickWand *wand, const ChannelType channel,
const char *expression );
wand:
The magick wand.
channel:
Identify which channel to level: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
BlackChannel.
expression:
The expression.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(expression :string))
(defcfun ("MagickGammaImage" %MagickGammaImage)
%magick-status
"Use MagickGammaImage\() to gamma-correct an image. The same image viewed on different devices will have perceptual differences in the way the image's intensities are represented on the screen. Specify individual gamma levels for the red, green, and blue channels, or adjust all three with the gamma parameter. Values typically range from 0.8 to 2.3.
You can also reduce the influence of a particular channel with a gamma
value of 0.
The format of the MagickGammaImage method is:
unsigned int MagickGammaImage\( MagickWand *wand, const double gamma );
A description of each parameter follows:
wand:
The magick wand.
gamme:
Define the level of gamma correction.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(gamma :double))
(defcfun ("MagickGammaImageChannel" %MagickGammaImageChannel)
%magick-status
"Use MagickGammaImageChannel\() to gamma-correct a particular image channel. The same image viewed on different devices will have perceptual differences in the way the image's intensities are represented on the screen. Specify individual gamma levels for the red, green, and blue channels, or adjust all three with the gamma parameter. Values typically range from 0.8 to 2.3.
You can also reduce the influence of a particular channel with a gamma
value of 0.
The format of the MagickGammaImageChannel method is:
unsigned int MagickGammaImageChannel\( MagickWand *wand, const ChannelType channel,
const double gamma );
wand:
The magick wand.
channel:
The channel.
level:
Define the level of gamma correction.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(gamma :double))
(defcfun ("MagickGetConfigureInfo" %MagickGetConfigureInfo)
:string
"Returns ImageMagick configure attributes such as NAME, VERSION, LIB_VERSION, COPYRIGHT, etc.
The format of the MagickGetConfigureInfo\() method is:
char *MagickGetConfigureInfo\( MagickWand *wand, const char *name );
A description of each parameter follows:
wand:
The magick wand.
name:
Return the attribute associated with this name.
WARN: GraphicsMagick return NULL whatever you passed. Do NOT use this API.
More detail could be found in source code.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(name :string))
(defcfun ("MagickGetCopyright" %MagickGetCopyright)
:string
"Returns the ImageMagick API copyright as a string.
The format of the MagickGetCopyright method is:
const char *MagickGetCopyright\( void );
Since GraphicsMagick v1.1.0")
(defcfun ("MagickGetException" %MagickGetException)
:string
"Returns the severity, reason, and description of any error that occurs when using other methods in this API.
The format of the MagickGetException method is:
char *MagickGetException\( const MagickWand *wand, ExceptionType *severity );
A description of each parameter follows:
wand:
The magick wand.
severity:
The severity of the error is returned here.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(severity :pointer)) ;; ExceptionType *severity
(defcfun ("MagickGetFilename" %MagickGetFilename)
:string
"Returns the filename associated with an image sequence.
The format of the MagickGetFilename method is:
const char *MagickGetFilename\( const MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetHomeURL" %MagickGetHomeURL)
:string
"Returns the ImageMagick home URL.
The format of the MagickGetHomeURL method is:
const char *MagickGetHomeURL\( void );
Since GraphicsMagick v1.1.0")
(defcfun ("MagickGetImage" %MagickGetImage)
%MagickWand
"Clones the image at the current image index.
The format of the MagickGetImage method is:
MagickWand *MagickGetImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageAttribute" %MagickGetImageAttribute)
:string
"MagickGetImageAttribute returns an image attribute as a string
The format of the MagickGetImageAttribute method is:
char *MagickGetImageAttribute\( MagickWand *wand, const char *name );
A description of each parameter follows:
wand:
The magick wand.
name:
The name of the attribute
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(name :string))
(defcfun ("MagickGetImageBackgroundColor" %MagickGetImageBackgroundColor)
%magick-status
"Returns the image background color.
The format of the MagickGetImageBackgroundColor method is:
unsigned int MagickGetImageBackgroundColor\( MagickWand *wand, PixelWand *background_color );
wand:
The magick wand.
background_color:
Return the background color.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(background_color %PixelWand))
(defcfun ("MagickGetImageBluePrimary" %MagickGetImageBluePrimary)
%magick-status
"Returns the chromaticy blue primary point for the image.
The format of the MagickGetImageBluePrimary method is:
unsigned int MagickGetImageBluePrimary\( MagickWand *wand, double *x, double *y );
wand:
The magick wand.
x:
The chromaticity blue primary x-point.
y:
The chromaticity blue primary y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImageBorderColor" %MagickGetImageBorderColor)
%magick-status
"Returns the image border color.
The format of the MagickGetImageBorderColor method is:
unsigned int MagickGetImageBorderColor\( MagickWand *wand, PixelWand *border_color );
wand:
The magick wand.
border_color:
Return the border color.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(border_color %PixelWand))
(defcfun ("MagickGetImageBoundingBox" %MagickGetImageBoundingBox)
%magick-status
"Obtains the crop bounding box required to remove a solid-color border from the image. Color quantums which differ less than the fuzz setting are considered to be the same. If a border is not detected, then the the original image dimensions are returned. The crop bounding box estimation uses the same algorithm as MagickTrimImage\().
The format of the MagickGetImageBoundingBox method is:
unsigned int MagickGetImageBoundingBox\( MagickWand *wand, const double fuzz,
unsigned long *width, unsigned long *height,
long *x, long *y );
wand:
The magick wand.
fuzz:
Color comparison fuzz factor. Use 0.0 for exact match.
width:
The crop width
height:
The crop height
x:
The crop x offset
y:
The crop y offset
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(fuzz :double)
(width :pointer)
(height :pointer)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImageChannelDepth" %MagickGetImageChannelDepth)
:unsigned-long
"Gets the depth for a particular image channel.
The format of the MagickGetImageChannelDepth method is:
unsigned long MagickGetImageChannelDepth\( MagickWand *wand, const ChannelType channel );
wand:
The magick wand.
channel:
Identify which channel to extract: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
BlackChannel.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType))
(defcfun ("MagickGetImageChannelExtrema" %MagickGetImageChannelExtrema)
%magick-status
"Gets the extrema for one or more image channels.
The format of the MagickGetImageChannelExtrema method is:
unsigned int MagickGetImageChannelExtrema\( MagickWand *wand, const ChannelType channel,
unsigned long *minima, unsigned long *maxima );
wand:
The magick wand.
channel:
Identify which channel to extract: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
or BlackChannel.
minima:
The minimum pixel value for the specified channel\(s).
maxima:
The maximum pixel value for the specified channel\(s).
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(minima :pointer)
(maxima :pointer))
(defcfun ("MagickGetImageChannelMean" %MagickGetImageChannelMean)
%magick-status
"Gets the mean and standard deviation of one or more image channels.
The format of the MagickGetImageChannelMean method is:
unsigned int MagickGetImageChannelMean\( MagickWand *wand, const ChannelType channel,
double *mean, double *standard_deviation );
wand:
The magick wand.
channel:
Identify which channel to extract: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
or BlackChannel.
mean:
The mean pixel value for the specified channel\(s).
standard_deviation:
The standard deviation for the specified channel\(s).
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(mean :pointer)
(standard_deviation :pointer))
(defcfun ("MagickGetImageColormapColor" %MagickGetImageColormapColor)
%magick-status
"Returns the color of the specified colormap index.
The format of the MagickGetImageColormapColor method is:
unsigned int MagickGetImageColormapColor\( MagickWand *wand, const unsigned long index,
PixelWand *color );
wand:
The magick wand.
index:
The offset into the image colormap.
color:
Return the colormap color in this wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(index :unsigned-long)
(color %PixelWand))
(defcfun ("MagickGetImageColors" %MagickGetImageColors)
:unsigned-long
"Gets the number of unique colors in the image.
The format of the MagickGetImageColors method is:
unsigned long MagickGetImageColors\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageColorspace" %MagickGetImageColorspace)
%ColorspaceType
"Gets the image colorspace.
The format of the MagickGetImageColorspace method is:
ColorspaceType MagickGetImageColorspace\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageCompose" %MagickGetImageCompose)
%CompositeOperator
"Returns the composite operator associated with the image.
The format of the MagickGetImageCompose method is:
CompositeOperator MagickGetImageCompose\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageCompression" %MagickGetImageCompression)
%CompressionType
"Gets the image compression.
The format of the MagickGetImageCompression method is:
CompressionType MagickGetImageCompression\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageDelay" %MagickGetImageDelay)
:unsigned-long
"Gets the image delay.
The format of the MagickGetImageDelay method is:
unsigned long MagickGetImageDelay\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageDepth" %MagickGetImageDepth)
:unsigned-long
"Gets the image depth.
The format of the MagickGetImageDepth method is:
unsigned long MagickGetImageDepth\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageExtrema" %MagickGetImageExtrema)
%magick-status
"Gets the extrema for the image.
The format of the MagickGetImageExtrema method is:
unsigned int MagickGetImageExtrema\( MagickWand *wand, unsigned long *min,
unsigned long *max );
wand:
The magick wand.
min:
The minimum pixel value for the specified channel\(s).
max:
The maximum pixel value for the specified channel\(s).
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(min :pointer)
(max :pointer))
(defcfun ("MagickGetImageDispose" %MagickGetImageDispose)
%DisposeType
"Gets the image disposal method.
The format of the MagickGetImageDispose method is:
DisposeType MagickGetImageDispose\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageFilename" %MagickGetImageFilename)
:char
"Returns the filename of a particular image in a sequence.
The format of the MagickGetImageFilename method is:
const char MagickGetImageFilename\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageFormat" %MagickGetImageFormat)
:string
"Returns the format of a particular image in a sequence.
The format of the MagickGetImageFormat method is:
char * MagickGetImageFormat\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageFuzz" %MagickGetImageFuzz)
:double
"Returns the color comparison fuzz factor. Colors closer than the fuzz factor are considered to be the same when comparing colors. Note that some other functions such as MagickColorFloodfillImage\() implicitly set this value.
The format of the MagickGetImageFuzz method is:
double MagickGetImageFuzz\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.3.8"
(wand %MagickWand))
(defcfun ("MagickGetImageGamma" %MagickGetImageGamma)
:double
"Gets the image gamma.
The format of the MagickGetImageGamma method is:
double MagickGetImageGamma\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageGeometry" %MagickGetImageGeometry)
:string
"Gets the image geometry string. NULL is returned if the image does not contain a geometry string.
The format of the MagickGetImageGeometry method is:
const char *MagickGetImageGeometry\( MagickWand *wand )
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.3.20"
(wand %MagickWand))
(defcfun ("MagickGetImageGravity" %MagickGetImageGravity)
%GravityType
"Gets the image gravity.
The format of the MagickGetImageGravity method is:
GravityType MagickGetImageGravity\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.3.22"
(wand %MagickWand))
(defcfun ("MagickGetImageGreenPrimary" %MagickGetImageGreenPrimary)
%magick-status
"Returns the chromaticy green primary point.
The format of the MagickGetImageGreenPrimary method is:
unsigned int MagickGetImageGreenPrimary\( MagickWand *wand, double *x, double *y );
wand:
The magick wand.
x:
The chromaticity green primary x-point.
y:
The chromaticity green primary y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImageHeight" %MagickGetImageHeight)
:unsigned-long
"Returns the image height.
The format of the MagickGetImageHeight method is:
unsigned long MagickGetImageHeight\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageHistogram" %MagickGetImageHistogram)
%PixelWand
"Returns the image histogram as an array of PixelWand wands.
The format of the MagickGetImageHistogram method is:
PixelWand *MagickGetImageHistogram\( MagickWand *wand, unsigned long *number_colors );
wand:
The magick wand.
number_colors:
The number of unique colors in the image and the number
of pixel wands returned.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(number_colors :pointer))
(defcfun ("MagickGetImageIndex" %MagickGetImageIndex)
:long
"Returns the index of the current image.
The format of the MagickGetImageIndex method is:
long MagickGetImageIndex\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageInterlaceScheme" %MagickGetImageInterlaceScheme)
%InterlaceType
"Gets the image interlace scheme.
The format of the MagickGetImageInterlaceScheme method is:
InterlaceType MagickGetImageInterlaceScheme\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageIterations" %MagickGetImageIterations)
:unsigned-long
"Gets the image iterations.
The format of the MagickGetImageIterations method is:
unsigned long MagickGetImageIterations\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageMatte" %MagickGetImageMatte)
%MagickBool
"Gets the image matte flag. The flag is MagickTrue if the image supports an opacity \(inverse of transparency) channel.
The format of the MagickGetImageMatte method is:
MagickBool MagickGetImageMatte\( MagickWand *wand )
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.3.20"
(wand %MagickWand))
(defcfun ("MagickGetImageMatteColor" %MagickGetImageMatteColor)
%magick-status
"Returns the image matte color.
The format of the MagickGetImageMatteColor method is:
unsigned int MagickGetImageMatteColor\( MagickWand *wand, PixelWand *matte_color );
wand:
The magick wand.
matte_color:
Return the matte color.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(matte_color %PixelWand))
(defcfun ("MagickGetImageOrientation" %MagickGetImageOrientation)
%OrientationType
"Gets the image orientation type. May be one of:
UndefinedOrientation Image orientation not specified or error.
TopLeftOrientation Left to right and Top to bottom.
TopRightOrientation Right to left and Top to bottom.
BottomRightOrientation Right to left and Bottom to top.
BottomLeftOrientation Left to right and Bottom to top.
LeftTopOrientation Top to bottom and Left to right.
RightTopOrientation Top to bottom and Right to left.
RightBottomOrientation Bottom to top and Right to left.
LeftBottomOrientation Bottom to top and Left to right.
The format of the MagickGetImageOrientation method is:
OrientationType MagickGetImageOrientation\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.3.26"
(wand %MagickWand))
(defcfun ("MagickGetImagePage" %MagickGetImagePage)
%magick-status
"Retrieves the image page size and offset used when placing \(e.g. compositing) the image.
The format of the MagickGetImagePage method is:
MagickGetImagePage\( MagickWand *wand, unsigned long *width, unsigned long *height, long *x,
long *y );
wand:
The magick wand.
width, height:
The region size.
x, y:
Offset \(from top left) on base canvas image on
which to composite image data.
Since GraphicsMagick v1.3.18"
(wand %MagickWand)
(width :pointer)
(height :pointer)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImagePixels" %MagickGetImagePixels)
%magick-status
"Extracts pixel data from an image and returns it to you. The method returns False on success otherwise True if an error is encountered. The data is returned as char, short int, int, long, float, or double in the order specified by map.
Suppose you want to extract the first scanline of a 640x480 image as
character data in red-green-blue order:
MagickGetImagePixels\(wand,0,0,640,1,\"RGB\",CharPixel,pixels);
The format of the MagickGetImagePixels method is:
unsigned int MagickGetImagePixels\( MagickWand *wand, const long x_offset, const long y_offset,
const unsigned long columns, const unsigned long rows,
const char *map, const StorageType storage,
unsigned char *pixels );
wand:
The magick wand.
x_offset, y_offset, columns, rows:
These values define the perimeter
of a region of pixels you want to extract.
map:
This string reflects the expected ordering of the pixel array.
It can be any combination or order of R = red, G = green, B = blue,
A = alpha, C = cyan, Y = yellow, M = magenta, K = black, or
I = intensity \(for grayscale).
storage:
Define the data type of the pixels. Float and double types are
expected to be normalized [0..1] otherwise [0..MaxRGB]. Choose from
these types: CharPixel, ShortPixel, IntegerPixel, LongPixel, FloatPixel,
or DoublePixel.
pixels:
This array of values contain the pixel components as defined by
map and type. You must preallocate this array where the expected
length varies depending on the values of width, height, map, and type.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x_offset :long)
(y_offset :long)
(columns :unsigned-long)
(rows :unsigned-long)
(map :string)
(storage %StorageType)
(pixels :pointer))
(defcfun ("MagickGetImageProfile" %MagickGetImageProfile)
:pointer
"Returns the named image profile.
The format of the MagickGetImageProfile method is:
unsigned char *MagickGetImageProfile\( MagickWand *wand, const char *name,
unsigned long *length );
wand:
The magick wand.
name:
Name of profile to return: ICC, IPTC, or generic profile.
length:
The length of the profile.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(name :string)
(length :pointer))
(defcfun ("MagickGetImageRedPrimary" %MagickGetImageRedPrimary)
%magick-status
"Returns the chromaticy red primary point.
The format of the MagickGetImageRedPrimary method is:
unsigned int MagickGetImageRedPrimary\( MagickWand *wand, double *x, double *y );
wand:
The magick wand.
x:
The chromaticity red primary x-point.
y:
The chromaticity red primary y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImageRenderingIntent" %MagickGetImageRenderingIntent)
%RenderingIntent
"Gets the image rendering intent.
The format of the MagickGetImageRenderingIntent method is:
RenderingIntent MagickGetImageRenderingIntent\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageResolution" %MagickGetImageResolution)
%magick-status
"Gets the image X & Y resolution.
The format of the MagickGetImageResolution method is:
unsigned int MagickGetImageResolution\( MagickWand *wand, double *x, double *y );
wand:
The magick wand.
x:
The image x-resolution.
y:
The image y-resolution.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImageScene" %MagickGetImageScene)
:unsigned-long
"Gets the image scene.
The format of the MagickGetImageScene method is:
unsigned long MagickGetImageScene\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageSignature" %MagickGetImageSignature)
:char
"Generates an SHA-256 message digest for the image pixel stream.
The format of the MagickGetImageSignature method is:
const char MagickGetImageSignature\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageSize" %MagickGetImageSize)
%MagickSizeType
"Returns the image size.
The format of the MagickGetImageSize method is:
MagickSizeType MagickGetImageSize\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageType" %MagickGetImageType)
%ImageType
"Gets the image type.
The format of the MagickGetImageType method is:
ImageType MagickGetImageType\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageSavedType" %MagickGetImageSavedType)
%ImageType
"Gets the image type that will be used when the image is saved. This may be different to the current image type, returned by MagickGetImageType\().
The format of the MagickGetImageSavedType method is:
ImageType MagickGetImageSavedType\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.3.13"
(wand %MagickWand))
(defcfun ("MagickGetImageUnits" %MagickGetImageUnits)
%ResolutionType
"Gets the image units of resolution.
The format of the MagickGetImageUnits method is:
ResolutionType MagickGetImageUnits\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageVirtualPixelMethod" %MagickGetImageVirtualPixelMethod)
%VirtualPixelMethod
"Returns the virtual pixel method for the sepcified image.
The format of the MagickGetImageVirtualPixelMethod method is:
VirtualPixelMethod MagickGetImageVirtualPixelMethod\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageWhitePoint" %MagickGetImageWhitePoint)
%magick-status
"Returns the chromaticy white point.
The format of the MagickGetImageWhitePoint method is:
unsigned int MagickGetImageWhitePoint\( MagickWand *wand, double *x, double *y );
wand:
The magick wand.
x:
The chromaticity white x-point.
y:
The chromaticity white y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImageWidth" %MagickGetImageWidth)
:unsigned-long
"Returns the image width.
The format of the MagickGetImageWidth method is:
unsigned long MagickGetImageWidth\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetNumberImages" %MagickGetNumberImages)
:unsigned-long
"Returns the number of images associated with a magick wand.
The format of the MagickGetNumberImages method is:
unsigned long MagickGetNumberImages\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetPackageName" %MagickGetPackageName)
:string
"Returns the ImageMagick package name.
The format of the MagickGetPackageName method is:
const char *MagickGetPackageName\( void );
Since GraphicsMagick v1.1.0")
(defcfun ("MagickGetQuantumDepth" %MagickGetQuantumDepth)
:string
"Returns the ImageMagick quantum depth.
The format of the MagickGetQuantumDepth method is:
const char *MagickGetQuantumDepth\( unsigned long *depth );
A description of each parameter follows:
depth:
The quantum depth is returned as a number.
Since GraphicsMagick v1.1.0"
(depth :pointer))
(defcfun ("MagickGetReleaseDate" %MagickGetReleaseDate)
:string
"Returns the ImageMagick release date.
The format of the MagickGetReleaseDate method is:
const char *MagickGetReleaseDate\( void );
Since GraphicsMagick v1.1.0")
(defcfun ("MagickGetResourceLimit" %MagickGetResourceLimit)
:unsigned-long
"Returns the the specified resource in megabytes.
The format of the MagickGetResourceLimit method is:
unsigned long MagickGetResourceLimit\( const ResourceType type );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(type %ResourceType))
(defcfun ("MagickGetSamplingFactors" %MagickGetSamplingFactors)
:double
"Gets the horizontal and vertical sampling factor.
The format of the MagickGetSamplingFactors method is:
double *MagickGetSamplingFactors\( MagickWand *wand, unsigned long *number_factors );
wand:
The magick wand.
number_factors:
The number of factors in the returned array.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(number_factors :pointer))
(defcfun ("MagickGetSize" %MagickGetSize)
%magick-status
"Returns the size associated with the magick wand.
The format of the MagickGetSize method is:
unsigned int MagickGetSize\( const MagickWand *wand, unsigned long *columns,
unsigned long *rows );
wand:
The magick wand.
columns:
The width in pixels.
height:
The height in pixels.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(columns :pointer)
(rows :pointer))
(defcfun ("MagickGetVersion" %MagickGetVersion)
:string
"Returns the ImageMagick API version as a string and as a number.
The format of the MagickGetVersion method is:
const char *MagickGetVersion\( unsigned long *version );
A description of each parameter follows:
version:
The ImageMagick version is returned as a number.
Since GraphicsMagick v1.1.0"
(version :pointer))
(defcfun ("MagickHaldClutImage" %MagickHaldClutImage)
%MagickPassFail
"The MagickHaldClutImage\() method apply a color lookup table \(Hald CLUT) to the image. The fundamental principle of the Hald CLUT algorithm is that application of an identity CLUT causes no change to the input image, but an identity CLUT image which has had its colors transformed in some way \(e.g. in Adobe Photoshop) may be used to implement an identical transform on any other image.
The minimum CLUT level is 2, and the maximum depends on available memory
\(largest successfully tested is 24). A CLUT image is required to have equal
width and height. A CLUT of level 8 is an image of dimension 512x512, a CLUT
of level 16 is an image of dimension 4096x4096. Interpolation is used so
extremely large CLUT images are not required.
GraphicsMagick provides an 'identity' coder which may be used to generate
identity HLUTs. For example, reading from \"identity:8\" creates an identity
CLUT of order 8.
The Hald CLUT algorithm has been developed by Eskil Steenberg as described
at http://www.quelsolaar.com/technology/clut.html, and was adapted for
GraphicsMagick by Clément Follet with support from Cédric Lejeune of
Workflowers.
The format of the HaldClutImage method is:
MagickPassFail MagickHaldClutImage\( MagickWand *wand, const MagickWand *clut_wand );
A description of each parameter follows:
wand:
The image wand.
clut_wand:
The color lookup table image wand
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(clut_wand %MagickWand))
(defcfun ("MagickHasNextImage" %MagickHasNextImage)
:boolean
"Returns True if the wand has more images when traversing the list in the forward direction
The format of the MagickHasNextImage method is:
unsigned int MagickHasNextImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickHasPreviousImage" %MagickHasPreviousImage)
%magick-status
"Returns True if the wand has more images when traversing the list in the reverse direction
The format of the MagickHasPreviousImage method is:
unsigned int MagickHasPreviousImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickImplodeImage" %MagickImplodeImage)
%magick-status
"Creates a new image that is a copy of an existing one with the image pixels \"implode\" by the specified percentage. It allocates the memory necessary for the new Image structure and returns a pointer to the new image.
The format of the MagickImplodeImage method is:
unsigned int MagickImplodeImage\( MagickWand *wand, const double radius );
A description of each parameter follows:
wand:
The magick wand.
amount:
Define the extent of the implosion.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double))
(defcfun ("MagickLabelImage" %MagickLabelImage)
%magick-status
"Adds a label to your image.
The format of the MagickLabelImage method is:
unsigned int MagickLabelImage\( MagickWand *wand, const char *label );
A description of each parameter follows:
wand:
The magick wand.
label:
The image label.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(label :string))
(defcfun ("MagickLevelImage" %MagickLevelImage)
%magick-status
"Adjusts the levels of an image by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid, and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value.
The format of the MagickLevelImage method is:
unsigned int MagickLevelImage\( MagickWand *wand, const double black_point, const double gamma,
const double white_point );
wand:
The magick wand.
black_point:
The black point.
gamma:
The gamma.
white_point:
The white point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(black_point :double)
(gamma :double)
(white_point :double))
(defcfun ("MagickLevelImageChannel" %MagickLevelImageChannel)
%magick-status
"Adjusts the levels of the specified channel of the reference image by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid, and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value.
The format of the MagickLevelImageChannel method is:
unsigned int MagickLevelImageChannel\( MagickWand *wand, const ChannelType channel,
const double black_point, const double gamma,
const double white_point );
wand:
The magick wand.
channel:
Identify which channel to level: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
BlackChannel.
black_point:
The black point.
gamma:
The gamma.
white_point:
The white point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(black_point :double)
(gamma :double)
(white_point :double))
(defcfun ("MagickMagnifyImage" %MagickMagnifyImage)
%magick-status
"Is a convenience method that scales an image proportionally to twice its original size.
The format of the MagickMagnifyImage method is:
unsigned int MagickMagnifyImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickMapImage" %MagickMapImage)
%magick-status
"Replaces the colors of an image with the closest color from a reference image.
The format of the MagickMapImage method is:
unsigned int MagickMapImage\( MagickWand *wand, const MagickWand *map_wand,
const unsigned int dither );
wand:
The magick wand.
map:
The map wand.
dither:
Set this integer value to something other than zero to dither
the mapped image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(map_wand %MagickWand)
(dither :unsigned-int))
(defcfun ("MagickMatteFloodfillImage" %MagickMatteFloodfillImage)
%magick-status
"Changes the transparency value of any pixel that matches target and is an immediate neighbor. If the method FillToBorderMethod is specified, the transparency value is changed for any neighbor pixel that does not match the bordercolor member of image.
The format of the MagickMatteFloodfillImage method is:
unsigned int MagickMatteFloodfillImage\( MagickWand *wand, const Quantum opacity,
const double fuzz, const PixelWand *bordercolor,
const long x, const long y );
wand:
The magick wand.
opacity:
The opacity.
fuzz:
By default target must match a particular pixel color
exactly. However, in many cases two colors may differ by a small amount.
The fuzz member of image defines how much tolerance is acceptable to
consider two colors as the same. For example, set fuzz to 10 and the
color red at intensities of 100 and 102 respectively are now interpreted
as the same color for the purposes of the floodfill.
bordercolor:
The border color pixel wand.
x,y:
The starting location of the operation.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(opacity %Quantum)
(fuzz :double)
(bordercolor %PixelWand)
(x :long)
(y :long))
(defcfun ("MagickMedianFilterImage" %MagickMedianFilterImage)
%magick-status
"Applies a digital filter that improves the quality of a noisy image. Each pixel is replaced by the median in a set of neighboring pixels as defined by radius.
The format of the MagickMedianFilterImage method is:
unsigned int MagickMedianFilterImage\( MagickWand *wand, const double radius );
wand:
The magick wand.
radius:
The radius of the pixel neighborhood.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double))
(defcfun ("MagickMinifyImage" %MagickMinifyImage)
%magick-status
"Is a convenience method that scales an image proportionally to one-half its original size
The format of the MagickMinifyImage method is:
unsigned int MagickMinifyImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickModulateImage" %MagickModulateImage)
%magick-status
"Lets you control the brightness, saturation, and hue of an image.
The format of the MagickModulateImage method is:
unsigned int MagickModulateImage\( MagickWand *wand, const double brightness,
const double saturation, const double hue );
wand:
The magick wand.
brightness:
The percent change in brighness \(-100 thru +100).
saturation:
The percent change in saturation \(-100 thru +100)
hue:
The percent change in hue \(-100 thru +100)
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(brightness :double)
(saturation :double)
(hue :double))
(defcfun ("MagickMontageImage" %MagickMontageImage)
%MagickWand
"Use MagickMontageImage\() to create a composite image by combining several separate images. The images are tiled on the composite image with the name of the image optionally appearing just below the individual tile.
The format of the MagickMontageImage method is:
MagickWand MagickMontageImage\( MagickWand *wand, const DrawingWand drawing_wand,
const char *tile_geometry, const char *thumbnail_geometry,
const MontageMode mode, const char *frame );
wand:
The magick wand.
drawing_wand:
The drawing wand. The font name, size, and color are
obtained from this wand.
tile_geometry:
the number of tiles per row and page \(e.g. 6x4+0+0).
thumbnail_geometry:
Preferred image size and border size of each
thumbnail \(e.g. 120x120+4+3>).
mode:
Thumbnail framing mode: Frame, Unframe, or Concatenate.
frame:
Surround the image with an ornamental border \(e.g. 15x15+3+3).
The frame color is that of the thumbnail's matte color.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(drawing_wand %DrawingWand)
(tile_geometry :string)
(thumbnail_geometry :string)
(mode %MontageMode)
(frame :string))
(defcfun ("MagickMorphImages" %MagickMorphImages)
%MagickWand
"Method morphs a set of images. Both the image pixels and size are linearly interpolated to give the appearance of a meta-morphosis from one image to the next.
The format of the MagickMorphImages method is:
MagickWand *MagickMorphImages\( MagickWand *wand, const unsigned long number_frames );
wand:
The magick wand.
number_frames:
The number of in-between images to generate.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(number_frames :unsigned-long))
(defcfun ("MagickMosaicImages" %MagickMosaicImages)
%MagickWand
"Inlays an image sequence to form a single coherent picture. It returns a wand with each image in the sequence composited at the location defined by the page offset of the image.
The format of the MagickMosaicImages method is:
MagickWand *MagickMosaicImages\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickMotionBlurImage" %MagickMotionBlurImage)
%magick-status
"Simulates motion blur. We convolve the image with a Gaussian operator of the given radius and standard deviation \(sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and MotionBlurImage\() selects a suitable radius for you. Angle gives the angle of the blurring motion.
The format of the MagickMotionBlurImage method is:
unsigned int MagickMotionBlurImage\( MagickWand *wand, const double radius, const double sigma,
const double angle );
wand:
The magick wand.
radius:
The radius of the Gaussian, in pixels, not counting
the center pixel.
sigma:
The standard deviation of the Gaussian, in pixels.
angle:
Apply the effect along this angle.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double)
(sigma :double)
(angle :double))
(defcfun ("MagickNegateImage" %MagickNegateImage)
%magick-status
"Negates the colors in the reference image. The Grayscale option means that only grayscale values within the image are negated.
You can also reduce the influence of a particular channel with a gamma
value of 0.
The format of the MagickNegateImage method is:
unsigned int MagickNegateImage\( MagickWand *wand, const unsigned int gray );
A description of each parameter follows:
wand:
The magick wand.
gray:
If True, only negate grayscale pixels within the image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(gray :unsigned-int))
(defcfun ("MagickNegateImageChannel" %MagickNegateImageChannel)
%magick-status
"Negates the colors in the specified channel of the reference image. The Grayscale option means that only grayscale values within the image are negated. Note that the Grayscale option has no effect for GraphicsMagick.
You can also reduce the influence of a particular channel with a gamma
value of 0.
The format of the MagickNegateImageChannel method is:
unsigned int MagickNegateImageChannel\( MagickWand *wand, const ChannelType channel,
const unsigned int gray );
wand:
The magick wand.
channel:
Identify which channel to extract: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
BlackChannel.
gray:
If True, only negate grayscale pixels within the image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(gray :unsigned-int))
(defcfun ("MagickNextImage" %MagickNextImage)
%magick-status
"Associates the next image in the image list with a magick wand. True is returned if the Wand iterated to a next image, or False is returned if the wand did not iterate to a next image.
The format of the MagickNextImage method is:
unsigned int MagickNextImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickNormalizeImage" %MagickNormalizeImage)
%magick-status
"Enhances the contrast of a color image by adjusting the pixels color to span the entire range of colors available
You can also reduce the influence of a particular channel with a gamma
value of 0.
The format of the MagickNormalizeImage method is:
unsigned int MagickNormalizeImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickOilPaintImage" %MagickOilPaintImage)
%magick-status
"Applies a special effect filter that simulates an oil painting. Each pixel is replaced by the most frequent color occurring in a circular region defined by radius.
The format of the MagickOilPaintImage method is:
unsigned int MagickOilPaintImage\( MagickWand *wand, const double radius );
A description of each parameter follows:
wand:
The magick wand.
radius:
The radius of the circular neighborhood.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double))
(defcfun ("MagickOpaqueImage" %MagickOpaqueImage)
%magick-status
"Changes any pixel that matches color with the color defined by fill.
The format of the MagickOpaqueImage method is:
unsigned int MagickOpaqueImage\( MagickWand *wand, const PixelWand *target,
const PixelWand *fill, const double fuzz );
wand:
The magick wand.
target:
Change this target color to the fill color within the image.
fill:
The fill pixel wand.
fuzz:
By default target must match a particular pixel color
exactly. However, in many cases two colors may differ by a small amount.
The fuzz member of image defines how much tolerance is acceptable to
consider two colors as the same. For example, set fuzz to 10 and the
color red at intensities of 100 and 102 respectively are now interpreted
as the same color for the purposes of the floodfill.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(target %PixelWand)
(fill %PixelWand)
(fuzz :double))
(defcfun ("MagickOperatorImageChannel" %MagickOperatorImageChannel)
%magick-status
"Performs the requested arithmetic,
bitwise-logical, or value operation on the selected channels of
the entire image. The AllChannels channel option operates on all
color channels whereas the GrayChannel channel option treats the
color channels as a grayscale intensity.
These operations are on the DirectClass pixels of the image and do not
update pixel indexes or colormap.
The format of the MagickOperatorImageChannel method is:
MagickPassFail MagickOperatorImageChannel\( MagickWand *wand,
const ChannelType channel,const QuantumOperator quantum_operator,
const double rvalue )
A description of each parameter follows:
wand: The magick wand.
channel: Channel to operate on \(RedChannel, CyanChannel,
GreenChannel, MagentaChannel, BlueChannel, YellowChannel,
OpacityChannel, BlackChannel, MatteChannel, AllChannels,
GrayChannel). The AllChannels type only updates color
channels. The GrayChannel type treats the color channels
as if they represent an intensity.
quantum_operator: Operator to use \(AddQuantumOp,AndQuantumOp,
AssignQuantumOp, DepthQuantumOp, DivideQuantumOp, GammaQuantumOp,
LShiftQuantumOp, MultiplyQuantumOp, NegateQuantumOp,
NoiseGaussianQuantumOp, NoiseImpulseQuantumOp,
NoiseLaplacianQuantumOp, NoiseMultiplicativeQuantumOp,
NoisePoissonQuantumOp, NoiseRandomQuantumOp, NoiseUniformQuantumOp,
OrQuantumOp, RShiftQuantumOp, SubtractQuantumOp,
ThresholdBlackQuantumOp, ThresholdQuantumOp, ThresholdWhiteQuantumOp,
ThresholdBlackNegateQuantumOp, ThresholdWhiteNegateQuantumOp,
XorQuantumOp).
rvalue: Operator argument.
Since GraphicsMagick v1.3.20"
(wand %MagickWand)
(channel %ChannelType)
(quantum_operator %QuantumOperator) ;; TODO
(rvalue :double))
(defcfun ("MagickPingImage" %MagickPingImage)
%magick-status
"Is like MagickReadImage\() except the only valid information returned is the image width, height, size, and format. It is designed to efficiently obtain this information from a file without reading the entire image sequence into memory.
The format of the MagickPingImage method is:
unsigned int MagickPingImage\( MagickWand *wand, const char *filename );
A description of each parameter follows:
wand:
The magick wand.
filename:
The image filename.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(filename :string))
(defcfun ("MagickPreviewImages" %MagickPreviewImages)
%MagickWand
"Tiles 9 thumbnails of the specified image with an image processing operation applied at varying strengths. This is helpful to quickly pin-point an appropriate parameter for an image processing operation.
The format of the MagickPreviewImages method is:
MagickWand *MagickPreviewImages\( MagickWand *wand, const PreviewType preview );
wand:
The magick wand.
preview:
The preview type.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(preview %PreviewType))
(defcfun ("MagickPreviousImage" %MagickPreviousImage)
%magick-status
"Selects the previous image associated with a magick wand.
The format of the MagickPreviousImage method is:
unsigned int MagickPreviousImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickProfileImage" %MagickProfileImage)
%magick-status
"Use MagickProfileImage\() to add or remove a ICC, IPTC, or generic profile from an image. If the profile is NULL, it is removed from the image otherwise added. Use a name of '*' and a profile of NULL to remove all profiles from the image.
The format of the MagickProfileImage method is:
unsigned int MagickProfileImage\( MagickWand *wand, const char *name,
const unsigned char *profile, const size_t length );
wand:
The magick wand.
name:
Name of profile to add or remove: ICC, IPTC, or generic profile.
profile:
The profile.
length:
The length of the profile.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(name :string)
(profile :pointer)
(length %size_t))
(defcfun ("MagickQuantizeImage" %MagickQuantizeImage)
%magick-status
"Analyzes the colors within a reference image and chooses a fixed number of colors to represent the image. The goal of the algorithm is to minimize the color difference between the input and output image while minimizing the processing time.
The format of the MagickQuantizeImage method is:
unsigned int MagickQuantizeImage\( MagickWand *wand, const unsigned long number_colors,
const ColorspaceType colorspace,
const unsigned long treedepth, const unsigned int dither,
const unsigned int measure_error );
wand:
The magick wand.
number_colors:
The number of colors.
colorspace:
Perform color reduction in this colorspace, typically
RGBColorspace.
treedepth:
Normally, this integer value is zero or one. A zero or
one tells Quantize to choose a optimal tree depth of Log4\(number_colors).% A tree of this depth generally allows the best representation of the
reference image with the least amount of memory and the fastest
computational speed. In some cases, such as an image with low color
dispersion \(a few number of colors), a value other than
Log4\(number_colors) is required. To expand the color tree completely,
use a value of 8.
dither:
A value other than zero distributes the difference between an
original image and the corresponding color reduced algorithm to
neighboring pixels along a Hilbert curve.
measure_error:
A value other than zero measures the difference between
the original and quantized images. This difference is the total
quantization error. The error is computed by summing over all pixels
in an image the distance squared in RGB space between each reference
pixel value and its quantized value.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(number_colors :unsigned-long)
(colorspace %ColorspaceType)
(treedepth :unsigned-long)
(dither :unsigned-int)
(measure_error :unsigned-int))
(defcfun ("MagickQuantizeImages" %MagickQuantizeImages)
%magick-status
"Analyzes the colors within a sequence of images and chooses a fixed number of colors to represent the image. The goal of the algorithm is to minimize the color difference between the input and output image while minimizing the processing time.
The format of the MagickQuantizeImages method is:
unsigned int MagickQuantizeImages\( MagickWand *wand, const unsigned long number_colors,
const ColorspaceType colorspace,
const unsigned long treedepth, const unsigned int dither,
const unsigned int measure_error );
wand:
The magick wand.
number_colors:
The number of colors.
colorspace:
Perform color reduction in this colorspace, typically
RGBColorspace.
treedepth:
Normally, this integer value is zero or one. A zero or
one tells Quantize to choose a optimal tree depth of Log4\(number_colors).% A tree of this depth generally allows the best representation of the
reference image with the least amount of memory and the fastest
computational speed. In some cases, such as an image with low color
dispersion \(a few number of colors), a value other than
Log4\(number_colors) is required. To expand the color tree completely,
use a value of 8.
dither:
A value other than zero distributes the difference between an
original image and the corresponding color reduced algorithm to
neighboring pixels along a Hilbert curve.
measure_error:
A value other than zero measures the difference between
the original and quantized images. This difference is the total
quantization error. The error is computed by summing over all pixels
in an image the distance squared in RGB space between each reference
pixel value and its quantized value.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(number_colors :unsigned-long)
(colorspace %ColorspaceType)
(treedepth :unsigned-long)
(dither :unsigned-int)
(measure_error :unsigned-int))
(defcfun ("MagickQueryFontMetrics" %MagickQueryFontMetrics)
:pointer
"Return a pointer to a double array with 7 elements:
0 character width
1 character height
2 ascender
3 descender
4 text width
5 text height
6 maximum horizontal advance
The format of the MagickQueryFontMetrics method is:
double *MagickQueryFontMetrics\( MagickWand *wand, const DrawingWand *drawing_wand,
const char *text );
wand:
The Magick wand.
drawing_wand:
The drawing wand.
text:
The text.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(drawing_wand %DrawingWand)
(text :string))
(defcfun ("MagickQueryFonts" %MagickQueryFonts)
:pointer
"Returns any font that match the specified pattern.
The format of the MagickQueryFonts function is:
char ** MagickQueryFonts\( const char *pattern, unsigned long *number_fonts );
A description of each parameter follows:
pattern:
Specifies a pointer to a text string containing a pattern.
number_fonts:
This integer returns the number of fonts in the list.
Since GraphicsMagick v1.1.0"
(pattern :string)
(number_fonts :pointer))
(defcfun ("MagickQueryFormats" %MagickQueryFormats)
:pointer
"Returns any image formats that match the specified pattern.
The format of the MagickQueryFormats function is:
char ** MagickQueryFormats\( const char *pattern, unsigned long *number_formats );
pattern:
Specifies a pointer to a text string containing a pattern.
number_formats:
This integer returns the number of image formats in the
list.
Since GraphicsMagick v1.1.0"
(pattern :string)
(number_formats :pointer))
(defcfun ("MagickRadialBlurImage" %MagickRadialBlurImage)
%magick-status
"Radial blurs an image.
The format of the MagickRadialBlurImage method is:
unsigned int MagickRadialBlurImage\( MagickWand *wand, const double angle );
A description of each parameter follows:
wand:
The magick wand.
angle:
The angle of the blur in degrees.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(angle :double))
(defcfun ("MagickRaiseImage" %MagickRaiseImage)
%magick-status
"Creates a simulated three-dimensional button-like effect by lightening and darkening the edges of the image. Members width and height of raise_info define the width of the vertical and horizontal edge of the effect.
The format of the MagickRaiseImage method is:
unsigned int MagickRaiseImage\( MagickWand *wand, const unsigned long width,
const unsigned long height, const long x, const long y,
const unsigned int raise_flag );
wand:
The magick wand.
width,height,x,y:
Define the dimensions of the area to raise.
raise_flag:
A value other than zero creates a 3-D raise effect,
otherwise it has a lowered effect.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(width :unsigned-long)
(height :unsigned-long)
(x :long)
(y :long)
(raise_flag :unsigned-int))
(defcfun ("MagickReadImage" %MagickReadImage)
%magick-status
"Reads an image or image sequence.
The format of the MagickReadImage method is:
unsigned int MagickReadImage\( MagickWand *wand, const char *filename );
A description of each parameter follows:
wand:
The magick wand.
filename:
The image filename.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(filename :string))
(defcfun ("MagickReadImageBlob" %MagickReadImageBlob)
%magick-status
"Reads an image or image sequence from a blob.
The format of the MagickReadImageBlob method is:
unsigned int MagickReadImageBlob\( MagickWand *wand, const unsigned char *blob,
const size_t length );
wand:
The magick wand.
blob:
The blob.
length:
The blob length.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(blob :pointer)
(length %size_t))
(defcfun ("MagickReadImageFile" %MagickReadImageFile)
%magick-status
"Reads an image or image sequence from an open file descriptor.
The format of the MagickReadImageFile method is:
unsigned int MagickReadImageFile\( MagickWand *wand, FILE *file );
A description of each parameter follows:
wand:
The magick wand.
file:
The file descriptor.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(file %FILE))
(defcfun ("MagickReduceNoiseImage" %MagickReduceNoiseImage)
%magick-status
"Smooths the contours of an image while still preserving edge information. The algorithm works by replacing each pixel with its neighbor closest in value. A neighbor is defined by radius. Use a radius of 0 and ReduceNoise\() selects a suitable radius for you.
The format of the MagickReduceNoiseImage method is:
unsigned int MagickReduceNoiseImage\( MagickWand *wand, const double radius );
A description of each parameter follows:
wand:
The magick wand.
radius:
The radius of the pixel neighborhood.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double))
(defcfun ("MagickRelinquishMemory" %MagickRelinquishMemory)
%magick-status
"Relinquishes memory resources returned by such methods as MagickDescribeImage\(), MagickGetException\(), etc.
The format of the MagickRelinquishMemory method is:
unsigned int MagickRelinquishMemory\( void *resource );
A description of each parameter follows:
resource:
Relinquish the memory associated with this resource.
Since GraphicsMagick v1.1.0"
(resource :pointer))
(defcfun ("MagickRemoveImage" %MagickRemoveImage)
%magick-status
"Removes an image from the image list.
The format of the MagickRemoveImage method is:
unsigned int MagickRemoveImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickRemoveImageOption" %MagickRemoveImageOption)
%magick-status
"Removes an image format-specific option from the the image \(.e.g MagickRemoveImageOption(wand,\"jpeg\",\"preserve-settings\").
The format of the MagickRemoveImageOption method is:
unsigned int MagickRemoveImageOption\( MagickWand *wand, const char *format,
const char *key );
wand:
The magick wand.
format:
The image format.
key:
The key.
Since GraphicsMagick v1.3.26"
(wand %MagickWand)
(format :string)
(key :string))
(defcfun ("MagickRemoveImageProfile" %MagickRemoveImageProfile)
:pointer
"Removes the named image profile and returns it.
The format of the MagickRemoveImageProfile method is:
unsigned char *MagickRemoveImageProfile\( MagickWand *wand, const char *name,
unsigned long *length );
wand:
The magick wand.
name:
Name of profile to return: ICC, IPTC, or generic profile.
length:
The length of the profile.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(name :string)
(length :pointer))
(defcfun ("MagickResetIterator" %MagickResetIterator)
:void
"Resets the wand iterator. Use it in conjunction with MagickNextImage\() to iterate over all the images in a wand container.
The format of the MagickReset method is:
void MagickResetIterator\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickResampleImage" %MagickResampleImage)
%magick-status
"Resample image to desired resolution.
Bessel Blackman Box
Catrom Cubic Gaussian
Hanning Hermite Lanczos
Mitchell Point Quandratic
Sinc Triangle
Most of the filters are FIR \(finite impulse response), however, Bessel,
Gaussian, and Sinc are IIR \(infinite impulse response). Bessel and Sinc
are windowed \(brought down to zero) with the Blackman filter.
The format of the MagickResampleImage method is:
unsigned int MagickResampleImage\( MagickWand *wand, const double x_resolution,
const double y_resolution, const FilterTypes filter,
const double blur );
wand:
The magick wand.
x_resolution:
The new image x resolution.
y_resolution:
The new image y resolution.
filter:
Image filter to use.
blur:
The blur factor where > 1 is blurry, < 1 is sharp.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x_resolution :double)
(y_resolution :double)
(filter %FilterTypes)
(blur :double))
(defcfun ("MagickResizeImage" %MagickResizeImage)
%magick-status
"Scales an image to the desired dimensions with one of these filters:
Bessel Blackman Box
Catrom Cubic Gaussian
Hanning Hermite Lanczos
Mitchell Point Quandratic
Sinc Triangle
Most of the filters are FIR \(finite impulse response), however, Bessel,
Gaussian, and Sinc are IIR \(infinite impulse response). Bessel and Sinc
are windowed \(brought down to zero) with the Blackman filter.
The format of the MagickResizeImage method is:
unsigned int MagickResizeImage\( MagickWand *wand, const unsigned long columns,
const unsigned long rows, const FilterTypes filter,
const double blur );
wand:
The magick wand.
columns:
The number of columns in the scaled image.
rows:
The number of rows in the scaled image.
filter:
Image filter to use.
blur:
The blur factor where > 1 is blurry, < 1 is sharp.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(columns :unsigned-long)
(rows :unsigned-long)
(filter %FilterTypes)
(blur %double))
(defcfun ("MagickRollImage" %MagickRollImage)
%magick-status
"Offsets an image as defined by x_offset and y_offset.
The format of the MagickRollImage method is:
unsigned int MagickRollImage\( MagickWand *wand, const long x_offset,
const long y_offset );
wand:
The magick wand.
x_offset:
The x offset.
y_offset:
The y offset.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x_offset :long)
(y_offset :long))
(defcfun ("MagickRotateImage" %MagickRotateImage)
%magick-status
"Rotates an image the specified number of degrees. Empty triangles left over from rotating the image are filled with the background color.
The format of the MagickRotateImage method is:
unsigned int MagickRotateImage\( MagickWand *wand, const PixelWand *background,
const double degrees );
wand:
The magick wand.
background:
The background pixel wand.
degrees:
The number of degrees to rotate the image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(background %PixelWand)
(degrees %double))
(defcfun ("MagickSampleImage" %MagickSampleImage)
%magick-status
"Scales an image to the desired dimensions with pixel sampling. Unlike other scaling methods, this method does not introduce any additional color into the scaled image.
The format of the MagickSampleImage method is:
unsigned int MagickSampleImage\( MagickWand *wand, const unsigned long columns,
const unsigned long rows );
wand:
The magick wand.
columns:
The number of columns in the scaled image.
rows:
The number of rows in the scaled image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(columns :unsigned-long)
(rows :unsigned-long))
(defcfun ("MagickScaleImage" %MagickScaleImage)
%magick-status
"Scales the size of an image to the given dimensions.
The format of the MagickScaleImage method is:
unsigned int MagickScaleImage\( MagickWand *wand, const unsigned long columns,
const unsigned long rows );
wand:
The magick wand.
columns:
The number of columns in the scaled image.
rows:
The number of rows in the scaled image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(columns :unsigned-long)
(rows :unsigned-long))
(defcfun ("MagickSeparateImageChannel" %MagickSeparateImageChannel)
%magick-status
"Separates a channel from the image and returns a grayscale image. A channel is a particular color component of each pixel in the image.
The format of the MagickChannelImage method is:
unsigned int MagickSeparateImageChannel\( MagickWand *wand, const ChannelType channel );
wand:
The magick wand.
channel:
Identify which channel to extract: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
BlackChannel.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType))
(defcfun ("MagickSetCompressionQuality" %MagickSetCompressionQuality)
%magick-status
"Sets the image quality factor, which determines compression options when saving the file.
For the JPEG and MPEG image formats, quality is 0 \(lowest image
quality and highest compression) to 100 \(best quality but least
effective compression). The default quality is 75. Use the
-sampling-factor option to specify the factors for chroma
downsampling. To use the same quality value as that found by the
JPEG decoder, use the -define jpeg:preserve-settings flag.
For the MIFF image format, and the TIFF format while using ZIP
compression, quality/10 is the zlib compres- sion level, which is 0
\(worst but fastest compression) to 9 \(best but slowest). It has no
effect on the image appearance, since the compression is always
lossless.
For the JPEG-2000 image format, quality is mapped using a non-linear
equation to the compression ratio required by the Jasper library.
This non-linear equation is intended to loosely approximate the
quality provided by the JPEG v1 format. The default quality value 75
results in a request for 16:1 compression. The quality value 100
results in a request for non-lossy compres- sion.
For the MNG and PNG image formats, the quality value sets the zlib
compression level \(quality / 10) and filter-type \(quality % 10).
Compression levels range from 0 \(fastest compression) to 100 \(best
but slowest). For compression level 0, the Huffman-only strategy is
used, which is fastest but not necessarily the worst compression. If
filter-type is 4 or less, the specified filter-type is used for all
scanlines:
none
sub
up
average
Paeth
If filter-type is 5, adaptive filtering is used when quality is
greater than 50 and the image does not have a color map, otherwise no
filtering is used.
If filter-type is 6, adaptive filtering with minimum-
sum-of-absolute-values is used.
Only if the output is MNG, if filter-type is 7, the LOCO color
transformation and adaptive filtering with
minimum-sum-of-absolute-values are used.
The default is quality is 75, which means nearly the best compression
with adaptive filtering. The quality setting has no effect on the
appearance of PNG and MNG images, since the compression is always
lossless.
For further information, see the PNG specification.
When writing a JNG image with transparency, two quality values are
required, one for the main image and one for the grayscale image that
conveys the opacity channel. These are written as a single integer
equal to the main image quality plus 1000 times the opacity quality.
For example, if you want to use quality 75 for the main image and
quality 90 to compress the opacity data, use -quality 90075.
For the PNM family of formats \(PNM, PGM, and PPM) specify a quality
factor of zero in order to obtain the ASCII variant of the
format. Note that -compress none used to be used to trigger ASCII
output but provided the opposite result of what was expected as
compared with other formats.
The format of the MagickSetCompressionQuality method is:
unsigned int MagickSetCompressionQuality\( MagickWand *wand, const unsigned long quality );
wand:
The magick wand.
delay:
The image quality.
Since GraphicsMagick v1.3.7"
(wand %MagickWand)
(quality :unsigned-long))
(defcfun ("MagickSetDepth" %MagickSetDepth)
%magick-status
"Sets the sample depth to be used when reading from a raw image or a format which requires that the depth be specified in advance by the user.
The format of the MagickSetDepth method is:
unsigned int MagickSetDepth\( MagickWand *wand, const size_t depth );
A description of each parameter follows:
wand:
The magick wand.
depth:
The sample depth.
Since GraphicsMagick v1.3.13"
(wand %MagickWand)
(depth %size_t))
(defcfun ("MagickSetFilename" %MagickSetFilename)
%magick-status
"Sets the filename before you read or write an image file.
The format of the MagickSetFilename method is:
unsigned int MagickSetFilename\( MagickWand *wand, const char *filename );
A description of each parameter follows:
wand:
The magick wand.
filename:
The image filename.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(filename :string))
(defcfun ("MagickSetFormat" %MagickSetFormat)
%magick-status
"Sets the file or blob format \(e.g. \"BMP\") to be used when a file or blob is read. Usually this is not necessary because GraphicsMagick is able to auto-detect the format based on the file header \(or the file extension), but some formats do not use a unique header or the selection may be ambigious. Use MagickSetImageFormat\() to set the format to be used when a file or blob is to be written.
The format of the MagickSetFormat method is:
unsigned int MagickSetFormat\( MagickWand *wand, const char *format );
A description of each parameter follows:
wand:
The magick wand.
filename:
The file or blob format.
Since GraphicsMagick v1.3.13"
(wand %MagickWand)
(format :string))
(defcfun ("MagickSetImage" %MagickSetImage)
%magick-status
"Replaces the last image returned by MagickSetImageIndex\(), MagickNextImage\(), MagickPreviousImage\() with the images from the specified wand.
The format of the MagickSetImage method is:
unsigned int MagickSetImage\( MagickWand *wand, const MagickWand *set_wand );
A description of each parameter follows:
wand:
The magick wand.
set_wand:
The set_wand wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(set_wand %MagickWand))
(defcfun ("MagickSetImageAttribute" %MagickSetImageAttribute)
%magick-status
"MagickSetImageAttribute sets an image attribute
The format of the MagickSetImageAttribute method is:
unsigned int MagickSetImageAttribute\( MagickWand *wand, const char *name,
const char *value );
A description of each parameter follows:
wand:
The magick wand.
name:
The name of the attribute
value:
The value of the attribute
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(name :string)
(value :string))
(defcfun ("MagickSetImageBackgroundColor" %MagickSetImageBackgroundColor)
%magick-status
"Sets the image background color.
The format of the MagickSetImageBackgroundColor method is:
unsigned int MagickSetImageBackgroundColor\( MagickWand *wand, const PixelWand *background );
wand:
The magick wand.
background:
The background pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(background %PixelWand))
(defcfun ("MagickSetImageBluePrimary" %MagickSetImageBluePrimary)
%magick-status
"Sets the image chromaticity blue primary point.
The format of the MagickSetImageBluePrimary method is:
unsigned int MagickSetImageBluePrimary\( MagickWand *wand, const double x, const double y );
wand:
The magick wand.
x:
The blue primary x-point.
y:
The blue primary y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x :double)
(y :double))
(defcfun ("MagickSetImageBorderColor" %MagickSetImageBorderColor)
%magick-status
"Sets the image border color.
The format of the MagickSetImageBorderColor method is:
unsigned int MagickSetImageBorderColor\( MagickWand *wand, const PixelWand *border );
wand:
The magick wand.
border:
The border pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(border %PixelWand))
(defcfun ("MagickSetImageColormapColor" %MagickSetImageColormapColor)
%magick-status
"Sets the color of the specified colormap index.
The format of the MagickSetImageColormapColor method is:
unsigned int MagickSetImageColormapColor\( MagickWand *wand, const unsigned long index,
const PixelWand *color );
wand:
The magick wand.
index:
The offset into the image colormap.
color:
Return the colormap color in this wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(index :unsigned-long)
(color %PixelWand))
(defcfun ("MagickSetImageColorspace" %MagickSetImageColorspace)
%magick-status
"Sets the image colorspace.
The format of the MagickSetImageColorspace method is:
unsigned int MagickSetImageColorspace\( MagickWand *wand, const ColorspaceType colorspace );
wand:
The magick wand.
colorspace:
The image colorspace: UndefinedColorspace, RGBColorspace,
GRAYColorspace, TransparentColorspace, OHTAColorspace, XYZColorspace,
YCbCrColorspace, YCCColorspace, YIQColorspace, YPbPrColorspace,
YPbPrColorspace, YUVColorspace, CMYKColorspace, sRGBColorspace,
HSLColorspace, or HWBColorspace.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(colorspace %ColorspaceType))
(defcfun ("MagickSetImageCompose" %MagickSetImageCompose)
%magick-status
"Sets the image composite operator, useful for specifying how to composite the image thumbnail when using the MagickMontageImage\() method.
The format of the MagickSetImageCompose method is:
unsigned int MagickSetImageCompose\( MagickWand *wand, const CompositeOperator compose );
wand:
The magick wand.
compose:
The image composite operator.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(compose %CompositeOperator))
(defcfun ("MagickSetImageCompression" %MagickSetImageCompression)
%magick-status
"Sets the image compression.
The format of the MagickSetImageCompression method is:
unsigned int MagickSetImageCompression\( MagickWand *wand,
const CompressionType compression );
wand:
The magick wand.
compression:
The image compression type.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(compression %CompressionType))
(defcfun ("MagickSetImageDelay" %MagickSetImageDelay)
%magick-status
"Sets the image delay.
The format of the MagickSetImageDelay method is:
unsigned int MagickSetImageDelay\( MagickWand *wand, const unsigned long delay );
wand:
The magick wand.
delay:
The image delay in 1/100th of a second.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(delay :unsigned-long))
(defcfun ("MagickSetImageChannelDepth" %MagickSetImageChannelDepth)
%magick-status
"Sets the depth of a particular image channel.
The format of the MagickSetImageChannelDepth method is:
unsigned int MagickSetImageChannelDepth\( MagickWand *wand, const ChannelType channel,
const unsigned long depth );
wand:
The magick wand.
channel:
Identify which channel to extract: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
BlackChannel.
depth:
The image depth in bits.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(depth :unsigned-long))
(defcfun ("MagickSetImageDepth" %MagickSetImageDepth)
%magick-status
"Sets the image depth.
The format of the MagickSetImageDepth method is:
unsigned int MagickSetImageDepth\( MagickWand *wand, const unsigned long depth );
wand:
The magick wand.
depth:
The image depth in bits: 8, 16, or 32.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(depth :unsigned-long))
(defcfun ("MagickSetImageDispose" %MagickSetImageDispose)
%magick-status
"Sets the image disposal method.
The format of the MagickSetImageDispose method is:
unsigned int MagickSetImageDispose\( MagickWand *wand, const DisposeType dispose );
wand:
The magick wand.
dispose:
The image disposeal type.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(dispose %DisposeType))
(defcfun ("MagickSetImageFilename" %MagickSetImageFilename)
%magick-status
"Sets the filename of a particular image in a sequence.
The format of the MagickSetImageFilename method is:
unsigned int MagickSetImageFilename\( MagickWand *wand, const char *filename );
wand:
The magick wand.
filename:
The image filename.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(filename :string))
(defcfun ("MagickSetImageFormat" %MagickSetImageFormat)
%magick-status
"Sets the format of a particular image in a sequence. The format is designated by a magick string \(e.g. \"GIF\").
The format of the MagickSetImageFormat method is:
unsigned int MagickSetImageFormat\( MagickWand *wand, const char *format );
wand:
The magick wand.
magick:
The image format.
Since GraphicsMagick v1.3.1"
(wand %MagickWand)
(format :string))
(defcfun ("MagickSetImageFuzz" %MagickSetImageFuzz)
%magick-status
"Sets the color comparison fuzz factor. Colors closer than the fuzz factor are considered to be the same when comparing colors. Note that some other functions such as MagickColorFloodfillImage\() implicitly set this value.
The format of the MagickSetImageFuzz method is:
unsigned int MagickSetImageFuzz\( MagickWand *wand, const double fuzz );
A description of each parameter follows:
wand:
The magick wand.
fuzz:
The color comparison fuzz factor
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(fuzz :double))
(defcfun ("MagickSetImageGamma" %MagickSetImageGamma)
%magick-status
"Sets the image gamma.
The format of the MagickSetImageGamma method is:
unsigned int MagickSetImageGamma\( MagickWand *wand, const double gamma );
A description of each parameter follows:
wand:
The magick wand.
gamma:
The image gamma.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(gamma :double))
(defcfun ("MagickSetImageGeometry" %MagickSetImageGeometry)
%magick-status
"Sets the image geometry string.
The format of the MagickSetImageGeometry method is:
unsigned int MagickSetImageGeometry\( MagickWand *wand, const char *geometry )
A description of each parameter follows:
wand: The magick wand.
geometry: The image geometry.
Since GraphicsMagick v1.3.20"
(wand %MagickWand)
(geometry :string))
(defcfun ("MagickSetImageGravity" %MagickSetImageGravity)
%magick-status
"Sets the image gravity. This is used when evaluating regions defined by a geometry and the image dimensions. It may be used in conjunction with operations which use a geometry parameter to adjust the x, y parameters of the final operation. Gravity is used in composition to determine where the image should be placed within the defined geometry region. It may be used with montage to effect placement of the image within the tile.
The format of the MagickSetImageGravity method is:
unsigned int MagickSetImageGravity\( MagickWand *wand, const GravityType );
A description of each parameter follows:
wand:
The magick wand.
gravity:
The image gravity. Available values are ForgetGravity,
NorthWestGravity, NorthGravity, NorthEastGravity, WestGravity,
CenterGravity, EastGravity, SouthWestGravity, SouthGravity,
SouthEastGravity, and StaticGravity
Since GraphicsMagick v1.3.20"
(wand %MagickWand)
(gravitytype %GravityType))
(defcfun ("MagickSetImageGreenPrimary" %MagickSetImageGreenPrimary)
%magick-status
"Sets the image chromaticity green primary point.
The format of the MagickSetImageGreenPrimary method is:
unsigned int MagickSetImageGreenPrimary\( MagickWand *wand, const double x, const double y );
wand:
The magick wand.
x:
The green primary x-point.
y:
The green primary y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x %double)
(y %double))
(defcfun ("MagickSetImageIndex" %MagickSetImageIndex)
%magick-status
"Set the current image to the position of the list specified with the index parameter.
The format of the MagickSetImageIndex method is:
unsigned int MagickSetImageIndex\( MagickWand *wand, const long index );
A description of each parameter follows:
wand:
The magick wand.
index:
The scene number.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(index :long))
(defcfun ("MagickSetImageInterlaceScheme" %MagickSetImageInterlaceScheme)
%magick-status
"Sets the image interlace scheme. Please use SetInterlaceScheme\() instead to change the interlace scheme used when writing the image.
The format of the MagickSetImageInterlaceScheme method is:
unsigned int MagickSetImageInterlaceScheme\( MagickWand *wand,
const InterlaceType interlace_scheme );
wand:
The magick wand.
interlace_scheme:
The image interlace scheme: NoInterlace, LineInterlace,
PlaneInterlace, PartitionInterlace.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(interlace_scheme %InterlaceType))
(defcfun ("MagickSetImageIterations" %MagickSetImageIterations)
%magick-status
"Sets the image iterations.
The format of the MagickSetImageIterations method is:
unsigned int MagickSetImageIterations\( MagickWand *wand, const unsigned long iterations );
wand:
The magick wand.
delay:
The image delay in 1/100th of a second.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(iterations :unsigned-long))
(defcfun ("MagickSetImageMatte" %MagickSetImageMatte)
%magick-status
"Sets the image matte flag. The image opacity \(inverse of transparency) channel is enabled if the matte flag is True.
The format of the MagickSetImageMatte method is:
unsigned int MagickSetImageMatte\( MagickWand *wand, const unsigned int matte )
A description of each parameter follows:
wand:
The magick wand.
matte:
The image matte.
Since GraphicsMagick v1.3.20"
(wand %MagickWand)
(matte :unsigned-int))
(defcfun ("MagickSetImageMatteColor" %MagickSetImageMatteColor)
%magick-status
"Sets the image matte color.
The format of the MagickSetImageMatteColor method is:
unsigned int MagickSetImageMatteColor\( MagickWand *wand, const PixelWand *matte );
wand:
The magick wand.
matte:
The matte pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(matte %PixelWand))
(defcfun ("MagickSetImageOption" %MagickSetImageOption)
%magick-status
"Associates one or options with a particular image format \(.e.g MagickSetImageOption\(wand,\"jpeg\",\"preserve-settings\",\"true\").
The format of the MagickSetImageOption method is:
unsigned int MagickSetImageOption\( MagickWand *wand, const char *format, const char *key,
const char *value );
wand:
The magick wand.
format:
The image format.
key:
The key.
value:
The value.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(format :string)
(key :string)
(value :string))
(defcfun ("MagickSetImageOrientation" %MagickSetImageOrientation)
%magick-status
"Sets the internal image orientation type.
The EXIF orientation tag will be updated if present.
The format of the MagickSetImageOrientation method is:
MagickSetImageOrientation\( MagickWand *wand, OrientationType new_orientation )
A description of each parameter follows:
wand:
The magick wand.
new_orientation:
The new orientation of the image. One of:
UndefinedOrientation Image orientation not specified.
TopLeftOrientation Left to right and Top to bottom.
TopRightOrientation Right to left and Top to bottom.
BottomRightOrientation Right to left and Bottom to top.
BottomLeftOrientation Left to right and Bottom to top.
LeftTopOrientation Top to bottom and Left to right.
RightTopOrientation Top to bottom and Right to left.
RightBottomOrientation Bottom to top and Right to left.
LeftBottomOrientation Bottom to top and Left to right.
Returns True on success, False otherwise.
Since GraphicsMagick v1.3.26"
(wand %MagickWand)
(new_orientation %OrientationType))
(defcfun ("MagickSetImagePage" %MagickSetImagePage)
%magick-status
"Sets the image page size and offset used when placing \(e.g. compositing) the image. Pass all zeros for the default placement.
The format of the MagickSetImagePage method is:
unsigned int MagickSetImagePage\( MagickWand *wand, const unsigned long width,
const unsigned long height, const long x, const long y );
wand:
The magick wand.
width, height:
The region size.
x, y:
Offset \(from top left) on base canvas image on
which to composite image data.
Since GraphicsMagick v1.3.18"
(wand %MagickWand)
(width :unsigned-long)
(height :unsigned-long)
(x :long)
(y :long))
(defcfun ("MagickSetImagePixels" %MagickSetImagePixels)
%magick-status
"Accepts pixel data and stores it in the image at the location you specify. The method returns False on success otherwise True if an error is encountered. The pixel data can be either char, short int, int, long, float, or double in the order specified by map.
Suppose your want want to upload the first scanline of a 640x480 image from
character data in red-green-blue order:
MagickSetImagePixels\(wand,0,0,0,640,1,\"RGB\",CharPixel,pixels);
The format of the MagickSetImagePixels method is:
unsigned int MagickSetImagePixels\( MagickWand *wand, const long x_offset, const long y_offset,
const unsigned long columns, const unsigned long rows,
const char *map, const StorageType storage,
unsigned char *pixels );
wand:
The magick wand.
x_offset, y_offset:
Offset \(from top left) on base canvas image on
which to composite image data.
columns, rows:
Dimensions of image.
map:
This string reflects the expected ordering of the pixel array.
It can be any combination or order of R = red, G = green, B = blue,
A = alpha \(same as Transparency), O = Opacity, T = Transparency,
C = cyan, Y = yellow, M = magenta, K = black, or I = intensity
\(for grayscale). Specify \"P\" = pad, to skip over a quantum which is
intentionally ignored. Creation of an alpha channel for CMYK images
is currently not supported.
storage:
Define the data type of the pixels. Float and double types are
expected to be normalized [0..1] otherwise [0..MaxRGB]. Choose from
these types: CharPixel, ShortPixel, IntegerPixel, LongPixel, FloatPixel,
or DoublePixel.
pixels:
This array of values contain the pixel components as defined by
map and type. You must preallocate this array where the expected
length varies depending on the values of width, height, map, and type.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x_offset :long)
(y_offset :long)
(columns :unsigned-long)
(rows :unsigned-long)
(map :string)
(storage %StorageType)
(pixels :pointer))
(defcfun ("MagickSetImageProfile" %MagickSetImageProfile)
%magick-status
"Adds a named profile to the magick wand. If a profile with the same name already exists, it is replaced. This method differs from the MagickProfileImage\() method in that it does not apply any CMS color profiles.
The format of the MagickSetImageProfile method is:
unsigned int MagickSetImageProfile\( MagickWand *wand, const char *name,
const unsigned char *profile,
const unsigned long length );
wand:
The magick wand.
name:
Name of profile to add or remove: ICC, IPTC, or generic profile.
profile:
The profile.
length:
The length of the profile.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(name :string)
(profile :pointer)
(length :unsigned-long))
(defcfun ("MagickSetImageRedPrimary" %MagickSetImageRedPrimary)
%magick-status
"Sets the image chromaticity red primary point.
The format of the MagickSetImageRedPrimary method is:
unsigned int MagickSetImageRedPrimary\( MagickWand *wand, const double x, const double y );
wand:
The magick wand.
x:
The red primary x-point.
y:
The red primary y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x %double)
(y %double))
(defcfun ("MagickSetImageRenderingIntent" %MagickSetImageRenderingIntent)
%magick-status
"Sets the image rendering intent.
The format of the MagickSetImageRenderingIntent method is:
unsigned int MagickSetImageRenderingIntent\( MagickWand *wand,
const RenderingIntent rendering_intent );
wand:
The magick wand.
rendering_intent:
The image rendering intent: UndefinedIntent,
SaturationIntent, PerceptualIntent, AbsoluteIntent, or RelativeIntent.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(rendering_intent %RenderingIntent))
(defcfun ("MagickSetImageResolution" %MagickSetImageResolution)
%magick-status
"Sets the image resolution.
The format of the MagickSetImageResolution method is:
unsigned int MagickSetImageResolution\( MagickWand *wand, const double x_resolution,
const doubtl y_resolution );
wand:
The magick wand.
x_resolution:
The image x resolution.
y_resolution:
The image y resolution.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x_resolution %double)
(y_resolution %double))
(defcfun ("MagickSetImageScene" %MagickSetImageScene)
%magick-status
"Sets the image scene.
The format of the MagickSetImageScene method is:
unsigned int MagickSetImageScene\( MagickWand *wand, const unsigned long scene );
wand:
The magick wand.
delay:
The image scene number.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(scene :unsigned-long))
(defcfun ("MagickSetImageType" %MagickSetImageType)
%magick-status
"Sets the image type.
The format of the MagickSetImageType method is:
unsigned int MagickSetImageType\( MagickWand *wand, const ImageType image_type );
wand:
The magick wand.
image_type:
The image type: UndefinedType, BilevelType, GrayscaleType,
GrayscaleMatteType, PaletteType, PaletteMatteType, TrueColorType,
TrueColorMatteType, ColorSeparationType, ColorSeparationMatteType,
or OptimizeType.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(image_type %ImageType))
(defcfun ("MagickSetImageSavedType" %MagickSetImageSavedType)
%magick-status
"Sets the image type that will be used when the image is saved.
The format of the MagickSetImageSavedType method is:
unsigned int MagickSetImageSavedType\( MagickWand *wand, const ImageType image_type );
wand:
The magick wand.
image_type:
The image type: UndefinedType, BilevelType, GrayscaleType,
GrayscaleMatteType, PaletteType, PaletteMatteType, TrueColorType,
TrueColorMatteType, ColorSeparationType, ColorSeparationMatteType,
or OptimizeType.
Since GraphicsMagick v1.3.13"
(wand %MagickWand)
(image_type %ImageType))
(defcfun ("MagickSetImageUnits" %MagickSetImageUnits)
%magick-status
"Sets the image units of resolution.
The format of the MagickSetImageUnits method is:
unsigned int MagickSetImageUnits\( MagickWand *wand, const ResolutionType units );
wand:
The magick wand.
units:
The image units of resolution : Undefinedresolution,
PixelsPerInchResolution, or PixelsPerCentimeterResolution.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(units %ResolutionType))
(defcfun ("MagickSetImageVirtualPixelMethod" %MagickSetImageVirtualPixelMethod)
%magick-status
"Sets the image virtual pixel method.
The format of the MagickSetImageVirtualPixelMethod method is:
unsigned int MagickSetImageVirtualPixelMethod\( MagickWand *wand,
const VirtualPixelMethod method );
wand:
The magick wand.
method:
The image virtual pixel method : UndefinedVirtualPixelMethod,
ConstantVirtualPixelMethod, EdgeVirtualPixelMethod,
MirrorVirtualPixelMethod, or TileVirtualPixelMethod.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(method %VirtualPixelMethod))
(defcfun ("MagickSetInterlaceScheme" %MagickSetInterlaceScheme)
%magick-status
"Sets the interlace scheme used when writing the image.
The format of the MagickSetInterlaceScheme method is:
unsigned int MagickSetInterlaceScheme\( MagickWand *wand,
const InterlaceType interlace_scheme );
wand:
The magick wand.
interlace_scheme:
The image interlace scheme: NoInterlace, LineInterlace,
PlaneInterlace, PartitionInterlace.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(interlace_scheme %InterlaceType))
(defcfun ("MagickSetResolution" %MagickSetResolution)
%magick-status
"Sets the resolution \(density) of the magick wand. Set it before you read an EPS, PDF, or Postscript file in order to influence the size of the returned image, or after an image has already been created to influence the rendered image size when used with typesetting software.
Also see MagickSetResolutionUnits\() which specifies the units to use for
the image resolution.
The format of the MagickSetResolution method is:
unsigned int MagickSetResolution\( MagickWand *wand, const double x_resolution,
const double y_resolution );
wand:
The magick wand.
x_resolution:
The horizontal resolution
y_resolution:
The vertical reesolution
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(x_resolution %double)
(y_resolution %double))
(defcfun ("MagickSetResolutionUnits" %MagickSetResolutionUnits)
%magick-status
"Sets the resolution units of the magick wand. It should be used in conjunction with MagickSetResolution\(). This method works both before and after an image has been read.
Also see MagickSetImageUnits\() which specifies the units which apply to
the image resolution setting after an image has been read.
The format of the MagickSetResolutionUnits method is:
unsigned int MagickSetResolutionUnits\( MagickWand *wand, const ResolutionType units );
wand:
The magick wand.
units:
The image units of resolution : Undefinedresolution,
PixelsPerInchResolution, or PixelsPerCentimeterResolution.
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(units %ResolutionType))
(defcfun ("MagickSetResourceLimit" %MagickSetResourceLimit)
%magick-status
"Sets the limit for a particular resource in megabytes.
The format of the MagickSetResourceLimit method is:
unsigned int MagickSetResourceLimit\( const ResourceType type, const unsigned long *limit );
type:
The type of resource: DiskResource, FileResource, MapResource,
MemoryResource, PixelsResource, ThreadsResource, WidthResource,
HeightResource.
o The maximum limit for the resource.
Since GraphicsMagick v1.1.0"
(type %ResourceType)
(limit :pointer))
(defcfun ("MagickSetSamplingFactors" %MagickSetSamplingFactors)
%magick-status
"Sets the image sampling factors.
The format of the MagickSetSamplingFactors method is:
unsigned int MagickSetSamplingFactors\( MagickWand *wand, const unsigned long number_factors,
const double *sampling_factors );
wand:
The magick wand.
number_factoes:
The number of factors.
sampling_factors:
An array of doubles representing the sampling factor
for each color component \(in RGB order).
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(number_factors :unsigned-long)
(sampling_factors :pointer))
(defcfun ("MagickSetSize" %MagickSetSize)
%magick-status
"Sets the size of the magick wand. Set it before you read a raw image format such as RGB, GRAY, or CMYK.
The format of the MagickSetSize method is:
unsigned int MagickSetSize\( MagickWand *wand, const unsigned long columns,
const unsigned long rows );
wand:
The magick wand.
columns:
The width in pixels.
height:
The height in pixels.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(columns :unsigned-long)
(rows :unsigned-long))
(defcfun ("MagickSetImageWhitePoint" %MagickSetImageWhitePoint)
%magick-status
"Sets the image chromaticity white point.
The format of the MagickSetImageWhitePoint method is:
unsigned int MagickSetImageWhitePoint\( MagickWand *wand, const double x, const double y );
wand:
The magick wand.
x:
The white x-point.
y:
The white y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x %double)
(y %double))
(defcfun ("MagickSetPassphrase" %MagickSetPassphrase)
%magick-status
"Sets the passphrase.
The format of the MagickSetPassphrase method is:
unsigned int MagickSetPassphrase\( MagickWand *wand, const char *passphrase );
A description of each parameter follows:
wand:
The magick wand.
passphrase:
The passphrase.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(passphrase :string))
(defcfun ("MagickSharpenImage" %MagickSharpenImage)
%magick-status
"Sharpens an image. We convolve the image with a Gaussian operator of the given radius and standard deviation \(sigma). For reasonable results, the radius should be larger than sigma. Use a radius of 0 and SharpenImage\() selects a suitable radius for you.
The format of the MagickSharpenImage method is:
unsigned int MagickSharpenImage\( MagickWand *wand, const double radius, const double sigma );
wand:
The magick wand.
radius:
The radius of the Gaussian, in pixels, not counting the center
pixel.
sigma:
The standard deviation of the Gaussian, in pixels.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius %double)
(sigma %double))
(defcfun ("MagickShaveImage" %MagickShaveImage)
%magick-status
"Shaves pixels from the image edges. It allocates the memory necessary for the new Image structure and returns a pointer to the new image.
The format of the MagickShaveImage method is:
unsigned int MagickShaveImage\( MagickWand *wand, const unsigned long columns,
const unsigned long rows );
wand:
The magick wand.
columns:
The number of columns in the scaled image.
rows:
The number of rows in the scaled image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(columns :unsigned-long)
(rows :unsigned-long))
(defcfun ("MagickShearImage" %MagickShearImage)
%magick-status
"Slides one edge of an image along the X or Y axis, creating a parallelogram. An X direction shear slides an edge along the X axis, while a Y direction shear slides an edge along the Y axis. The amount of the shear is controlled by a shear angle. For X direction shears, x_shear is measured relative to the Y axis, and similarly, for Y direction shears y_shear is measured relative to the X axis. Empty triangles left over from shearing the image are filled with the background color.
The format of the MagickShearImage method is:
unsigned int MagickShearImage\( MagickWand *wand, const PixelWand *background,
const double x_shear, onst double y_shear );
wand:
The magick wand.
background:
The background pixel wand.
x_shear:
The number of degrees to shear the image.
y_shear:
The number of degrees to shear the image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(background %PixelWand)
(x_shear %double)
(y_shear %double))
(defcfun ("MagickSolarizeImage" %MagickSolarizeImage)
%magick-status
"Applies a special effect to the image, similar to the effect achieved in a photo darkroom by selectively exposing areas of photo sensitive paper to light. Threshold ranges from 0 to MaxRGB and is a measure of the extent of the solarization.
The format of the MagickSolarizeImage method is:
unsigned int MagickSolarizeImage\( MagickWand *wand, const double threshold );
A description of each parameter follows:
wand:
The magick wand.
threshold:
Define the extent of the solarization.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(threshold %double))
(defcfun ("MagickSpreadImage" %MagickSpreadImage)
%magick-status
"Is a special effects method that randomly displaces each pixel in a block defined by the radius parameter.
The format of the MagickSpreadImage method is:
unsigned int MagickSpreadImage\( MagickWand *wand, const double radius );
A description of each parameter follows:
wand:
The magick wand.
radius:
Choose a random pixel in a neighborhood of this extent.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius %double))
(defcfun ("MagickSteganoImage" %MagickSteganoImage)
%MagickWand
"Use MagickSteganoImage\() to hide a digital watermark within the image. Recover the hidden watermark later to prove that the authenticity of an image. Offset defines the start position within the image to hide the watermark.
The format of the MagickSteganoImage method is:
MagickWand *MagickSteganoImage\( MagickWand *wand, const MagickWand *watermark_wand,
const long offset );
wand:
The magick wand.
watermark_wand:
The watermark wand.
offset:
Start hiding at this offset into the image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(watermark_wand %MagickWand)
(offset :long))
(defcfun ("MagickStereoImage" %MagickStereoImage)
%MagickWand
"Composites two images and produces a single image that is the composite of a left and right image of a stereo pair
The format of the MagickStereoImage method is:
MagickWand *MagickStereoImage\( MagickWand *wand, const MagickWand *offset_wand );
wand:
The magick wand.
offset_wand:
Another image wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(offset_wand %MagickWand))
(defcfun ("MagickStripImage" %MagickStripImage)
%magick-status
"Removes all profiles and text attributes from the image.
The format of the MagickStripImage method is:
unsigned int MagickStripImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickSwirlImage" %MagickSwirlImage)
%magick-status
"Swirls the pixels about the center of the image, where degrees indicates the sweep of the arc through which each pixel is moved. You get a more dramatic effect as the degrees move from 1 to 360.
The format of the MagickSwirlImage method is:
unsigned int MagickSwirlImage\( MagickWand *wand, const double degrees );
A description of each parameter follows:
wand:
The magick wand.
degrees:
Define the tightness of the swirling effect.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(degrees %double))
(defcfun ("MagickTextureImage" %MagickTextureImage)
%MagickWand
"Repeatedly tiles the texture image across and down the image canvas.
The format of the MagickTextureImage method is:
MagickWand *MagickTextureImage\( MagickWand *wand, const MagickWand *texture_wand );
wand:
The magick wand.
texture_wand:
The texture wand
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(texture_wand %MagickWand))
(defcfun ("MagickThresholdImage" %MagickThresholdImage)
%magick-status
"Changes the value of individual pixels based on the intensity of each pixel compared to threshold. The result is a high-contrast, two color image.
The format of the MagickThresholdImage method is:
unsigned int MagickThresholdImage\( MagickWand *wand, const double threshold );
wand:
The magick wand.
threshold:
Define the threshold value.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(threshold %double))
(defcfun ("MagickThresholdImageChannel" %MagickThresholdImageChannel)
%magick-status
"Changes the value of individual pixel component based on the intensity of each pixel compared to threshold. The result is a high-contrast, two color image.
The format of the MagickThresholdImage method is:
unsigned int MagickThresholdImageChannel\( MagickWand *wand, const ChannelType channel,
const double threshold );
wand:
The magick wand.
channel:
The channel.
threshold:
Define the threshold value.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(threshold %double))
(defcfun ("MagickTintImage" %MagickTintImage)
%magick-status
"Applies a color vector to each pixel in the image. The length of the vector is 0 for black and white and at its maximum for the midtones. The vector weighting function is f\(x)=\(1-\(4.0*\(\(x-0.5)*\(x-0.5)))).
The format of the MagickTintImage method is:
unsigned int MagickTintImage\( MagickWand *wand, const PixelWand *tint,
const PixelWand *opacity );
wand:
The magick wand.
tint:
The tint pixel wand.
opacity:
The opacity pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(tint %PixelWand)
(opacity %PixelWand))
(defcfun ("MagickTransformImage" %MagickTransformImage)
%MagickWand
"Is a convenience method that behaves like MagickResizeImage\() or MagickCropImage\() but accepts scaling and/or cropping information as a region geometry specification. If the operation fails, the original image handle is returned.
The format of the MagickTransformImage method is:
MagickWand *MagickTransformImage\( MagickWand *wand, const char *crop,
const char *geometry );
wand:
The magick wand.
crop:
A crop geometry string. This geometry defines a subregion of the
image to crop.
geometry:
An image geometry string. This geometry defines the final
size of the image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(crop :string)
(geometry :string))
(defcfun ("MagickTransparentImage" %MagickTransparentImage)
%magick-status
"Changes any pixel that matches color with the color defined by fill.
The format of the MagickTransparentImage method is:
unsigned int MagickTransparentImage\( MagickWand *wand, const PixelWand *target,
const unsigned int opacity, const double fuzz );
wand:
The magick wand.
target:
Change this target color to specified opacity value within
the image.
opacity:
The replacement opacity value.
fuzz:
By default target must match a particular pixel color
exactly. However, in many cases two colors may differ by a small amount.
The fuzz member of image defines how much tolerance is acceptable to
consider two colors as the same. For example, set fuzz to 10 and the
color red at intensities of 100 and 102 respectively are now interpreted
as the same color for the purposes of the floodfill.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(target %PixelWand)
(opacity :unsigned-int)
(fuzz %double))
(defcfun ("MagickTrimImage" %MagickTrimImage)
%magick-status
"Remove edges that are the background color from the image.
The format of the MagickTrimImage method is:
unsigned int MagickTrimImage\( MagickWand *wand, const double fuzz );
A description of each parameter follows:
wand:
The magick wand.
fuzz:
By default target must match a particular pixel color
exactly. However, in many cases two colors may differ by a small amount.
The fuzz member of image defines how much tolerance is acceptable to
consider two colors as the same. For example, set fuzz to 10 and the
color red at intensities of 100 and 102 respectively are now interpreted
as the same color for the purposes of the floodfill.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(fuzz %double))
(defcfun ("MagickUnsharpMaskImage" %MagickUnsharpMaskImage)
%magick-status
"Sharpens an image. We convolve the image with a Gaussian operator of the given radius and standard deviation \(sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and UnsharpMaskImage\() selects a suitable radius for you.
The format of the MagickUnsharpMaskImage method is:
unsigned int MagickUnsharpMaskImage\( MagickWand *wand, const double radius, const double sigma,
const double amount, const double threshold );
wand:
The magick wand.
radius:
The radius of the Gaussian, in pixels, not counting the center
pixel.
sigma:
The standard deviation of the Gaussian, in pixels.
amount:
The percentage of the difference between the original and the
blur image that is added back into the original.
threshold:
The threshold in pixels needed to apply the diffence amount.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius %double)
(sigma %double)
(amount %double)
(threshold %double))
(defcfun ("MagickWaveImage" %MagickWaveImage)
%magick-status
"Creates a \"ripple\" effect in the image by shifting the pixels vertically along a sine wave whose amplitude and wavelength is specified by the given parameters.
The format of the MagickWaveImage method is:
unsigned int MagickWaveImage\( MagickWand *wand, const double amplitude,
const double wave_length );
wand:
The magick wand.
amplitude, wave_length:
Define the amplitude and wave length of the
sine wave.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(amplitude %double)
(wave_length %double))
(defcfun ("MagickWhiteThresholdImage" %MagickWhiteThresholdImage)
%magick-status
"Is like ThresholdImage\() but forces all pixels above the threshold into white while leaving all pixels below the threshold unchanged.
The format of the MagickWhiteThresholdImage method is:
unsigned int MagickWhiteThresholdImage\( MagickWand *wand, const PixelWand *threshold );
wand:
The magick wand.
threshold:
The pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(threshold %PixelWand))
(defcfun ("MagickWriteImage" %MagickWriteImage)
%magick-status
"Writes an image.
The format of the MagickWriteImage method is:
unsigned int MagickWriteImage\( MagickWand *wand, const char *filename );
A description of each parameter follows:
wand:
The magick wand.
filename:
The image filename.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(filename :string))
(defcfun ("MagickWriteImagesFile" %MagickWriteImagesFile)
%magick-status
"Writes an image or image sequence to a stdio FILE handle. This may be used to append an encoded image to an already existing appended image sequence if the file seek position is at the end of an existing file.
The format of the MagickWriteImages method is:
unsigned int MagickWriteImagesFile\( MagickWand *wand, FILE *file, const unsigned int adjoin );
wand:
The magick wand.
file:
The open \(and positioned) file handle.
adjoin:
join images into a single multi-image file.
Since GraphicsMagick v1.3.13"
(wand %MagickWand)
(file %FILE)
(adjoin :unsigned-int))
(defcfun ("MagickWriteImageBlob" %MagickWriteImageBlob)
:pointer
"Implements direct to memory image formats. It returns the image as a blob \(a formatted \"file\" in memory) and its length, starting from the current position in the image sequence. Use MagickSetImageFormat\() to set the format to write to the blob \(GIF, JPEG, PNG, etc.).
Use MagickResetIterator\() on the wand if it is desired to write
a sequence from the beginning and the iterator is not currently
at the beginning.
The format of the MagickWriteImageBlob method is:
unsigned char *MagickWriteImageBlob\( MagickWand *wand, size_t *length );
A description of each parameter follows:
wand:
The magick wand.
length:
The length of the blob.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(length :pointer))
(defcfun ("MagickWriteImageFile" %MagickWriteImageFile)
%magick-status
"Writes an image to an open file descriptor.
The format of the MagickWandToFile method is:
unsigned int MagickWriteImageFile\( MagickWand *wand, FILE *file );
A description of each parameter follows:
wand:
The magick wand.
file:
The file descriptor.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(file %FILE))
(defcfun ("MagickWriteImages" %MagickWriteImages)
%magick-status
"Writes an image or image sequence. If the wand represents an image sequence, then it is written starting at the first frame in the sequence.
The format of the MagickWriteImages method is:
unsigned int MagickWriteImages\( MagickWand *wand, const char *filename,
const unsigned int adjoin );
wand:
The magick wand.
filename:
The image filename.
adjoin:
join images into a single multi-image file.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(filename :string)
(adjoin :unsigned-int))
(defcfun ("NewMagickWand" %NewMagickWand)
%MagickWand
"Returns a wand required for all other methods in the API.
The format of the NewMagickWand method is:
MagickWand NewMagickWand\( void );
Since GraphicsMagick v1.1.0")
|
62803
|
;;; magick_wand
(in-package :gm)
(defcfun ("InitializeMagick" %InitializeMagick)
:void
"Initialize GraphicsMagick environment. Must do this to prevent ERROR: Assertion failed: \(semaphore_info != \(SemaphoreInfo *) NULL), function LockSemaphoreInfo, file magick/semaphore.c, line 601.
InitializeMagick() initializes the GraphicsMagick environment.
InitializeMagick() MUST be invoked by the using program before making
use of GraphicsMagick functions or else the library will be unusable.
This function should be invoked in the primary \(original) thread of the
application's process, and before starting any OpenMP threads, as part
of program initialization.
The format of the InitializeMagick function is:
InitializeMagick\(const char *path)
A description of each parameter follows:
o path: The execution path of the current GraphicsMagick client.
Note: InitializeMagick is declared in file magick/magick.c
Since GraphicsMagick v1.1.0"
(path :string))
;; InitializeMagick is called by NewMagickWand NewPixelWand & NewDrawingWand,
;; but call InitializeMagick here to make sure all other functions
;; like MagickQueryFormats works immediately after loaded.
(%InitializeMagick (null-pointer))
(defcfun ("CloneMagickWand" %CloneMagickWand)
%MagickWand
"Makes an exact copy of the specified wand.
The format of the CloneMagickWand method is:
MagickWand *CloneMagickWand\( const MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand to clone.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("DestroyMagickWand" %DestroyMagickWand)
:void
"Deallocates memory associated with an MagickWand.
The format of the DestroyMagickWand method is:
void DestroyMagickWand\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickAdaptiveThresholdImage" %MagickAdaptiveThresholdImage)
%magick-status
"Selects an individual threshold for each pixel based on the range of intensity values in its local neighborhood. This allows for thresholding of an image whose global intensity histogram doesn't contain distinctive peaks.
The format of the MagickAdaptiveThresholdImage method is:
unsigned int MagickAdaptiveThresholdImage\( MagickWand *wand, const unsigned long width,
const unsigned long height, const long offset );
wand:
The magick wand.
width:
The width of the local neighborhood.
height:
The height of the local neighborhood.
offset:
The mean offset.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(width :unsigned-long)
(height :unsigned-long)
(offset :long))
(defcfun ("MagickAddImage" %MagickAddImage)
%magick-status
"Adds the specified images at the current image location.
The format of the MagickAddImage method is:
unsigned int MagickAddImage\( MagickWand *wand, const MagickWand *add_wand );
wand:
The magick wand.
insert:
The splice wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(add_wand %MagickWand))
(defcfun ("MagickAddNoiseImage" %MagickAddNoiseImage)
%magick-status
"Adds random noise to the image.
The format of the MagickAddNoiseImage method is:
unsigned int MagickAddNoiseImage\( MagickWand *wand, const NoiseType noise_type );
wand:
The magick wand.
noise_type:
The type of noise: Uniform, Gaussian, Multiplicative,
Impulse, Laplacian, Poisson, or Random.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(noise_type %NoiseType))
(defcfun ("MagickAffineTransformImage" %MagickAffineTransformImage)
%magick-status
"Transforms an image as dictated by the affine matrix of the drawing wand.
The format of the MagickAffineTransformImage method is:
unsigned int MagickAffineTransformImage\( MagickWand *wand, const DrawingWand *drawing_wand );
wand:
The magick wand.
drawing_wand:
The draw wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(drawing_wand %DrawingWand))
(defcfun ("MagickAnnotateImage" %MagickAnnotateImage)
%magick-status
"Annotates an image with text.
The format of the MagickAnnotateImage method is:
unsigned int MagickAnnotateImage\( MagickWand *wand, const DrawingWand *drawing_wand,
const double x, const double y, const double angle,
const char *text );
wand:
The magick wand.
drawing_wand:
The draw wand.
x:
x ordinate to left of text
y:
y ordinate to text baseline
angle:
rotate text relative to this angle.
text:
text to draw
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(drawing_wand %DrawingWand)
(x :double)
(y :double)
(angle :double)
(text :string))
(defcfun ("MagickAnimateImages" %MagickAnimateImages)
%magick-status
"Animates an image or image sequence.
The format of the MagickAnimateImages method is:
unsigned int MagickAnimateImages\( MagickWand *wand, const char *server_name );
wand:
The magick wand.
server_name:
The X server name.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(server_name :string))
(defcfun ("MagickAppendImages" %MagickAppendImages)
%MagickWand
"Append a set of images.
The format of the MagickAppendImages method is:
MagickWand *MagickAppendImages\( MagickWand *wand, const unsigned int stack );
wand:
The magick wand.
stack:
By default, images are stacked left-to-right. Set stack to True
to stack them top-to-bottom.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(stack :unsigned-int))
(defcfun ("MagickAutoOrientImage" %MagickAutoOrientImage)
%magick-status
"Adjusts the current image so that its orientation is suitable for viewing \(i.e. top-left orientation).
The format of the MagickAutoOrientImage method is:
unsigned int MagickAutoOrientImage\( MagickWand *wand,
const OrientationType current_orientation,
ExceptionInfo *exception );
wand:
The magick wand.
current_orientation:
Current image orientation. May be one of: TopLeftOrientation Left to right and Top to bottom TopRightOrientation Right to left and Top to bottom BottomRightOrientation Right to left and Bottom to top BottomLeftOrientation Left to right and Bottom to top LeftTopOrientation Top to bottom and Left to right RightTopOrientation Top to bottom and Right to left RightBottomOrientation Bottom to top and Right to left LeftBottomOrientation Bottom to top and Left to right UndefinedOrientation Current orientation is not known. Use orientation defined by the current image if any. Equivalent to MagickGetImageOrientation\().
Returns True on success, False otherwise.
Note that after successful auto-orientation the internal orientation will be set to TopLeftOrientation. However this internal value is only written to TIFF files. For JPEG files, there is currently no support for resetting the EXIF orientation tag to TopLeft so the JPEG should be stripped or EXIF profile removed if present to prevent saved auto-oriented images from being incorrectly rotated a second time by follow-on viewers that understand the EXIF orientation tag.
Since GraphicsMagick v1.3.26"
(wand %MagickWand)
(current_orientation %OrientationType)
(exception %ExceptionInfo))
(defcfun ("MagickAverageImages" %MagickAverageImages)
%MagickWand
"Average a set of images.
The format of the MagickAverageImages method is:
MagickWand *MagickAverageImages\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickBlackThresholdImage" %MagickBlackThresholdImage)
%magick-status
"Is like MagickThresholdImage\() but forces all pixels below the threshold into black while leaving all pixels above the threshold unchanged.
The format of the MagickBlackThresholdImage method is:
unsigned int MagickBlackThresholdImage\( MagickWand *wand, const PixelWand *threshold );
wand:
The magick wand.
threshold:
The pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(threshold %PixelWand))
(defcfun ("MagickBlurImage" %MagickBlurImage)
%magick-status
"Blurs an image. We convolve the image with a Gaussian operator of the given radius and standard deviation \(sigma). For reasonable results, the radius should be larger than sigma. Use a radius of 0 and BlurImage\() selects a suitable radius for you.
The format of the MagickBlurImage method is:
unsigned int MagickBlurImage\( MagickWand *wand, const double radius, const double sigma );
wand:
The magick wand.
radius:
The radius of the Gaussian, in pixels, not counting the center
pixel.
sigma:
The standard deviation of the Gaussian, in pixels.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double)
(sigma :double))
(defcfun ("MagickBorderImage" %MagickBorderImage)
%magick-status
"Surrounds the image with a border of the color defined by the bordercolor pixel wand.
The format of the MagickBorderImage method is:
unsigned int MagickBorderImage\( MagickWand *wand, const PixelWand *bordercolor,
const unsigned long width, const unsigned long height );
wand:
The magick wand.
bordercolor:
The border color pixel wand.
width:
The border width.
height:
The border height.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(bordercolor %PixelWand)
(width :unsigned-long)
(height :unsigned-long))
(defcfun ("MagickCdlImage" %MagickCdlImage)
%MagickPassFail
"The MagickCdlImage\() method applies \(\"bakes in\") the ASC-CDL which is a format for the exchange of basic primary color grading information between equipment and software from different manufacturers. The format defines the math for three functions: slope, offset and power. Each function uses a number for the red, green, and blue color channels for a total of nine numbers comprising a single color decision. A tenth number for chrominance \(saturation) has been proposed but is not yet standardized.
The cdl argument string is comma delimited and is in the form \(but
without invervening spaces or line breaks):
redslope, redoffset, redpower :
greenslope, greenoffset, greenpower :
blueslope, blueoffset, bluepower :
saturation
with the unity \(no change) specification being:
\"1.0,0.0,1.0:1.0,0.0,1.0:1.0,0.0,1.0:0.0\"
See http://en.wikipedia.org/wiki/ASC_CDL for more information.
The format of the MagickCdlImage method is:
MagickPassFail MagickCdlImage\( MagickWand *wand, const char *cdl );
A description of each parameter follows:
wand:
The image wand.
cdl:
Define the coefficients for slope offset and power in the
red green and blue channels, plus saturation.
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(cdl :string))
(defcfun ("MagickCharcoalImage" %MagickCharcoalImage)
%magick-status
"Simulates a charcoal drawing.
The format of the MagickCharcoalImage method is:
unsigned int MagickCharcoalImage\( MagickWand *wand, const double radius, const double sigma );
wand:
The magick wand.
radius:
The radius of the Gaussian, in pixels, not counting the center
pixel.
sigma:
The standard deviation of the Gaussian, in pixels.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double)
(sigma :double))
(defcfun ("MagickChopImage" %MagickChopImage)
%magick-status
"Removes a region of an image and collapses the image to occupy the removed portion
The format of the MagickChopImage method is:
unsigned int MagickChopImage\( MagickWand *wand, const unsigned long width,
const unsigned long height, const long x, const long y );
wand:
The magick wand.
width:
The region width.
height:
The region height.
x:
The region x offset.
y:
The region y offset.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(width :unsigned-long)
(height :unsigned-long)
(x :long)
(y :long))
(defcfun ("MagickClearException" %MagickClearException)
:void
"Clears the last wand exception.
The format of the MagickClearException method is:
void MagickClearException\( MagickWand *wand );
wand:
The magick wand.
Since GraphicsMagick v1.3.26"
(wand %MagickWand))
(defcfun ("MagickClipImage" %MagickClipImage)
%magick-status
"Clips along the first path from the 8BIM profile, if present.
The format of the MagickClipImage method is:
unsigned int MagickClipImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickClipPathImage" %MagickClipPathImage)
%magick-status
"Clips along the named paths from the 8BIM profile, if present. Later operations take effect inside the path. Id may be a number if preceded with #, to work on a numbered path, e.g., \"#1\" to use the first path.
The format of the MagickClipPathImage method is:
unsigned int MagickClipPathImage\( MagickWand *wand, const char *pathname,
const unsigned int inside );
wand:
The magick wand.
pathname:
name of clipping path resource. If name is preceded by #, use
clipping path numbered by name.
inside:
if non-zero, later operations take effect inside clipping path.
Otherwise later operations take effect outside clipping path.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(pathname :string)
(inside :unsigned-int))
(defcfun ("MagickCoalesceImages" %MagickCoalesceImages)
%MagickWand
"Composites a set of images while respecting any page offsets and disposal methods. GIF, MIFF, and MNG animation sequences typically start with an image background and each subsequent image varies in size and offset. MagickCoalesceImages\() returns a new sequence where each image in the sequence is the same size as the first and composited with the next image in the sequence.
The format of the MagickCoalesceImages method is:
MagickWand *MagickCoalesceImages\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickColorFloodfillImage" %MagickColorFloodfillImage)
%magick-status
"Changes the color value of any pixel that matches target and is an immediate neighbor. If the method FillToBorderMethod is specified, the color value is changed for any neighbor pixel that does not match the bordercolor member of image.
The format of the MagickColorFloodfillImage method is:
unsigned int MagickColorFloodfillImage\( MagickWand *wand, const PixelWand *fill,
const double fuzz, const PixelWand *bordercolor,
const long x, const long y );
wand:
The magick wand.
fill:
The floodfill color pixel wand.
fuzz:
By default target must match a particular pixel color
exactly. However, in many cases two colors may differ by a small amount.
The fuzz member of image defines how much tolerance is acceptable to
consider two colors as the same. For example, set fuzz to 10 and the
color red at intensities of 100 and 102 respectively are now interpreted
as the same color for the purposes of the floodfill.
bordercolor:
The border color pixel wand.
x,y:
The starting location of the operation.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(fill %PixelWand)
(fuzz :double)
(bordercolor %PixelWand)
(x :long)
(y :long))
(defcfun ("MagickColorizeImage" %MagickColorizeImage)
%magick-status
"Blends the fill color with each pixel in the image.
The format of the MagickColorizeImage method is:
unsigned int MagickColorizeImage\( MagickWand *wand, const PixelWand *colorize,
const PixelWand *opacity );
wand:
The magick wand.
colorize:
The colorize pixel wand.
opacity:
The opacity pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(colorize %PixelWand)
(opacity %PixelWand))
(defcfun ("MagickCommentImage" %MagickCommentImage)
%magick-status
"Adds a comment to your image.
The format of the MagickCommentImage method is:
unsigned int MagickCommentImage\( MagickWand *wand, const char *comment );
A description of each parameter follows:
wand:
The magick wand.
comment:
The image comment.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(comment :string))
(defcfun ("MagickCompareImageChannels" %MagickCompareImageChannels)
%MagickWand
"Compares one or more image channels and returns the specified distortion metric.
The format of the MagickCompareImageChannels method is:
MagickWand *MagickCompareImageChannels\( MagickWand *wand, const MagickWand *reference,
const ChannelType channel, const MetricType metric,
double *distortion );
wand:
The magick wand.
reference:
The reference wand.
channel:
The channel.
metric:
The metric.
distortion:
The computed distortion between the images.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(reference %MagickWand)
(channel %ChannelType)
(metric %MetricType)
(distortion :pointer))
(defcfun ("MagickCompareImages" %MagickCompareImages)
%MagickWand
"Compares one or more images and returns the specified distortion metric.
The format of the MagickCompareImages method is:
MagickWand *MagickCompareImages\( MagickWand *wand, const MagickWand *reference,
const MetricType metric, double *distortion );
wand:
The magick wand.
reference:
The reference wand.
metric:
The metric.
distortion:
The computed distortion between the images.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(reference %MagickWand)
(metric %MetricType)
(distortion :pointer))
(defcfun ("MagickCompositeImage" %MagickCompositeImage)
%magick-status
"Composite one image onto another at the specified offset.
The format of the MagickCompositeImage method is:
unsigned int MagickCompositeImage\( MagickWand *wand, const MagickWand *composite_wand,
const CompositeOperator compose, const long x,
const long y );
wand:
The magick wand.
composite_image:
The composite image.
compose:
This operator affects how the composite is applied to the
image. The default is Over. Choose from these operators:
OverCompositeOp InCompositeOp OutCompositeOP
AtopCompositeOP XorCompositeOP PlusCompositeOP
MinusCompositeOP AddCompositeOP SubtractCompositeOP
DifferenceCompositeOP BumpmapCompositeOP CopyCompositeOP
DisplaceCompositeOP
x_offset:
The column offset of the composited image.
y_offset:
The row offset of the composited image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(composite_wand %MagickWand)
(compose %CompositeOperator)
(x :long)
(y :long))
(defcfun ("MagickContrastImage" %MagickContrastImage)
%magick-status
"Enhances the intensity differences between the lighter and darker elements of the image. Set sharpen to a value other than 0 to increase the image contrast otherwise the contrast is reduced.
The format of the MagickContrastImage method is:
unsigned int MagickContrastImage\( MagickWand *wand, const unsigned int sharpen );
wand:
The magick wand.
sharpen:
Increase or decrease image contrast.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(sharpen :unsigned-int))
(defcfun ("MagickConvolveImage" %MagickConvolveImage)
%magick-status
"Applies a custom convolution kernel to the image.
The format of the MagickConvolveImage method is:
unsigned int MagickConvolveImage\( MagickWand *wand, const unsigned long order,
const double *kernel );
wand:
The magick wand.
order:
The number of columns and rows in the filter kernel.
kernel:
An array of doubles representing the convolution kernel.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(order :unsigned-long)
(kernel :pointer))
(defcfun ("MagickCropImage" %MagickCropImage)
%magick-status
"Extracts a region of the image.
The format of the MagickCropImage method is:
unsigned int MagickCropImage\( MagickWand *wand, const unsigned long width,
const unsigned long height, const long x, const long y );
wand:
The magick wand.
width:
The region width.
height:
The region height.
x:
The region x offset.
y:
The region y offset.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(width :unsigned-long)
(height :unsigned-long)
(x :long)
(y :long))
(defcfun ("MagickCycleColormapImage" %MagickCycleColormapImage)
%magick-status
"Displaces an image's colormap by a given number of positions. If you cycle the colormap a number of times you can produce a psychodelic effect.
The format of the MagickCycleColormapImage method is:
unsigned int MagickCycleColormapImage\( MagickWand *wand, const long displace );
wand:
The magick wand.
pixel_wand:
The pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(displace :long))
(defcfun ("MagickDeconstructImages" %MagickDeconstructImages)
%MagickWand
"Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers.
The format of the MagickDeconstructImages method is:
MagickWand *MagickDeconstructImages\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickDescribeImage" %MagickDescribeImage)
:string
"Describes an image by formatting its attributes to an allocated string which must be freed by the user. Attributes include the image width, height, size, and others. The string is similar to the output of 'identify -verbose'.
The format of the MagickDescribeImage method is:
const char *MagickDescribeImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickDespeckleImage" %MagickDespeckleImage)
%magick-status
"Reduces the speckle noise in an image while perserving the edges of the original image.
The format of the MagickDespeckleImage method is:
unsigned int MagickDespeckleImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickDisplayImage" %MagickDisplayImage)
%magick-status
"Displays an image.
The format of the MagickDisplayImage method is:
unsigned int MagickDisplayImage\( MagickWand *wand, const char *server_name );
A description of each parameter follows:
wand:
The magick wand.
server_name:
The X server name.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(server_name :string))
(defcfun ("MagickDisplayImages" %MagickDisplayImages)
%magick-status
"Displays an image or image sequence.
The format of the MagickDisplayImages method is:
unsigned int MagickDisplayImages\( MagickWand *wand, const char *server_name );
wand:
The magick wand.
server_name:
The X server name.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(server_name :string))
(defcfun ("MagickDrawImage" %MagickDrawImage)
%magick-status
"Draws vectors on the image as described by DrawingWand.
The format of the MagickDrawImage method is:
unsigned int MagickDrawImage\( MagickWand *wand, const DrawingWand *drawing_wand );
wand:
The magick wand.
drawing_wand:
The draw wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(drawing_wand %DrawingWand))
(defcfun ("MagickEdgeImage" %MagickEdgeImage)
%magick-status
"Enhance edges within the image with a convolution filter of the given radius. Use a radius of 0 and Edge\() selects a suitable radius for you.
The format of the MagickEdgeImage method is:
unsigned int MagickEdgeImage\( MagickWand *wand, const double radius );
A description of each parameter follows:
wand:
The magick wand.
radius:
the radius of the pixel neighborhood.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double))
(defcfun ("MagickEmbossImage" %MagickEmbossImage)
%magick-status
"Returns a grayscale image with a three-dimensional effect. We convolve the image with a Gaussian operator of the given radius and standard deviation \(sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and Emboss\() selects a suitable radius for you.
The format of the MagickEmbossImage method is:
unsigned int MagickEmbossImage\( MagickWand *wand, const double radius, const double sigma );
wand:
The magick wand.
radius:
The radius of the Gaussian, in pixels, not counting the center
pixel.
sigma:
The standard deviation of the Gaussian, in pixels.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double)
(sigma :double))
(defcfun ("MagickEnhanceImage" %MagickEnhanceImage)
%magick-status
"Applies a digital filter that improves the quality of a noisy image.
The format of the MagickEnhanceImage method is:
unsigned int MagickEnhanceImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickEqualizeImage" %MagickEqualizeImage)
%magick-status
"Equalizes the image histogram.
The format of the MagickEqualizeImage method is:
unsigned int MagickEqualizeImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickExtentImage" %MagickExtentImage)
%magick-status
"Use MagickExtentImage\() to change the image dimensions as specified by geometry width and height. The existing image content is composited at the position specified by geometry x and y using the image compose method. Existing image content which falls outside the bounds of the new image dimensions is discarded.
The format of the MagickExtentImage method is:
unsigned int MagickExtentImage\( MagickWand *wand, const size_t width, const size_t height,
const ssize_t x, const ssize_t y );
wand:
The magick wand.
width:
New image width
height:
New image height
x, y:
Top left composition coordinate to place existing image content
on the new image.
Since GraphicsMagick v1.3.14"
(wand %MagickWand)
(width %size_t)
(height %size_t)
(x %ssize_t)
(y %ssize_t))
(defcfun ("MagickFlattenImages" %MagickFlattenImages)
%MagickWand
"Merges a sequence of images. This is useful for combining Photoshop layers into a single image.
The format of the MagickFlattenImages method is:
MagickWand *MagickFlattenImages\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickFlipImage" %MagickFlipImage)
%magick-status
"Creates a vertical mirror image by reflecting the pixels around the central x-axis\(swap up/down).
The format of the MagickFlipImage method is:
unsigned int MagickFlipImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickFlopImage" %MagickFlopImage)
%magick-status
"Creates a horizontal mirror image by reflecting the pixels around the central y-axis\(swap left/right).
The format of the MagickFlopImage method is:
unsigned int MagickFlopImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickFrameImage" %MagickFrameImage)
%magick-status
"Adds a simulated three-dimensional border around the image. The width and height specify the border width of the vertical and horizontal sides of the frame. The inner and outer bevels indicate the width of the inner and outer shadows of the frame.
The format of the MagickFrameImage method is:
unsigned int MagickFrameImage\( MagickWand *wand, const PixelWand *matte_color,
const unsigned long width, const unsigned long height,
const long inner_bevel, const long outer_bevel );
wand:
The magick wand.
matte_color:
The frame color pixel wand.
width:
The border width.
height:
The border height.
inner_bevel:
The inner bevel width.
outer_bevel:
The outer bevel width.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(matte_color %PixelWand)
(width :unsigned-long)
(height :unsigned-long)
(inner_bevel :long)
(outer_bevel :long))
(defcfun ("MagickFxImage" %MagickFxImage)
%MagickWand
"Evaluate expression for each pixel in the image.
The format of the MagickFxImage method is:
MagickWand *MagickFxImage\( MagickWand *wand, const char *expression );
A description of each parameter follows:
wand:
The magick wand.
expression:
The expression.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(expression :string))
(defcfun ("MagickFxImageChannel" %MagickFxImageChannel)
%MagickWand
"Evaluate expression for each pixel in the specified channel.
The format of the MagickFxImageChannel method is:
MagickWand *MagickFxImageChannel\( MagickWand *wand, const ChannelType channel,
const char *expression );
wand:
The magick wand.
channel:
Identify which channel to level: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
BlackChannel.
expression:
The expression.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(expression :string))
(defcfun ("MagickGammaImage" %MagickGammaImage)
%magick-status
"Use MagickGammaImage\() to gamma-correct an image. The same image viewed on different devices will have perceptual differences in the way the image's intensities are represented on the screen. Specify individual gamma levels for the red, green, and blue channels, or adjust all three with the gamma parameter. Values typically range from 0.8 to 2.3.
You can also reduce the influence of a particular channel with a gamma
value of 0.
The format of the MagickGammaImage method is:
unsigned int MagickGammaImage\( MagickWand *wand, const double gamma );
A description of each parameter follows:
wand:
The magick wand.
gamme:
Define the level of gamma correction.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(gamma :double))
(defcfun ("MagickGammaImageChannel" %MagickGammaImageChannel)
%magick-status
"Use MagickGammaImageChannel\() to gamma-correct a particular image channel. The same image viewed on different devices will have perceptual differences in the way the image's intensities are represented on the screen. Specify individual gamma levels for the red, green, and blue channels, or adjust all three with the gamma parameter. Values typically range from 0.8 to 2.3.
You can also reduce the influence of a particular channel with a gamma
value of 0.
The format of the MagickGammaImageChannel method is:
unsigned int MagickGammaImageChannel\( MagickWand *wand, const ChannelType channel,
const double gamma );
wand:
The magick wand.
channel:
The channel.
level:
Define the level of gamma correction.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(gamma :double))
(defcfun ("MagickGetConfigureInfo" %MagickGetConfigureInfo)
:string
"Returns ImageMagick configure attributes such as NAME, VERSION, LIB_VERSION, COPYRIGHT, etc.
The format of the MagickGetConfigureInfo\() method is:
char *MagickGetConfigureInfo\( MagickWand *wand, const char *name );
A description of each parameter follows:
wand:
The magick wand.
name:
Return the attribute associated with this name.
WARN: GraphicsMagick return NULL whatever you passed. Do NOT use this API.
More detail could be found in source code.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(name :string))
(defcfun ("MagickGetCopyright" %MagickGetCopyright)
:string
"Returns the ImageMagick API copyright as a string.
The format of the MagickGetCopyright method is:
const char *MagickGetCopyright\( void );
Since GraphicsMagick v1.1.0")
(defcfun ("MagickGetException" %MagickGetException)
:string
"Returns the severity, reason, and description of any error that occurs when using other methods in this API.
The format of the MagickGetException method is:
char *MagickGetException\( const MagickWand *wand, ExceptionType *severity );
A description of each parameter follows:
wand:
The magick wand.
severity:
The severity of the error is returned here.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(severity :pointer)) ;; ExceptionType *severity
(defcfun ("MagickGetFilename" %MagickGetFilename)
:string
"Returns the filename associated with an image sequence.
The format of the MagickGetFilename method is:
const char *MagickGetFilename\( const MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetHomeURL" %MagickGetHomeURL)
:string
"Returns the ImageMagick home URL.
The format of the MagickGetHomeURL method is:
const char *MagickGetHomeURL\( void );
Since GraphicsMagick v1.1.0")
(defcfun ("MagickGetImage" %MagickGetImage)
%MagickWand
"Clones the image at the current image index.
The format of the MagickGetImage method is:
MagickWand *MagickGetImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageAttribute" %MagickGetImageAttribute)
:string
"MagickGetImageAttribute returns an image attribute as a string
The format of the MagickGetImageAttribute method is:
char *MagickGetImageAttribute\( MagickWand *wand, const char *name );
A description of each parameter follows:
wand:
The magick wand.
name:
The name of the attribute
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(name :string))
(defcfun ("MagickGetImageBackgroundColor" %MagickGetImageBackgroundColor)
%magick-status
"Returns the image background color.
The format of the MagickGetImageBackgroundColor method is:
unsigned int MagickGetImageBackgroundColor\( MagickWand *wand, PixelWand *background_color );
wand:
The magick wand.
background_color:
Return the background color.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(background_color %PixelWand))
(defcfun ("MagickGetImageBluePrimary" %MagickGetImageBluePrimary)
%magick-status
"Returns the chromaticy blue primary point for the image.
The format of the MagickGetImageBluePrimary method is:
unsigned int MagickGetImageBluePrimary\( MagickWand *wand, double *x, double *y );
wand:
The magick wand.
x:
The chromaticity blue primary x-point.
y:
The chromaticity blue primary y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImageBorderColor" %MagickGetImageBorderColor)
%magick-status
"Returns the image border color.
The format of the MagickGetImageBorderColor method is:
unsigned int MagickGetImageBorderColor\( MagickWand *wand, PixelWand *border_color );
wand:
The magick wand.
border_color:
Return the border color.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(border_color %PixelWand))
(defcfun ("MagickGetImageBoundingBox" %MagickGetImageBoundingBox)
%magick-status
"Obtains the crop bounding box required to remove a solid-color border from the image. Color quantums which differ less than the fuzz setting are considered to be the same. If a border is not detected, then the the original image dimensions are returned. The crop bounding box estimation uses the same algorithm as MagickTrimImage\().
The format of the MagickGetImageBoundingBox method is:
unsigned int MagickGetImageBoundingBox\( MagickWand *wand, const double fuzz,
unsigned long *width, unsigned long *height,
long *x, long *y );
wand:
The magick wand.
fuzz:
Color comparison fuzz factor. Use 0.0 for exact match.
width:
The crop width
height:
The crop height
x:
The crop x offset
y:
The crop y offset
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(fuzz :double)
(width :pointer)
(height :pointer)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImageChannelDepth" %MagickGetImageChannelDepth)
:unsigned-long
"Gets the depth for a particular image channel.
The format of the MagickGetImageChannelDepth method is:
unsigned long MagickGetImageChannelDepth\( MagickWand *wand, const ChannelType channel );
wand:
The magick wand.
channel:
Identify which channel to extract: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
BlackChannel.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType))
(defcfun ("MagickGetImageChannelExtrema" %MagickGetImageChannelExtrema)
%magick-status
"Gets the extrema for one or more image channels.
The format of the MagickGetImageChannelExtrema method is:
unsigned int MagickGetImageChannelExtrema\( MagickWand *wand, const ChannelType channel,
unsigned long *minima, unsigned long *maxima );
wand:
The magick wand.
channel:
Identify which channel to extract: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
or BlackChannel.
minima:
The minimum pixel value for the specified channel\(s).
maxima:
The maximum pixel value for the specified channel\(s).
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(minima :pointer)
(maxima :pointer))
(defcfun ("MagickGetImageChannelMean" %MagickGetImageChannelMean)
%magick-status
"Gets the mean and standard deviation of one or more image channels.
The format of the MagickGetImageChannelMean method is:
unsigned int MagickGetImageChannelMean\( MagickWand *wand, const ChannelType channel,
double *mean, double *standard_deviation );
wand:
The magick wand.
channel:
Identify which channel to extract: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
or BlackChannel.
mean:
The mean pixel value for the specified channel\(s).
standard_deviation:
The standard deviation for the specified channel\(s).
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(mean :pointer)
(standard_deviation :pointer))
(defcfun ("MagickGetImageColormapColor" %MagickGetImageColormapColor)
%magick-status
"Returns the color of the specified colormap index.
The format of the MagickGetImageColormapColor method is:
unsigned int MagickGetImageColormapColor\( MagickWand *wand, const unsigned long index,
PixelWand *color );
wand:
The magick wand.
index:
The offset into the image colormap.
color:
Return the colormap color in this wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(index :unsigned-long)
(color %PixelWand))
(defcfun ("MagickGetImageColors" %MagickGetImageColors)
:unsigned-long
"Gets the number of unique colors in the image.
The format of the MagickGetImageColors method is:
unsigned long MagickGetImageColors\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageColorspace" %MagickGetImageColorspace)
%ColorspaceType
"Gets the image colorspace.
The format of the MagickGetImageColorspace method is:
ColorspaceType MagickGetImageColorspace\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageCompose" %MagickGetImageCompose)
%CompositeOperator
"Returns the composite operator associated with the image.
The format of the MagickGetImageCompose method is:
CompositeOperator MagickGetImageCompose\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageCompression" %MagickGetImageCompression)
%CompressionType
"Gets the image compression.
The format of the MagickGetImageCompression method is:
CompressionType MagickGetImageCompression\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageDelay" %MagickGetImageDelay)
:unsigned-long
"Gets the image delay.
The format of the MagickGetImageDelay method is:
unsigned long MagickGetImageDelay\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageDepth" %MagickGetImageDepth)
:unsigned-long
"Gets the image depth.
The format of the MagickGetImageDepth method is:
unsigned long MagickGetImageDepth\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageExtrema" %MagickGetImageExtrema)
%magick-status
"Gets the extrema for the image.
The format of the MagickGetImageExtrema method is:
unsigned int MagickGetImageExtrema\( MagickWand *wand, unsigned long *min,
unsigned long *max );
wand:
The magick wand.
min:
The minimum pixel value for the specified channel\(s).
max:
The maximum pixel value for the specified channel\(s).
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(min :pointer)
(max :pointer))
(defcfun ("MagickGetImageDispose" %MagickGetImageDispose)
%DisposeType
"Gets the image disposal method.
The format of the MagickGetImageDispose method is:
DisposeType MagickGetImageDispose\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageFilename" %MagickGetImageFilename)
:char
"Returns the filename of a particular image in a sequence.
The format of the MagickGetImageFilename method is:
const char MagickGetImageFilename\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageFormat" %MagickGetImageFormat)
:string
"Returns the format of a particular image in a sequence.
The format of the MagickGetImageFormat method is:
char * MagickGetImageFormat\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageFuzz" %MagickGetImageFuzz)
:double
"Returns the color comparison fuzz factor. Colors closer than the fuzz factor are considered to be the same when comparing colors. Note that some other functions such as MagickColorFloodfillImage\() implicitly set this value.
The format of the MagickGetImageFuzz method is:
double MagickGetImageFuzz\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.3.8"
(wand %MagickWand))
(defcfun ("MagickGetImageGamma" %MagickGetImageGamma)
:double
"Gets the image gamma.
The format of the MagickGetImageGamma method is:
double MagickGetImageGamma\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageGeometry" %MagickGetImageGeometry)
:string
"Gets the image geometry string. NULL is returned if the image does not contain a geometry string.
The format of the MagickGetImageGeometry method is:
const char *MagickGetImageGeometry\( MagickWand *wand )
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.3.20"
(wand %MagickWand))
(defcfun ("MagickGetImageGravity" %MagickGetImageGravity)
%GravityType
"Gets the image gravity.
The format of the MagickGetImageGravity method is:
GravityType MagickGetImageGravity\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.3.22"
(wand %MagickWand))
(defcfun ("MagickGetImageGreenPrimary" %MagickGetImageGreenPrimary)
%magick-status
"Returns the chromaticy green primary point.
The format of the MagickGetImageGreenPrimary method is:
unsigned int MagickGetImageGreenPrimary\( MagickWand *wand, double *x, double *y );
wand:
The magick wand.
x:
The chromaticity green primary x-point.
y:
The chromaticity green primary y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImageHeight" %MagickGetImageHeight)
:unsigned-long
"Returns the image height.
The format of the MagickGetImageHeight method is:
unsigned long MagickGetImageHeight\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageHistogram" %MagickGetImageHistogram)
%PixelWand
"Returns the image histogram as an array of PixelWand wands.
The format of the MagickGetImageHistogram method is:
PixelWand *MagickGetImageHistogram\( MagickWand *wand, unsigned long *number_colors );
wand:
The magick wand.
number_colors:
The number of unique colors in the image and the number
of pixel wands returned.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(number_colors :pointer))
(defcfun ("MagickGetImageIndex" %MagickGetImageIndex)
:long
"Returns the index of the current image.
The format of the MagickGetImageIndex method is:
long MagickGetImageIndex\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageInterlaceScheme" %MagickGetImageInterlaceScheme)
%InterlaceType
"Gets the image interlace scheme.
The format of the MagickGetImageInterlaceScheme method is:
InterlaceType MagickGetImageInterlaceScheme\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageIterations" %MagickGetImageIterations)
:unsigned-long
"Gets the image iterations.
The format of the MagickGetImageIterations method is:
unsigned long MagickGetImageIterations\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageMatte" %MagickGetImageMatte)
%MagickBool
"Gets the image matte flag. The flag is MagickTrue if the image supports an opacity \(inverse of transparency) channel.
The format of the MagickGetImageMatte method is:
MagickBool MagickGetImageMatte\( MagickWand *wand )
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.3.20"
(wand %MagickWand))
(defcfun ("MagickGetImageMatteColor" %MagickGetImageMatteColor)
%magick-status
"Returns the image matte color.
The format of the MagickGetImageMatteColor method is:
unsigned int MagickGetImageMatteColor\( MagickWand *wand, PixelWand *matte_color );
wand:
The magick wand.
matte_color:
Return the matte color.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(matte_color %PixelWand))
(defcfun ("MagickGetImageOrientation" %MagickGetImageOrientation)
%OrientationType
"Gets the image orientation type. May be one of:
UndefinedOrientation Image orientation not specified or error.
TopLeftOrientation Left to right and Top to bottom.
TopRightOrientation Right to left and Top to bottom.
BottomRightOrientation Right to left and Bottom to top.
BottomLeftOrientation Left to right and Bottom to top.
LeftTopOrientation Top to bottom and Left to right.
RightTopOrientation Top to bottom and Right to left.
RightBottomOrientation Bottom to top and Right to left.
LeftBottomOrientation Bottom to top and Left to right.
The format of the MagickGetImageOrientation method is:
OrientationType MagickGetImageOrientation\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.3.26"
(wand %MagickWand))
(defcfun ("MagickGetImagePage" %MagickGetImagePage)
%magick-status
"Retrieves the image page size and offset used when placing \(e.g. compositing) the image.
The format of the MagickGetImagePage method is:
MagickGetImagePage\( MagickWand *wand, unsigned long *width, unsigned long *height, long *x,
long *y );
wand:
The magick wand.
width, height:
The region size.
x, y:
Offset \(from top left) on base canvas image on
which to composite image data.
Since GraphicsMagick v1.3.18"
(wand %MagickWand)
(width :pointer)
(height :pointer)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImagePixels" %MagickGetImagePixels)
%magick-status
"Extracts pixel data from an image and returns it to you. The method returns False on success otherwise True if an error is encountered. The data is returned as char, short int, int, long, float, or double in the order specified by map.
Suppose you want to extract the first scanline of a 640x480 image as
character data in red-green-blue order:
MagickGetImagePixels\(wand,0,0,640,1,\"RGB\",CharPixel,pixels);
The format of the MagickGetImagePixels method is:
unsigned int MagickGetImagePixels\( MagickWand *wand, const long x_offset, const long y_offset,
const unsigned long columns, const unsigned long rows,
const char *map, const StorageType storage,
unsigned char *pixels );
wand:
The magick wand.
x_offset, y_offset, columns, rows:
These values define the perimeter
of a region of pixels you want to extract.
map:
This string reflects the expected ordering of the pixel array.
It can be any combination or order of R = red, G = green, B = blue,
A = alpha, C = cyan, Y = yellow, M = magenta, K = black, or
I = intensity \(for grayscale).
storage:
Define the data type of the pixels. Float and double types are
expected to be normalized [0..1] otherwise [0..MaxRGB]. Choose from
these types: CharPixel, ShortPixel, IntegerPixel, LongPixel, FloatPixel,
or DoublePixel.
pixels:
This array of values contain the pixel components as defined by
map and type. You must preallocate this array where the expected
length varies depending on the values of width, height, map, and type.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x_offset :long)
(y_offset :long)
(columns :unsigned-long)
(rows :unsigned-long)
(map :string)
(storage %StorageType)
(pixels :pointer))
(defcfun ("MagickGetImageProfile" %MagickGetImageProfile)
:pointer
"Returns the named image profile.
The format of the MagickGetImageProfile method is:
unsigned char *MagickGetImageProfile\( MagickWand *wand, const char *name,
unsigned long *length );
wand:
The magick wand.
name:
Name of profile to return: ICC, IPTC, or generic profile.
length:
The length of the profile.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(name :string)
(length :pointer))
(defcfun ("MagickGetImageRedPrimary" %MagickGetImageRedPrimary)
%magick-status
"Returns the chromaticy red primary point.
The format of the MagickGetImageRedPrimary method is:
unsigned int MagickGetImageRedPrimary\( MagickWand *wand, double *x, double *y );
wand:
The magick wand.
x:
The chromaticity red primary x-point.
y:
The chromaticity red primary y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImageRenderingIntent" %MagickGetImageRenderingIntent)
%RenderingIntent
"Gets the image rendering intent.
The format of the MagickGetImageRenderingIntent method is:
RenderingIntent MagickGetImageRenderingIntent\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageResolution" %MagickGetImageResolution)
%magick-status
"Gets the image X & Y resolution.
The format of the MagickGetImageResolution method is:
unsigned int MagickGetImageResolution\( MagickWand *wand, double *x, double *y );
wand:
The magick wand.
x:
The image x-resolution.
y:
The image y-resolution.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImageScene" %MagickGetImageScene)
:unsigned-long
"Gets the image scene.
The format of the MagickGetImageScene method is:
unsigned long MagickGetImageScene\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageSignature" %MagickGetImageSignature)
:char
"Generates an SHA-256 message digest for the image pixel stream.
The format of the MagickGetImageSignature method is:
const char MagickGetImageSignature\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageSize" %MagickGetImageSize)
%MagickSizeType
"Returns the image size.
The format of the MagickGetImageSize method is:
MagickSizeType MagickGetImageSize\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageType" %MagickGetImageType)
%ImageType
"Gets the image type.
The format of the MagickGetImageType method is:
ImageType MagickGetImageType\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageSavedType" %MagickGetImageSavedType)
%ImageType
"Gets the image type that will be used when the image is saved. This may be different to the current image type, returned by MagickGetImageType\().
The format of the MagickGetImageSavedType method is:
ImageType MagickGetImageSavedType\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.3.13"
(wand %MagickWand))
(defcfun ("MagickGetImageUnits" %MagickGetImageUnits)
%ResolutionType
"Gets the image units of resolution.
The format of the MagickGetImageUnits method is:
ResolutionType MagickGetImageUnits\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageVirtualPixelMethod" %MagickGetImageVirtualPixelMethod)
%VirtualPixelMethod
"Returns the virtual pixel method for the sepcified image.
The format of the MagickGetImageVirtualPixelMethod method is:
VirtualPixelMethod MagickGetImageVirtualPixelMethod\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageWhitePoint" %MagickGetImageWhitePoint)
%magick-status
"Returns the chromaticy white point.
The format of the MagickGetImageWhitePoint method is:
unsigned int MagickGetImageWhitePoint\( MagickWand *wand, double *x, double *y );
wand:
The magick wand.
x:
The chromaticity white x-point.
y:
The chromaticity white y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImageWidth" %MagickGetImageWidth)
:unsigned-long
"Returns the image width.
The format of the MagickGetImageWidth method is:
unsigned long MagickGetImageWidth\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetNumberImages" %MagickGetNumberImages)
:unsigned-long
"Returns the number of images associated with a magick wand.
The format of the MagickGetNumberImages method is:
unsigned long MagickGetNumberImages\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetPackageName" %MagickGetPackageName)
:string
"Returns the ImageMagick package name.
The format of the MagickGetPackageName method is:
const char *MagickGetPackageName\( void );
Since GraphicsMagick v1.1.0")
(defcfun ("MagickGetQuantumDepth" %MagickGetQuantumDepth)
:string
"Returns the ImageMagick quantum depth.
The format of the MagickGetQuantumDepth method is:
const char *MagickGetQuantumDepth\( unsigned long *depth );
A description of each parameter follows:
depth:
The quantum depth is returned as a number.
Since GraphicsMagick v1.1.0"
(depth :pointer))
(defcfun ("MagickGetReleaseDate" %MagickGetReleaseDate)
:string
"Returns the ImageMagick release date.
The format of the MagickGetReleaseDate method is:
const char *MagickGetReleaseDate\( void );
Since GraphicsMagick v1.1.0")
(defcfun ("MagickGetResourceLimit" %MagickGetResourceLimit)
:unsigned-long
"Returns the the specified resource in megabytes.
The format of the MagickGetResourceLimit method is:
unsigned long MagickGetResourceLimit\( const ResourceType type );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(type %ResourceType))
(defcfun ("MagickGetSamplingFactors" %MagickGetSamplingFactors)
:double
"Gets the horizontal and vertical sampling factor.
The format of the MagickGetSamplingFactors method is:
double *MagickGetSamplingFactors\( MagickWand *wand, unsigned long *number_factors );
wand:
The magick wand.
number_factors:
The number of factors in the returned array.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(number_factors :pointer))
(defcfun ("MagickGetSize" %MagickGetSize)
%magick-status
"Returns the size associated with the magick wand.
The format of the MagickGetSize method is:
unsigned int MagickGetSize\( const MagickWand *wand, unsigned long *columns,
unsigned long *rows );
wand:
The magick wand.
columns:
The width in pixels.
height:
The height in pixels.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(columns :pointer)
(rows :pointer))
(defcfun ("MagickGetVersion" %MagickGetVersion)
:string
"Returns the ImageMagick API version as a string and as a number.
The format of the MagickGetVersion method is:
const char *MagickGetVersion\( unsigned long *version );
A description of each parameter follows:
version:
The ImageMagick version is returned as a number.
Since GraphicsMagick v1.1.0"
(version :pointer))
(defcfun ("MagickHaldClutImage" %MagickHaldClutImage)
%MagickPassFail
"The MagickHaldClutImage\() method apply a color lookup table \(Hald CLUT) to the image. The fundamental principle of the Hald CLUT algorithm is that application of an identity CLUT causes no change to the input image, but an identity CLUT image which has had its colors transformed in some way \(e.g. in Adobe Photoshop) may be used to implement an identical transform on any other image.
The minimum CLUT level is 2, and the maximum depends on available memory
\(largest successfully tested is 24). A CLUT image is required to have equal
width and height. A CLUT of level 8 is an image of dimension 512x512, a CLUT
of level 16 is an image of dimension 4096x4096. Interpolation is used so
extremely large CLUT images are not required.
GraphicsMagick provides an 'identity' coder which may be used to generate
identity HLUTs. For example, reading from \"identity:8\" creates an identity
CLUT of order 8.
The Hald CLUT algorithm has been developed by <NAME> as described
at http://www.quelsolaar.com/technology/clut.html, and was adapted for
GraphicsMagick by <NAME> with support from <NAME> of
Workflowers.
The format of the HaldClutImage method is:
MagickPassFail MagickHaldClutImage\( MagickWand *wand, const MagickWand *clut_wand );
A description of each parameter follows:
wand:
The image wand.
clut_wand:
The color lookup table image wand
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(clut_wand %MagickWand))
(defcfun ("MagickHasNextImage" %MagickHasNextImage)
:boolean
"Returns True if the wand has more images when traversing the list in the forward direction
The format of the MagickHasNextImage method is:
unsigned int MagickHasNextImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickHasPreviousImage" %MagickHasPreviousImage)
%magick-status
"Returns True if the wand has more images when traversing the list in the reverse direction
The format of the MagickHasPreviousImage method is:
unsigned int MagickHasPreviousImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickImplodeImage" %MagickImplodeImage)
%magick-status
"Creates a new image that is a copy of an existing one with the image pixels \"implode\" by the specified percentage. It allocates the memory necessary for the new Image structure and returns a pointer to the new image.
The format of the MagickImplodeImage method is:
unsigned int MagickImplodeImage\( MagickWand *wand, const double radius );
A description of each parameter follows:
wand:
The magick wand.
amount:
Define the extent of the implosion.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double))
(defcfun ("MagickLabelImage" %MagickLabelImage)
%magick-status
"Adds a label to your image.
The format of the MagickLabelImage method is:
unsigned int MagickLabelImage\( MagickWand *wand, const char *label );
A description of each parameter follows:
wand:
The magick wand.
label:
The image label.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(label :string))
(defcfun ("MagickLevelImage" %MagickLevelImage)
%magick-status
"Adjusts the levels of an image by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid, and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value.
The format of the MagickLevelImage method is:
unsigned int MagickLevelImage\( MagickWand *wand, const double black_point, const double gamma,
const double white_point );
wand:
The magick wand.
black_point:
The black point.
gamma:
The gamma.
white_point:
The white point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(black_point :double)
(gamma :double)
(white_point :double))
(defcfun ("MagickLevelImageChannel" %MagickLevelImageChannel)
%magick-status
"Adjusts the levels of the specified channel of the reference image by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid, and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value.
The format of the MagickLevelImageChannel method is:
unsigned int MagickLevelImageChannel\( MagickWand *wand, const ChannelType channel,
const double black_point, const double gamma,
const double white_point );
wand:
The magick wand.
channel:
Identify which channel to level: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
BlackChannel.
black_point:
The black point.
gamma:
The gamma.
white_point:
The white point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(black_point :double)
(gamma :double)
(white_point :double))
(defcfun ("MagickMagnifyImage" %MagickMagnifyImage)
%magick-status
"Is a convenience method that scales an image proportionally to twice its original size.
The format of the MagickMagnifyImage method is:
unsigned int MagickMagnifyImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickMapImage" %MagickMapImage)
%magick-status
"Replaces the colors of an image with the closest color from a reference image.
The format of the MagickMapImage method is:
unsigned int MagickMapImage\( MagickWand *wand, const MagickWand *map_wand,
const unsigned int dither );
wand:
The magick wand.
map:
The map wand.
dither:
Set this integer value to something other than zero to dither
the mapped image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(map_wand %MagickWand)
(dither :unsigned-int))
(defcfun ("MagickMatteFloodfillImage" %MagickMatteFloodfillImage)
%magick-status
"Changes the transparency value of any pixel that matches target and is an immediate neighbor. If the method FillToBorderMethod is specified, the transparency value is changed for any neighbor pixel that does not match the bordercolor member of image.
The format of the MagickMatteFloodfillImage method is:
unsigned int MagickMatteFloodfillImage\( MagickWand *wand, const Quantum opacity,
const double fuzz, const PixelWand *bordercolor,
const long x, const long y );
wand:
The magick wand.
opacity:
The opacity.
fuzz:
By default target must match a particular pixel color
exactly. However, in many cases two colors may differ by a small amount.
The fuzz member of image defines how much tolerance is acceptable to
consider two colors as the same. For example, set fuzz to 10 and the
color red at intensities of 100 and 102 respectively are now interpreted
as the same color for the purposes of the floodfill.
bordercolor:
The border color pixel wand.
x,y:
The starting location of the operation.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(opacity %Quantum)
(fuzz :double)
(bordercolor %PixelWand)
(x :long)
(y :long))
(defcfun ("MagickMedianFilterImage" %MagickMedianFilterImage)
%magick-status
"Applies a digital filter that improves the quality of a noisy image. Each pixel is replaced by the median in a set of neighboring pixels as defined by radius.
The format of the MagickMedianFilterImage method is:
unsigned int MagickMedianFilterImage\( MagickWand *wand, const double radius );
wand:
The magick wand.
radius:
The radius of the pixel neighborhood.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double))
(defcfun ("MagickMinifyImage" %MagickMinifyImage)
%magick-status
"Is a convenience method that scales an image proportionally to one-half its original size
The format of the MagickMinifyImage method is:
unsigned int MagickMinifyImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickModulateImage" %MagickModulateImage)
%magick-status
"Lets you control the brightness, saturation, and hue of an image.
The format of the MagickModulateImage method is:
unsigned int MagickModulateImage\( MagickWand *wand, const double brightness,
const double saturation, const double hue );
wand:
The magick wand.
brightness:
The percent change in brighness \(-100 thru +100).
saturation:
The percent change in saturation \(-100 thru +100)
hue:
The percent change in hue \(-100 thru +100)
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(brightness :double)
(saturation :double)
(hue :double))
(defcfun ("MagickMontageImage" %MagickMontageImage)
%MagickWand
"Use MagickMontageImage\() to create a composite image by combining several separate images. The images are tiled on the composite image with the name of the image optionally appearing just below the individual tile.
The format of the MagickMontageImage method is:
MagickWand MagickMontageImage\( MagickWand *wand, const DrawingWand drawing_wand,
const char *tile_geometry, const char *thumbnail_geometry,
const MontageMode mode, const char *frame );
wand:
The magick wand.
drawing_wand:
The drawing wand. The font name, size, and color are
obtained from this wand.
tile_geometry:
the number of tiles per row and page \(e.g. 6x4+0+0).
thumbnail_geometry:
Preferred image size and border size of each
thumbnail \(e.g. 120x120+4+3>).
mode:
Thumbnail framing mode: Frame, Unframe, or Concatenate.
frame:
Surround the image with an ornamental border \(e.g. 15x15+3+3).
The frame color is that of the thumbnail's matte color.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(drawing_wand %DrawingWand)
(tile_geometry :string)
(thumbnail_geometry :string)
(mode %MontageMode)
(frame :string))
(defcfun ("MagickMorphImages" %MagickMorphImages)
%MagickWand
"Method morphs a set of images. Both the image pixels and size are linearly interpolated to give the appearance of a meta-morphosis from one image to the next.
The format of the MagickMorphImages method is:
MagickWand *MagickMorphImages\( MagickWand *wand, const unsigned long number_frames );
wand:
The magick wand.
number_frames:
The number of in-between images to generate.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(number_frames :unsigned-long))
(defcfun ("MagickMosaicImages" %MagickMosaicImages)
%MagickWand
"Inlays an image sequence to form a single coherent picture. It returns a wand with each image in the sequence composited at the location defined by the page offset of the image.
The format of the MagickMosaicImages method is:
MagickWand *MagickMosaicImages\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickMotionBlurImage" %MagickMotionBlurImage)
%magick-status
"Simulates motion blur. We convolve the image with a Gaussian operator of the given radius and standard deviation \(sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and MotionBlurImage\() selects a suitable radius for you. Angle gives the angle of the blurring motion.
The format of the MagickMotionBlurImage method is:
unsigned int MagickMotionBlurImage\( MagickWand *wand, const double radius, const double sigma,
const double angle );
wand:
The magick wand.
radius:
The radius of the Gaussian, in pixels, not counting
the center pixel.
sigma:
The standard deviation of the Gaussian, in pixels.
angle:
Apply the effect along this angle.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double)
(sigma :double)
(angle :double))
(defcfun ("MagickNegateImage" %MagickNegateImage)
%magick-status
"Negates the colors in the reference image. The Grayscale option means that only grayscale values within the image are negated.
You can also reduce the influence of a particular channel with a gamma
value of 0.
The format of the MagickNegateImage method is:
unsigned int MagickNegateImage\( MagickWand *wand, const unsigned int gray );
A description of each parameter follows:
wand:
The magick wand.
gray:
If True, only negate grayscale pixels within the image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(gray :unsigned-int))
(defcfun ("MagickNegateImageChannel" %MagickNegateImageChannel)
%magick-status
"Negates the colors in the specified channel of the reference image. The Grayscale option means that only grayscale values within the image are negated. Note that the Grayscale option has no effect for GraphicsMagick.
You can also reduce the influence of a particular channel with a gamma
value of 0.
The format of the MagickNegateImageChannel method is:
unsigned int MagickNegateImageChannel\( MagickWand *wand, const ChannelType channel,
const unsigned int gray );
wand:
The magick wand.
channel:
Identify which channel to extract: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
BlackChannel.
gray:
If True, only negate grayscale pixels within the image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(gray :unsigned-int))
(defcfun ("MagickNextImage" %MagickNextImage)
%magick-status
"Associates the next image in the image list with a magick wand. True is returned if the Wand iterated to a next image, or False is returned if the wand did not iterate to a next image.
The format of the MagickNextImage method is:
unsigned int MagickNextImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickNormalizeImage" %MagickNormalizeImage)
%magick-status
"Enhances the contrast of a color image by adjusting the pixels color to span the entire range of colors available
You can also reduce the influence of a particular channel with a gamma
value of 0.
The format of the MagickNormalizeImage method is:
unsigned int MagickNormalizeImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickOilPaintImage" %MagickOilPaintImage)
%magick-status
"Applies a special effect filter that simulates an oil painting. Each pixel is replaced by the most frequent color occurring in a circular region defined by radius.
The format of the MagickOilPaintImage method is:
unsigned int MagickOilPaintImage\( MagickWand *wand, const double radius );
A description of each parameter follows:
wand:
The magick wand.
radius:
The radius of the circular neighborhood.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double))
(defcfun ("MagickOpaqueImage" %MagickOpaqueImage)
%magick-status
"Changes any pixel that matches color with the color defined by fill.
The format of the MagickOpaqueImage method is:
unsigned int MagickOpaqueImage\( MagickWand *wand, const PixelWand *target,
const PixelWand *fill, const double fuzz );
wand:
The magick wand.
target:
Change this target color to the fill color within the image.
fill:
The fill pixel wand.
fuzz:
By default target must match a particular pixel color
exactly. However, in many cases two colors may differ by a small amount.
The fuzz member of image defines how much tolerance is acceptable to
consider two colors as the same. For example, set fuzz to 10 and the
color red at intensities of 100 and 102 respectively are now interpreted
as the same color for the purposes of the floodfill.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(target %PixelWand)
(fill %PixelWand)
(fuzz :double))
(defcfun ("MagickOperatorImageChannel" %MagickOperatorImageChannel)
%magick-status
"Performs the requested arithmetic,
bitwise-logical, or value operation on the selected channels of
the entire image. The AllChannels channel option operates on all
color channels whereas the GrayChannel channel option treats the
color channels as a grayscale intensity.
These operations are on the DirectClass pixels of the image and do not
update pixel indexes or colormap.
The format of the MagickOperatorImageChannel method is:
MagickPassFail MagickOperatorImageChannel\( MagickWand *wand,
const ChannelType channel,const QuantumOperator quantum_operator,
const double rvalue )
A description of each parameter follows:
wand: The magick wand.
channel: Channel to operate on \(RedChannel, CyanChannel,
GreenChannel, MagentaChannel, BlueChannel, YellowChannel,
OpacityChannel, BlackChannel, MatteChannel, AllChannels,
GrayChannel). The AllChannels type only updates color
channels. The GrayChannel type treats the color channels
as if they represent an intensity.
quantum_operator: Operator to use \(AddQuantumOp,AndQuantumOp,
AssignQuantumOp, DepthQuantumOp, DivideQuantumOp, GammaQuantumOp,
LShiftQuantumOp, MultiplyQuantumOp, NegateQuantumOp,
NoiseGaussianQuantumOp, NoiseImpulseQuantumOp,
NoiseLaplacianQuantumOp, NoiseMultiplicativeQuantumOp,
NoisePoissonQuantumOp, NoiseRandomQuantumOp, NoiseUniformQuantumOp,
OrQuantumOp, RShiftQuantumOp, SubtractQuantumOp,
ThresholdBlackQuantumOp, ThresholdQuantumOp, ThresholdWhiteQuantumOp,
ThresholdBlackNegateQuantumOp, ThresholdWhiteNegateQuantumOp,
XorQuantumOp).
rvalue: Operator argument.
Since GraphicsMagick v1.3.20"
(wand %MagickWand)
(channel %ChannelType)
(quantum_operator %QuantumOperator) ;; TODO
(rvalue :double))
(defcfun ("MagickPingImage" %MagickPingImage)
%magick-status
"Is like MagickReadImage\() except the only valid information returned is the image width, height, size, and format. It is designed to efficiently obtain this information from a file without reading the entire image sequence into memory.
The format of the MagickPingImage method is:
unsigned int MagickPingImage\( MagickWand *wand, const char *filename );
A description of each parameter follows:
wand:
The magick wand.
filename:
The image filename.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(filename :string))
(defcfun ("MagickPreviewImages" %MagickPreviewImages)
%MagickWand
"Tiles 9 thumbnails of the specified image with an image processing operation applied at varying strengths. This is helpful to quickly pin-point an appropriate parameter for an image processing operation.
The format of the MagickPreviewImages method is:
MagickWand *MagickPreviewImages\( MagickWand *wand, const PreviewType preview );
wand:
The magick wand.
preview:
The preview type.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(preview %PreviewType))
(defcfun ("MagickPreviousImage" %MagickPreviousImage)
%magick-status
"Selects the previous image associated with a magick wand.
The format of the MagickPreviousImage method is:
unsigned int MagickPreviousImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickProfileImage" %MagickProfileImage)
%magick-status
"Use MagickProfileImage\() to add or remove a ICC, IPTC, or generic profile from an image. If the profile is NULL, it is removed from the image otherwise added. Use a name of '*' and a profile of NULL to remove all profiles from the image.
The format of the MagickProfileImage method is:
unsigned int MagickProfileImage\( MagickWand *wand, const char *name,
const unsigned char *profile, const size_t length );
wand:
The magick wand.
name:
Name of profile to add or remove: ICC, IPTC, or generic profile.
profile:
The profile.
length:
The length of the profile.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(name :string)
(profile :pointer)
(length %size_t))
(defcfun ("MagickQuantizeImage" %MagickQuantizeImage)
%magick-status
"Analyzes the colors within a reference image and chooses a fixed number of colors to represent the image. The goal of the algorithm is to minimize the color difference between the input and output image while minimizing the processing time.
The format of the MagickQuantizeImage method is:
unsigned int MagickQuantizeImage\( MagickWand *wand, const unsigned long number_colors,
const ColorspaceType colorspace,
const unsigned long treedepth, const unsigned int dither,
const unsigned int measure_error );
wand:
The magick wand.
number_colors:
The number of colors.
colorspace:
Perform color reduction in this colorspace, typically
RGBColorspace.
treedepth:
Normally, this integer value is zero or one. A zero or
one tells Quantize to choose a optimal tree depth of Log4\(number_colors).% A tree of this depth generally allows the best representation of the
reference image with the least amount of memory and the fastest
computational speed. In some cases, such as an image with low color
dispersion \(a few number of colors), a value other than
Log4\(number_colors) is required. To expand the color tree completely,
use a value of 8.
dither:
A value other than zero distributes the difference between an
original image and the corresponding color reduced algorithm to
neighboring pixels along a Hilbert curve.
measure_error:
A value other than zero measures the difference between
the original and quantized images. This difference is the total
quantization error. The error is computed by summing over all pixels
in an image the distance squared in RGB space between each reference
pixel value and its quantized value.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(number_colors :unsigned-long)
(colorspace %ColorspaceType)
(treedepth :unsigned-long)
(dither :unsigned-int)
(measure_error :unsigned-int))
(defcfun ("MagickQuantizeImages" %MagickQuantizeImages)
%magick-status
"Analyzes the colors within a sequence of images and chooses a fixed number of colors to represent the image. The goal of the algorithm is to minimize the color difference between the input and output image while minimizing the processing time.
The format of the MagickQuantizeImages method is:
unsigned int MagickQuantizeImages\( MagickWand *wand, const unsigned long number_colors,
const ColorspaceType colorspace,
const unsigned long treedepth, const unsigned int dither,
const unsigned int measure_error );
wand:
The magick wand.
number_colors:
The number of colors.
colorspace:
Perform color reduction in this colorspace, typically
RGBColorspace.
treedepth:
Normally, this integer value is zero or one. A zero or
one tells Quantize to choose a optimal tree depth of Log4\(number_colors).% A tree of this depth generally allows the best representation of the
reference image with the least amount of memory and the fastest
computational speed. In some cases, such as an image with low color
dispersion \(a few number of colors), a value other than
Log4\(number_colors) is required. To expand the color tree completely,
use a value of 8.
dither:
A value other than zero distributes the difference between an
original image and the corresponding color reduced algorithm to
neighboring pixels along a Hilbert curve.
measure_error:
A value other than zero measures the difference between
the original and quantized images. This difference is the total
quantization error. The error is computed by summing over all pixels
in an image the distance squared in RGB space between each reference
pixel value and its quantized value.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(number_colors :unsigned-long)
(colorspace %ColorspaceType)
(treedepth :unsigned-long)
(dither :unsigned-int)
(measure_error :unsigned-int))
(defcfun ("MagickQueryFontMetrics" %MagickQueryFontMetrics)
:pointer
"Return a pointer to a double array with 7 elements:
0 character width
1 character height
2 ascender
3 descender
4 text width
5 text height
6 maximum horizontal advance
The format of the MagickQueryFontMetrics method is:
double *MagickQueryFontMetrics\( MagickWand *wand, const DrawingWand *drawing_wand,
const char *text );
wand:
The Magick wand.
drawing_wand:
The drawing wand.
text:
The text.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(drawing_wand %DrawingWand)
(text :string))
(defcfun ("MagickQueryFonts" %MagickQueryFonts)
:pointer
"Returns any font that match the specified pattern.
The format of the MagickQueryFonts function is:
char ** MagickQueryFonts\( const char *pattern, unsigned long *number_fonts );
A description of each parameter follows:
pattern:
Specifies a pointer to a text string containing a pattern.
number_fonts:
This integer returns the number of fonts in the list.
Since GraphicsMagick v1.1.0"
(pattern :string)
(number_fonts :pointer))
(defcfun ("MagickQueryFormats" %MagickQueryFormats)
:pointer
"Returns any image formats that match the specified pattern.
The format of the MagickQueryFormats function is:
char ** MagickQueryFormats\( const char *pattern, unsigned long *number_formats );
pattern:
Specifies a pointer to a text string containing a pattern.
number_formats:
This integer returns the number of image formats in the
list.
Since GraphicsMagick v1.1.0"
(pattern :string)
(number_formats :pointer))
(defcfun ("MagickRadialBlurImage" %MagickRadialBlurImage)
%magick-status
"Radial blurs an image.
The format of the MagickRadialBlurImage method is:
unsigned int MagickRadialBlurImage\( MagickWand *wand, const double angle );
A description of each parameter follows:
wand:
The magick wand.
angle:
The angle of the blur in degrees.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(angle :double))
(defcfun ("MagickRaiseImage" %MagickRaiseImage)
%magick-status
"Creates a simulated three-dimensional button-like effect by lightening and darkening the edges of the image. Members width and height of raise_info define the width of the vertical and horizontal edge of the effect.
The format of the MagickRaiseImage method is:
unsigned int MagickRaiseImage\( MagickWand *wand, const unsigned long width,
const unsigned long height, const long x, const long y,
const unsigned int raise_flag );
wand:
The magick wand.
width,height,x,y:
Define the dimensions of the area to raise.
raise_flag:
A value other than zero creates a 3-D raise effect,
otherwise it has a lowered effect.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(width :unsigned-long)
(height :unsigned-long)
(x :long)
(y :long)
(raise_flag :unsigned-int))
(defcfun ("MagickReadImage" %MagickReadImage)
%magick-status
"Reads an image or image sequence.
The format of the MagickReadImage method is:
unsigned int MagickReadImage\( MagickWand *wand, const char *filename );
A description of each parameter follows:
wand:
The magick wand.
filename:
The image filename.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(filename :string))
(defcfun ("MagickReadImageBlob" %MagickReadImageBlob)
%magick-status
"Reads an image or image sequence from a blob.
The format of the MagickReadImageBlob method is:
unsigned int MagickReadImageBlob\( MagickWand *wand, const unsigned char *blob,
const size_t length );
wand:
The magick wand.
blob:
The blob.
length:
The blob length.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(blob :pointer)
(length %size_t))
(defcfun ("MagickReadImageFile" %MagickReadImageFile)
%magick-status
"Reads an image or image sequence from an open file descriptor.
The format of the MagickReadImageFile method is:
unsigned int MagickReadImageFile\( MagickWand *wand, FILE *file );
A description of each parameter follows:
wand:
The magick wand.
file:
The file descriptor.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(file %FILE))
(defcfun ("MagickReduceNoiseImage" %MagickReduceNoiseImage)
%magick-status
"Smooths the contours of an image while still preserving edge information. The algorithm works by replacing each pixel with its neighbor closest in value. A neighbor is defined by radius. Use a radius of 0 and ReduceNoise\() selects a suitable radius for you.
The format of the MagickReduceNoiseImage method is:
unsigned int MagickReduceNoiseImage\( MagickWand *wand, const double radius );
A description of each parameter follows:
wand:
The magick wand.
radius:
The radius of the pixel neighborhood.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double))
(defcfun ("MagickRelinquishMemory" %MagickRelinquishMemory)
%magick-status
"Relinquishes memory resources returned by such methods as MagickDescribeImage\(), MagickGetException\(), etc.
The format of the MagickRelinquishMemory method is:
unsigned int MagickRelinquishMemory\( void *resource );
A description of each parameter follows:
resource:
Relinquish the memory associated with this resource.
Since GraphicsMagick v1.1.0"
(resource :pointer))
(defcfun ("MagickRemoveImage" %MagickRemoveImage)
%magick-status
"Removes an image from the image list.
The format of the MagickRemoveImage method is:
unsigned int MagickRemoveImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickRemoveImageOption" %MagickRemoveImageOption)
%magick-status
"Removes an image format-specific option from the the image \(.e.g MagickRemoveImageOption(wand,\"jpeg\",\"preserve-settings\").
The format of the MagickRemoveImageOption method is:
unsigned int MagickRemoveImageOption\( MagickWand *wand, const char *format,
const char *key );
wand:
The magick wand.
format:
The image format.
key:
The key.
Since GraphicsMagick v1.3.26"
(wand %MagickWand)
(format :string)
(key :string))
(defcfun ("MagickRemoveImageProfile" %MagickRemoveImageProfile)
:pointer
"Removes the named image profile and returns it.
The format of the MagickRemoveImageProfile method is:
unsigned char *MagickRemoveImageProfile\( MagickWand *wand, const char *name,
unsigned long *length );
wand:
The magick wand.
name:
Name of profile to return: ICC, IPTC, or generic profile.
length:
The length of the profile.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(name :string)
(length :pointer))
(defcfun ("MagickResetIterator" %MagickResetIterator)
:void
"Resets the wand iterator. Use it in conjunction with MagickNextImage\() to iterate over all the images in a wand container.
The format of the MagickReset method is:
void MagickResetIterator\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickResampleImage" %MagickResampleImage)
%magick-status
"Resample image to desired resolution.
Bessel Blackman Box
Catrom Cubic Gaussian
Hanning Hermite Lanczos
Mitchell Point Quandratic
Sinc Triangle
Most of the filters are FIR \(finite impulse response), however, Bessel,
Gaussian, and Sinc are IIR \(infinite impulse response). Bessel and Sinc
are windowed \(brought down to zero) with the Blackman filter.
The format of the MagickResampleImage method is:
unsigned int MagickResampleImage\( MagickWand *wand, const double x_resolution,
const double y_resolution, const FilterTypes filter,
const double blur );
wand:
The magick wand.
x_resolution:
The new image x resolution.
y_resolution:
The new image y resolution.
filter:
Image filter to use.
blur:
The blur factor where > 1 is blurry, < 1 is sharp.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x_resolution :double)
(y_resolution :double)
(filter %FilterTypes)
(blur :double))
(defcfun ("MagickResizeImage" %MagickResizeImage)
%magick-status
"Scales an image to the desired dimensions with one of these filters:
Bessel Blackman Box
Catrom Cubic Gaussian
Hanning Hermite Lanczos
Mitchell Point Quandratic
Sinc Triangle
Most of the filters are FIR \(finite impulse response), however, Bessel,
Gaussian, and Sinc are IIR \(infinite impulse response). Bessel and Sinc
are windowed \(brought down to zero) with the Blackman filter.
The format of the MagickResizeImage method is:
unsigned int MagickResizeImage\( MagickWand *wand, const unsigned long columns,
const unsigned long rows, const FilterTypes filter,
const double blur );
wand:
The magick wand.
columns:
The number of columns in the scaled image.
rows:
The number of rows in the scaled image.
filter:
Image filter to use.
blur:
The blur factor where > 1 is blurry, < 1 is sharp.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(columns :unsigned-long)
(rows :unsigned-long)
(filter %FilterTypes)
(blur %double))
(defcfun ("MagickRollImage" %MagickRollImage)
%magick-status
"Offsets an image as defined by x_offset and y_offset.
The format of the MagickRollImage method is:
unsigned int MagickRollImage\( MagickWand *wand, const long x_offset,
const long y_offset );
wand:
The magick wand.
x_offset:
The x offset.
y_offset:
The y offset.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x_offset :long)
(y_offset :long))
(defcfun ("MagickRotateImage" %MagickRotateImage)
%magick-status
"Rotates an image the specified number of degrees. Empty triangles left over from rotating the image are filled with the background color.
The format of the MagickRotateImage method is:
unsigned int MagickRotateImage\( MagickWand *wand, const PixelWand *background,
const double degrees );
wand:
The magick wand.
background:
The background pixel wand.
degrees:
The number of degrees to rotate the image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(background %PixelWand)
(degrees %double))
(defcfun ("MagickSampleImage" %MagickSampleImage)
%magick-status
"Scales an image to the desired dimensions with pixel sampling. Unlike other scaling methods, this method does not introduce any additional color into the scaled image.
The format of the MagickSampleImage method is:
unsigned int MagickSampleImage\( MagickWand *wand, const unsigned long columns,
const unsigned long rows );
wand:
The magick wand.
columns:
The number of columns in the scaled image.
rows:
The number of rows in the scaled image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(columns :unsigned-long)
(rows :unsigned-long))
(defcfun ("MagickScaleImage" %MagickScaleImage)
%magick-status
"Scales the size of an image to the given dimensions.
The format of the MagickScaleImage method is:
unsigned int MagickScaleImage\( MagickWand *wand, const unsigned long columns,
const unsigned long rows );
wand:
The magick wand.
columns:
The number of columns in the scaled image.
rows:
The number of rows in the scaled image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(columns :unsigned-long)
(rows :unsigned-long))
(defcfun ("MagickSeparateImageChannel" %MagickSeparateImageChannel)
%magick-status
"Separates a channel from the image and returns a grayscale image. A channel is a particular color component of each pixel in the image.
The format of the MagickChannelImage method is:
unsigned int MagickSeparateImageChannel\( MagickWand *wand, const ChannelType channel );
wand:
The magick wand.
channel:
Identify which channel to extract: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
BlackChannel.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType))
(defcfun ("MagickSetCompressionQuality" %MagickSetCompressionQuality)
%magick-status
"Sets the image quality factor, which determines compression options when saving the file.
For the JPEG and MPEG image formats, quality is 0 \(lowest image
quality and highest compression) to 100 \(best quality but least
effective compression). The default quality is 75. Use the
-sampling-factor option to specify the factors for chroma
downsampling. To use the same quality value as that found by the
JPEG decoder, use the -define jpeg:preserve-settings flag.
For the MIFF image format, and the TIFF format while using ZIP
compression, quality/10 is the zlib compres- sion level, which is 0
\(worst but fastest compression) to 9 \(best but slowest). It has no
effect on the image appearance, since the compression is always
lossless.
For the JPEG-2000 image format, quality is mapped using a non-linear
equation to the compression ratio required by the Jasper library.
This non-linear equation is intended to loosely approximate the
quality provided by the JPEG v1 format. The default quality value 75
results in a request for 16:1 compression. The quality value 100
results in a request for non-lossy compres- sion.
For the MNG and PNG image formats, the quality value sets the zlib
compression level \(quality / 10) and filter-type \(quality % 10).
Compression levels range from 0 \(fastest compression) to 100 \(best
but slowest). For compression level 0, the Huffman-only strategy is
used, which is fastest but not necessarily the worst compression. If
filter-type is 4 or less, the specified filter-type is used for all
scanlines:
none
sub
up
average
Paeth
If filter-type is 5, adaptive filtering is used when quality is
greater than 50 and the image does not have a color map, otherwise no
filtering is used.
If filter-type is 6, adaptive filtering with minimum-
sum-of-absolute-values is used.
Only if the output is MNG, if filter-type is 7, the LOCO color
transformation and adaptive filtering with
minimum-sum-of-absolute-values are used.
The default is quality is 75, which means nearly the best compression
with adaptive filtering. The quality setting has no effect on the
appearance of PNG and MNG images, since the compression is always
lossless.
For further information, see the PNG specification.
When writing a JNG image with transparency, two quality values are
required, one for the main image and one for the grayscale image that
conveys the opacity channel. These are written as a single integer
equal to the main image quality plus 1000 times the opacity quality.
For example, if you want to use quality 75 for the main image and
quality 90 to compress the opacity data, use -quality 90075.
For the PNM family of formats \(PNM, PGM, and PPM) specify a quality
factor of zero in order to obtain the ASCII variant of the
format. Note that -compress none used to be used to trigger ASCII
output but provided the opposite result of what was expected as
compared with other formats.
The format of the MagickSetCompressionQuality method is:
unsigned int MagickSetCompressionQuality\( MagickWand *wand, const unsigned long quality );
wand:
The magick wand.
delay:
The image quality.
Since GraphicsMagick v1.3.7"
(wand %MagickWand)
(quality :unsigned-long))
(defcfun ("MagickSetDepth" %MagickSetDepth)
%magick-status
"Sets the sample depth to be used when reading from a raw image or a format which requires that the depth be specified in advance by the user.
The format of the MagickSetDepth method is:
unsigned int MagickSetDepth\( MagickWand *wand, const size_t depth );
A description of each parameter follows:
wand:
The magick wand.
depth:
The sample depth.
Since GraphicsMagick v1.3.13"
(wand %MagickWand)
(depth %size_t))
(defcfun ("MagickSetFilename" %MagickSetFilename)
%magick-status
"Sets the filename before you read or write an image file.
The format of the MagickSetFilename method is:
unsigned int MagickSetFilename\( MagickWand *wand, const char *filename );
A description of each parameter follows:
wand:
The magick wand.
filename:
The image filename.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(filename :string))
(defcfun ("MagickSetFormat" %MagickSetFormat)
%magick-status
"Sets the file or blob format \(e.g. \"BMP\") to be used when a file or blob is read. Usually this is not necessary because GraphicsMagick is able to auto-detect the format based on the file header \(or the file extension), but some formats do not use a unique header or the selection may be ambigious. Use MagickSetImageFormat\() to set the format to be used when a file or blob is to be written.
The format of the MagickSetFormat method is:
unsigned int MagickSetFormat\( MagickWand *wand, const char *format );
A description of each parameter follows:
wand:
The magick wand.
filename:
The file or blob format.
Since GraphicsMagick v1.3.13"
(wand %MagickWand)
(format :string))
(defcfun ("MagickSetImage" %MagickSetImage)
%magick-status
"Replaces the last image returned by MagickSetImageIndex\(), MagickNextImage\(), MagickPreviousImage\() with the images from the specified wand.
The format of the MagickSetImage method is:
unsigned int MagickSetImage\( MagickWand *wand, const MagickWand *set_wand );
A description of each parameter follows:
wand:
The magick wand.
set_wand:
The set_wand wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(set_wand %MagickWand))
(defcfun ("MagickSetImageAttribute" %MagickSetImageAttribute)
%magick-status
"MagickSetImageAttribute sets an image attribute
The format of the MagickSetImageAttribute method is:
unsigned int MagickSetImageAttribute\( MagickWand *wand, const char *name,
const char *value );
A description of each parameter follows:
wand:
The magick wand.
name:
The name of the attribute
value:
The value of the attribute
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(name :string)
(value :string))
(defcfun ("MagickSetImageBackgroundColor" %MagickSetImageBackgroundColor)
%magick-status
"Sets the image background color.
The format of the MagickSetImageBackgroundColor method is:
unsigned int MagickSetImageBackgroundColor\( MagickWand *wand, const PixelWand *background );
wand:
The magick wand.
background:
The background pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(background %PixelWand))
(defcfun ("MagickSetImageBluePrimary" %MagickSetImageBluePrimary)
%magick-status
"Sets the image chromaticity blue primary point.
The format of the MagickSetImageBluePrimary method is:
unsigned int MagickSetImageBluePrimary\( MagickWand *wand, const double x, const double y );
wand:
The magick wand.
x:
The blue primary x-point.
y:
The blue primary y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x :double)
(y :double))
(defcfun ("MagickSetImageBorderColor" %MagickSetImageBorderColor)
%magick-status
"Sets the image border color.
The format of the MagickSetImageBorderColor method is:
unsigned int MagickSetImageBorderColor\( MagickWand *wand, const PixelWand *border );
wand:
The magick wand.
border:
The border pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(border %PixelWand))
(defcfun ("MagickSetImageColormapColor" %MagickSetImageColormapColor)
%magick-status
"Sets the color of the specified colormap index.
The format of the MagickSetImageColormapColor method is:
unsigned int MagickSetImageColormapColor\( MagickWand *wand, const unsigned long index,
const PixelWand *color );
wand:
The magick wand.
index:
The offset into the image colormap.
color:
Return the colormap color in this wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(index :unsigned-long)
(color %PixelWand))
(defcfun ("MagickSetImageColorspace" %MagickSetImageColorspace)
%magick-status
"Sets the image colorspace.
The format of the MagickSetImageColorspace method is:
unsigned int MagickSetImageColorspace\( MagickWand *wand, const ColorspaceType colorspace );
wand:
The magick wand.
colorspace:
The image colorspace: UndefinedColorspace, RGBColorspace,
GRAYColorspace, TransparentColorspace, OHTAColorspace, XYZColorspace,
YCbCrColorspace, YCCColorspace, YIQColorspace, YPbPrColorspace,
YPbPrColorspace, YUVColorspace, CMYKColorspace, sRGBColorspace,
HSLColorspace, or HWBColorspace.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(colorspace %ColorspaceType))
(defcfun ("MagickSetImageCompose" %MagickSetImageCompose)
%magick-status
"Sets the image composite operator, useful for specifying how to composite the image thumbnail when using the MagickMontageImage\() method.
The format of the MagickSetImageCompose method is:
unsigned int MagickSetImageCompose\( MagickWand *wand, const CompositeOperator compose );
wand:
The magick wand.
compose:
The image composite operator.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(compose %CompositeOperator))
(defcfun ("MagickSetImageCompression" %MagickSetImageCompression)
%magick-status
"Sets the image compression.
The format of the MagickSetImageCompression method is:
unsigned int MagickSetImageCompression\( MagickWand *wand,
const CompressionType compression );
wand:
The magick wand.
compression:
The image compression type.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(compression %CompressionType))
(defcfun ("MagickSetImageDelay" %MagickSetImageDelay)
%magick-status
"Sets the image delay.
The format of the MagickSetImageDelay method is:
unsigned int MagickSetImageDelay\( MagickWand *wand, const unsigned long delay );
wand:
The magick wand.
delay:
The image delay in 1/100th of a second.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(delay :unsigned-long))
(defcfun ("MagickSetImageChannelDepth" %MagickSetImageChannelDepth)
%magick-status
"Sets the depth of a particular image channel.
The format of the MagickSetImageChannelDepth method is:
unsigned int MagickSetImageChannelDepth\( MagickWand *wand, const ChannelType channel,
const unsigned long depth );
wand:
The magick wand.
channel:
Identify which channel to extract: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
BlackChannel.
depth:
The image depth in bits.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(depth :unsigned-long))
(defcfun ("MagickSetImageDepth" %MagickSetImageDepth)
%magick-status
"Sets the image depth.
The format of the MagickSetImageDepth method is:
unsigned int MagickSetImageDepth\( MagickWand *wand, const unsigned long depth );
wand:
The magick wand.
depth:
The image depth in bits: 8, 16, or 32.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(depth :unsigned-long))
(defcfun ("MagickSetImageDispose" %MagickSetImageDispose)
%magick-status
"Sets the image disposal method.
The format of the MagickSetImageDispose method is:
unsigned int MagickSetImageDispose\( MagickWand *wand, const DisposeType dispose );
wand:
The magick wand.
dispose:
The image disposeal type.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(dispose %DisposeType))
(defcfun ("MagickSetImageFilename" %MagickSetImageFilename)
%magick-status
"Sets the filename of a particular image in a sequence.
The format of the MagickSetImageFilename method is:
unsigned int MagickSetImageFilename\( MagickWand *wand, const char *filename );
wand:
The magick wand.
filename:
The image filename.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(filename :string))
(defcfun ("MagickSetImageFormat" %MagickSetImageFormat)
%magick-status
"Sets the format of a particular image in a sequence. The format is designated by a magick string \(e.g. \"GIF\").
The format of the MagickSetImageFormat method is:
unsigned int MagickSetImageFormat\( MagickWand *wand, const char *format );
wand:
The magick wand.
magick:
The image format.
Since GraphicsMagick v1.3.1"
(wand %MagickWand)
(format :string))
(defcfun ("MagickSetImageFuzz" %MagickSetImageFuzz)
%magick-status
"Sets the color comparison fuzz factor. Colors closer than the fuzz factor are considered to be the same when comparing colors. Note that some other functions such as MagickColorFloodfillImage\() implicitly set this value.
The format of the MagickSetImageFuzz method is:
unsigned int MagickSetImageFuzz\( MagickWand *wand, const double fuzz );
A description of each parameter follows:
wand:
The magick wand.
fuzz:
The color comparison fuzz factor
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(fuzz :double))
(defcfun ("MagickSetImageGamma" %MagickSetImageGamma)
%magick-status
"Sets the image gamma.
The format of the MagickSetImageGamma method is:
unsigned int MagickSetImageGamma\( MagickWand *wand, const double gamma );
A description of each parameter follows:
wand:
The magick wand.
gamma:
The image gamma.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(gamma :double))
(defcfun ("MagickSetImageGeometry" %MagickSetImageGeometry)
%magick-status
"Sets the image geometry string.
The format of the MagickSetImageGeometry method is:
unsigned int MagickSetImageGeometry\( MagickWand *wand, const char *geometry )
A description of each parameter follows:
wand: The magick wand.
geometry: The image geometry.
Since GraphicsMagick v1.3.20"
(wand %MagickWand)
(geometry :string))
(defcfun ("MagickSetImageGravity" %MagickSetImageGravity)
%magick-status
"Sets the image gravity. This is used when evaluating regions defined by a geometry and the image dimensions. It may be used in conjunction with operations which use a geometry parameter to adjust the x, y parameters of the final operation. Gravity is used in composition to determine where the image should be placed within the defined geometry region. It may be used with montage to effect placement of the image within the tile.
The format of the MagickSetImageGravity method is:
unsigned int MagickSetImageGravity\( MagickWand *wand, const GravityType );
A description of each parameter follows:
wand:
The magick wand.
gravity:
The image gravity. Available values are ForgetGravity,
NorthWestGravity, NorthGravity, NorthEastGravity, WestGravity,
CenterGravity, EastGravity, SouthWestGravity, SouthGravity,
SouthEastGravity, and StaticGravity
Since GraphicsMagick v1.3.20"
(wand %MagickWand)
(gravitytype %GravityType))
(defcfun ("MagickSetImageGreenPrimary" %MagickSetImageGreenPrimary)
%magick-status
"Sets the image chromaticity green primary point.
The format of the MagickSetImageGreenPrimary method is:
unsigned int MagickSetImageGreenPrimary\( MagickWand *wand, const double x, const double y );
wand:
The magick wand.
x:
The green primary x-point.
y:
The green primary y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x %double)
(y %double))
(defcfun ("MagickSetImageIndex" %MagickSetImageIndex)
%magick-status
"Set the current image to the position of the list specified with the index parameter.
The format of the MagickSetImageIndex method is:
unsigned int MagickSetImageIndex\( MagickWand *wand, const long index );
A description of each parameter follows:
wand:
The magick wand.
index:
The scene number.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(index :long))
(defcfun ("MagickSetImageInterlaceScheme" %MagickSetImageInterlaceScheme)
%magick-status
"Sets the image interlace scheme. Please use SetInterlaceScheme\() instead to change the interlace scheme used when writing the image.
The format of the MagickSetImageInterlaceScheme method is:
unsigned int MagickSetImageInterlaceScheme\( MagickWand *wand,
const InterlaceType interlace_scheme );
wand:
The magick wand.
interlace_scheme:
The image interlace scheme: NoInterlace, LineInterlace,
PlaneInterlace, PartitionInterlace.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(interlace_scheme %InterlaceType))
(defcfun ("MagickSetImageIterations" %MagickSetImageIterations)
%magick-status
"Sets the image iterations.
The format of the MagickSetImageIterations method is:
unsigned int MagickSetImageIterations\( MagickWand *wand, const unsigned long iterations );
wand:
The magick wand.
delay:
The image delay in 1/100th of a second.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(iterations :unsigned-long))
(defcfun ("MagickSetImageMatte" %MagickSetImageMatte)
%magick-status
"Sets the image matte flag. The image opacity \(inverse of transparency) channel is enabled if the matte flag is True.
The format of the MagickSetImageMatte method is:
unsigned int MagickSetImageMatte\( MagickWand *wand, const unsigned int matte )
A description of each parameter follows:
wand:
The magick wand.
matte:
The image matte.
Since GraphicsMagick v1.3.20"
(wand %MagickWand)
(matte :unsigned-int))
(defcfun ("MagickSetImageMatteColor" %MagickSetImageMatteColor)
%magick-status
"Sets the image matte color.
The format of the MagickSetImageMatteColor method is:
unsigned int MagickSetImageMatteColor\( MagickWand *wand, const PixelWand *matte );
wand:
The magick wand.
matte:
The matte pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(matte %PixelWand))
(defcfun ("MagickSetImageOption" %MagickSetImageOption)
%magick-status
"Associates one or options with a particular image format \(.e.g MagickSetImageOption\(wand,\"jpeg\",\"preserve-settings\",\"true\").
The format of the MagickSetImageOption method is:
unsigned int MagickSetImageOption\( MagickWand *wand, const char *format, const char *key,
const char *value );
wand:
The magick wand.
format:
The image format.
key:
The key.
value:
The value.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(format :string)
(key :string)
(value :string))
(defcfun ("MagickSetImageOrientation" %MagickSetImageOrientation)
%magick-status
"Sets the internal image orientation type.
The EXIF orientation tag will be updated if present.
The format of the MagickSetImageOrientation method is:
MagickSetImageOrientation\( MagickWand *wand, OrientationType new_orientation )
A description of each parameter follows:
wand:
The magick wand.
new_orientation:
The new orientation of the image. One of:
UndefinedOrientation Image orientation not specified.
TopLeftOrientation Left to right and Top to bottom.
TopRightOrientation Right to left and Top to bottom.
BottomRightOrientation Right to left and Bottom to top.
BottomLeftOrientation Left to right and Bottom to top.
LeftTopOrientation Top to bottom and Left to right.
RightTopOrientation Top to bottom and Right to left.
RightBottomOrientation Bottom to top and Right to left.
LeftBottomOrientation Bottom to top and Left to right.
Returns True on success, False otherwise.
Since GraphicsMagick v1.3.26"
(wand %MagickWand)
(new_orientation %OrientationType))
(defcfun ("MagickSetImagePage" %MagickSetImagePage)
%magick-status
"Sets the image page size and offset used when placing \(e.g. compositing) the image. Pass all zeros for the default placement.
The format of the MagickSetImagePage method is:
unsigned int MagickSetImagePage\( MagickWand *wand, const unsigned long width,
const unsigned long height, const long x, const long y );
wand:
The magick wand.
width, height:
The region size.
x, y:
Offset \(from top left) on base canvas image on
which to composite image data.
Since GraphicsMagick v1.3.18"
(wand %MagickWand)
(width :unsigned-long)
(height :unsigned-long)
(x :long)
(y :long))
(defcfun ("MagickSetImagePixels" %MagickSetImagePixels)
%magick-status
"Accepts pixel data and stores it in the image at the location you specify. The method returns False on success otherwise True if an error is encountered. The pixel data can be either char, short int, int, long, float, or double in the order specified by map.
Suppose your want want to upload the first scanline of a 640x480 image from
character data in red-green-blue order:
MagickSetImagePixels\(wand,0,0,0,640,1,\"RGB\",CharPixel,pixels);
The format of the MagickSetImagePixels method is:
unsigned int MagickSetImagePixels\( MagickWand *wand, const long x_offset, const long y_offset,
const unsigned long columns, const unsigned long rows,
const char *map, const StorageType storage,
unsigned char *pixels );
wand:
The magick wand.
x_offset, y_offset:
Offset \(from top left) on base canvas image on
which to composite image data.
columns, rows:
Dimensions of image.
map:
This string reflects the expected ordering of the pixel array.
It can be any combination or order of R = red, G = green, B = blue,
A = alpha \(same as Transparency), O = Opacity, T = Transparency,
C = cyan, Y = yellow, M = magenta, K = black, or I = intensity
\(for grayscale). Specify \"P\" = pad, to skip over a quantum which is
intentionally ignored. Creation of an alpha channel for CMYK images
is currently not supported.
storage:
Define the data type of the pixels. Float and double types are
expected to be normalized [0..1] otherwise [0..MaxRGB]. Choose from
these types: CharPixel, ShortPixel, IntegerPixel, LongPixel, FloatPixel,
or DoublePixel.
pixels:
This array of values contain the pixel components as defined by
map and type. You must preallocate this array where the expected
length varies depending on the values of width, height, map, and type.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x_offset :long)
(y_offset :long)
(columns :unsigned-long)
(rows :unsigned-long)
(map :string)
(storage %StorageType)
(pixels :pointer))
(defcfun ("MagickSetImageProfile" %MagickSetImageProfile)
%magick-status
"Adds a named profile to the magick wand. If a profile with the same name already exists, it is replaced. This method differs from the MagickProfileImage\() method in that it does not apply any CMS color profiles.
The format of the MagickSetImageProfile method is:
unsigned int MagickSetImageProfile\( MagickWand *wand, const char *name,
const unsigned char *profile,
const unsigned long length );
wand:
The magick wand.
name:
Name of profile to add or remove: ICC, IPTC, or generic profile.
profile:
The profile.
length:
The length of the profile.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(name :string)
(profile :pointer)
(length :unsigned-long))
(defcfun ("MagickSetImageRedPrimary" %MagickSetImageRedPrimary)
%magick-status
"Sets the image chromaticity red primary point.
The format of the MagickSetImageRedPrimary method is:
unsigned int MagickSetImageRedPrimary\( MagickWand *wand, const double x, const double y );
wand:
The magick wand.
x:
The red primary x-point.
y:
The red primary y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x %double)
(y %double))
(defcfun ("MagickSetImageRenderingIntent" %MagickSetImageRenderingIntent)
%magick-status
"Sets the image rendering intent.
The format of the MagickSetImageRenderingIntent method is:
unsigned int MagickSetImageRenderingIntent\( MagickWand *wand,
const RenderingIntent rendering_intent );
wand:
The magick wand.
rendering_intent:
The image rendering intent: UndefinedIntent,
SaturationIntent, PerceptualIntent, AbsoluteIntent, or RelativeIntent.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(rendering_intent %RenderingIntent))
(defcfun ("MagickSetImageResolution" %MagickSetImageResolution)
%magick-status
"Sets the image resolution.
The format of the MagickSetImageResolution method is:
unsigned int MagickSetImageResolution\( MagickWand *wand, const double x_resolution,
const doubtl y_resolution );
wand:
The magick wand.
x_resolution:
The image x resolution.
y_resolution:
The image y resolution.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x_resolution %double)
(y_resolution %double))
(defcfun ("MagickSetImageScene" %MagickSetImageScene)
%magick-status
"Sets the image scene.
The format of the MagickSetImageScene method is:
unsigned int MagickSetImageScene\( MagickWand *wand, const unsigned long scene );
wand:
The magick wand.
delay:
The image scene number.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(scene :unsigned-long))
(defcfun ("MagickSetImageType" %MagickSetImageType)
%magick-status
"Sets the image type.
The format of the MagickSetImageType method is:
unsigned int MagickSetImageType\( MagickWand *wand, const ImageType image_type );
wand:
The magick wand.
image_type:
The image type: UndefinedType, BilevelType, GrayscaleType,
GrayscaleMatteType, PaletteType, PaletteMatteType, TrueColorType,
TrueColorMatteType, ColorSeparationType, ColorSeparationMatteType,
or OptimizeType.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(image_type %ImageType))
(defcfun ("MagickSetImageSavedType" %MagickSetImageSavedType)
%magick-status
"Sets the image type that will be used when the image is saved.
The format of the MagickSetImageSavedType method is:
unsigned int MagickSetImageSavedType\( MagickWand *wand, const ImageType image_type );
wand:
The magick wand.
image_type:
The image type: UndefinedType, BilevelType, GrayscaleType,
GrayscaleMatteType, PaletteType, PaletteMatteType, TrueColorType,
TrueColorMatteType, ColorSeparationType, ColorSeparationMatteType,
or OptimizeType.
Since GraphicsMagick v1.3.13"
(wand %MagickWand)
(image_type %ImageType))
(defcfun ("MagickSetImageUnits" %MagickSetImageUnits)
%magick-status
"Sets the image units of resolution.
The format of the MagickSetImageUnits method is:
unsigned int MagickSetImageUnits\( MagickWand *wand, const ResolutionType units );
wand:
The magick wand.
units:
The image units of resolution : Undefinedresolution,
PixelsPerInchResolution, or PixelsPerCentimeterResolution.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(units %ResolutionType))
(defcfun ("MagickSetImageVirtualPixelMethod" %MagickSetImageVirtualPixelMethod)
%magick-status
"Sets the image virtual pixel method.
The format of the MagickSetImageVirtualPixelMethod method is:
unsigned int MagickSetImageVirtualPixelMethod\( MagickWand *wand,
const VirtualPixelMethod method );
wand:
The magick wand.
method:
The image virtual pixel method : UndefinedVirtualPixelMethod,
ConstantVirtualPixelMethod, EdgeVirtualPixelMethod,
MirrorVirtualPixelMethod, or TileVirtualPixelMethod.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(method %VirtualPixelMethod))
(defcfun ("MagickSetInterlaceScheme" %MagickSetInterlaceScheme)
%magick-status
"Sets the interlace scheme used when writing the image.
The format of the MagickSetInterlaceScheme method is:
unsigned int MagickSetInterlaceScheme\( MagickWand *wand,
const InterlaceType interlace_scheme );
wand:
The magick wand.
interlace_scheme:
The image interlace scheme: NoInterlace, LineInterlace,
PlaneInterlace, PartitionInterlace.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(interlace_scheme %InterlaceType))
(defcfun ("MagickSetResolution" %MagickSetResolution)
%magick-status
"Sets the resolution \(density) of the magick wand. Set it before you read an EPS, PDF, or Postscript file in order to influence the size of the returned image, or after an image has already been created to influence the rendered image size when used with typesetting software.
Also see MagickSetResolutionUnits\() which specifies the units to use for
the image resolution.
The format of the MagickSetResolution method is:
unsigned int MagickSetResolution\( MagickWand *wand, const double x_resolution,
const double y_resolution );
wand:
The magick wand.
x_resolution:
The horizontal resolution
y_resolution:
The vertical reesolution
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(x_resolution %double)
(y_resolution %double))
(defcfun ("MagickSetResolutionUnits" %MagickSetResolutionUnits)
%magick-status
"Sets the resolution units of the magick wand. It should be used in conjunction with MagickSetResolution\(). This method works both before and after an image has been read.
Also see MagickSetImageUnits\() which specifies the units which apply to
the image resolution setting after an image has been read.
The format of the MagickSetResolutionUnits method is:
unsigned int MagickSetResolutionUnits\( MagickWand *wand, const ResolutionType units );
wand:
The magick wand.
units:
The image units of resolution : Undefinedresolution,
PixelsPerInchResolution, or PixelsPerCentimeterResolution.
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(units %ResolutionType))
(defcfun ("MagickSetResourceLimit" %MagickSetResourceLimit)
%magick-status
"Sets the limit for a particular resource in megabytes.
The format of the MagickSetResourceLimit method is:
unsigned int MagickSetResourceLimit\( const ResourceType type, const unsigned long *limit );
type:
The type of resource: DiskResource, FileResource, MapResource,
MemoryResource, PixelsResource, ThreadsResource, WidthResource,
HeightResource.
o The maximum limit for the resource.
Since GraphicsMagick v1.1.0"
(type %ResourceType)
(limit :pointer))
(defcfun ("MagickSetSamplingFactors" %MagickSetSamplingFactors)
%magick-status
"Sets the image sampling factors.
The format of the MagickSetSamplingFactors method is:
unsigned int MagickSetSamplingFactors\( MagickWand *wand, const unsigned long number_factors,
const double *sampling_factors );
wand:
The magick wand.
number_factoes:
The number of factors.
sampling_factors:
An array of doubles representing the sampling factor
for each color component \(in RGB order).
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(number_factors :unsigned-long)
(sampling_factors :pointer))
(defcfun ("MagickSetSize" %MagickSetSize)
%magick-status
"Sets the size of the magick wand. Set it before you read a raw image format such as RGB, GRAY, or CMYK.
The format of the MagickSetSize method is:
unsigned int MagickSetSize\( MagickWand *wand, const unsigned long columns,
const unsigned long rows );
wand:
The magick wand.
columns:
The width in pixels.
height:
The height in pixels.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(columns :unsigned-long)
(rows :unsigned-long))
(defcfun ("MagickSetImageWhitePoint" %MagickSetImageWhitePoint)
%magick-status
"Sets the image chromaticity white point.
The format of the MagickSetImageWhitePoint method is:
unsigned int MagickSetImageWhitePoint\( MagickWand *wand, const double x, const double y );
wand:
The magick wand.
x:
The white x-point.
y:
The white y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x %double)
(y %double))
(defcfun ("MagickSetPassphrase" %MagickSetPassphrase)
%magick-status
"Sets the passphrase.
The format of the MagickSetPassphrase method is:
unsigned int MagickSetPassphrase\( MagickWand *wand, const char *passphrase );
A description of each parameter follows:
wand:
The magick wand.
passphrase:
The passphrase.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(passphrase :string))
(defcfun ("MagickSharpenImage" %MagickSharpenImage)
%magick-status
"Sharpens an image. We convolve the image with a Gaussian operator of the given radius and standard deviation \(sigma). For reasonable results, the radius should be larger than sigma. Use a radius of 0 and SharpenImage\() selects a suitable radius for you.
The format of the MagickSharpenImage method is:
unsigned int MagickSharpenImage\( MagickWand *wand, const double radius, const double sigma );
wand:
The magick wand.
radius:
The radius of the Gaussian, in pixels, not counting the center
pixel.
sigma:
The standard deviation of the Gaussian, in pixels.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius %double)
(sigma %double))
(defcfun ("MagickShaveImage" %MagickShaveImage)
%magick-status
"Shaves pixels from the image edges. It allocates the memory necessary for the new Image structure and returns a pointer to the new image.
The format of the MagickShaveImage method is:
unsigned int MagickShaveImage\( MagickWand *wand, const unsigned long columns,
const unsigned long rows );
wand:
The magick wand.
columns:
The number of columns in the scaled image.
rows:
The number of rows in the scaled image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(columns :unsigned-long)
(rows :unsigned-long))
(defcfun ("MagickShearImage" %MagickShearImage)
%magick-status
"Slides one edge of an image along the X or Y axis, creating a parallelogram. An X direction shear slides an edge along the X axis, while a Y direction shear slides an edge along the Y axis. The amount of the shear is controlled by a shear angle. For X direction shears, x_shear is measured relative to the Y axis, and similarly, for Y direction shears y_shear is measured relative to the X axis. Empty triangles left over from shearing the image are filled with the background color.
The format of the MagickShearImage method is:
unsigned int MagickShearImage\( MagickWand *wand, const PixelWand *background,
const double x_shear, onst double y_shear );
wand:
The magick wand.
background:
The background pixel wand.
x_shear:
The number of degrees to shear the image.
y_shear:
The number of degrees to shear the image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(background %PixelWand)
(x_shear %double)
(y_shear %double))
(defcfun ("MagickSolarizeImage" %MagickSolarizeImage)
%magick-status
"Applies a special effect to the image, similar to the effect achieved in a photo darkroom by selectively exposing areas of photo sensitive paper to light. Threshold ranges from 0 to MaxRGB and is a measure of the extent of the solarization.
The format of the MagickSolarizeImage method is:
unsigned int MagickSolarizeImage\( MagickWand *wand, const double threshold );
A description of each parameter follows:
wand:
The magick wand.
threshold:
Define the extent of the solarization.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(threshold %double))
(defcfun ("MagickSpreadImage" %MagickSpreadImage)
%magick-status
"Is a special effects method that randomly displaces each pixel in a block defined by the radius parameter.
The format of the MagickSpreadImage method is:
unsigned int MagickSpreadImage\( MagickWand *wand, const double radius );
A description of each parameter follows:
wand:
The magick wand.
radius:
Choose a random pixel in a neighborhood of this extent.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius %double))
(defcfun ("MagickSteganoImage" %MagickSteganoImage)
%MagickWand
"Use MagickSteganoImage\() to hide a digital watermark within the image. Recover the hidden watermark later to prove that the authenticity of an image. Offset defines the start position within the image to hide the watermark.
The format of the MagickSteganoImage method is:
MagickWand *MagickSteganoImage\( MagickWand *wand, const MagickWand *watermark_wand,
const long offset );
wand:
The magick wand.
watermark_wand:
The watermark wand.
offset:
Start hiding at this offset into the image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(watermark_wand %MagickWand)
(offset :long))
(defcfun ("MagickStereoImage" %MagickStereoImage)
%MagickWand
"Composites two images and produces a single image that is the composite of a left and right image of a stereo pair
The format of the MagickStereoImage method is:
MagickWand *MagickStereoImage\( MagickWand *wand, const MagickWand *offset_wand );
wand:
The magick wand.
offset_wand:
Another image wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(offset_wand %MagickWand))
(defcfun ("MagickStripImage" %MagickStripImage)
%magick-status
"Removes all profiles and text attributes from the image.
The format of the MagickStripImage method is:
unsigned int MagickStripImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickSwirlImage" %MagickSwirlImage)
%magick-status
"Swirls the pixels about the center of the image, where degrees indicates the sweep of the arc through which each pixel is moved. You get a more dramatic effect as the degrees move from 1 to 360.
The format of the MagickSwirlImage method is:
unsigned int MagickSwirlImage\( MagickWand *wand, const double degrees );
A description of each parameter follows:
wand:
The magick wand.
degrees:
Define the tightness of the swirling effect.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(degrees %double))
(defcfun ("MagickTextureImage" %MagickTextureImage)
%MagickWand
"Repeatedly tiles the texture image across and down the image canvas.
The format of the MagickTextureImage method is:
MagickWand *MagickTextureImage\( MagickWand *wand, const MagickWand *texture_wand );
wand:
The magick wand.
texture_wand:
The texture wand
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(texture_wand %MagickWand))
(defcfun ("MagickThresholdImage" %MagickThresholdImage)
%magick-status
"Changes the value of individual pixels based on the intensity of each pixel compared to threshold. The result is a high-contrast, two color image.
The format of the MagickThresholdImage method is:
unsigned int MagickThresholdImage\( MagickWand *wand, const double threshold );
wand:
The magick wand.
threshold:
Define the threshold value.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(threshold %double))
(defcfun ("MagickThresholdImageChannel" %MagickThresholdImageChannel)
%magick-status
"Changes the value of individual pixel component based on the intensity of each pixel compared to threshold. The result is a high-contrast, two color image.
The format of the MagickThresholdImage method is:
unsigned int MagickThresholdImageChannel\( MagickWand *wand, const ChannelType channel,
const double threshold );
wand:
The magick wand.
channel:
The channel.
threshold:
Define the threshold value.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(threshold %double))
(defcfun ("MagickTintImage" %MagickTintImage)
%magick-status
"Applies a color vector to each pixel in the image. The length of the vector is 0 for black and white and at its maximum for the midtones. The vector weighting function is f\(x)=\(1-\(4.0*\(\(x-0.5)*\(x-0.5)))).
The format of the MagickTintImage method is:
unsigned int MagickTintImage\( MagickWand *wand, const PixelWand *tint,
const PixelWand *opacity );
wand:
The magick wand.
tint:
The tint pixel wand.
opacity:
The opacity pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(tint %PixelWand)
(opacity %PixelWand))
(defcfun ("MagickTransformImage" %MagickTransformImage)
%MagickWand
"Is a convenience method that behaves like MagickResizeImage\() or MagickCropImage\() but accepts scaling and/or cropping information as a region geometry specification. If the operation fails, the original image handle is returned.
The format of the MagickTransformImage method is:
MagickWand *MagickTransformImage\( MagickWand *wand, const char *crop,
const char *geometry );
wand:
The magick wand.
crop:
A crop geometry string. This geometry defines a subregion of the
image to crop.
geometry:
An image geometry string. This geometry defines the final
size of the image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(crop :string)
(geometry :string))
(defcfun ("MagickTransparentImage" %MagickTransparentImage)
%magick-status
"Changes any pixel that matches color with the color defined by fill.
The format of the MagickTransparentImage method is:
unsigned int MagickTransparentImage\( MagickWand *wand, const PixelWand *target,
const unsigned int opacity, const double fuzz );
wand:
The magick wand.
target:
Change this target color to specified opacity value within
the image.
opacity:
The replacement opacity value.
fuzz:
By default target must match a particular pixel color
exactly. However, in many cases two colors may differ by a small amount.
The fuzz member of image defines how much tolerance is acceptable to
consider two colors as the same. For example, set fuzz to 10 and the
color red at intensities of 100 and 102 respectively are now interpreted
as the same color for the purposes of the floodfill.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(target %PixelWand)
(opacity :unsigned-int)
(fuzz %double))
(defcfun ("MagickTrimImage" %MagickTrimImage)
%magick-status
"Remove edges that are the background color from the image.
The format of the MagickTrimImage method is:
unsigned int MagickTrimImage\( MagickWand *wand, const double fuzz );
A description of each parameter follows:
wand:
The magick wand.
fuzz:
By default target must match a particular pixel color
exactly. However, in many cases two colors may differ by a small amount.
The fuzz member of image defines how much tolerance is acceptable to
consider two colors as the same. For example, set fuzz to 10 and the
color red at intensities of 100 and 102 respectively are now interpreted
as the same color for the purposes of the floodfill.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(fuzz %double))
(defcfun ("MagickUnsharpMaskImage" %MagickUnsharpMaskImage)
%magick-status
"Sharpens an image. We convolve the image with a Gaussian operator of the given radius and standard deviation \(sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and UnsharpMaskImage\() selects a suitable radius for you.
The format of the MagickUnsharpMaskImage method is:
unsigned int MagickUnsharpMaskImage\( MagickWand *wand, const double radius, const double sigma,
const double amount, const double threshold );
wand:
The magick wand.
radius:
The radius of the Gaussian, in pixels, not counting the center
pixel.
sigma:
The standard deviation of the Gaussian, in pixels.
amount:
The percentage of the difference between the original and the
blur image that is added back into the original.
threshold:
The threshold in pixels needed to apply the diffence amount.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius %double)
(sigma %double)
(amount %double)
(threshold %double))
(defcfun ("MagickWaveImage" %MagickWaveImage)
%magick-status
"Creates a \"ripple\" effect in the image by shifting the pixels vertically along a sine wave whose amplitude and wavelength is specified by the given parameters.
The format of the MagickWaveImage method is:
unsigned int MagickWaveImage\( MagickWand *wand, const double amplitude,
const double wave_length );
wand:
The magick wand.
amplitude, wave_length:
Define the amplitude and wave length of the
sine wave.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(amplitude %double)
(wave_length %double))
(defcfun ("MagickWhiteThresholdImage" %MagickWhiteThresholdImage)
%magick-status
"Is like ThresholdImage\() but forces all pixels above the threshold into white while leaving all pixels below the threshold unchanged.
The format of the MagickWhiteThresholdImage method is:
unsigned int MagickWhiteThresholdImage\( MagickWand *wand, const PixelWand *threshold );
wand:
The magick wand.
threshold:
The pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(threshold %PixelWand))
(defcfun ("MagickWriteImage" %MagickWriteImage)
%magick-status
"Writes an image.
The format of the MagickWriteImage method is:
unsigned int MagickWriteImage\( MagickWand *wand, const char *filename );
A description of each parameter follows:
wand:
The magick wand.
filename:
The image filename.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(filename :string))
(defcfun ("MagickWriteImagesFile" %MagickWriteImagesFile)
%magick-status
"Writes an image or image sequence to a stdio FILE handle. This may be used to append an encoded image to an already existing appended image sequence if the file seek position is at the end of an existing file.
The format of the MagickWriteImages method is:
unsigned int MagickWriteImagesFile\( MagickWand *wand, FILE *file, const unsigned int adjoin );
wand:
The magick wand.
file:
The open \(and positioned) file handle.
adjoin:
join images into a single multi-image file.
Since GraphicsMagick v1.3.13"
(wand %MagickWand)
(file %FILE)
(adjoin :unsigned-int))
(defcfun ("MagickWriteImageBlob" %MagickWriteImageBlob)
:pointer
"Implements direct to memory image formats. It returns the image as a blob \(a formatted \"file\" in memory) and its length, starting from the current position in the image sequence. Use MagickSetImageFormat\() to set the format to write to the blob \(GIF, JPEG, PNG, etc.).
Use MagickResetIterator\() on the wand if it is desired to write
a sequence from the beginning and the iterator is not currently
at the beginning.
The format of the MagickWriteImageBlob method is:
unsigned char *MagickWriteImageBlob\( MagickWand *wand, size_t *length );
A description of each parameter follows:
wand:
The magick wand.
length:
The length of the blob.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(length :pointer))
(defcfun ("MagickWriteImageFile" %MagickWriteImageFile)
%magick-status
"Writes an image to an open file descriptor.
The format of the MagickWandToFile method is:
unsigned int MagickWriteImageFile\( MagickWand *wand, FILE *file );
A description of each parameter follows:
wand:
The magick wand.
file:
The file descriptor.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(file %FILE))
(defcfun ("MagickWriteImages" %MagickWriteImages)
%magick-status
"Writes an image or image sequence. If the wand represents an image sequence, then it is written starting at the first frame in the sequence.
The format of the MagickWriteImages method is:
unsigned int MagickWriteImages\( MagickWand *wand, const char *filename,
const unsigned int adjoin );
wand:
The magick wand.
filename:
The image filename.
adjoin:
join images into a single multi-image file.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(filename :string)
(adjoin :unsigned-int))
(defcfun ("NewMagickWand" %NewMagickWand)
%MagickWand
"Returns a wand required for all other methods in the API.
The format of the NewMagickWand method is:
MagickWand NewMagickWand\( void );
Since GraphicsMagick v1.1.0")
| true |
;;; magick_wand
(in-package :gm)
(defcfun ("InitializeMagick" %InitializeMagick)
:void
"Initialize GraphicsMagick environment. Must do this to prevent ERROR: Assertion failed: \(semaphore_info != \(SemaphoreInfo *) NULL), function LockSemaphoreInfo, file magick/semaphore.c, line 601.
InitializeMagick() initializes the GraphicsMagick environment.
InitializeMagick() MUST be invoked by the using program before making
use of GraphicsMagick functions or else the library will be unusable.
This function should be invoked in the primary \(original) thread of the
application's process, and before starting any OpenMP threads, as part
of program initialization.
The format of the InitializeMagick function is:
InitializeMagick\(const char *path)
A description of each parameter follows:
o path: The execution path of the current GraphicsMagick client.
Note: InitializeMagick is declared in file magick/magick.c
Since GraphicsMagick v1.1.0"
(path :string))
;; InitializeMagick is called by NewMagickWand NewPixelWand & NewDrawingWand,
;; but call InitializeMagick here to make sure all other functions
;; like MagickQueryFormats works immediately after loaded.
(%InitializeMagick (null-pointer))
(defcfun ("CloneMagickWand" %CloneMagickWand)
%MagickWand
"Makes an exact copy of the specified wand.
The format of the CloneMagickWand method is:
MagickWand *CloneMagickWand\( const MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand to clone.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("DestroyMagickWand" %DestroyMagickWand)
:void
"Deallocates memory associated with an MagickWand.
The format of the DestroyMagickWand method is:
void DestroyMagickWand\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickAdaptiveThresholdImage" %MagickAdaptiveThresholdImage)
%magick-status
"Selects an individual threshold for each pixel based on the range of intensity values in its local neighborhood. This allows for thresholding of an image whose global intensity histogram doesn't contain distinctive peaks.
The format of the MagickAdaptiveThresholdImage method is:
unsigned int MagickAdaptiveThresholdImage\( MagickWand *wand, const unsigned long width,
const unsigned long height, const long offset );
wand:
The magick wand.
width:
The width of the local neighborhood.
height:
The height of the local neighborhood.
offset:
The mean offset.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(width :unsigned-long)
(height :unsigned-long)
(offset :long))
(defcfun ("MagickAddImage" %MagickAddImage)
%magick-status
"Adds the specified images at the current image location.
The format of the MagickAddImage method is:
unsigned int MagickAddImage\( MagickWand *wand, const MagickWand *add_wand );
wand:
The magick wand.
insert:
The splice wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(add_wand %MagickWand))
(defcfun ("MagickAddNoiseImage" %MagickAddNoiseImage)
%magick-status
"Adds random noise to the image.
The format of the MagickAddNoiseImage method is:
unsigned int MagickAddNoiseImage\( MagickWand *wand, const NoiseType noise_type );
wand:
The magick wand.
noise_type:
The type of noise: Uniform, Gaussian, Multiplicative,
Impulse, Laplacian, Poisson, or Random.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(noise_type %NoiseType))
(defcfun ("MagickAffineTransformImage" %MagickAffineTransformImage)
%magick-status
"Transforms an image as dictated by the affine matrix of the drawing wand.
The format of the MagickAffineTransformImage method is:
unsigned int MagickAffineTransformImage\( MagickWand *wand, const DrawingWand *drawing_wand );
wand:
The magick wand.
drawing_wand:
The draw wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(drawing_wand %DrawingWand))
(defcfun ("MagickAnnotateImage" %MagickAnnotateImage)
%magick-status
"Annotates an image with text.
The format of the MagickAnnotateImage method is:
unsigned int MagickAnnotateImage\( MagickWand *wand, const DrawingWand *drawing_wand,
const double x, const double y, const double angle,
const char *text );
wand:
The magick wand.
drawing_wand:
The draw wand.
x:
x ordinate to left of text
y:
y ordinate to text baseline
angle:
rotate text relative to this angle.
text:
text to draw
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(drawing_wand %DrawingWand)
(x :double)
(y :double)
(angle :double)
(text :string))
(defcfun ("MagickAnimateImages" %MagickAnimateImages)
%magick-status
"Animates an image or image sequence.
The format of the MagickAnimateImages method is:
unsigned int MagickAnimateImages\( MagickWand *wand, const char *server_name );
wand:
The magick wand.
server_name:
The X server name.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(server_name :string))
(defcfun ("MagickAppendImages" %MagickAppendImages)
%MagickWand
"Append a set of images.
The format of the MagickAppendImages method is:
MagickWand *MagickAppendImages\( MagickWand *wand, const unsigned int stack );
wand:
The magick wand.
stack:
By default, images are stacked left-to-right. Set stack to True
to stack them top-to-bottom.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(stack :unsigned-int))
(defcfun ("MagickAutoOrientImage" %MagickAutoOrientImage)
%magick-status
"Adjusts the current image so that its orientation is suitable for viewing \(i.e. top-left orientation).
The format of the MagickAutoOrientImage method is:
unsigned int MagickAutoOrientImage\( MagickWand *wand,
const OrientationType current_orientation,
ExceptionInfo *exception );
wand:
The magick wand.
current_orientation:
Current image orientation. May be one of: TopLeftOrientation Left to right and Top to bottom TopRightOrientation Right to left and Top to bottom BottomRightOrientation Right to left and Bottom to top BottomLeftOrientation Left to right and Bottom to top LeftTopOrientation Top to bottom and Left to right RightTopOrientation Top to bottom and Right to left RightBottomOrientation Bottom to top and Right to left LeftBottomOrientation Bottom to top and Left to right UndefinedOrientation Current orientation is not known. Use orientation defined by the current image if any. Equivalent to MagickGetImageOrientation\().
Returns True on success, False otherwise.
Note that after successful auto-orientation the internal orientation will be set to TopLeftOrientation. However this internal value is only written to TIFF files. For JPEG files, there is currently no support for resetting the EXIF orientation tag to TopLeft so the JPEG should be stripped or EXIF profile removed if present to prevent saved auto-oriented images from being incorrectly rotated a second time by follow-on viewers that understand the EXIF orientation tag.
Since GraphicsMagick v1.3.26"
(wand %MagickWand)
(current_orientation %OrientationType)
(exception %ExceptionInfo))
(defcfun ("MagickAverageImages" %MagickAverageImages)
%MagickWand
"Average a set of images.
The format of the MagickAverageImages method is:
MagickWand *MagickAverageImages\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickBlackThresholdImage" %MagickBlackThresholdImage)
%magick-status
"Is like MagickThresholdImage\() but forces all pixels below the threshold into black while leaving all pixels above the threshold unchanged.
The format of the MagickBlackThresholdImage method is:
unsigned int MagickBlackThresholdImage\( MagickWand *wand, const PixelWand *threshold );
wand:
The magick wand.
threshold:
The pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(threshold %PixelWand))
(defcfun ("MagickBlurImage" %MagickBlurImage)
%magick-status
"Blurs an image. We convolve the image with a Gaussian operator of the given radius and standard deviation \(sigma). For reasonable results, the radius should be larger than sigma. Use a radius of 0 and BlurImage\() selects a suitable radius for you.
The format of the MagickBlurImage method is:
unsigned int MagickBlurImage\( MagickWand *wand, const double radius, const double sigma );
wand:
The magick wand.
radius:
The radius of the Gaussian, in pixels, not counting the center
pixel.
sigma:
The standard deviation of the Gaussian, in pixels.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double)
(sigma :double))
(defcfun ("MagickBorderImage" %MagickBorderImage)
%magick-status
"Surrounds the image with a border of the color defined by the bordercolor pixel wand.
The format of the MagickBorderImage method is:
unsigned int MagickBorderImage\( MagickWand *wand, const PixelWand *bordercolor,
const unsigned long width, const unsigned long height );
wand:
The magick wand.
bordercolor:
The border color pixel wand.
width:
The border width.
height:
The border height.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(bordercolor %PixelWand)
(width :unsigned-long)
(height :unsigned-long))
(defcfun ("MagickCdlImage" %MagickCdlImage)
%MagickPassFail
"The MagickCdlImage\() method applies \(\"bakes in\") the ASC-CDL which is a format for the exchange of basic primary color grading information between equipment and software from different manufacturers. The format defines the math for three functions: slope, offset and power. Each function uses a number for the red, green, and blue color channels for a total of nine numbers comprising a single color decision. A tenth number for chrominance \(saturation) has been proposed but is not yet standardized.
The cdl argument string is comma delimited and is in the form \(but
without invervening spaces or line breaks):
redslope, redoffset, redpower :
greenslope, greenoffset, greenpower :
blueslope, blueoffset, bluepower :
saturation
with the unity \(no change) specification being:
\"1.0,0.0,1.0:1.0,0.0,1.0:1.0,0.0,1.0:0.0\"
See http://en.wikipedia.org/wiki/ASC_CDL for more information.
The format of the MagickCdlImage method is:
MagickPassFail MagickCdlImage\( MagickWand *wand, const char *cdl );
A description of each parameter follows:
wand:
The image wand.
cdl:
Define the coefficients for slope offset and power in the
red green and blue channels, plus saturation.
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(cdl :string))
(defcfun ("MagickCharcoalImage" %MagickCharcoalImage)
%magick-status
"Simulates a charcoal drawing.
The format of the MagickCharcoalImage method is:
unsigned int MagickCharcoalImage\( MagickWand *wand, const double radius, const double sigma );
wand:
The magick wand.
radius:
The radius of the Gaussian, in pixels, not counting the center
pixel.
sigma:
The standard deviation of the Gaussian, in pixels.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double)
(sigma :double))
(defcfun ("MagickChopImage" %MagickChopImage)
%magick-status
"Removes a region of an image and collapses the image to occupy the removed portion
The format of the MagickChopImage method is:
unsigned int MagickChopImage\( MagickWand *wand, const unsigned long width,
const unsigned long height, const long x, const long y );
wand:
The magick wand.
width:
The region width.
height:
The region height.
x:
The region x offset.
y:
The region y offset.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(width :unsigned-long)
(height :unsigned-long)
(x :long)
(y :long))
(defcfun ("MagickClearException" %MagickClearException)
:void
"Clears the last wand exception.
The format of the MagickClearException method is:
void MagickClearException\( MagickWand *wand );
wand:
The magick wand.
Since GraphicsMagick v1.3.26"
(wand %MagickWand))
(defcfun ("MagickClipImage" %MagickClipImage)
%magick-status
"Clips along the first path from the 8BIM profile, if present.
The format of the MagickClipImage method is:
unsigned int MagickClipImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickClipPathImage" %MagickClipPathImage)
%magick-status
"Clips along the named paths from the 8BIM profile, if present. Later operations take effect inside the path. Id may be a number if preceded with #, to work on a numbered path, e.g., \"#1\" to use the first path.
The format of the MagickClipPathImage method is:
unsigned int MagickClipPathImage\( MagickWand *wand, const char *pathname,
const unsigned int inside );
wand:
The magick wand.
pathname:
name of clipping path resource. If name is preceded by #, use
clipping path numbered by name.
inside:
if non-zero, later operations take effect inside clipping path.
Otherwise later operations take effect outside clipping path.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(pathname :string)
(inside :unsigned-int))
(defcfun ("MagickCoalesceImages" %MagickCoalesceImages)
%MagickWand
"Composites a set of images while respecting any page offsets and disposal methods. GIF, MIFF, and MNG animation sequences typically start with an image background and each subsequent image varies in size and offset. MagickCoalesceImages\() returns a new sequence where each image in the sequence is the same size as the first and composited with the next image in the sequence.
The format of the MagickCoalesceImages method is:
MagickWand *MagickCoalesceImages\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickColorFloodfillImage" %MagickColorFloodfillImage)
%magick-status
"Changes the color value of any pixel that matches target and is an immediate neighbor. If the method FillToBorderMethod is specified, the color value is changed for any neighbor pixel that does not match the bordercolor member of image.
The format of the MagickColorFloodfillImage method is:
unsigned int MagickColorFloodfillImage\( MagickWand *wand, const PixelWand *fill,
const double fuzz, const PixelWand *bordercolor,
const long x, const long y );
wand:
The magick wand.
fill:
The floodfill color pixel wand.
fuzz:
By default target must match a particular pixel color
exactly. However, in many cases two colors may differ by a small amount.
The fuzz member of image defines how much tolerance is acceptable to
consider two colors as the same. For example, set fuzz to 10 and the
color red at intensities of 100 and 102 respectively are now interpreted
as the same color for the purposes of the floodfill.
bordercolor:
The border color pixel wand.
x,y:
The starting location of the operation.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(fill %PixelWand)
(fuzz :double)
(bordercolor %PixelWand)
(x :long)
(y :long))
(defcfun ("MagickColorizeImage" %MagickColorizeImage)
%magick-status
"Blends the fill color with each pixel in the image.
The format of the MagickColorizeImage method is:
unsigned int MagickColorizeImage\( MagickWand *wand, const PixelWand *colorize,
const PixelWand *opacity );
wand:
The magick wand.
colorize:
The colorize pixel wand.
opacity:
The opacity pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(colorize %PixelWand)
(opacity %PixelWand))
(defcfun ("MagickCommentImage" %MagickCommentImage)
%magick-status
"Adds a comment to your image.
The format of the MagickCommentImage method is:
unsigned int MagickCommentImage\( MagickWand *wand, const char *comment );
A description of each parameter follows:
wand:
The magick wand.
comment:
The image comment.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(comment :string))
(defcfun ("MagickCompareImageChannels" %MagickCompareImageChannels)
%MagickWand
"Compares one or more image channels and returns the specified distortion metric.
The format of the MagickCompareImageChannels method is:
MagickWand *MagickCompareImageChannels\( MagickWand *wand, const MagickWand *reference,
const ChannelType channel, const MetricType metric,
double *distortion );
wand:
The magick wand.
reference:
The reference wand.
channel:
The channel.
metric:
The metric.
distortion:
The computed distortion between the images.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(reference %MagickWand)
(channel %ChannelType)
(metric %MetricType)
(distortion :pointer))
(defcfun ("MagickCompareImages" %MagickCompareImages)
%MagickWand
"Compares one or more images and returns the specified distortion metric.
The format of the MagickCompareImages method is:
MagickWand *MagickCompareImages\( MagickWand *wand, const MagickWand *reference,
const MetricType metric, double *distortion );
wand:
The magick wand.
reference:
The reference wand.
metric:
The metric.
distortion:
The computed distortion between the images.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(reference %MagickWand)
(metric %MetricType)
(distortion :pointer))
(defcfun ("MagickCompositeImage" %MagickCompositeImage)
%magick-status
"Composite one image onto another at the specified offset.
The format of the MagickCompositeImage method is:
unsigned int MagickCompositeImage\( MagickWand *wand, const MagickWand *composite_wand,
const CompositeOperator compose, const long x,
const long y );
wand:
The magick wand.
composite_image:
The composite image.
compose:
This operator affects how the composite is applied to the
image. The default is Over. Choose from these operators:
OverCompositeOp InCompositeOp OutCompositeOP
AtopCompositeOP XorCompositeOP PlusCompositeOP
MinusCompositeOP AddCompositeOP SubtractCompositeOP
DifferenceCompositeOP BumpmapCompositeOP CopyCompositeOP
DisplaceCompositeOP
x_offset:
The column offset of the composited image.
y_offset:
The row offset of the composited image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(composite_wand %MagickWand)
(compose %CompositeOperator)
(x :long)
(y :long))
(defcfun ("MagickContrastImage" %MagickContrastImage)
%magick-status
"Enhances the intensity differences between the lighter and darker elements of the image. Set sharpen to a value other than 0 to increase the image contrast otherwise the contrast is reduced.
The format of the MagickContrastImage method is:
unsigned int MagickContrastImage\( MagickWand *wand, const unsigned int sharpen );
wand:
The magick wand.
sharpen:
Increase or decrease image contrast.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(sharpen :unsigned-int))
(defcfun ("MagickConvolveImage" %MagickConvolveImage)
%magick-status
"Applies a custom convolution kernel to the image.
The format of the MagickConvolveImage method is:
unsigned int MagickConvolveImage\( MagickWand *wand, const unsigned long order,
const double *kernel );
wand:
The magick wand.
order:
The number of columns and rows in the filter kernel.
kernel:
An array of doubles representing the convolution kernel.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(order :unsigned-long)
(kernel :pointer))
(defcfun ("MagickCropImage" %MagickCropImage)
%magick-status
"Extracts a region of the image.
The format of the MagickCropImage method is:
unsigned int MagickCropImage\( MagickWand *wand, const unsigned long width,
const unsigned long height, const long x, const long y );
wand:
The magick wand.
width:
The region width.
height:
The region height.
x:
The region x offset.
y:
The region y offset.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(width :unsigned-long)
(height :unsigned-long)
(x :long)
(y :long))
(defcfun ("MagickCycleColormapImage" %MagickCycleColormapImage)
%magick-status
"Displaces an image's colormap by a given number of positions. If you cycle the colormap a number of times you can produce a psychodelic effect.
The format of the MagickCycleColormapImage method is:
unsigned int MagickCycleColormapImage\( MagickWand *wand, const long displace );
wand:
The magick wand.
pixel_wand:
The pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(displace :long))
(defcfun ("MagickDeconstructImages" %MagickDeconstructImages)
%MagickWand
"Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers.
The format of the MagickDeconstructImages method is:
MagickWand *MagickDeconstructImages\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickDescribeImage" %MagickDescribeImage)
:string
"Describes an image by formatting its attributes to an allocated string which must be freed by the user. Attributes include the image width, height, size, and others. The string is similar to the output of 'identify -verbose'.
The format of the MagickDescribeImage method is:
const char *MagickDescribeImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickDespeckleImage" %MagickDespeckleImage)
%magick-status
"Reduces the speckle noise in an image while perserving the edges of the original image.
The format of the MagickDespeckleImage method is:
unsigned int MagickDespeckleImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickDisplayImage" %MagickDisplayImage)
%magick-status
"Displays an image.
The format of the MagickDisplayImage method is:
unsigned int MagickDisplayImage\( MagickWand *wand, const char *server_name );
A description of each parameter follows:
wand:
The magick wand.
server_name:
The X server name.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(server_name :string))
(defcfun ("MagickDisplayImages" %MagickDisplayImages)
%magick-status
"Displays an image or image sequence.
The format of the MagickDisplayImages method is:
unsigned int MagickDisplayImages\( MagickWand *wand, const char *server_name );
wand:
The magick wand.
server_name:
The X server name.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(server_name :string))
(defcfun ("MagickDrawImage" %MagickDrawImage)
%magick-status
"Draws vectors on the image as described by DrawingWand.
The format of the MagickDrawImage method is:
unsigned int MagickDrawImage\( MagickWand *wand, const DrawingWand *drawing_wand );
wand:
The magick wand.
drawing_wand:
The draw wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(drawing_wand %DrawingWand))
(defcfun ("MagickEdgeImage" %MagickEdgeImage)
%magick-status
"Enhance edges within the image with a convolution filter of the given radius. Use a radius of 0 and Edge\() selects a suitable radius for you.
The format of the MagickEdgeImage method is:
unsigned int MagickEdgeImage\( MagickWand *wand, const double radius );
A description of each parameter follows:
wand:
The magick wand.
radius:
the radius of the pixel neighborhood.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double))
(defcfun ("MagickEmbossImage" %MagickEmbossImage)
%magick-status
"Returns a grayscale image with a three-dimensional effect. We convolve the image with a Gaussian operator of the given radius and standard deviation \(sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and Emboss\() selects a suitable radius for you.
The format of the MagickEmbossImage method is:
unsigned int MagickEmbossImage\( MagickWand *wand, const double radius, const double sigma );
wand:
The magick wand.
radius:
The radius of the Gaussian, in pixels, not counting the center
pixel.
sigma:
The standard deviation of the Gaussian, in pixels.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double)
(sigma :double))
(defcfun ("MagickEnhanceImage" %MagickEnhanceImage)
%magick-status
"Applies a digital filter that improves the quality of a noisy image.
The format of the MagickEnhanceImage method is:
unsigned int MagickEnhanceImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickEqualizeImage" %MagickEqualizeImage)
%magick-status
"Equalizes the image histogram.
The format of the MagickEqualizeImage method is:
unsigned int MagickEqualizeImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickExtentImage" %MagickExtentImage)
%magick-status
"Use MagickExtentImage\() to change the image dimensions as specified by geometry width and height. The existing image content is composited at the position specified by geometry x and y using the image compose method. Existing image content which falls outside the bounds of the new image dimensions is discarded.
The format of the MagickExtentImage method is:
unsigned int MagickExtentImage\( MagickWand *wand, const size_t width, const size_t height,
const ssize_t x, const ssize_t y );
wand:
The magick wand.
width:
New image width
height:
New image height
x, y:
Top left composition coordinate to place existing image content
on the new image.
Since GraphicsMagick v1.3.14"
(wand %MagickWand)
(width %size_t)
(height %size_t)
(x %ssize_t)
(y %ssize_t))
(defcfun ("MagickFlattenImages" %MagickFlattenImages)
%MagickWand
"Merges a sequence of images. This is useful for combining Photoshop layers into a single image.
The format of the MagickFlattenImages method is:
MagickWand *MagickFlattenImages\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickFlipImage" %MagickFlipImage)
%magick-status
"Creates a vertical mirror image by reflecting the pixels around the central x-axis\(swap up/down).
The format of the MagickFlipImage method is:
unsigned int MagickFlipImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickFlopImage" %MagickFlopImage)
%magick-status
"Creates a horizontal mirror image by reflecting the pixels around the central y-axis\(swap left/right).
The format of the MagickFlopImage method is:
unsigned int MagickFlopImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickFrameImage" %MagickFrameImage)
%magick-status
"Adds a simulated three-dimensional border around the image. The width and height specify the border width of the vertical and horizontal sides of the frame. The inner and outer bevels indicate the width of the inner and outer shadows of the frame.
The format of the MagickFrameImage method is:
unsigned int MagickFrameImage\( MagickWand *wand, const PixelWand *matte_color,
const unsigned long width, const unsigned long height,
const long inner_bevel, const long outer_bevel );
wand:
The magick wand.
matte_color:
The frame color pixel wand.
width:
The border width.
height:
The border height.
inner_bevel:
The inner bevel width.
outer_bevel:
The outer bevel width.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(matte_color %PixelWand)
(width :unsigned-long)
(height :unsigned-long)
(inner_bevel :long)
(outer_bevel :long))
(defcfun ("MagickFxImage" %MagickFxImage)
%MagickWand
"Evaluate expression for each pixel in the image.
The format of the MagickFxImage method is:
MagickWand *MagickFxImage\( MagickWand *wand, const char *expression );
A description of each parameter follows:
wand:
The magick wand.
expression:
The expression.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(expression :string))
(defcfun ("MagickFxImageChannel" %MagickFxImageChannel)
%MagickWand
"Evaluate expression for each pixel in the specified channel.
The format of the MagickFxImageChannel method is:
MagickWand *MagickFxImageChannel\( MagickWand *wand, const ChannelType channel,
const char *expression );
wand:
The magick wand.
channel:
Identify which channel to level: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
BlackChannel.
expression:
The expression.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(expression :string))
(defcfun ("MagickGammaImage" %MagickGammaImage)
%magick-status
"Use MagickGammaImage\() to gamma-correct an image. The same image viewed on different devices will have perceptual differences in the way the image's intensities are represented on the screen. Specify individual gamma levels for the red, green, and blue channels, or adjust all three with the gamma parameter. Values typically range from 0.8 to 2.3.
You can also reduce the influence of a particular channel with a gamma
value of 0.
The format of the MagickGammaImage method is:
unsigned int MagickGammaImage\( MagickWand *wand, const double gamma );
A description of each parameter follows:
wand:
The magick wand.
gamme:
Define the level of gamma correction.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(gamma :double))
(defcfun ("MagickGammaImageChannel" %MagickGammaImageChannel)
%magick-status
"Use MagickGammaImageChannel\() to gamma-correct a particular image channel. The same image viewed on different devices will have perceptual differences in the way the image's intensities are represented on the screen. Specify individual gamma levels for the red, green, and blue channels, or adjust all three with the gamma parameter. Values typically range from 0.8 to 2.3.
You can also reduce the influence of a particular channel with a gamma
value of 0.
The format of the MagickGammaImageChannel method is:
unsigned int MagickGammaImageChannel\( MagickWand *wand, const ChannelType channel,
const double gamma );
wand:
The magick wand.
channel:
The channel.
level:
Define the level of gamma correction.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(gamma :double))
(defcfun ("MagickGetConfigureInfo" %MagickGetConfigureInfo)
:string
"Returns ImageMagick configure attributes such as NAME, VERSION, LIB_VERSION, COPYRIGHT, etc.
The format of the MagickGetConfigureInfo\() method is:
char *MagickGetConfigureInfo\( MagickWand *wand, const char *name );
A description of each parameter follows:
wand:
The magick wand.
name:
Return the attribute associated with this name.
WARN: GraphicsMagick return NULL whatever you passed. Do NOT use this API.
More detail could be found in source code.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(name :string))
(defcfun ("MagickGetCopyright" %MagickGetCopyright)
:string
"Returns the ImageMagick API copyright as a string.
The format of the MagickGetCopyright method is:
const char *MagickGetCopyright\( void );
Since GraphicsMagick v1.1.0")
(defcfun ("MagickGetException" %MagickGetException)
:string
"Returns the severity, reason, and description of any error that occurs when using other methods in this API.
The format of the MagickGetException method is:
char *MagickGetException\( const MagickWand *wand, ExceptionType *severity );
A description of each parameter follows:
wand:
The magick wand.
severity:
The severity of the error is returned here.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(severity :pointer)) ;; ExceptionType *severity
(defcfun ("MagickGetFilename" %MagickGetFilename)
:string
"Returns the filename associated with an image sequence.
The format of the MagickGetFilename method is:
const char *MagickGetFilename\( const MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetHomeURL" %MagickGetHomeURL)
:string
"Returns the ImageMagick home URL.
The format of the MagickGetHomeURL method is:
const char *MagickGetHomeURL\( void );
Since GraphicsMagick v1.1.0")
(defcfun ("MagickGetImage" %MagickGetImage)
%MagickWand
"Clones the image at the current image index.
The format of the MagickGetImage method is:
MagickWand *MagickGetImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageAttribute" %MagickGetImageAttribute)
:string
"MagickGetImageAttribute returns an image attribute as a string
The format of the MagickGetImageAttribute method is:
char *MagickGetImageAttribute\( MagickWand *wand, const char *name );
A description of each parameter follows:
wand:
The magick wand.
name:
The name of the attribute
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(name :string))
(defcfun ("MagickGetImageBackgroundColor" %MagickGetImageBackgroundColor)
%magick-status
"Returns the image background color.
The format of the MagickGetImageBackgroundColor method is:
unsigned int MagickGetImageBackgroundColor\( MagickWand *wand, PixelWand *background_color );
wand:
The magick wand.
background_color:
Return the background color.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(background_color %PixelWand))
(defcfun ("MagickGetImageBluePrimary" %MagickGetImageBluePrimary)
%magick-status
"Returns the chromaticy blue primary point for the image.
The format of the MagickGetImageBluePrimary method is:
unsigned int MagickGetImageBluePrimary\( MagickWand *wand, double *x, double *y );
wand:
The magick wand.
x:
The chromaticity blue primary x-point.
y:
The chromaticity blue primary y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImageBorderColor" %MagickGetImageBorderColor)
%magick-status
"Returns the image border color.
The format of the MagickGetImageBorderColor method is:
unsigned int MagickGetImageBorderColor\( MagickWand *wand, PixelWand *border_color );
wand:
The magick wand.
border_color:
Return the border color.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(border_color %PixelWand))
(defcfun ("MagickGetImageBoundingBox" %MagickGetImageBoundingBox)
%magick-status
"Obtains the crop bounding box required to remove a solid-color border from the image. Color quantums which differ less than the fuzz setting are considered to be the same. If a border is not detected, then the the original image dimensions are returned. The crop bounding box estimation uses the same algorithm as MagickTrimImage\().
The format of the MagickGetImageBoundingBox method is:
unsigned int MagickGetImageBoundingBox\( MagickWand *wand, const double fuzz,
unsigned long *width, unsigned long *height,
long *x, long *y );
wand:
The magick wand.
fuzz:
Color comparison fuzz factor. Use 0.0 for exact match.
width:
The crop width
height:
The crop height
x:
The crop x offset
y:
The crop y offset
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(fuzz :double)
(width :pointer)
(height :pointer)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImageChannelDepth" %MagickGetImageChannelDepth)
:unsigned-long
"Gets the depth for a particular image channel.
The format of the MagickGetImageChannelDepth method is:
unsigned long MagickGetImageChannelDepth\( MagickWand *wand, const ChannelType channel );
wand:
The magick wand.
channel:
Identify which channel to extract: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
BlackChannel.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType))
(defcfun ("MagickGetImageChannelExtrema" %MagickGetImageChannelExtrema)
%magick-status
"Gets the extrema for one or more image channels.
The format of the MagickGetImageChannelExtrema method is:
unsigned int MagickGetImageChannelExtrema\( MagickWand *wand, const ChannelType channel,
unsigned long *minima, unsigned long *maxima );
wand:
The magick wand.
channel:
Identify which channel to extract: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
or BlackChannel.
minima:
The minimum pixel value for the specified channel\(s).
maxima:
The maximum pixel value for the specified channel\(s).
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(minima :pointer)
(maxima :pointer))
(defcfun ("MagickGetImageChannelMean" %MagickGetImageChannelMean)
%magick-status
"Gets the mean and standard deviation of one or more image channels.
The format of the MagickGetImageChannelMean method is:
unsigned int MagickGetImageChannelMean\( MagickWand *wand, const ChannelType channel,
double *mean, double *standard_deviation );
wand:
The magick wand.
channel:
Identify which channel to extract: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
or BlackChannel.
mean:
The mean pixel value for the specified channel\(s).
standard_deviation:
The standard deviation for the specified channel\(s).
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(mean :pointer)
(standard_deviation :pointer))
(defcfun ("MagickGetImageColormapColor" %MagickGetImageColormapColor)
%magick-status
"Returns the color of the specified colormap index.
The format of the MagickGetImageColormapColor method is:
unsigned int MagickGetImageColormapColor\( MagickWand *wand, const unsigned long index,
PixelWand *color );
wand:
The magick wand.
index:
The offset into the image colormap.
color:
Return the colormap color in this wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(index :unsigned-long)
(color %PixelWand))
(defcfun ("MagickGetImageColors" %MagickGetImageColors)
:unsigned-long
"Gets the number of unique colors in the image.
The format of the MagickGetImageColors method is:
unsigned long MagickGetImageColors\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageColorspace" %MagickGetImageColorspace)
%ColorspaceType
"Gets the image colorspace.
The format of the MagickGetImageColorspace method is:
ColorspaceType MagickGetImageColorspace\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageCompose" %MagickGetImageCompose)
%CompositeOperator
"Returns the composite operator associated with the image.
The format of the MagickGetImageCompose method is:
CompositeOperator MagickGetImageCompose\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageCompression" %MagickGetImageCompression)
%CompressionType
"Gets the image compression.
The format of the MagickGetImageCompression method is:
CompressionType MagickGetImageCompression\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageDelay" %MagickGetImageDelay)
:unsigned-long
"Gets the image delay.
The format of the MagickGetImageDelay method is:
unsigned long MagickGetImageDelay\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageDepth" %MagickGetImageDepth)
:unsigned-long
"Gets the image depth.
The format of the MagickGetImageDepth method is:
unsigned long MagickGetImageDepth\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageExtrema" %MagickGetImageExtrema)
%magick-status
"Gets the extrema for the image.
The format of the MagickGetImageExtrema method is:
unsigned int MagickGetImageExtrema\( MagickWand *wand, unsigned long *min,
unsigned long *max );
wand:
The magick wand.
min:
The minimum pixel value for the specified channel\(s).
max:
The maximum pixel value for the specified channel\(s).
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(min :pointer)
(max :pointer))
(defcfun ("MagickGetImageDispose" %MagickGetImageDispose)
%DisposeType
"Gets the image disposal method.
The format of the MagickGetImageDispose method is:
DisposeType MagickGetImageDispose\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageFilename" %MagickGetImageFilename)
:char
"Returns the filename of a particular image in a sequence.
The format of the MagickGetImageFilename method is:
const char MagickGetImageFilename\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageFormat" %MagickGetImageFormat)
:string
"Returns the format of a particular image in a sequence.
The format of the MagickGetImageFormat method is:
char * MagickGetImageFormat\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageFuzz" %MagickGetImageFuzz)
:double
"Returns the color comparison fuzz factor. Colors closer than the fuzz factor are considered to be the same when comparing colors. Note that some other functions such as MagickColorFloodfillImage\() implicitly set this value.
The format of the MagickGetImageFuzz method is:
double MagickGetImageFuzz\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.3.8"
(wand %MagickWand))
(defcfun ("MagickGetImageGamma" %MagickGetImageGamma)
:double
"Gets the image gamma.
The format of the MagickGetImageGamma method is:
double MagickGetImageGamma\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageGeometry" %MagickGetImageGeometry)
:string
"Gets the image geometry string. NULL is returned if the image does not contain a geometry string.
The format of the MagickGetImageGeometry method is:
const char *MagickGetImageGeometry\( MagickWand *wand )
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.3.20"
(wand %MagickWand))
(defcfun ("MagickGetImageGravity" %MagickGetImageGravity)
%GravityType
"Gets the image gravity.
The format of the MagickGetImageGravity method is:
GravityType MagickGetImageGravity\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.3.22"
(wand %MagickWand))
(defcfun ("MagickGetImageGreenPrimary" %MagickGetImageGreenPrimary)
%magick-status
"Returns the chromaticy green primary point.
The format of the MagickGetImageGreenPrimary method is:
unsigned int MagickGetImageGreenPrimary\( MagickWand *wand, double *x, double *y );
wand:
The magick wand.
x:
The chromaticity green primary x-point.
y:
The chromaticity green primary y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImageHeight" %MagickGetImageHeight)
:unsigned-long
"Returns the image height.
The format of the MagickGetImageHeight method is:
unsigned long MagickGetImageHeight\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageHistogram" %MagickGetImageHistogram)
%PixelWand
"Returns the image histogram as an array of PixelWand wands.
The format of the MagickGetImageHistogram method is:
PixelWand *MagickGetImageHistogram\( MagickWand *wand, unsigned long *number_colors );
wand:
The magick wand.
number_colors:
The number of unique colors in the image and the number
of pixel wands returned.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(number_colors :pointer))
(defcfun ("MagickGetImageIndex" %MagickGetImageIndex)
:long
"Returns the index of the current image.
The format of the MagickGetImageIndex method is:
long MagickGetImageIndex\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageInterlaceScheme" %MagickGetImageInterlaceScheme)
%InterlaceType
"Gets the image interlace scheme.
The format of the MagickGetImageInterlaceScheme method is:
InterlaceType MagickGetImageInterlaceScheme\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageIterations" %MagickGetImageIterations)
:unsigned-long
"Gets the image iterations.
The format of the MagickGetImageIterations method is:
unsigned long MagickGetImageIterations\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageMatte" %MagickGetImageMatte)
%MagickBool
"Gets the image matte flag. The flag is MagickTrue if the image supports an opacity \(inverse of transparency) channel.
The format of the MagickGetImageMatte method is:
MagickBool MagickGetImageMatte\( MagickWand *wand )
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.3.20"
(wand %MagickWand))
(defcfun ("MagickGetImageMatteColor" %MagickGetImageMatteColor)
%magick-status
"Returns the image matte color.
The format of the MagickGetImageMatteColor method is:
unsigned int MagickGetImageMatteColor\( MagickWand *wand, PixelWand *matte_color );
wand:
The magick wand.
matte_color:
Return the matte color.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(matte_color %PixelWand))
(defcfun ("MagickGetImageOrientation" %MagickGetImageOrientation)
%OrientationType
"Gets the image orientation type. May be one of:
UndefinedOrientation Image orientation not specified or error.
TopLeftOrientation Left to right and Top to bottom.
TopRightOrientation Right to left and Top to bottom.
BottomRightOrientation Right to left and Bottom to top.
BottomLeftOrientation Left to right and Bottom to top.
LeftTopOrientation Top to bottom and Left to right.
RightTopOrientation Top to bottom and Right to left.
RightBottomOrientation Bottom to top and Right to left.
LeftBottomOrientation Bottom to top and Left to right.
The format of the MagickGetImageOrientation method is:
OrientationType MagickGetImageOrientation\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.3.26"
(wand %MagickWand))
(defcfun ("MagickGetImagePage" %MagickGetImagePage)
%magick-status
"Retrieves the image page size and offset used when placing \(e.g. compositing) the image.
The format of the MagickGetImagePage method is:
MagickGetImagePage\( MagickWand *wand, unsigned long *width, unsigned long *height, long *x,
long *y );
wand:
The magick wand.
width, height:
The region size.
x, y:
Offset \(from top left) on base canvas image on
which to composite image data.
Since GraphicsMagick v1.3.18"
(wand %MagickWand)
(width :pointer)
(height :pointer)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImagePixels" %MagickGetImagePixels)
%magick-status
"Extracts pixel data from an image and returns it to you. The method returns False on success otherwise True if an error is encountered. The data is returned as char, short int, int, long, float, or double in the order specified by map.
Suppose you want to extract the first scanline of a 640x480 image as
character data in red-green-blue order:
MagickGetImagePixels\(wand,0,0,640,1,\"RGB\",CharPixel,pixels);
The format of the MagickGetImagePixels method is:
unsigned int MagickGetImagePixels\( MagickWand *wand, const long x_offset, const long y_offset,
const unsigned long columns, const unsigned long rows,
const char *map, const StorageType storage,
unsigned char *pixels );
wand:
The magick wand.
x_offset, y_offset, columns, rows:
These values define the perimeter
of a region of pixels you want to extract.
map:
This string reflects the expected ordering of the pixel array.
It can be any combination or order of R = red, G = green, B = blue,
A = alpha, C = cyan, Y = yellow, M = magenta, K = black, or
I = intensity \(for grayscale).
storage:
Define the data type of the pixels. Float and double types are
expected to be normalized [0..1] otherwise [0..MaxRGB]. Choose from
these types: CharPixel, ShortPixel, IntegerPixel, LongPixel, FloatPixel,
or DoublePixel.
pixels:
This array of values contain the pixel components as defined by
map and type. You must preallocate this array where the expected
length varies depending on the values of width, height, map, and type.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x_offset :long)
(y_offset :long)
(columns :unsigned-long)
(rows :unsigned-long)
(map :string)
(storage %StorageType)
(pixels :pointer))
(defcfun ("MagickGetImageProfile" %MagickGetImageProfile)
:pointer
"Returns the named image profile.
The format of the MagickGetImageProfile method is:
unsigned char *MagickGetImageProfile\( MagickWand *wand, const char *name,
unsigned long *length );
wand:
The magick wand.
name:
Name of profile to return: ICC, IPTC, or generic profile.
length:
The length of the profile.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(name :string)
(length :pointer))
(defcfun ("MagickGetImageRedPrimary" %MagickGetImageRedPrimary)
%magick-status
"Returns the chromaticy red primary point.
The format of the MagickGetImageRedPrimary method is:
unsigned int MagickGetImageRedPrimary\( MagickWand *wand, double *x, double *y );
wand:
The magick wand.
x:
The chromaticity red primary x-point.
y:
The chromaticity red primary y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImageRenderingIntent" %MagickGetImageRenderingIntent)
%RenderingIntent
"Gets the image rendering intent.
The format of the MagickGetImageRenderingIntent method is:
RenderingIntent MagickGetImageRenderingIntent\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageResolution" %MagickGetImageResolution)
%magick-status
"Gets the image X & Y resolution.
The format of the MagickGetImageResolution method is:
unsigned int MagickGetImageResolution\( MagickWand *wand, double *x, double *y );
wand:
The magick wand.
x:
The image x-resolution.
y:
The image y-resolution.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImageScene" %MagickGetImageScene)
:unsigned-long
"Gets the image scene.
The format of the MagickGetImageScene method is:
unsigned long MagickGetImageScene\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageSignature" %MagickGetImageSignature)
:char
"Generates an SHA-256 message digest for the image pixel stream.
The format of the MagickGetImageSignature method is:
const char MagickGetImageSignature\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageSize" %MagickGetImageSize)
%MagickSizeType
"Returns the image size.
The format of the MagickGetImageSize method is:
MagickSizeType MagickGetImageSize\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageType" %MagickGetImageType)
%ImageType
"Gets the image type.
The format of the MagickGetImageType method is:
ImageType MagickGetImageType\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageSavedType" %MagickGetImageSavedType)
%ImageType
"Gets the image type that will be used when the image is saved. This may be different to the current image type, returned by MagickGetImageType\().
The format of the MagickGetImageSavedType method is:
ImageType MagickGetImageSavedType\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.3.13"
(wand %MagickWand))
(defcfun ("MagickGetImageUnits" %MagickGetImageUnits)
%ResolutionType
"Gets the image units of resolution.
The format of the MagickGetImageUnits method is:
ResolutionType MagickGetImageUnits\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageVirtualPixelMethod" %MagickGetImageVirtualPixelMethod)
%VirtualPixelMethod
"Returns the virtual pixel method for the sepcified image.
The format of the MagickGetImageVirtualPixelMethod method is:
VirtualPixelMethod MagickGetImageVirtualPixelMethod\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetImageWhitePoint" %MagickGetImageWhitePoint)
%magick-status
"Returns the chromaticy white point.
The format of the MagickGetImageWhitePoint method is:
unsigned int MagickGetImageWhitePoint\( MagickWand *wand, double *x, double *y );
wand:
The magick wand.
x:
The chromaticity white x-point.
y:
The chromaticity white y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x :pointer)
(y :pointer))
(defcfun ("MagickGetImageWidth" %MagickGetImageWidth)
:unsigned-long
"Returns the image width.
The format of the MagickGetImageWidth method is:
unsigned long MagickGetImageWidth\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetNumberImages" %MagickGetNumberImages)
:unsigned-long
"Returns the number of images associated with a magick wand.
The format of the MagickGetNumberImages method is:
unsigned long MagickGetNumberImages\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickGetPackageName" %MagickGetPackageName)
:string
"Returns the ImageMagick package name.
The format of the MagickGetPackageName method is:
const char *MagickGetPackageName\( void );
Since GraphicsMagick v1.1.0")
(defcfun ("MagickGetQuantumDepth" %MagickGetQuantumDepth)
:string
"Returns the ImageMagick quantum depth.
The format of the MagickGetQuantumDepth method is:
const char *MagickGetQuantumDepth\( unsigned long *depth );
A description of each parameter follows:
depth:
The quantum depth is returned as a number.
Since GraphicsMagick v1.1.0"
(depth :pointer))
(defcfun ("MagickGetReleaseDate" %MagickGetReleaseDate)
:string
"Returns the ImageMagick release date.
The format of the MagickGetReleaseDate method is:
const char *MagickGetReleaseDate\( void );
Since GraphicsMagick v1.1.0")
(defcfun ("MagickGetResourceLimit" %MagickGetResourceLimit)
:unsigned-long
"Returns the the specified resource in megabytes.
The format of the MagickGetResourceLimit method is:
unsigned long MagickGetResourceLimit\( const ResourceType type );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(type %ResourceType))
(defcfun ("MagickGetSamplingFactors" %MagickGetSamplingFactors)
:double
"Gets the horizontal and vertical sampling factor.
The format of the MagickGetSamplingFactors method is:
double *MagickGetSamplingFactors\( MagickWand *wand, unsigned long *number_factors );
wand:
The magick wand.
number_factors:
The number of factors in the returned array.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(number_factors :pointer))
(defcfun ("MagickGetSize" %MagickGetSize)
%magick-status
"Returns the size associated with the magick wand.
The format of the MagickGetSize method is:
unsigned int MagickGetSize\( const MagickWand *wand, unsigned long *columns,
unsigned long *rows );
wand:
The magick wand.
columns:
The width in pixels.
height:
The height in pixels.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(columns :pointer)
(rows :pointer))
(defcfun ("MagickGetVersion" %MagickGetVersion)
:string
"Returns the ImageMagick API version as a string and as a number.
The format of the MagickGetVersion method is:
const char *MagickGetVersion\( unsigned long *version );
A description of each parameter follows:
version:
The ImageMagick version is returned as a number.
Since GraphicsMagick v1.1.0"
(version :pointer))
(defcfun ("MagickHaldClutImage" %MagickHaldClutImage)
%MagickPassFail
"The MagickHaldClutImage\() method apply a color lookup table \(Hald CLUT) to the image. The fundamental principle of the Hald CLUT algorithm is that application of an identity CLUT causes no change to the input image, but an identity CLUT image which has had its colors transformed in some way \(e.g. in Adobe Photoshop) may be used to implement an identical transform on any other image.
The minimum CLUT level is 2, and the maximum depends on available memory
\(largest successfully tested is 24). A CLUT image is required to have equal
width and height. A CLUT of level 8 is an image of dimension 512x512, a CLUT
of level 16 is an image of dimension 4096x4096. Interpolation is used so
extremely large CLUT images are not required.
GraphicsMagick provides an 'identity' coder which may be used to generate
identity HLUTs. For example, reading from \"identity:8\" creates an identity
CLUT of order 8.
The Hald CLUT algorithm has been developed by PI:NAME:<NAME>END_PI as described
at http://www.quelsolaar.com/technology/clut.html, and was adapted for
GraphicsMagick by PI:NAME:<NAME>END_PI with support from PI:NAME:<NAME>END_PI of
Workflowers.
The format of the HaldClutImage method is:
MagickPassFail MagickHaldClutImage\( MagickWand *wand, const MagickWand *clut_wand );
A description of each parameter follows:
wand:
The image wand.
clut_wand:
The color lookup table image wand
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(clut_wand %MagickWand))
(defcfun ("MagickHasNextImage" %MagickHasNextImage)
:boolean
"Returns True if the wand has more images when traversing the list in the forward direction
The format of the MagickHasNextImage method is:
unsigned int MagickHasNextImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickHasPreviousImage" %MagickHasPreviousImage)
%magick-status
"Returns True if the wand has more images when traversing the list in the reverse direction
The format of the MagickHasPreviousImage method is:
unsigned int MagickHasPreviousImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickImplodeImage" %MagickImplodeImage)
%magick-status
"Creates a new image that is a copy of an existing one with the image pixels \"implode\" by the specified percentage. It allocates the memory necessary for the new Image structure and returns a pointer to the new image.
The format of the MagickImplodeImage method is:
unsigned int MagickImplodeImage\( MagickWand *wand, const double radius );
A description of each parameter follows:
wand:
The magick wand.
amount:
Define the extent of the implosion.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double))
(defcfun ("MagickLabelImage" %MagickLabelImage)
%magick-status
"Adds a label to your image.
The format of the MagickLabelImage method is:
unsigned int MagickLabelImage\( MagickWand *wand, const char *label );
A description of each parameter follows:
wand:
The magick wand.
label:
The image label.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(label :string))
(defcfun ("MagickLevelImage" %MagickLevelImage)
%magick-status
"Adjusts the levels of an image by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid, and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value.
The format of the MagickLevelImage method is:
unsigned int MagickLevelImage\( MagickWand *wand, const double black_point, const double gamma,
const double white_point );
wand:
The magick wand.
black_point:
The black point.
gamma:
The gamma.
white_point:
The white point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(black_point :double)
(gamma :double)
(white_point :double))
(defcfun ("MagickLevelImageChannel" %MagickLevelImageChannel)
%magick-status
"Adjusts the levels of the specified channel of the reference image by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid, and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value.
The format of the MagickLevelImageChannel method is:
unsigned int MagickLevelImageChannel\( MagickWand *wand, const ChannelType channel,
const double black_point, const double gamma,
const double white_point );
wand:
The magick wand.
channel:
Identify which channel to level: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
BlackChannel.
black_point:
The black point.
gamma:
The gamma.
white_point:
The white point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(black_point :double)
(gamma :double)
(white_point :double))
(defcfun ("MagickMagnifyImage" %MagickMagnifyImage)
%magick-status
"Is a convenience method that scales an image proportionally to twice its original size.
The format of the MagickMagnifyImage method is:
unsigned int MagickMagnifyImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickMapImage" %MagickMapImage)
%magick-status
"Replaces the colors of an image with the closest color from a reference image.
The format of the MagickMapImage method is:
unsigned int MagickMapImage\( MagickWand *wand, const MagickWand *map_wand,
const unsigned int dither );
wand:
The magick wand.
map:
The map wand.
dither:
Set this integer value to something other than zero to dither
the mapped image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(map_wand %MagickWand)
(dither :unsigned-int))
(defcfun ("MagickMatteFloodfillImage" %MagickMatteFloodfillImage)
%magick-status
"Changes the transparency value of any pixel that matches target and is an immediate neighbor. If the method FillToBorderMethod is specified, the transparency value is changed for any neighbor pixel that does not match the bordercolor member of image.
The format of the MagickMatteFloodfillImage method is:
unsigned int MagickMatteFloodfillImage\( MagickWand *wand, const Quantum opacity,
const double fuzz, const PixelWand *bordercolor,
const long x, const long y );
wand:
The magick wand.
opacity:
The opacity.
fuzz:
By default target must match a particular pixel color
exactly. However, in many cases two colors may differ by a small amount.
The fuzz member of image defines how much tolerance is acceptable to
consider two colors as the same. For example, set fuzz to 10 and the
color red at intensities of 100 and 102 respectively are now interpreted
as the same color for the purposes of the floodfill.
bordercolor:
The border color pixel wand.
x,y:
The starting location of the operation.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(opacity %Quantum)
(fuzz :double)
(bordercolor %PixelWand)
(x :long)
(y :long))
(defcfun ("MagickMedianFilterImage" %MagickMedianFilterImage)
%magick-status
"Applies a digital filter that improves the quality of a noisy image. Each pixel is replaced by the median in a set of neighboring pixels as defined by radius.
The format of the MagickMedianFilterImage method is:
unsigned int MagickMedianFilterImage\( MagickWand *wand, const double radius );
wand:
The magick wand.
radius:
The radius of the pixel neighborhood.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double))
(defcfun ("MagickMinifyImage" %MagickMinifyImage)
%magick-status
"Is a convenience method that scales an image proportionally to one-half its original size
The format of the MagickMinifyImage method is:
unsigned int MagickMinifyImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickModulateImage" %MagickModulateImage)
%magick-status
"Lets you control the brightness, saturation, and hue of an image.
The format of the MagickModulateImage method is:
unsigned int MagickModulateImage\( MagickWand *wand, const double brightness,
const double saturation, const double hue );
wand:
The magick wand.
brightness:
The percent change in brighness \(-100 thru +100).
saturation:
The percent change in saturation \(-100 thru +100)
hue:
The percent change in hue \(-100 thru +100)
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(brightness :double)
(saturation :double)
(hue :double))
(defcfun ("MagickMontageImage" %MagickMontageImage)
%MagickWand
"Use MagickMontageImage\() to create a composite image by combining several separate images. The images are tiled on the composite image with the name of the image optionally appearing just below the individual tile.
The format of the MagickMontageImage method is:
MagickWand MagickMontageImage\( MagickWand *wand, const DrawingWand drawing_wand,
const char *tile_geometry, const char *thumbnail_geometry,
const MontageMode mode, const char *frame );
wand:
The magick wand.
drawing_wand:
The drawing wand. The font name, size, and color are
obtained from this wand.
tile_geometry:
the number of tiles per row and page \(e.g. 6x4+0+0).
thumbnail_geometry:
Preferred image size and border size of each
thumbnail \(e.g. 120x120+4+3>).
mode:
Thumbnail framing mode: Frame, Unframe, or Concatenate.
frame:
Surround the image with an ornamental border \(e.g. 15x15+3+3).
The frame color is that of the thumbnail's matte color.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(drawing_wand %DrawingWand)
(tile_geometry :string)
(thumbnail_geometry :string)
(mode %MontageMode)
(frame :string))
(defcfun ("MagickMorphImages" %MagickMorphImages)
%MagickWand
"Method morphs a set of images. Both the image pixels and size are linearly interpolated to give the appearance of a meta-morphosis from one image to the next.
The format of the MagickMorphImages method is:
MagickWand *MagickMorphImages\( MagickWand *wand, const unsigned long number_frames );
wand:
The magick wand.
number_frames:
The number of in-between images to generate.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(number_frames :unsigned-long))
(defcfun ("MagickMosaicImages" %MagickMosaicImages)
%MagickWand
"Inlays an image sequence to form a single coherent picture. It returns a wand with each image in the sequence composited at the location defined by the page offset of the image.
The format of the MagickMosaicImages method is:
MagickWand *MagickMosaicImages\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickMotionBlurImage" %MagickMotionBlurImage)
%magick-status
"Simulates motion blur. We convolve the image with a Gaussian operator of the given radius and standard deviation \(sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and MotionBlurImage\() selects a suitable radius for you. Angle gives the angle of the blurring motion.
The format of the MagickMotionBlurImage method is:
unsigned int MagickMotionBlurImage\( MagickWand *wand, const double radius, const double sigma,
const double angle );
wand:
The magick wand.
radius:
The radius of the Gaussian, in pixels, not counting
the center pixel.
sigma:
The standard deviation of the Gaussian, in pixels.
angle:
Apply the effect along this angle.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double)
(sigma :double)
(angle :double))
(defcfun ("MagickNegateImage" %MagickNegateImage)
%magick-status
"Negates the colors in the reference image. The Grayscale option means that only grayscale values within the image are negated.
You can also reduce the influence of a particular channel with a gamma
value of 0.
The format of the MagickNegateImage method is:
unsigned int MagickNegateImage\( MagickWand *wand, const unsigned int gray );
A description of each parameter follows:
wand:
The magick wand.
gray:
If True, only negate grayscale pixels within the image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(gray :unsigned-int))
(defcfun ("MagickNegateImageChannel" %MagickNegateImageChannel)
%magick-status
"Negates the colors in the specified channel of the reference image. The Grayscale option means that only grayscale values within the image are negated. Note that the Grayscale option has no effect for GraphicsMagick.
You can also reduce the influence of a particular channel with a gamma
value of 0.
The format of the MagickNegateImageChannel method is:
unsigned int MagickNegateImageChannel\( MagickWand *wand, const ChannelType channel,
const unsigned int gray );
wand:
The magick wand.
channel:
Identify which channel to extract: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
BlackChannel.
gray:
If True, only negate grayscale pixels within the image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(gray :unsigned-int))
(defcfun ("MagickNextImage" %MagickNextImage)
%magick-status
"Associates the next image in the image list with a magick wand. True is returned if the Wand iterated to a next image, or False is returned if the wand did not iterate to a next image.
The format of the MagickNextImage method is:
unsigned int MagickNextImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickNormalizeImage" %MagickNormalizeImage)
%magick-status
"Enhances the contrast of a color image by adjusting the pixels color to span the entire range of colors available
You can also reduce the influence of a particular channel with a gamma
value of 0.
The format of the MagickNormalizeImage method is:
unsigned int MagickNormalizeImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickOilPaintImage" %MagickOilPaintImage)
%magick-status
"Applies a special effect filter that simulates an oil painting. Each pixel is replaced by the most frequent color occurring in a circular region defined by radius.
The format of the MagickOilPaintImage method is:
unsigned int MagickOilPaintImage\( MagickWand *wand, const double radius );
A description of each parameter follows:
wand:
The magick wand.
radius:
The radius of the circular neighborhood.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double))
(defcfun ("MagickOpaqueImage" %MagickOpaqueImage)
%magick-status
"Changes any pixel that matches color with the color defined by fill.
The format of the MagickOpaqueImage method is:
unsigned int MagickOpaqueImage\( MagickWand *wand, const PixelWand *target,
const PixelWand *fill, const double fuzz );
wand:
The magick wand.
target:
Change this target color to the fill color within the image.
fill:
The fill pixel wand.
fuzz:
By default target must match a particular pixel color
exactly. However, in many cases two colors may differ by a small amount.
The fuzz member of image defines how much tolerance is acceptable to
consider two colors as the same. For example, set fuzz to 10 and the
color red at intensities of 100 and 102 respectively are now interpreted
as the same color for the purposes of the floodfill.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(target %PixelWand)
(fill %PixelWand)
(fuzz :double))
(defcfun ("MagickOperatorImageChannel" %MagickOperatorImageChannel)
%magick-status
"Performs the requested arithmetic,
bitwise-logical, or value operation on the selected channels of
the entire image. The AllChannels channel option operates on all
color channels whereas the GrayChannel channel option treats the
color channels as a grayscale intensity.
These operations are on the DirectClass pixels of the image and do not
update pixel indexes or colormap.
The format of the MagickOperatorImageChannel method is:
MagickPassFail MagickOperatorImageChannel\( MagickWand *wand,
const ChannelType channel,const QuantumOperator quantum_operator,
const double rvalue )
A description of each parameter follows:
wand: The magick wand.
channel: Channel to operate on \(RedChannel, CyanChannel,
GreenChannel, MagentaChannel, BlueChannel, YellowChannel,
OpacityChannel, BlackChannel, MatteChannel, AllChannels,
GrayChannel). The AllChannels type only updates color
channels. The GrayChannel type treats the color channels
as if they represent an intensity.
quantum_operator: Operator to use \(AddQuantumOp,AndQuantumOp,
AssignQuantumOp, DepthQuantumOp, DivideQuantumOp, GammaQuantumOp,
LShiftQuantumOp, MultiplyQuantumOp, NegateQuantumOp,
NoiseGaussianQuantumOp, NoiseImpulseQuantumOp,
NoiseLaplacianQuantumOp, NoiseMultiplicativeQuantumOp,
NoisePoissonQuantumOp, NoiseRandomQuantumOp, NoiseUniformQuantumOp,
OrQuantumOp, RShiftQuantumOp, SubtractQuantumOp,
ThresholdBlackQuantumOp, ThresholdQuantumOp, ThresholdWhiteQuantumOp,
ThresholdBlackNegateQuantumOp, ThresholdWhiteNegateQuantumOp,
XorQuantumOp).
rvalue: Operator argument.
Since GraphicsMagick v1.3.20"
(wand %MagickWand)
(channel %ChannelType)
(quantum_operator %QuantumOperator) ;; TODO
(rvalue :double))
(defcfun ("MagickPingImage" %MagickPingImage)
%magick-status
"Is like MagickReadImage\() except the only valid information returned is the image width, height, size, and format. It is designed to efficiently obtain this information from a file without reading the entire image sequence into memory.
The format of the MagickPingImage method is:
unsigned int MagickPingImage\( MagickWand *wand, const char *filename );
A description of each parameter follows:
wand:
The magick wand.
filename:
The image filename.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(filename :string))
(defcfun ("MagickPreviewImages" %MagickPreviewImages)
%MagickWand
"Tiles 9 thumbnails of the specified image with an image processing operation applied at varying strengths. This is helpful to quickly pin-point an appropriate parameter for an image processing operation.
The format of the MagickPreviewImages method is:
MagickWand *MagickPreviewImages\( MagickWand *wand, const PreviewType preview );
wand:
The magick wand.
preview:
The preview type.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(preview %PreviewType))
(defcfun ("MagickPreviousImage" %MagickPreviousImage)
%magick-status
"Selects the previous image associated with a magick wand.
The format of the MagickPreviousImage method is:
unsigned int MagickPreviousImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickProfileImage" %MagickProfileImage)
%magick-status
"Use MagickProfileImage\() to add or remove a ICC, IPTC, or generic profile from an image. If the profile is NULL, it is removed from the image otherwise added. Use a name of '*' and a profile of NULL to remove all profiles from the image.
The format of the MagickProfileImage method is:
unsigned int MagickProfileImage\( MagickWand *wand, const char *name,
const unsigned char *profile, const size_t length );
wand:
The magick wand.
name:
Name of profile to add or remove: ICC, IPTC, or generic profile.
profile:
The profile.
length:
The length of the profile.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(name :string)
(profile :pointer)
(length %size_t))
(defcfun ("MagickQuantizeImage" %MagickQuantizeImage)
%magick-status
"Analyzes the colors within a reference image and chooses a fixed number of colors to represent the image. The goal of the algorithm is to minimize the color difference between the input and output image while minimizing the processing time.
The format of the MagickQuantizeImage method is:
unsigned int MagickQuantizeImage\( MagickWand *wand, const unsigned long number_colors,
const ColorspaceType colorspace,
const unsigned long treedepth, const unsigned int dither,
const unsigned int measure_error );
wand:
The magick wand.
number_colors:
The number of colors.
colorspace:
Perform color reduction in this colorspace, typically
RGBColorspace.
treedepth:
Normally, this integer value is zero or one. A zero or
one tells Quantize to choose a optimal tree depth of Log4\(number_colors).% A tree of this depth generally allows the best representation of the
reference image with the least amount of memory and the fastest
computational speed. In some cases, such as an image with low color
dispersion \(a few number of colors), a value other than
Log4\(number_colors) is required. To expand the color tree completely,
use a value of 8.
dither:
A value other than zero distributes the difference between an
original image and the corresponding color reduced algorithm to
neighboring pixels along a Hilbert curve.
measure_error:
A value other than zero measures the difference between
the original and quantized images. This difference is the total
quantization error. The error is computed by summing over all pixels
in an image the distance squared in RGB space between each reference
pixel value and its quantized value.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(number_colors :unsigned-long)
(colorspace %ColorspaceType)
(treedepth :unsigned-long)
(dither :unsigned-int)
(measure_error :unsigned-int))
(defcfun ("MagickQuantizeImages" %MagickQuantizeImages)
%magick-status
"Analyzes the colors within a sequence of images and chooses a fixed number of colors to represent the image. The goal of the algorithm is to minimize the color difference between the input and output image while minimizing the processing time.
The format of the MagickQuantizeImages method is:
unsigned int MagickQuantizeImages\( MagickWand *wand, const unsigned long number_colors,
const ColorspaceType colorspace,
const unsigned long treedepth, const unsigned int dither,
const unsigned int measure_error );
wand:
The magick wand.
number_colors:
The number of colors.
colorspace:
Perform color reduction in this colorspace, typically
RGBColorspace.
treedepth:
Normally, this integer value is zero or one. A zero or
one tells Quantize to choose a optimal tree depth of Log4\(number_colors).% A tree of this depth generally allows the best representation of the
reference image with the least amount of memory and the fastest
computational speed. In some cases, such as an image with low color
dispersion \(a few number of colors), a value other than
Log4\(number_colors) is required. To expand the color tree completely,
use a value of 8.
dither:
A value other than zero distributes the difference between an
original image and the corresponding color reduced algorithm to
neighboring pixels along a Hilbert curve.
measure_error:
A value other than zero measures the difference between
the original and quantized images. This difference is the total
quantization error. The error is computed by summing over all pixels
in an image the distance squared in RGB space between each reference
pixel value and its quantized value.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(number_colors :unsigned-long)
(colorspace %ColorspaceType)
(treedepth :unsigned-long)
(dither :unsigned-int)
(measure_error :unsigned-int))
(defcfun ("MagickQueryFontMetrics" %MagickQueryFontMetrics)
:pointer
"Return a pointer to a double array with 7 elements:
0 character width
1 character height
2 ascender
3 descender
4 text width
5 text height
6 maximum horizontal advance
The format of the MagickQueryFontMetrics method is:
double *MagickQueryFontMetrics\( MagickWand *wand, const DrawingWand *drawing_wand,
const char *text );
wand:
The Magick wand.
drawing_wand:
The drawing wand.
text:
The text.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(drawing_wand %DrawingWand)
(text :string))
(defcfun ("MagickQueryFonts" %MagickQueryFonts)
:pointer
"Returns any font that match the specified pattern.
The format of the MagickQueryFonts function is:
char ** MagickQueryFonts\( const char *pattern, unsigned long *number_fonts );
A description of each parameter follows:
pattern:
Specifies a pointer to a text string containing a pattern.
number_fonts:
This integer returns the number of fonts in the list.
Since GraphicsMagick v1.1.0"
(pattern :string)
(number_fonts :pointer))
(defcfun ("MagickQueryFormats" %MagickQueryFormats)
:pointer
"Returns any image formats that match the specified pattern.
The format of the MagickQueryFormats function is:
char ** MagickQueryFormats\( const char *pattern, unsigned long *number_formats );
pattern:
Specifies a pointer to a text string containing a pattern.
number_formats:
This integer returns the number of image formats in the
list.
Since GraphicsMagick v1.1.0"
(pattern :string)
(number_formats :pointer))
(defcfun ("MagickRadialBlurImage" %MagickRadialBlurImage)
%magick-status
"Radial blurs an image.
The format of the MagickRadialBlurImage method is:
unsigned int MagickRadialBlurImage\( MagickWand *wand, const double angle );
A description of each parameter follows:
wand:
The magick wand.
angle:
The angle of the blur in degrees.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(angle :double))
(defcfun ("MagickRaiseImage" %MagickRaiseImage)
%magick-status
"Creates a simulated three-dimensional button-like effect by lightening and darkening the edges of the image. Members width and height of raise_info define the width of the vertical and horizontal edge of the effect.
The format of the MagickRaiseImage method is:
unsigned int MagickRaiseImage\( MagickWand *wand, const unsigned long width,
const unsigned long height, const long x, const long y,
const unsigned int raise_flag );
wand:
The magick wand.
width,height,x,y:
Define the dimensions of the area to raise.
raise_flag:
A value other than zero creates a 3-D raise effect,
otherwise it has a lowered effect.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(width :unsigned-long)
(height :unsigned-long)
(x :long)
(y :long)
(raise_flag :unsigned-int))
(defcfun ("MagickReadImage" %MagickReadImage)
%magick-status
"Reads an image or image sequence.
The format of the MagickReadImage method is:
unsigned int MagickReadImage\( MagickWand *wand, const char *filename );
A description of each parameter follows:
wand:
The magick wand.
filename:
The image filename.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(filename :string))
(defcfun ("MagickReadImageBlob" %MagickReadImageBlob)
%magick-status
"Reads an image or image sequence from a blob.
The format of the MagickReadImageBlob method is:
unsigned int MagickReadImageBlob\( MagickWand *wand, const unsigned char *blob,
const size_t length );
wand:
The magick wand.
blob:
The blob.
length:
The blob length.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(blob :pointer)
(length %size_t))
(defcfun ("MagickReadImageFile" %MagickReadImageFile)
%magick-status
"Reads an image or image sequence from an open file descriptor.
The format of the MagickReadImageFile method is:
unsigned int MagickReadImageFile\( MagickWand *wand, FILE *file );
A description of each parameter follows:
wand:
The magick wand.
file:
The file descriptor.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(file %FILE))
(defcfun ("MagickReduceNoiseImage" %MagickReduceNoiseImage)
%magick-status
"Smooths the contours of an image while still preserving edge information. The algorithm works by replacing each pixel with its neighbor closest in value. A neighbor is defined by radius. Use a radius of 0 and ReduceNoise\() selects a suitable radius for you.
The format of the MagickReduceNoiseImage method is:
unsigned int MagickReduceNoiseImage\( MagickWand *wand, const double radius );
A description of each parameter follows:
wand:
The magick wand.
radius:
The radius of the pixel neighborhood.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius :double))
(defcfun ("MagickRelinquishMemory" %MagickRelinquishMemory)
%magick-status
"Relinquishes memory resources returned by such methods as MagickDescribeImage\(), MagickGetException\(), etc.
The format of the MagickRelinquishMemory method is:
unsigned int MagickRelinquishMemory\( void *resource );
A description of each parameter follows:
resource:
Relinquish the memory associated with this resource.
Since GraphicsMagick v1.1.0"
(resource :pointer))
(defcfun ("MagickRemoveImage" %MagickRemoveImage)
%magick-status
"Removes an image from the image list.
The format of the MagickRemoveImage method is:
unsigned int MagickRemoveImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickRemoveImageOption" %MagickRemoveImageOption)
%magick-status
"Removes an image format-specific option from the the image \(.e.g MagickRemoveImageOption(wand,\"jpeg\",\"preserve-settings\").
The format of the MagickRemoveImageOption method is:
unsigned int MagickRemoveImageOption\( MagickWand *wand, const char *format,
const char *key );
wand:
The magick wand.
format:
The image format.
key:
The key.
Since GraphicsMagick v1.3.26"
(wand %MagickWand)
(format :string)
(key :string))
(defcfun ("MagickRemoveImageProfile" %MagickRemoveImageProfile)
:pointer
"Removes the named image profile and returns it.
The format of the MagickRemoveImageProfile method is:
unsigned char *MagickRemoveImageProfile\( MagickWand *wand, const char *name,
unsigned long *length );
wand:
The magick wand.
name:
Name of profile to return: ICC, IPTC, or generic profile.
length:
The length of the profile.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(name :string)
(length :pointer))
(defcfun ("MagickResetIterator" %MagickResetIterator)
:void
"Resets the wand iterator. Use it in conjunction with MagickNextImage\() to iterate over all the images in a wand container.
The format of the MagickReset method is:
void MagickResetIterator\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickResampleImage" %MagickResampleImage)
%magick-status
"Resample image to desired resolution.
Bessel Blackman Box
Catrom Cubic Gaussian
Hanning Hermite Lanczos
Mitchell Point Quandratic
Sinc Triangle
Most of the filters are FIR \(finite impulse response), however, Bessel,
Gaussian, and Sinc are IIR \(infinite impulse response). Bessel and Sinc
are windowed \(brought down to zero) with the Blackman filter.
The format of the MagickResampleImage method is:
unsigned int MagickResampleImage\( MagickWand *wand, const double x_resolution,
const double y_resolution, const FilterTypes filter,
const double blur );
wand:
The magick wand.
x_resolution:
The new image x resolution.
y_resolution:
The new image y resolution.
filter:
Image filter to use.
blur:
The blur factor where > 1 is blurry, < 1 is sharp.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x_resolution :double)
(y_resolution :double)
(filter %FilterTypes)
(blur :double))
(defcfun ("MagickResizeImage" %MagickResizeImage)
%magick-status
"Scales an image to the desired dimensions with one of these filters:
Bessel Blackman Box
Catrom Cubic Gaussian
Hanning Hermite Lanczos
Mitchell Point Quandratic
Sinc Triangle
Most of the filters are FIR \(finite impulse response), however, Bessel,
Gaussian, and Sinc are IIR \(infinite impulse response). Bessel and Sinc
are windowed \(brought down to zero) with the Blackman filter.
The format of the MagickResizeImage method is:
unsigned int MagickResizeImage\( MagickWand *wand, const unsigned long columns,
const unsigned long rows, const FilterTypes filter,
const double blur );
wand:
The magick wand.
columns:
The number of columns in the scaled image.
rows:
The number of rows in the scaled image.
filter:
Image filter to use.
blur:
The blur factor where > 1 is blurry, < 1 is sharp.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(columns :unsigned-long)
(rows :unsigned-long)
(filter %FilterTypes)
(blur %double))
(defcfun ("MagickRollImage" %MagickRollImage)
%magick-status
"Offsets an image as defined by x_offset and y_offset.
The format of the MagickRollImage method is:
unsigned int MagickRollImage\( MagickWand *wand, const long x_offset,
const long y_offset );
wand:
The magick wand.
x_offset:
The x offset.
y_offset:
The y offset.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x_offset :long)
(y_offset :long))
(defcfun ("MagickRotateImage" %MagickRotateImage)
%magick-status
"Rotates an image the specified number of degrees. Empty triangles left over from rotating the image are filled with the background color.
The format of the MagickRotateImage method is:
unsigned int MagickRotateImage\( MagickWand *wand, const PixelWand *background,
const double degrees );
wand:
The magick wand.
background:
The background pixel wand.
degrees:
The number of degrees to rotate the image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(background %PixelWand)
(degrees %double))
(defcfun ("MagickSampleImage" %MagickSampleImage)
%magick-status
"Scales an image to the desired dimensions with pixel sampling. Unlike other scaling methods, this method does not introduce any additional color into the scaled image.
The format of the MagickSampleImage method is:
unsigned int MagickSampleImage\( MagickWand *wand, const unsigned long columns,
const unsigned long rows );
wand:
The magick wand.
columns:
The number of columns in the scaled image.
rows:
The number of rows in the scaled image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(columns :unsigned-long)
(rows :unsigned-long))
(defcfun ("MagickScaleImage" %MagickScaleImage)
%magick-status
"Scales the size of an image to the given dimensions.
The format of the MagickScaleImage method is:
unsigned int MagickScaleImage\( MagickWand *wand, const unsigned long columns,
const unsigned long rows );
wand:
The magick wand.
columns:
The number of columns in the scaled image.
rows:
The number of rows in the scaled image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(columns :unsigned-long)
(rows :unsigned-long))
(defcfun ("MagickSeparateImageChannel" %MagickSeparateImageChannel)
%magick-status
"Separates a channel from the image and returns a grayscale image. A channel is a particular color component of each pixel in the image.
The format of the MagickChannelImage method is:
unsigned int MagickSeparateImageChannel\( MagickWand *wand, const ChannelType channel );
wand:
The magick wand.
channel:
Identify which channel to extract: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
BlackChannel.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType))
(defcfun ("MagickSetCompressionQuality" %MagickSetCompressionQuality)
%magick-status
"Sets the image quality factor, which determines compression options when saving the file.
For the JPEG and MPEG image formats, quality is 0 \(lowest image
quality and highest compression) to 100 \(best quality but least
effective compression). The default quality is 75. Use the
-sampling-factor option to specify the factors for chroma
downsampling. To use the same quality value as that found by the
JPEG decoder, use the -define jpeg:preserve-settings flag.
For the MIFF image format, and the TIFF format while using ZIP
compression, quality/10 is the zlib compres- sion level, which is 0
\(worst but fastest compression) to 9 \(best but slowest). It has no
effect on the image appearance, since the compression is always
lossless.
For the JPEG-2000 image format, quality is mapped using a non-linear
equation to the compression ratio required by the Jasper library.
This non-linear equation is intended to loosely approximate the
quality provided by the JPEG v1 format. The default quality value 75
results in a request for 16:1 compression. The quality value 100
results in a request for non-lossy compres- sion.
For the MNG and PNG image formats, the quality value sets the zlib
compression level \(quality / 10) and filter-type \(quality % 10).
Compression levels range from 0 \(fastest compression) to 100 \(best
but slowest). For compression level 0, the Huffman-only strategy is
used, which is fastest but not necessarily the worst compression. If
filter-type is 4 or less, the specified filter-type is used for all
scanlines:
none
sub
up
average
Paeth
If filter-type is 5, adaptive filtering is used when quality is
greater than 50 and the image does not have a color map, otherwise no
filtering is used.
If filter-type is 6, adaptive filtering with minimum-
sum-of-absolute-values is used.
Only if the output is MNG, if filter-type is 7, the LOCO color
transformation and adaptive filtering with
minimum-sum-of-absolute-values are used.
The default is quality is 75, which means nearly the best compression
with adaptive filtering. The quality setting has no effect on the
appearance of PNG and MNG images, since the compression is always
lossless.
For further information, see the PNG specification.
When writing a JNG image with transparency, two quality values are
required, one for the main image and one for the grayscale image that
conveys the opacity channel. These are written as a single integer
equal to the main image quality plus 1000 times the opacity quality.
For example, if you want to use quality 75 for the main image and
quality 90 to compress the opacity data, use -quality 90075.
For the PNM family of formats \(PNM, PGM, and PPM) specify a quality
factor of zero in order to obtain the ASCII variant of the
format. Note that -compress none used to be used to trigger ASCII
output but provided the opposite result of what was expected as
compared with other formats.
The format of the MagickSetCompressionQuality method is:
unsigned int MagickSetCompressionQuality\( MagickWand *wand, const unsigned long quality );
wand:
The magick wand.
delay:
The image quality.
Since GraphicsMagick v1.3.7"
(wand %MagickWand)
(quality :unsigned-long))
(defcfun ("MagickSetDepth" %MagickSetDepth)
%magick-status
"Sets the sample depth to be used when reading from a raw image or a format which requires that the depth be specified in advance by the user.
The format of the MagickSetDepth method is:
unsigned int MagickSetDepth\( MagickWand *wand, const size_t depth );
A description of each parameter follows:
wand:
The magick wand.
depth:
The sample depth.
Since GraphicsMagick v1.3.13"
(wand %MagickWand)
(depth %size_t))
(defcfun ("MagickSetFilename" %MagickSetFilename)
%magick-status
"Sets the filename before you read or write an image file.
The format of the MagickSetFilename method is:
unsigned int MagickSetFilename\( MagickWand *wand, const char *filename );
A description of each parameter follows:
wand:
The magick wand.
filename:
The image filename.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(filename :string))
(defcfun ("MagickSetFormat" %MagickSetFormat)
%magick-status
"Sets the file or blob format \(e.g. \"BMP\") to be used when a file or blob is read. Usually this is not necessary because GraphicsMagick is able to auto-detect the format based on the file header \(or the file extension), but some formats do not use a unique header or the selection may be ambigious. Use MagickSetImageFormat\() to set the format to be used when a file or blob is to be written.
The format of the MagickSetFormat method is:
unsigned int MagickSetFormat\( MagickWand *wand, const char *format );
A description of each parameter follows:
wand:
The magick wand.
filename:
The file or blob format.
Since GraphicsMagick v1.3.13"
(wand %MagickWand)
(format :string))
(defcfun ("MagickSetImage" %MagickSetImage)
%magick-status
"Replaces the last image returned by MagickSetImageIndex\(), MagickNextImage\(), MagickPreviousImage\() with the images from the specified wand.
The format of the MagickSetImage method is:
unsigned int MagickSetImage\( MagickWand *wand, const MagickWand *set_wand );
A description of each parameter follows:
wand:
The magick wand.
set_wand:
The set_wand wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(set_wand %MagickWand))
(defcfun ("MagickSetImageAttribute" %MagickSetImageAttribute)
%magick-status
"MagickSetImageAttribute sets an image attribute
The format of the MagickSetImageAttribute method is:
unsigned int MagickSetImageAttribute\( MagickWand *wand, const char *name,
const char *value );
A description of each parameter follows:
wand:
The magick wand.
name:
The name of the attribute
value:
The value of the attribute
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(name :string)
(value :string))
(defcfun ("MagickSetImageBackgroundColor" %MagickSetImageBackgroundColor)
%magick-status
"Sets the image background color.
The format of the MagickSetImageBackgroundColor method is:
unsigned int MagickSetImageBackgroundColor\( MagickWand *wand, const PixelWand *background );
wand:
The magick wand.
background:
The background pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(background %PixelWand))
(defcfun ("MagickSetImageBluePrimary" %MagickSetImageBluePrimary)
%magick-status
"Sets the image chromaticity blue primary point.
The format of the MagickSetImageBluePrimary method is:
unsigned int MagickSetImageBluePrimary\( MagickWand *wand, const double x, const double y );
wand:
The magick wand.
x:
The blue primary x-point.
y:
The blue primary y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x :double)
(y :double))
(defcfun ("MagickSetImageBorderColor" %MagickSetImageBorderColor)
%magick-status
"Sets the image border color.
The format of the MagickSetImageBorderColor method is:
unsigned int MagickSetImageBorderColor\( MagickWand *wand, const PixelWand *border );
wand:
The magick wand.
border:
The border pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(border %PixelWand))
(defcfun ("MagickSetImageColormapColor" %MagickSetImageColormapColor)
%magick-status
"Sets the color of the specified colormap index.
The format of the MagickSetImageColormapColor method is:
unsigned int MagickSetImageColormapColor\( MagickWand *wand, const unsigned long index,
const PixelWand *color );
wand:
The magick wand.
index:
The offset into the image colormap.
color:
Return the colormap color in this wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(index :unsigned-long)
(color %PixelWand))
(defcfun ("MagickSetImageColorspace" %MagickSetImageColorspace)
%magick-status
"Sets the image colorspace.
The format of the MagickSetImageColorspace method is:
unsigned int MagickSetImageColorspace\( MagickWand *wand, const ColorspaceType colorspace );
wand:
The magick wand.
colorspace:
The image colorspace: UndefinedColorspace, RGBColorspace,
GRAYColorspace, TransparentColorspace, OHTAColorspace, XYZColorspace,
YCbCrColorspace, YCCColorspace, YIQColorspace, YPbPrColorspace,
YPbPrColorspace, YUVColorspace, CMYKColorspace, sRGBColorspace,
HSLColorspace, or HWBColorspace.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(colorspace %ColorspaceType))
(defcfun ("MagickSetImageCompose" %MagickSetImageCompose)
%magick-status
"Sets the image composite operator, useful for specifying how to composite the image thumbnail when using the MagickMontageImage\() method.
The format of the MagickSetImageCompose method is:
unsigned int MagickSetImageCompose\( MagickWand *wand, const CompositeOperator compose );
wand:
The magick wand.
compose:
The image composite operator.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(compose %CompositeOperator))
(defcfun ("MagickSetImageCompression" %MagickSetImageCompression)
%magick-status
"Sets the image compression.
The format of the MagickSetImageCompression method is:
unsigned int MagickSetImageCompression\( MagickWand *wand,
const CompressionType compression );
wand:
The magick wand.
compression:
The image compression type.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(compression %CompressionType))
(defcfun ("MagickSetImageDelay" %MagickSetImageDelay)
%magick-status
"Sets the image delay.
The format of the MagickSetImageDelay method is:
unsigned int MagickSetImageDelay\( MagickWand *wand, const unsigned long delay );
wand:
The magick wand.
delay:
The image delay in 1/100th of a second.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(delay :unsigned-long))
(defcfun ("MagickSetImageChannelDepth" %MagickSetImageChannelDepth)
%magick-status
"Sets the depth of a particular image channel.
The format of the MagickSetImageChannelDepth method is:
unsigned int MagickSetImageChannelDepth\( MagickWand *wand, const ChannelType channel,
const unsigned long depth );
wand:
The magick wand.
channel:
Identify which channel to extract: RedChannel, GreenChannel,
BlueChannel, OpacityChannel, CyanChannel, MagentaChannel, YellowChannel,
BlackChannel.
depth:
The image depth in bits.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(depth :unsigned-long))
(defcfun ("MagickSetImageDepth" %MagickSetImageDepth)
%magick-status
"Sets the image depth.
The format of the MagickSetImageDepth method is:
unsigned int MagickSetImageDepth\( MagickWand *wand, const unsigned long depth );
wand:
The magick wand.
depth:
The image depth in bits: 8, 16, or 32.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(depth :unsigned-long))
(defcfun ("MagickSetImageDispose" %MagickSetImageDispose)
%magick-status
"Sets the image disposal method.
The format of the MagickSetImageDispose method is:
unsigned int MagickSetImageDispose\( MagickWand *wand, const DisposeType dispose );
wand:
The magick wand.
dispose:
The image disposeal type.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(dispose %DisposeType))
(defcfun ("MagickSetImageFilename" %MagickSetImageFilename)
%magick-status
"Sets the filename of a particular image in a sequence.
The format of the MagickSetImageFilename method is:
unsigned int MagickSetImageFilename\( MagickWand *wand, const char *filename );
wand:
The magick wand.
filename:
The image filename.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(filename :string))
(defcfun ("MagickSetImageFormat" %MagickSetImageFormat)
%magick-status
"Sets the format of a particular image in a sequence. The format is designated by a magick string \(e.g. \"GIF\").
The format of the MagickSetImageFormat method is:
unsigned int MagickSetImageFormat\( MagickWand *wand, const char *format );
wand:
The magick wand.
magick:
The image format.
Since GraphicsMagick v1.3.1"
(wand %MagickWand)
(format :string))
(defcfun ("MagickSetImageFuzz" %MagickSetImageFuzz)
%magick-status
"Sets the color comparison fuzz factor. Colors closer than the fuzz factor are considered to be the same when comparing colors. Note that some other functions such as MagickColorFloodfillImage\() implicitly set this value.
The format of the MagickSetImageFuzz method is:
unsigned int MagickSetImageFuzz\( MagickWand *wand, const double fuzz );
A description of each parameter follows:
wand:
The magick wand.
fuzz:
The color comparison fuzz factor
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(fuzz :double))
(defcfun ("MagickSetImageGamma" %MagickSetImageGamma)
%magick-status
"Sets the image gamma.
The format of the MagickSetImageGamma method is:
unsigned int MagickSetImageGamma\( MagickWand *wand, const double gamma );
A description of each parameter follows:
wand:
The magick wand.
gamma:
The image gamma.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(gamma :double))
(defcfun ("MagickSetImageGeometry" %MagickSetImageGeometry)
%magick-status
"Sets the image geometry string.
The format of the MagickSetImageGeometry method is:
unsigned int MagickSetImageGeometry\( MagickWand *wand, const char *geometry )
A description of each parameter follows:
wand: The magick wand.
geometry: The image geometry.
Since GraphicsMagick v1.3.20"
(wand %MagickWand)
(geometry :string))
(defcfun ("MagickSetImageGravity" %MagickSetImageGravity)
%magick-status
"Sets the image gravity. This is used when evaluating regions defined by a geometry and the image dimensions. It may be used in conjunction with operations which use a geometry parameter to adjust the x, y parameters of the final operation. Gravity is used in composition to determine where the image should be placed within the defined geometry region. It may be used with montage to effect placement of the image within the tile.
The format of the MagickSetImageGravity method is:
unsigned int MagickSetImageGravity\( MagickWand *wand, const GravityType );
A description of each parameter follows:
wand:
The magick wand.
gravity:
The image gravity. Available values are ForgetGravity,
NorthWestGravity, NorthGravity, NorthEastGravity, WestGravity,
CenterGravity, EastGravity, SouthWestGravity, SouthGravity,
SouthEastGravity, and StaticGravity
Since GraphicsMagick v1.3.20"
(wand %MagickWand)
(gravitytype %GravityType))
(defcfun ("MagickSetImageGreenPrimary" %MagickSetImageGreenPrimary)
%magick-status
"Sets the image chromaticity green primary point.
The format of the MagickSetImageGreenPrimary method is:
unsigned int MagickSetImageGreenPrimary\( MagickWand *wand, const double x, const double y );
wand:
The magick wand.
x:
The green primary x-point.
y:
The green primary y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x %double)
(y %double))
(defcfun ("MagickSetImageIndex" %MagickSetImageIndex)
%magick-status
"Set the current image to the position of the list specified with the index parameter.
The format of the MagickSetImageIndex method is:
unsigned int MagickSetImageIndex\( MagickWand *wand, const long index );
A description of each parameter follows:
wand:
The magick wand.
index:
The scene number.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(index :long))
(defcfun ("MagickSetImageInterlaceScheme" %MagickSetImageInterlaceScheme)
%magick-status
"Sets the image interlace scheme. Please use SetInterlaceScheme\() instead to change the interlace scheme used when writing the image.
The format of the MagickSetImageInterlaceScheme method is:
unsigned int MagickSetImageInterlaceScheme\( MagickWand *wand,
const InterlaceType interlace_scheme );
wand:
The magick wand.
interlace_scheme:
The image interlace scheme: NoInterlace, LineInterlace,
PlaneInterlace, PartitionInterlace.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(interlace_scheme %InterlaceType))
(defcfun ("MagickSetImageIterations" %MagickSetImageIterations)
%magick-status
"Sets the image iterations.
The format of the MagickSetImageIterations method is:
unsigned int MagickSetImageIterations\( MagickWand *wand, const unsigned long iterations );
wand:
The magick wand.
delay:
The image delay in 1/100th of a second.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(iterations :unsigned-long))
(defcfun ("MagickSetImageMatte" %MagickSetImageMatte)
%magick-status
"Sets the image matte flag. The image opacity \(inverse of transparency) channel is enabled if the matte flag is True.
The format of the MagickSetImageMatte method is:
unsigned int MagickSetImageMatte\( MagickWand *wand, const unsigned int matte )
A description of each parameter follows:
wand:
The magick wand.
matte:
The image matte.
Since GraphicsMagick v1.3.20"
(wand %MagickWand)
(matte :unsigned-int))
(defcfun ("MagickSetImageMatteColor" %MagickSetImageMatteColor)
%magick-status
"Sets the image matte color.
The format of the MagickSetImageMatteColor method is:
unsigned int MagickSetImageMatteColor\( MagickWand *wand, const PixelWand *matte );
wand:
The magick wand.
matte:
The matte pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(matte %PixelWand))
(defcfun ("MagickSetImageOption" %MagickSetImageOption)
%magick-status
"Associates one or options with a particular image format \(.e.g MagickSetImageOption\(wand,\"jpeg\",\"preserve-settings\",\"true\").
The format of the MagickSetImageOption method is:
unsigned int MagickSetImageOption\( MagickWand *wand, const char *format, const char *key,
const char *value );
wand:
The magick wand.
format:
The image format.
key:
The key.
value:
The value.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(format :string)
(key :string)
(value :string))
(defcfun ("MagickSetImageOrientation" %MagickSetImageOrientation)
%magick-status
"Sets the internal image orientation type.
The EXIF orientation tag will be updated if present.
The format of the MagickSetImageOrientation method is:
MagickSetImageOrientation\( MagickWand *wand, OrientationType new_orientation )
A description of each parameter follows:
wand:
The magick wand.
new_orientation:
The new orientation of the image. One of:
UndefinedOrientation Image orientation not specified.
TopLeftOrientation Left to right and Top to bottom.
TopRightOrientation Right to left and Top to bottom.
BottomRightOrientation Right to left and Bottom to top.
BottomLeftOrientation Left to right and Bottom to top.
LeftTopOrientation Top to bottom and Left to right.
RightTopOrientation Top to bottom and Right to left.
RightBottomOrientation Bottom to top and Right to left.
LeftBottomOrientation Bottom to top and Left to right.
Returns True on success, False otherwise.
Since GraphicsMagick v1.3.26"
(wand %MagickWand)
(new_orientation %OrientationType))
(defcfun ("MagickSetImagePage" %MagickSetImagePage)
%magick-status
"Sets the image page size and offset used when placing \(e.g. compositing) the image. Pass all zeros for the default placement.
The format of the MagickSetImagePage method is:
unsigned int MagickSetImagePage\( MagickWand *wand, const unsigned long width,
const unsigned long height, const long x, const long y );
wand:
The magick wand.
width, height:
The region size.
x, y:
Offset \(from top left) on base canvas image on
which to composite image data.
Since GraphicsMagick v1.3.18"
(wand %MagickWand)
(width :unsigned-long)
(height :unsigned-long)
(x :long)
(y :long))
(defcfun ("MagickSetImagePixels" %MagickSetImagePixels)
%magick-status
"Accepts pixel data and stores it in the image at the location you specify. The method returns False on success otherwise True if an error is encountered. The pixel data can be either char, short int, int, long, float, or double in the order specified by map.
Suppose your want want to upload the first scanline of a 640x480 image from
character data in red-green-blue order:
MagickSetImagePixels\(wand,0,0,0,640,1,\"RGB\",CharPixel,pixels);
The format of the MagickSetImagePixels method is:
unsigned int MagickSetImagePixels\( MagickWand *wand, const long x_offset, const long y_offset,
const unsigned long columns, const unsigned long rows,
const char *map, const StorageType storage,
unsigned char *pixels );
wand:
The magick wand.
x_offset, y_offset:
Offset \(from top left) on base canvas image on
which to composite image data.
columns, rows:
Dimensions of image.
map:
This string reflects the expected ordering of the pixel array.
It can be any combination or order of R = red, G = green, B = blue,
A = alpha \(same as Transparency), O = Opacity, T = Transparency,
C = cyan, Y = yellow, M = magenta, K = black, or I = intensity
\(for grayscale). Specify \"P\" = pad, to skip over a quantum which is
intentionally ignored. Creation of an alpha channel for CMYK images
is currently not supported.
storage:
Define the data type of the pixels. Float and double types are
expected to be normalized [0..1] otherwise [0..MaxRGB]. Choose from
these types: CharPixel, ShortPixel, IntegerPixel, LongPixel, FloatPixel,
or DoublePixel.
pixels:
This array of values contain the pixel components as defined by
map and type. You must preallocate this array where the expected
length varies depending on the values of width, height, map, and type.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x_offset :long)
(y_offset :long)
(columns :unsigned-long)
(rows :unsigned-long)
(map :string)
(storage %StorageType)
(pixels :pointer))
(defcfun ("MagickSetImageProfile" %MagickSetImageProfile)
%magick-status
"Adds a named profile to the magick wand. If a profile with the same name already exists, it is replaced. This method differs from the MagickProfileImage\() method in that it does not apply any CMS color profiles.
The format of the MagickSetImageProfile method is:
unsigned int MagickSetImageProfile\( MagickWand *wand, const char *name,
const unsigned char *profile,
const unsigned long length );
wand:
The magick wand.
name:
Name of profile to add or remove: ICC, IPTC, or generic profile.
profile:
The profile.
length:
The length of the profile.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(name :string)
(profile :pointer)
(length :unsigned-long))
(defcfun ("MagickSetImageRedPrimary" %MagickSetImageRedPrimary)
%magick-status
"Sets the image chromaticity red primary point.
The format of the MagickSetImageRedPrimary method is:
unsigned int MagickSetImageRedPrimary\( MagickWand *wand, const double x, const double y );
wand:
The magick wand.
x:
The red primary x-point.
y:
The red primary y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x %double)
(y %double))
(defcfun ("MagickSetImageRenderingIntent" %MagickSetImageRenderingIntent)
%magick-status
"Sets the image rendering intent.
The format of the MagickSetImageRenderingIntent method is:
unsigned int MagickSetImageRenderingIntent\( MagickWand *wand,
const RenderingIntent rendering_intent );
wand:
The magick wand.
rendering_intent:
The image rendering intent: UndefinedIntent,
SaturationIntent, PerceptualIntent, AbsoluteIntent, or RelativeIntent.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(rendering_intent %RenderingIntent))
(defcfun ("MagickSetImageResolution" %MagickSetImageResolution)
%magick-status
"Sets the image resolution.
The format of the MagickSetImageResolution method is:
unsigned int MagickSetImageResolution\( MagickWand *wand, const double x_resolution,
const doubtl y_resolution );
wand:
The magick wand.
x_resolution:
The image x resolution.
y_resolution:
The image y resolution.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x_resolution %double)
(y_resolution %double))
(defcfun ("MagickSetImageScene" %MagickSetImageScene)
%magick-status
"Sets the image scene.
The format of the MagickSetImageScene method is:
unsigned int MagickSetImageScene\( MagickWand *wand, const unsigned long scene );
wand:
The magick wand.
delay:
The image scene number.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(scene :unsigned-long))
(defcfun ("MagickSetImageType" %MagickSetImageType)
%magick-status
"Sets the image type.
The format of the MagickSetImageType method is:
unsigned int MagickSetImageType\( MagickWand *wand, const ImageType image_type );
wand:
The magick wand.
image_type:
The image type: UndefinedType, BilevelType, GrayscaleType,
GrayscaleMatteType, PaletteType, PaletteMatteType, TrueColorType,
TrueColorMatteType, ColorSeparationType, ColorSeparationMatteType,
or OptimizeType.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(image_type %ImageType))
(defcfun ("MagickSetImageSavedType" %MagickSetImageSavedType)
%magick-status
"Sets the image type that will be used when the image is saved.
The format of the MagickSetImageSavedType method is:
unsigned int MagickSetImageSavedType\( MagickWand *wand, const ImageType image_type );
wand:
The magick wand.
image_type:
The image type: UndefinedType, BilevelType, GrayscaleType,
GrayscaleMatteType, PaletteType, PaletteMatteType, TrueColorType,
TrueColorMatteType, ColorSeparationType, ColorSeparationMatteType,
or OptimizeType.
Since GraphicsMagick v1.3.13"
(wand %MagickWand)
(image_type %ImageType))
(defcfun ("MagickSetImageUnits" %MagickSetImageUnits)
%magick-status
"Sets the image units of resolution.
The format of the MagickSetImageUnits method is:
unsigned int MagickSetImageUnits\( MagickWand *wand, const ResolutionType units );
wand:
The magick wand.
units:
The image units of resolution : Undefinedresolution,
PixelsPerInchResolution, or PixelsPerCentimeterResolution.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(units %ResolutionType))
(defcfun ("MagickSetImageVirtualPixelMethod" %MagickSetImageVirtualPixelMethod)
%magick-status
"Sets the image virtual pixel method.
The format of the MagickSetImageVirtualPixelMethod method is:
unsigned int MagickSetImageVirtualPixelMethod\( MagickWand *wand,
const VirtualPixelMethod method );
wand:
The magick wand.
method:
The image virtual pixel method : UndefinedVirtualPixelMethod,
ConstantVirtualPixelMethod, EdgeVirtualPixelMethod,
MirrorVirtualPixelMethod, or TileVirtualPixelMethod.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(method %VirtualPixelMethod))
(defcfun ("MagickSetInterlaceScheme" %MagickSetInterlaceScheme)
%magick-status
"Sets the interlace scheme used when writing the image.
The format of the MagickSetInterlaceScheme method is:
unsigned int MagickSetInterlaceScheme\( MagickWand *wand,
const InterlaceType interlace_scheme );
wand:
The magick wand.
interlace_scheme:
The image interlace scheme: NoInterlace, LineInterlace,
PlaneInterlace, PartitionInterlace.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(interlace_scheme %InterlaceType))
(defcfun ("MagickSetResolution" %MagickSetResolution)
%magick-status
"Sets the resolution \(density) of the magick wand. Set it before you read an EPS, PDF, or Postscript file in order to influence the size of the returned image, or after an image has already been created to influence the rendered image size when used with typesetting software.
Also see MagickSetResolutionUnits\() which specifies the units to use for
the image resolution.
The format of the MagickSetResolution method is:
unsigned int MagickSetResolution\( MagickWand *wand, const double x_resolution,
const double y_resolution );
wand:
The magick wand.
x_resolution:
The horizontal resolution
y_resolution:
The vertical reesolution
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(x_resolution %double)
(y_resolution %double))
(defcfun ("MagickSetResolutionUnits" %MagickSetResolutionUnits)
%magick-status
"Sets the resolution units of the magick wand. It should be used in conjunction with MagickSetResolution\(). This method works both before and after an image has been read.
Also see MagickSetImageUnits\() which specifies the units which apply to
the image resolution setting after an image has been read.
The format of the MagickSetResolutionUnits method is:
unsigned int MagickSetResolutionUnits\( MagickWand *wand, const ResolutionType units );
wand:
The magick wand.
units:
The image units of resolution : Undefinedresolution,
PixelsPerInchResolution, or PixelsPerCentimeterResolution.
Since GraphicsMagick v1.3.8"
(wand %MagickWand)
(units %ResolutionType))
(defcfun ("MagickSetResourceLimit" %MagickSetResourceLimit)
%magick-status
"Sets the limit for a particular resource in megabytes.
The format of the MagickSetResourceLimit method is:
unsigned int MagickSetResourceLimit\( const ResourceType type, const unsigned long *limit );
type:
The type of resource: DiskResource, FileResource, MapResource,
MemoryResource, PixelsResource, ThreadsResource, WidthResource,
HeightResource.
o The maximum limit for the resource.
Since GraphicsMagick v1.1.0"
(type %ResourceType)
(limit :pointer))
(defcfun ("MagickSetSamplingFactors" %MagickSetSamplingFactors)
%magick-status
"Sets the image sampling factors.
The format of the MagickSetSamplingFactors method is:
unsigned int MagickSetSamplingFactors\( MagickWand *wand, const unsigned long number_factors,
const double *sampling_factors );
wand:
The magick wand.
number_factoes:
The number of factors.
sampling_factors:
An array of doubles representing the sampling factor
for each color component \(in RGB order).
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(number_factors :unsigned-long)
(sampling_factors :pointer))
(defcfun ("MagickSetSize" %MagickSetSize)
%magick-status
"Sets the size of the magick wand. Set it before you read a raw image format such as RGB, GRAY, or CMYK.
The format of the MagickSetSize method is:
unsigned int MagickSetSize\( MagickWand *wand, const unsigned long columns,
const unsigned long rows );
wand:
The magick wand.
columns:
The width in pixels.
height:
The height in pixels.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(columns :unsigned-long)
(rows :unsigned-long))
(defcfun ("MagickSetImageWhitePoint" %MagickSetImageWhitePoint)
%magick-status
"Sets the image chromaticity white point.
The format of the MagickSetImageWhitePoint method is:
unsigned int MagickSetImageWhitePoint\( MagickWand *wand, const double x, const double y );
wand:
The magick wand.
x:
The white x-point.
y:
The white y-point.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(x %double)
(y %double))
(defcfun ("MagickSetPassphrase" %MagickSetPassphrase)
%magick-status
"Sets the passphrase.
The format of the MagickSetPassphrase method is:
unsigned int MagickSetPassphrase\( MagickWand *wand, const char *passphrase );
A description of each parameter follows:
wand:
The magick wand.
passphrase:
The passphrase.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(passphrase :string))
(defcfun ("MagickSharpenImage" %MagickSharpenImage)
%magick-status
"Sharpens an image. We convolve the image with a Gaussian operator of the given radius and standard deviation \(sigma). For reasonable results, the radius should be larger than sigma. Use a radius of 0 and SharpenImage\() selects a suitable radius for you.
The format of the MagickSharpenImage method is:
unsigned int MagickSharpenImage\( MagickWand *wand, const double radius, const double sigma );
wand:
The magick wand.
radius:
The radius of the Gaussian, in pixels, not counting the center
pixel.
sigma:
The standard deviation of the Gaussian, in pixels.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius %double)
(sigma %double))
(defcfun ("MagickShaveImage" %MagickShaveImage)
%magick-status
"Shaves pixels from the image edges. It allocates the memory necessary for the new Image structure and returns a pointer to the new image.
The format of the MagickShaveImage method is:
unsigned int MagickShaveImage\( MagickWand *wand, const unsigned long columns,
const unsigned long rows );
wand:
The magick wand.
columns:
The number of columns in the scaled image.
rows:
The number of rows in the scaled image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(columns :unsigned-long)
(rows :unsigned-long))
(defcfun ("MagickShearImage" %MagickShearImage)
%magick-status
"Slides one edge of an image along the X or Y axis, creating a parallelogram. An X direction shear slides an edge along the X axis, while a Y direction shear slides an edge along the Y axis. The amount of the shear is controlled by a shear angle. For X direction shears, x_shear is measured relative to the Y axis, and similarly, for Y direction shears y_shear is measured relative to the X axis. Empty triangles left over from shearing the image are filled with the background color.
The format of the MagickShearImage method is:
unsigned int MagickShearImage\( MagickWand *wand, const PixelWand *background,
const double x_shear, onst double y_shear );
wand:
The magick wand.
background:
The background pixel wand.
x_shear:
The number of degrees to shear the image.
y_shear:
The number of degrees to shear the image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(background %PixelWand)
(x_shear %double)
(y_shear %double))
(defcfun ("MagickSolarizeImage" %MagickSolarizeImage)
%magick-status
"Applies a special effect to the image, similar to the effect achieved in a photo darkroom by selectively exposing areas of photo sensitive paper to light. Threshold ranges from 0 to MaxRGB and is a measure of the extent of the solarization.
The format of the MagickSolarizeImage method is:
unsigned int MagickSolarizeImage\( MagickWand *wand, const double threshold );
A description of each parameter follows:
wand:
The magick wand.
threshold:
Define the extent of the solarization.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(threshold %double))
(defcfun ("MagickSpreadImage" %MagickSpreadImage)
%magick-status
"Is a special effects method that randomly displaces each pixel in a block defined by the radius parameter.
The format of the MagickSpreadImage method is:
unsigned int MagickSpreadImage\( MagickWand *wand, const double radius );
A description of each parameter follows:
wand:
The magick wand.
radius:
Choose a random pixel in a neighborhood of this extent.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius %double))
(defcfun ("MagickSteganoImage" %MagickSteganoImage)
%MagickWand
"Use MagickSteganoImage\() to hide a digital watermark within the image. Recover the hidden watermark later to prove that the authenticity of an image. Offset defines the start position within the image to hide the watermark.
The format of the MagickSteganoImage method is:
MagickWand *MagickSteganoImage\( MagickWand *wand, const MagickWand *watermark_wand,
const long offset );
wand:
The magick wand.
watermark_wand:
The watermark wand.
offset:
Start hiding at this offset into the image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(watermark_wand %MagickWand)
(offset :long))
(defcfun ("MagickStereoImage" %MagickStereoImage)
%MagickWand
"Composites two images and produces a single image that is the composite of a left and right image of a stereo pair
The format of the MagickStereoImage method is:
MagickWand *MagickStereoImage\( MagickWand *wand, const MagickWand *offset_wand );
wand:
The magick wand.
offset_wand:
Another image wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(offset_wand %MagickWand))
(defcfun ("MagickStripImage" %MagickStripImage)
%magick-status
"Removes all profiles and text attributes from the image.
The format of the MagickStripImage method is:
unsigned int MagickStripImage\( MagickWand *wand );
A description of each parameter follows:
wand:
The magick wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand))
(defcfun ("MagickSwirlImage" %MagickSwirlImage)
%magick-status
"Swirls the pixels about the center of the image, where degrees indicates the sweep of the arc through which each pixel is moved. You get a more dramatic effect as the degrees move from 1 to 360.
The format of the MagickSwirlImage method is:
unsigned int MagickSwirlImage\( MagickWand *wand, const double degrees );
A description of each parameter follows:
wand:
The magick wand.
degrees:
Define the tightness of the swirling effect.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(degrees %double))
(defcfun ("MagickTextureImage" %MagickTextureImage)
%MagickWand
"Repeatedly tiles the texture image across and down the image canvas.
The format of the MagickTextureImage method is:
MagickWand *MagickTextureImage\( MagickWand *wand, const MagickWand *texture_wand );
wand:
The magick wand.
texture_wand:
The texture wand
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(texture_wand %MagickWand))
(defcfun ("MagickThresholdImage" %MagickThresholdImage)
%magick-status
"Changes the value of individual pixels based on the intensity of each pixel compared to threshold. The result is a high-contrast, two color image.
The format of the MagickThresholdImage method is:
unsigned int MagickThresholdImage\( MagickWand *wand, const double threshold );
wand:
The magick wand.
threshold:
Define the threshold value.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(threshold %double))
(defcfun ("MagickThresholdImageChannel" %MagickThresholdImageChannel)
%magick-status
"Changes the value of individual pixel component based on the intensity of each pixel compared to threshold. The result is a high-contrast, two color image.
The format of the MagickThresholdImage method is:
unsigned int MagickThresholdImageChannel\( MagickWand *wand, const ChannelType channel,
const double threshold );
wand:
The magick wand.
channel:
The channel.
threshold:
Define the threshold value.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(channel %ChannelType)
(threshold %double))
(defcfun ("MagickTintImage" %MagickTintImage)
%magick-status
"Applies a color vector to each pixel in the image. The length of the vector is 0 for black and white and at its maximum for the midtones. The vector weighting function is f\(x)=\(1-\(4.0*\(\(x-0.5)*\(x-0.5)))).
The format of the MagickTintImage method is:
unsigned int MagickTintImage\( MagickWand *wand, const PixelWand *tint,
const PixelWand *opacity );
wand:
The magick wand.
tint:
The tint pixel wand.
opacity:
The opacity pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(tint %PixelWand)
(opacity %PixelWand))
(defcfun ("MagickTransformImage" %MagickTransformImage)
%MagickWand
"Is a convenience method that behaves like MagickResizeImage\() or MagickCropImage\() but accepts scaling and/or cropping information as a region geometry specification. If the operation fails, the original image handle is returned.
The format of the MagickTransformImage method is:
MagickWand *MagickTransformImage\( MagickWand *wand, const char *crop,
const char *geometry );
wand:
The magick wand.
crop:
A crop geometry string. This geometry defines a subregion of the
image to crop.
geometry:
An image geometry string. This geometry defines the final
size of the image.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(crop :string)
(geometry :string))
(defcfun ("MagickTransparentImage" %MagickTransparentImage)
%magick-status
"Changes any pixel that matches color with the color defined by fill.
The format of the MagickTransparentImage method is:
unsigned int MagickTransparentImage\( MagickWand *wand, const PixelWand *target,
const unsigned int opacity, const double fuzz );
wand:
The magick wand.
target:
Change this target color to specified opacity value within
the image.
opacity:
The replacement opacity value.
fuzz:
By default target must match a particular pixel color
exactly. However, in many cases two colors may differ by a small amount.
The fuzz member of image defines how much tolerance is acceptable to
consider two colors as the same. For example, set fuzz to 10 and the
color red at intensities of 100 and 102 respectively are now interpreted
as the same color for the purposes of the floodfill.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(target %PixelWand)
(opacity :unsigned-int)
(fuzz %double))
(defcfun ("MagickTrimImage" %MagickTrimImage)
%magick-status
"Remove edges that are the background color from the image.
The format of the MagickTrimImage method is:
unsigned int MagickTrimImage\( MagickWand *wand, const double fuzz );
A description of each parameter follows:
wand:
The magick wand.
fuzz:
By default target must match a particular pixel color
exactly. However, in many cases two colors may differ by a small amount.
The fuzz member of image defines how much tolerance is acceptable to
consider two colors as the same. For example, set fuzz to 10 and the
color red at intensities of 100 and 102 respectively are now interpreted
as the same color for the purposes of the floodfill.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(fuzz %double))
(defcfun ("MagickUnsharpMaskImage" %MagickUnsharpMaskImage)
%magick-status
"Sharpens an image. We convolve the image with a Gaussian operator of the given radius and standard deviation \(sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and UnsharpMaskImage\() selects a suitable radius for you.
The format of the MagickUnsharpMaskImage method is:
unsigned int MagickUnsharpMaskImage\( MagickWand *wand, const double radius, const double sigma,
const double amount, const double threshold );
wand:
The magick wand.
radius:
The radius of the Gaussian, in pixels, not counting the center
pixel.
sigma:
The standard deviation of the Gaussian, in pixels.
amount:
The percentage of the difference between the original and the
blur image that is added back into the original.
threshold:
The threshold in pixels needed to apply the diffence amount.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(radius %double)
(sigma %double)
(amount %double)
(threshold %double))
(defcfun ("MagickWaveImage" %MagickWaveImage)
%magick-status
"Creates a \"ripple\" effect in the image by shifting the pixels vertically along a sine wave whose amplitude and wavelength is specified by the given parameters.
The format of the MagickWaveImage method is:
unsigned int MagickWaveImage\( MagickWand *wand, const double amplitude,
const double wave_length );
wand:
The magick wand.
amplitude, wave_length:
Define the amplitude and wave length of the
sine wave.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(amplitude %double)
(wave_length %double))
(defcfun ("MagickWhiteThresholdImage" %MagickWhiteThresholdImage)
%magick-status
"Is like ThresholdImage\() but forces all pixels above the threshold into white while leaving all pixels below the threshold unchanged.
The format of the MagickWhiteThresholdImage method is:
unsigned int MagickWhiteThresholdImage\( MagickWand *wand, const PixelWand *threshold );
wand:
The magick wand.
threshold:
The pixel wand.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(threshold %PixelWand))
(defcfun ("MagickWriteImage" %MagickWriteImage)
%magick-status
"Writes an image.
The format of the MagickWriteImage method is:
unsigned int MagickWriteImage\( MagickWand *wand, const char *filename );
A description of each parameter follows:
wand:
The magick wand.
filename:
The image filename.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(filename :string))
(defcfun ("MagickWriteImagesFile" %MagickWriteImagesFile)
%magick-status
"Writes an image or image sequence to a stdio FILE handle. This may be used to append an encoded image to an already existing appended image sequence if the file seek position is at the end of an existing file.
The format of the MagickWriteImages method is:
unsigned int MagickWriteImagesFile\( MagickWand *wand, FILE *file, const unsigned int adjoin );
wand:
The magick wand.
file:
The open \(and positioned) file handle.
adjoin:
join images into a single multi-image file.
Since GraphicsMagick v1.3.13"
(wand %MagickWand)
(file %FILE)
(adjoin :unsigned-int))
(defcfun ("MagickWriteImageBlob" %MagickWriteImageBlob)
:pointer
"Implements direct to memory image formats. It returns the image as a blob \(a formatted \"file\" in memory) and its length, starting from the current position in the image sequence. Use MagickSetImageFormat\() to set the format to write to the blob \(GIF, JPEG, PNG, etc.).
Use MagickResetIterator\() on the wand if it is desired to write
a sequence from the beginning and the iterator is not currently
at the beginning.
The format of the MagickWriteImageBlob method is:
unsigned char *MagickWriteImageBlob\( MagickWand *wand, size_t *length );
A description of each parameter follows:
wand:
The magick wand.
length:
The length of the blob.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(length :pointer))
(defcfun ("MagickWriteImageFile" %MagickWriteImageFile)
%magick-status
"Writes an image to an open file descriptor.
The format of the MagickWandToFile method is:
unsigned int MagickWriteImageFile\( MagickWand *wand, FILE *file );
A description of each parameter follows:
wand:
The magick wand.
file:
The file descriptor.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(file %FILE))
(defcfun ("MagickWriteImages" %MagickWriteImages)
%magick-status
"Writes an image or image sequence. If the wand represents an image sequence, then it is written starting at the first frame in the sequence.
The format of the MagickWriteImages method is:
unsigned int MagickWriteImages\( MagickWand *wand, const char *filename,
const unsigned int adjoin );
wand:
The magick wand.
filename:
The image filename.
adjoin:
join images into a single multi-image file.
Since GraphicsMagick v1.1.0"
(wand %MagickWand)
(filename :string)
(adjoin :unsigned-int))
(defcfun ("NewMagickWand" %NewMagickWand)
%MagickWand
"Returns a wand required for all other methods in the API.
The format of the NewMagickWand method is:
MagickWand NewMagickWand\( void );
Since GraphicsMagick v1.1.0")
|
[
{
"context": "22 09:20:30 edi Exp $\n\n;;; Copyright (c) 2003, Dr. Edmund Weitz. All rights reserved.\n\n;;; Redistribution and use",
"end": 206,
"score": 0.9998337030410767,
"start": 194,
"tag": "NAME",
"value": "Edmund Weitz"
},
{
"context": "string.\"\n ;; this function originally provided by JP Massar for CL-PPCRE; note\n ;; that we can't use APPLY w",
"end": 2133,
"score": 0.9880314469337463,
"start": 2124,
"tag": "NAME",
"value": "JP Massar"
}
] |
thirdparty/cl-interpol-0.1.2/util.lisp
|
hanshuebner/cadr2
| 13 |
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-INTERPOL; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-interpol/util.lisp,v 1.7 2003/10/22 09:20:30 edi Exp $
;;; Copyright (c) 2003, Dr. Edmund Weitz. 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 AUTHOR 'AS IS' AND ANY EXPRESSED
;;; 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 AUTHOR 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-interpol)
(define-condition simple-reader-error (simple-condition reader-error)
()
(:documentation "A reader error which can be signalled by ERROR."))
(defmacro signal-reader-error (format-control &rest format-arguments)
"Like ERROR but signals a SIMPLE-READER-ERROR for the stream
*STREAM*."
`(error 'simple-reader-error
:stream *stream*
:format-control ,format-control
:format-arguments (list ,@format-arguments)))
(defun string-list-to-string (string-list)
"Concatenates a list of strings to one string."
;; this function originally provided by JP Massar for CL-PPCRE; note
;; that we can't use APPLY with CONCATENATE here because of
;; CALL-ARGUMENTS-LIMIT
(let ((total-size 0))
(dolist (string string-list)
(incf total-size (length string)))
(let ((result-string (make-array total-size :element-type 'character))
(curr-pos 0))
(dolist (string string-list)
(replace result-string string :start1 curr-pos)
(incf curr-pos (length string)))
result-string)))
(defun quote-meta-chars (string)
"Quote, i.e. prefix with #\\\\, all non-word characters in STRING."
(with-output-to-string (s)
(loop for char across string
if (or (char<= #\a char #\z)
(char<= #\A char #\Z)
(char<= #\0 char #\9)
(char= #\_ char)) do
(write-char char s)
else do
(write-char #\\ s)
(write-char char s))))
(defun get-end-delimiter (start-delimiter delimiters &key errorp)
"Find the closing delimiter corresponding to the opening delimiter
START-DELIMITER in a list DELIMITERS which is formatted like
*OUTER-DELIMITERS*. If ERRORP is true, signal an error if none was
found, otherwise return NIL."
(loop for element in delimiters
if (eql start-delimiter element)
do (return-from get-end-delimiter start-delimiter)
else if (and (consp element)
(char= start-delimiter (car element)))
do (return-from get-end-delimiter (cdr element)))
(when errorp
(signal-reader-error "~S not allowed as a delimiter here" start-delimiter)))
(declaim (inline make-collector))
(defun make-collector ()
"Create an empty string which can be extended by
VECTOR-PUSH-EXTEND."
(make-array 0
:element-type 'character
:fill-pointer t
:adjustable t))
(declaim (inline make-char-from-code))
(defun make-char-from-code (number)
"Create character from char-code NUMBER. NUMBER can be NIL which is
interpreted as 0."
;; Only look at rightmost eight bits in compliance with Perl
(let ((code (logand #o377 (or number 0))))
(or (and (< code char-code-limit)
(code-char code))
(signal-reader-error "No character for char-code #x~X"
number))))
(declaim (inline lower-case-p*))
(defun lower-case-p* (char)
"Whether CHAR is a character which has case and is lowercase."
(or (not (both-case-p char))
(lower-case-p char)))
(defmacro read-char* ()
"Convenience macro because we always read from the same string with
the same arguments."
`(read-char *stream* t nil t))
(defmacro peek-char* ()
"Convenience macro because we always peek at the same string with
the same arguments."
`(peek-char nil *stream* t nil t))
(declaim (inline copy-readtable*))
(defun copy-readtable* ()
"Returns a copy of the readtable which was current when
INTERPOL-READER was invoked. Memoizes its result."
(or *readtable-copy*
(setq *readtable-copy* (copy-readtable))))
(declaim (inline nsubvec))
(defun nsubvec (sequence start &optional (end (length sequence)))
"Return a subvector by pointing to location in original vector."
(make-array (- end start)
:element-type (array-element-type sequence)
:displaced-to sequence
:displaced-index-offset start))
|
82101
|
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-INTERPOL; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-interpol/util.lisp,v 1.7 2003/10/22 09:20:30 edi Exp $
;;; Copyright (c) 2003, Dr. <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 AUTHOR 'AS IS' AND ANY EXPRESSED
;;; 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 AUTHOR 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-interpol)
(define-condition simple-reader-error (simple-condition reader-error)
()
(:documentation "A reader error which can be signalled by ERROR."))
(defmacro signal-reader-error (format-control &rest format-arguments)
"Like ERROR but signals a SIMPLE-READER-ERROR for the stream
*STREAM*."
`(error 'simple-reader-error
:stream *stream*
:format-control ,format-control
:format-arguments (list ,@format-arguments)))
(defun string-list-to-string (string-list)
"Concatenates a list of strings to one string."
;; this function originally provided by <NAME> for CL-PPCRE; note
;; that we can't use APPLY with CONCATENATE here because of
;; CALL-ARGUMENTS-LIMIT
(let ((total-size 0))
(dolist (string string-list)
(incf total-size (length string)))
(let ((result-string (make-array total-size :element-type 'character))
(curr-pos 0))
(dolist (string string-list)
(replace result-string string :start1 curr-pos)
(incf curr-pos (length string)))
result-string)))
(defun quote-meta-chars (string)
"Quote, i.e. prefix with #\\\\, all non-word characters in STRING."
(with-output-to-string (s)
(loop for char across string
if (or (char<= #\a char #\z)
(char<= #\A char #\Z)
(char<= #\0 char #\9)
(char= #\_ char)) do
(write-char char s)
else do
(write-char #\\ s)
(write-char char s))))
(defun get-end-delimiter (start-delimiter delimiters &key errorp)
"Find the closing delimiter corresponding to the opening delimiter
START-DELIMITER in a list DELIMITERS which is formatted like
*OUTER-DELIMITERS*. If ERRORP is true, signal an error if none was
found, otherwise return NIL."
(loop for element in delimiters
if (eql start-delimiter element)
do (return-from get-end-delimiter start-delimiter)
else if (and (consp element)
(char= start-delimiter (car element)))
do (return-from get-end-delimiter (cdr element)))
(when errorp
(signal-reader-error "~S not allowed as a delimiter here" start-delimiter)))
(declaim (inline make-collector))
(defun make-collector ()
"Create an empty string which can be extended by
VECTOR-PUSH-EXTEND."
(make-array 0
:element-type 'character
:fill-pointer t
:adjustable t))
(declaim (inline make-char-from-code))
(defun make-char-from-code (number)
"Create character from char-code NUMBER. NUMBER can be NIL which is
interpreted as 0."
;; Only look at rightmost eight bits in compliance with Perl
(let ((code (logand #o377 (or number 0))))
(or (and (< code char-code-limit)
(code-char code))
(signal-reader-error "No character for char-code #x~X"
number))))
(declaim (inline lower-case-p*))
(defun lower-case-p* (char)
"Whether CHAR is a character which has case and is lowercase."
(or (not (both-case-p char))
(lower-case-p char)))
(defmacro read-char* ()
"Convenience macro because we always read from the same string with
the same arguments."
`(read-char *stream* t nil t))
(defmacro peek-char* ()
"Convenience macro because we always peek at the same string with
the same arguments."
`(peek-char nil *stream* t nil t))
(declaim (inline copy-readtable*))
(defun copy-readtable* ()
"Returns a copy of the readtable which was current when
INTERPOL-READER was invoked. Memoizes its result."
(or *readtable-copy*
(setq *readtable-copy* (copy-readtable))))
(declaim (inline nsubvec))
(defun nsubvec (sequence start &optional (end (length sequence)))
"Return a subvector by pointing to location in original vector."
(make-array (- end start)
:element-type (array-element-type sequence)
:displaced-to sequence
:displaced-index-offset start))
| true |
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-INTERPOL; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-interpol/util.lisp,v 1.7 2003/10/22 09:20:30 edi Exp $
;;; Copyright (c) 2003, Dr. 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 AUTHOR 'AS IS' AND ANY EXPRESSED
;;; 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 AUTHOR 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-interpol)
(define-condition simple-reader-error (simple-condition reader-error)
()
(:documentation "A reader error which can be signalled by ERROR."))
(defmacro signal-reader-error (format-control &rest format-arguments)
"Like ERROR but signals a SIMPLE-READER-ERROR for the stream
*STREAM*."
`(error 'simple-reader-error
:stream *stream*
:format-control ,format-control
:format-arguments (list ,@format-arguments)))
(defun string-list-to-string (string-list)
"Concatenates a list of strings to one string."
;; this function originally provided by PI:NAME:<NAME>END_PI for CL-PPCRE; note
;; that we can't use APPLY with CONCATENATE here because of
;; CALL-ARGUMENTS-LIMIT
(let ((total-size 0))
(dolist (string string-list)
(incf total-size (length string)))
(let ((result-string (make-array total-size :element-type 'character))
(curr-pos 0))
(dolist (string string-list)
(replace result-string string :start1 curr-pos)
(incf curr-pos (length string)))
result-string)))
(defun quote-meta-chars (string)
"Quote, i.e. prefix with #\\\\, all non-word characters in STRING."
(with-output-to-string (s)
(loop for char across string
if (or (char<= #\a char #\z)
(char<= #\A char #\Z)
(char<= #\0 char #\9)
(char= #\_ char)) do
(write-char char s)
else do
(write-char #\\ s)
(write-char char s))))
(defun get-end-delimiter (start-delimiter delimiters &key errorp)
"Find the closing delimiter corresponding to the opening delimiter
START-DELIMITER in a list DELIMITERS which is formatted like
*OUTER-DELIMITERS*. If ERRORP is true, signal an error if none was
found, otherwise return NIL."
(loop for element in delimiters
if (eql start-delimiter element)
do (return-from get-end-delimiter start-delimiter)
else if (and (consp element)
(char= start-delimiter (car element)))
do (return-from get-end-delimiter (cdr element)))
(when errorp
(signal-reader-error "~S not allowed as a delimiter here" start-delimiter)))
(declaim (inline make-collector))
(defun make-collector ()
"Create an empty string which can be extended by
VECTOR-PUSH-EXTEND."
(make-array 0
:element-type 'character
:fill-pointer t
:adjustable t))
(declaim (inline make-char-from-code))
(defun make-char-from-code (number)
"Create character from char-code NUMBER. NUMBER can be NIL which is
interpreted as 0."
;; Only look at rightmost eight bits in compliance with Perl
(let ((code (logand #o377 (or number 0))))
(or (and (< code char-code-limit)
(code-char code))
(signal-reader-error "No character for char-code #x~X"
number))))
(declaim (inline lower-case-p*))
(defun lower-case-p* (char)
"Whether CHAR is a character which has case and is lowercase."
(or (not (both-case-p char))
(lower-case-p char)))
(defmacro read-char* ()
"Convenience macro because we always read from the same string with
the same arguments."
`(read-char *stream* t nil t))
(defmacro peek-char* ()
"Convenience macro because we always peek at the same string with
the same arguments."
`(peek-char nil *stream* t nil t))
(declaim (inline copy-readtable*))
(defun copy-readtable* ()
"Returns a copy of the readtable which was current when
INTERPOL-READER was invoked. Memoizes its result."
(or *readtable-copy*
(setq *readtable-copy* (copy-readtable))))
(declaim (inline nsubvec))
(defun nsubvec (sequence start &optional (end (length sequence)))
"Return a subvector by pointing to location in original vector."
(make-array (- end start)
:element-type (array-element-type sequence)
:displaced-to sequence
:displaced-index-offset start))
|
[
{
"context": "E.\n;\n; beta-reduce-full.lisp\n;\n; Original authors: Sol Swords <[email protected]>\n\n(in-package \"ACL2\")\n\n(inc",
"end": 1420,
"score": 0.9998691082000732,
"start": 1410,
"tag": "NAME",
"value": "Sol Swords"
},
{
"context": "educe-full.lisp\n;\n; Original authors: Sol Swords <[email protected]>\n\n(in-package \"ACL2\")\n\n(include-book \"tools/bstar",
"end": 1442,
"score": 0.9999302625656128,
"start": 1422,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/centaur/misc/beta-reduce-full.lisp
|
ragerdl/acl2-defthm-rc2
| 1 |
; Centaur Miscellaneous Books
; Copyright (C) 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.
;
; beta-reduce-full.lisp
;
; Original authors: Sol Swords <[email protected]>
(in-package "ACL2")
(include-book "tools/bstar" :dir :system)
(include-book "tools/flag" :dir :system)
;; note: intended to be compatible (redundant) with misc/beta-reduce.lisp
(defevaluator beta-eval beta-eval-list nil)
(mutual-recursion
(defun beta-reduce-full-rec (x alist)
(declare (xargs :guard (and (pseudo-termp x)
(symbol-alistp alist))
:verify-guards nil))
(b* (((when (null x)) nil)
((when (variablep x)) (cdr (assoc x alist)))
((when (fquotep x)) x)
(args (beta-reduce-full-rec-list (fargs x) alist))
(fn (ffn-symb x))
((when (atom fn)) (cons fn args))
(formals (lambda-formals fn))
(body (lambda-body fn)))
(beta-reduce-full-rec body (pairlis$ formals args))))
(defun beta-reduce-full-rec-list (x alist)
(declare (xargs :guard (and (pseudo-term-listp x)
(symbol-alistp alist))))
(if (endp x)
nil
(cons (beta-reduce-full-rec (car x) alist)
(beta-reduce-full-rec-list (cdr x) alist)))))
(flag::make-flag beta-reduce-flg beta-reduce-full-rec
:flag-mapping ((beta-reduce-full-rec . term)
(beta-reduce-full-rec-list . list)))
(defthm len-of-beta-reduce-full-rec-list
(equal (len (beta-reduce-full-rec-list x alist))
(len x)))
(defthm true-listp-of-beta-reduce-full-rec-list
(true-listp (beta-reduce-full-rec-list x alist))
:hints (("goal" :induct (len x))))
(defthm symbol-alistp-pairlis
(implies (symbol-listp keys)
(symbol-alistp (pairlis$ keys vals))))
(verify-guards beta-reduce-full-rec)
(defun beta-eval-alist (x a)
(if (atom x)
nil
(cons (cons (caar x) (beta-eval (cdar x) a))
(beta-eval-alist (cdr x) a))))
(defthm beta-eval-alist-of-pairlis
(equal (beta-eval-alist (pairlis$ keys vals) a)
(pairlis$ keys (beta-eval-list vals a))))
(defthm lookup-in-beta-eval-alist
(implies k
(equal (assoc k (beta-eval-alist x a))
(and (assoc k x)
(cons k (beta-eval (cdr (assoc k x)) a))))))
(local
(defthm strip-cdrs-of-pairlis
(implies (and (true-listp vals)
(equal (len keys) (len vals)))
(equal (strip-cdrs (pairlis$ keys valS))
vals))))
(defthm-beta-reduce-flg
(defthm pseudo-termp-of-beta-reduce-full-rec
(implies (and (pseudo-termp x)
(pseudo-term-listp (strip-cdrs alist)))
(pseudo-termp (beta-reduce-full-rec x alist)))
:flag term)
(defthm pseudo-term-listp-of-beta-reduce-full-rec-list
(implies (and (pseudo-term-listp x)
(pseudo-term-listp (strip-cdrs alist)))
(pseudo-term-listp (beta-reduce-full-rec-list x alist)))
:flag list))
(defthm-beta-reduce-flg
(defthm beta-reduce-full-rec-correct
(implies (pseudo-termp x)
(equal (beta-eval (beta-reduce-full-rec x alist) a)
(beta-eval x (beta-eval-alist alist a))))
:hints ('(:in-theory (enable beta-eval-constraint-0)))
:flag term)
(defthm beta-reduce-full-rec-list-correct
(implies (pseudo-term-listp x)
(equal (beta-eval-list (beta-reduce-full-rec-list x alist) a)
(beta-eval-list x (beta-eval-alist alist a))))
:flag list))
(mutual-recursion
(defun beta-reduce-full (x)
(declare (xargs :guard (pseudo-termp x)))
(b* (((when (or (variablep x)
(fquotep x))) x)
(args (beta-reduce-full-list (fargs x)))
(fn (ffn-symb x))
((when (atom fn)) (cons fn args))
(formals (lambda-formals fn))
(body (lambda-body fn)))
(beta-reduce-full-rec body (pairlis$ formals args))))
(defun beta-reduce-full-list (x)
(declare (xargs :guard (pseudo-term-listp x)))
(if (endp x)
nil
(cons (beta-reduce-full (car x))
(beta-reduce-full-list (cdr x))))))
(defthm len-of-beta-reduce-full-list
(equal (len (beta-reduce-full-list x))
(len x)))
(defthm true-listp-of-beta-reduce-full-list
(true-listp (beta-reduce-full-list x))
:hints (("goal" :induct (len x))))
(defthm-beta-reduce-flg
(defthm pseudo-termp-of-beta-reduce-full
(implies (pseudo-termp x)
(pseudo-termp (beta-reduce-full x)))
:flag term)
(defthm pseudo-term-listp-of-beta-reduce-full-list
(implies (pseudo-term-listp x)
(pseudo-term-listp (beta-reduce-full-list x)))
:flag list))
(defthm-beta-reduce-flg
(defthm beta-reduce-full-correct
(implies (pseudo-termp x)
(equal (beta-eval (beta-reduce-full x) a)
(beta-eval x a)))
:hints ('(:in-theory (enable beta-eval-constraint-0)))
:flag term)
(defthm beta-reduce-full-list-correct
(implies (pseudo-term-listp x)
(equal (beta-eval-list (beta-reduce-full-list x) a)
(beta-eval-list x a)))
:flag list))
|
69906
|
; Centaur Miscellaneous Books
; Copyright (C) 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.
;
; beta-reduce-full.lisp
;
; Original authors: <NAME> <<EMAIL>>
(in-package "ACL2")
(include-book "tools/bstar" :dir :system)
(include-book "tools/flag" :dir :system)
;; note: intended to be compatible (redundant) with misc/beta-reduce.lisp
(defevaluator beta-eval beta-eval-list nil)
(mutual-recursion
(defun beta-reduce-full-rec (x alist)
(declare (xargs :guard (and (pseudo-termp x)
(symbol-alistp alist))
:verify-guards nil))
(b* (((when (null x)) nil)
((when (variablep x)) (cdr (assoc x alist)))
((when (fquotep x)) x)
(args (beta-reduce-full-rec-list (fargs x) alist))
(fn (ffn-symb x))
((when (atom fn)) (cons fn args))
(formals (lambda-formals fn))
(body (lambda-body fn)))
(beta-reduce-full-rec body (pairlis$ formals args))))
(defun beta-reduce-full-rec-list (x alist)
(declare (xargs :guard (and (pseudo-term-listp x)
(symbol-alistp alist))))
(if (endp x)
nil
(cons (beta-reduce-full-rec (car x) alist)
(beta-reduce-full-rec-list (cdr x) alist)))))
(flag::make-flag beta-reduce-flg beta-reduce-full-rec
:flag-mapping ((beta-reduce-full-rec . term)
(beta-reduce-full-rec-list . list)))
(defthm len-of-beta-reduce-full-rec-list
(equal (len (beta-reduce-full-rec-list x alist))
(len x)))
(defthm true-listp-of-beta-reduce-full-rec-list
(true-listp (beta-reduce-full-rec-list x alist))
:hints (("goal" :induct (len x))))
(defthm symbol-alistp-pairlis
(implies (symbol-listp keys)
(symbol-alistp (pairlis$ keys vals))))
(verify-guards beta-reduce-full-rec)
(defun beta-eval-alist (x a)
(if (atom x)
nil
(cons (cons (caar x) (beta-eval (cdar x) a))
(beta-eval-alist (cdr x) a))))
(defthm beta-eval-alist-of-pairlis
(equal (beta-eval-alist (pairlis$ keys vals) a)
(pairlis$ keys (beta-eval-list vals a))))
(defthm lookup-in-beta-eval-alist
(implies k
(equal (assoc k (beta-eval-alist x a))
(and (assoc k x)
(cons k (beta-eval (cdr (assoc k x)) a))))))
(local
(defthm strip-cdrs-of-pairlis
(implies (and (true-listp vals)
(equal (len keys) (len vals)))
(equal (strip-cdrs (pairlis$ keys valS))
vals))))
(defthm-beta-reduce-flg
(defthm pseudo-termp-of-beta-reduce-full-rec
(implies (and (pseudo-termp x)
(pseudo-term-listp (strip-cdrs alist)))
(pseudo-termp (beta-reduce-full-rec x alist)))
:flag term)
(defthm pseudo-term-listp-of-beta-reduce-full-rec-list
(implies (and (pseudo-term-listp x)
(pseudo-term-listp (strip-cdrs alist)))
(pseudo-term-listp (beta-reduce-full-rec-list x alist)))
:flag list))
(defthm-beta-reduce-flg
(defthm beta-reduce-full-rec-correct
(implies (pseudo-termp x)
(equal (beta-eval (beta-reduce-full-rec x alist) a)
(beta-eval x (beta-eval-alist alist a))))
:hints ('(:in-theory (enable beta-eval-constraint-0)))
:flag term)
(defthm beta-reduce-full-rec-list-correct
(implies (pseudo-term-listp x)
(equal (beta-eval-list (beta-reduce-full-rec-list x alist) a)
(beta-eval-list x (beta-eval-alist alist a))))
:flag list))
(mutual-recursion
(defun beta-reduce-full (x)
(declare (xargs :guard (pseudo-termp x)))
(b* (((when (or (variablep x)
(fquotep x))) x)
(args (beta-reduce-full-list (fargs x)))
(fn (ffn-symb x))
((when (atom fn)) (cons fn args))
(formals (lambda-formals fn))
(body (lambda-body fn)))
(beta-reduce-full-rec body (pairlis$ formals args))))
(defun beta-reduce-full-list (x)
(declare (xargs :guard (pseudo-term-listp x)))
(if (endp x)
nil
(cons (beta-reduce-full (car x))
(beta-reduce-full-list (cdr x))))))
(defthm len-of-beta-reduce-full-list
(equal (len (beta-reduce-full-list x))
(len x)))
(defthm true-listp-of-beta-reduce-full-list
(true-listp (beta-reduce-full-list x))
:hints (("goal" :induct (len x))))
(defthm-beta-reduce-flg
(defthm pseudo-termp-of-beta-reduce-full
(implies (pseudo-termp x)
(pseudo-termp (beta-reduce-full x)))
:flag term)
(defthm pseudo-term-listp-of-beta-reduce-full-list
(implies (pseudo-term-listp x)
(pseudo-term-listp (beta-reduce-full-list x)))
:flag list))
(defthm-beta-reduce-flg
(defthm beta-reduce-full-correct
(implies (pseudo-termp x)
(equal (beta-eval (beta-reduce-full x) a)
(beta-eval x a)))
:hints ('(:in-theory (enable beta-eval-constraint-0)))
:flag term)
(defthm beta-reduce-full-list-correct
(implies (pseudo-term-listp x)
(equal (beta-eval-list (beta-reduce-full-list x) a)
(beta-eval-list x a)))
:flag list))
| true |
; Centaur Miscellaneous Books
; Copyright (C) 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.
;
; beta-reduce-full.lisp
;
; Original authors: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
(in-package "ACL2")
(include-book "tools/bstar" :dir :system)
(include-book "tools/flag" :dir :system)
;; note: intended to be compatible (redundant) with misc/beta-reduce.lisp
(defevaluator beta-eval beta-eval-list nil)
(mutual-recursion
(defun beta-reduce-full-rec (x alist)
(declare (xargs :guard (and (pseudo-termp x)
(symbol-alistp alist))
:verify-guards nil))
(b* (((when (null x)) nil)
((when (variablep x)) (cdr (assoc x alist)))
((when (fquotep x)) x)
(args (beta-reduce-full-rec-list (fargs x) alist))
(fn (ffn-symb x))
((when (atom fn)) (cons fn args))
(formals (lambda-formals fn))
(body (lambda-body fn)))
(beta-reduce-full-rec body (pairlis$ formals args))))
(defun beta-reduce-full-rec-list (x alist)
(declare (xargs :guard (and (pseudo-term-listp x)
(symbol-alistp alist))))
(if (endp x)
nil
(cons (beta-reduce-full-rec (car x) alist)
(beta-reduce-full-rec-list (cdr x) alist)))))
(flag::make-flag beta-reduce-flg beta-reduce-full-rec
:flag-mapping ((beta-reduce-full-rec . term)
(beta-reduce-full-rec-list . list)))
(defthm len-of-beta-reduce-full-rec-list
(equal (len (beta-reduce-full-rec-list x alist))
(len x)))
(defthm true-listp-of-beta-reduce-full-rec-list
(true-listp (beta-reduce-full-rec-list x alist))
:hints (("goal" :induct (len x))))
(defthm symbol-alistp-pairlis
(implies (symbol-listp keys)
(symbol-alistp (pairlis$ keys vals))))
(verify-guards beta-reduce-full-rec)
(defun beta-eval-alist (x a)
(if (atom x)
nil
(cons (cons (caar x) (beta-eval (cdar x) a))
(beta-eval-alist (cdr x) a))))
(defthm beta-eval-alist-of-pairlis
(equal (beta-eval-alist (pairlis$ keys vals) a)
(pairlis$ keys (beta-eval-list vals a))))
(defthm lookup-in-beta-eval-alist
(implies k
(equal (assoc k (beta-eval-alist x a))
(and (assoc k x)
(cons k (beta-eval (cdr (assoc k x)) a))))))
(local
(defthm strip-cdrs-of-pairlis
(implies (and (true-listp vals)
(equal (len keys) (len vals)))
(equal (strip-cdrs (pairlis$ keys valS))
vals))))
(defthm-beta-reduce-flg
(defthm pseudo-termp-of-beta-reduce-full-rec
(implies (and (pseudo-termp x)
(pseudo-term-listp (strip-cdrs alist)))
(pseudo-termp (beta-reduce-full-rec x alist)))
:flag term)
(defthm pseudo-term-listp-of-beta-reduce-full-rec-list
(implies (and (pseudo-term-listp x)
(pseudo-term-listp (strip-cdrs alist)))
(pseudo-term-listp (beta-reduce-full-rec-list x alist)))
:flag list))
(defthm-beta-reduce-flg
(defthm beta-reduce-full-rec-correct
(implies (pseudo-termp x)
(equal (beta-eval (beta-reduce-full-rec x alist) a)
(beta-eval x (beta-eval-alist alist a))))
:hints ('(:in-theory (enable beta-eval-constraint-0)))
:flag term)
(defthm beta-reduce-full-rec-list-correct
(implies (pseudo-term-listp x)
(equal (beta-eval-list (beta-reduce-full-rec-list x alist) a)
(beta-eval-list x (beta-eval-alist alist a))))
:flag list))
(mutual-recursion
(defun beta-reduce-full (x)
(declare (xargs :guard (pseudo-termp x)))
(b* (((when (or (variablep x)
(fquotep x))) x)
(args (beta-reduce-full-list (fargs x)))
(fn (ffn-symb x))
((when (atom fn)) (cons fn args))
(formals (lambda-formals fn))
(body (lambda-body fn)))
(beta-reduce-full-rec body (pairlis$ formals args))))
(defun beta-reduce-full-list (x)
(declare (xargs :guard (pseudo-term-listp x)))
(if (endp x)
nil
(cons (beta-reduce-full (car x))
(beta-reduce-full-list (cdr x))))))
(defthm len-of-beta-reduce-full-list
(equal (len (beta-reduce-full-list x))
(len x)))
(defthm true-listp-of-beta-reduce-full-list
(true-listp (beta-reduce-full-list x))
:hints (("goal" :induct (len x))))
(defthm-beta-reduce-flg
(defthm pseudo-termp-of-beta-reduce-full
(implies (pseudo-termp x)
(pseudo-termp (beta-reduce-full x)))
:flag term)
(defthm pseudo-term-listp-of-beta-reduce-full-list
(implies (pseudo-term-listp x)
(pseudo-term-listp (beta-reduce-full-list x)))
:flag list))
(defthm-beta-reduce-flg
(defthm beta-reduce-full-correct
(implies (pseudo-termp x)
(equal (beta-eval (beta-reduce-full x) a)
(beta-eval x a)))
:hints ('(:in-theory (enable beta-eval-constraint-0)))
:flag term)
(defthm beta-reduce-full-list-correct
(implies (pseudo-term-listp x)
(equal (beta-eval-list (beta-reduce-full-list x) a)
(beta-eval-list x a)))
:flag list))
|
[
{
"context": "ity of British Columbia\n;; Written (originally) by Yan Peng (19th October, 2021)\n;;\n;; License: A 3-clause BS",
"end": 89,
"score": 0.9996252655982971,
"start": 81,
"tag": "NAME",
"value": "Yan Peng"
}
] |
books/projects/smtlink/trusted/z3-py/translate-uninterpreted.lisp
|
pennyan/acl2
| 3 |
;; Copyright (C) 2015, University of British Columbia
;; Written (originally) by Yan Peng (19th October, 2021)
;;
;; License: A 3-clause BSD license.
;; See the LICENSE file distributed with ACL2
(in-package "SMT")
(include-book "centaur/fty/top" :dir :system)
(include-book "xdoc/top" :dir :system)
(include-book "std/util/define" :dir :system)
(include-book "std/strings/top" :dir :system)
(include-book "../../verified/hint-interface")
(include-book "../property/uninterpreted-property")
(include-book "translate-declarations")
(include-book "datatypes")
(local (in-theory (enable paragraph-p word-p string-or-symbol-p)))
(define generate-uninterpreted-property ((name symbolp)
(hints smt-function-p))
:returns (property pseudo-term-listp)
(b* ((name (symbol-fix name))
(hints (smt-function-fix hints))
((smt-function h) hints))
(uninterpreted-property name h.formal-types h.return-type)))
(define translate-uninterpreted-arguments ((types symbol-listp)
(type-alst symbol-smt-type-alist-p))
:returns (translated paragraph-p)
:measure (len types)
(b* ((types (symbol-list-fix types))
(type-alst (symbol-smt-type-alist-fix type-alst))
((unless (consp types)) nil)
((cons first rest) types)
(translated-type (translate-type first (cdr (assoc-equal first type-alst)))))
(cons `(#\, #\Space ,translated-type)
(translate-uninterpreted-arguments rest type-alst))))
(define translate-one-uninterpreted ((name symbolp)
(hints smt-function-p)
(types symbol-smt-type-alist-p))
:returns (translated paragraph-p)
(b* ((name (symbol-fix name))
(hints (smt-function-fix hints))
(types (symbol-smt-type-alist-fix types))
((smt-function h) hints)
(translated-formals
(translate-uninterpreted-arguments h.formal-types types))
(translated-returns
(translate-uninterpreted-arguments (list h.return-type) types)))
`(,(translate-variable name) "= z3.Function("
#\' ,name #\' ,translated-formals ,translated-returns
")" #\Newline)))
(define translate-uninterpreted ((uninterpreted symbol-smt-function-alist-p)
(types symbol-smt-type-alist-p))
:returns (mv (py-term paragraph-p)
(smt-property pseudo-term-list-listp))
:measure (len (symbol-smt-function-alist-fix uninterpreted))
(b* ((uninterpreted (symbol-smt-function-alist-fix uninterpreted))
(types (symbol-smt-type-alist-fix types))
((unless (consp uninterpreted)) (mv nil nil))
((cons first rest) uninterpreted)
((cons name hints) first)
(first-decl (translate-one-uninterpreted name hints types))
(first-property (generate-uninterpreted-property name hints))
((mv rest-decl rest-property) (translate-uninterpreted rest types)))
(mv (cons first-decl rest-decl)
(cons first-property rest-property))))
|
16370
|
;; Copyright (C) 2015, University of British Columbia
;; Written (originally) by <NAME> (19th October, 2021)
;;
;; License: A 3-clause BSD license.
;; See the LICENSE file distributed with ACL2
(in-package "SMT")
(include-book "centaur/fty/top" :dir :system)
(include-book "xdoc/top" :dir :system)
(include-book "std/util/define" :dir :system)
(include-book "std/strings/top" :dir :system)
(include-book "../../verified/hint-interface")
(include-book "../property/uninterpreted-property")
(include-book "translate-declarations")
(include-book "datatypes")
(local (in-theory (enable paragraph-p word-p string-or-symbol-p)))
(define generate-uninterpreted-property ((name symbolp)
(hints smt-function-p))
:returns (property pseudo-term-listp)
(b* ((name (symbol-fix name))
(hints (smt-function-fix hints))
((smt-function h) hints))
(uninterpreted-property name h.formal-types h.return-type)))
(define translate-uninterpreted-arguments ((types symbol-listp)
(type-alst symbol-smt-type-alist-p))
:returns (translated paragraph-p)
:measure (len types)
(b* ((types (symbol-list-fix types))
(type-alst (symbol-smt-type-alist-fix type-alst))
((unless (consp types)) nil)
((cons first rest) types)
(translated-type (translate-type first (cdr (assoc-equal first type-alst)))))
(cons `(#\, #\Space ,translated-type)
(translate-uninterpreted-arguments rest type-alst))))
(define translate-one-uninterpreted ((name symbolp)
(hints smt-function-p)
(types symbol-smt-type-alist-p))
:returns (translated paragraph-p)
(b* ((name (symbol-fix name))
(hints (smt-function-fix hints))
(types (symbol-smt-type-alist-fix types))
((smt-function h) hints)
(translated-formals
(translate-uninterpreted-arguments h.formal-types types))
(translated-returns
(translate-uninterpreted-arguments (list h.return-type) types)))
`(,(translate-variable name) "= z3.Function("
#\' ,name #\' ,translated-formals ,translated-returns
")" #\Newline)))
(define translate-uninterpreted ((uninterpreted symbol-smt-function-alist-p)
(types symbol-smt-type-alist-p))
:returns (mv (py-term paragraph-p)
(smt-property pseudo-term-list-listp))
:measure (len (symbol-smt-function-alist-fix uninterpreted))
(b* ((uninterpreted (symbol-smt-function-alist-fix uninterpreted))
(types (symbol-smt-type-alist-fix types))
((unless (consp uninterpreted)) (mv nil nil))
((cons first rest) uninterpreted)
((cons name hints) first)
(first-decl (translate-one-uninterpreted name hints types))
(first-property (generate-uninterpreted-property name hints))
((mv rest-decl rest-property) (translate-uninterpreted rest types)))
(mv (cons first-decl rest-decl)
(cons first-property rest-property))))
| true |
;; Copyright (C) 2015, University of British Columbia
;; Written (originally) by PI:NAME:<NAME>END_PI (19th October, 2021)
;;
;; License: A 3-clause BSD license.
;; See the LICENSE file distributed with ACL2
(in-package "SMT")
(include-book "centaur/fty/top" :dir :system)
(include-book "xdoc/top" :dir :system)
(include-book "std/util/define" :dir :system)
(include-book "std/strings/top" :dir :system)
(include-book "../../verified/hint-interface")
(include-book "../property/uninterpreted-property")
(include-book "translate-declarations")
(include-book "datatypes")
(local (in-theory (enable paragraph-p word-p string-or-symbol-p)))
(define generate-uninterpreted-property ((name symbolp)
(hints smt-function-p))
:returns (property pseudo-term-listp)
(b* ((name (symbol-fix name))
(hints (smt-function-fix hints))
((smt-function h) hints))
(uninterpreted-property name h.formal-types h.return-type)))
(define translate-uninterpreted-arguments ((types symbol-listp)
(type-alst symbol-smt-type-alist-p))
:returns (translated paragraph-p)
:measure (len types)
(b* ((types (symbol-list-fix types))
(type-alst (symbol-smt-type-alist-fix type-alst))
((unless (consp types)) nil)
((cons first rest) types)
(translated-type (translate-type first (cdr (assoc-equal first type-alst)))))
(cons `(#\, #\Space ,translated-type)
(translate-uninterpreted-arguments rest type-alst))))
(define translate-one-uninterpreted ((name symbolp)
(hints smt-function-p)
(types symbol-smt-type-alist-p))
:returns (translated paragraph-p)
(b* ((name (symbol-fix name))
(hints (smt-function-fix hints))
(types (symbol-smt-type-alist-fix types))
((smt-function h) hints)
(translated-formals
(translate-uninterpreted-arguments h.formal-types types))
(translated-returns
(translate-uninterpreted-arguments (list h.return-type) types)))
`(,(translate-variable name) "= z3.Function("
#\' ,name #\' ,translated-formals ,translated-returns
")" #\Newline)))
(define translate-uninterpreted ((uninterpreted symbol-smt-function-alist-p)
(types symbol-smt-type-alist-p))
:returns (mv (py-term paragraph-p)
(smt-property pseudo-term-list-listp))
:measure (len (symbol-smt-function-alist-fix uninterpreted))
(b* ((uninterpreted (symbol-smt-function-alist-fix uninterpreted))
(types (symbol-smt-type-alist-fix types))
((unless (consp uninterpreted)) (mv nil nil))
((cons first rest) uninterpreted)
((cons name hints) first)
(first-decl (translate-one-uninterpreted name hints types))
(first-property (generate-uninterpreted-property name hints))
((mv rest-decl rest-property) (translate-uninterpreted rest types)))
(mv (cons first-decl rest-decl)
(cons first-property rest-property))))
|
[
{
"context": ";;;; magical-gen.asd\n;;;;\n;;;; Author: Robert Smith\n\n(asdf:defsystem #:magicl-gen\n :license \"BSD 3-C",
"end": 51,
"score": 0.9997747540473938,
"start": 39,
"tag": "NAME",
"value": "Robert Smith"
}
] |
magicl-gen.asd
|
selwynsimsek/magicl
| 0 |
;;;; magical-gen.asd
;;;;
;;;; Author: Robert Smith
(asdf:defsystem #:magicl-gen
:license "BSD 3-Clause (See LICENSE.txt)"
:description "Generate MAGICL interfaces"
:maintainer "Rigetti Computing"
:author "Rigetti Computing"
:depends-on (#:cffi
#:cffi-libffi)
:serial t
:components
((:file "src/packages")
(:module "transcendental"
:serial t
:components ((:file "package")))
(:file "src/cffi-types")
(:file "src/generate-interface/generate-interface")))
|
83780
|
;;;; magical-gen.asd
;;;;
;;;; Author: <NAME>
(asdf:defsystem #:magicl-gen
:license "BSD 3-Clause (See LICENSE.txt)"
:description "Generate MAGICL interfaces"
:maintainer "Rigetti Computing"
:author "Rigetti Computing"
:depends-on (#:cffi
#:cffi-libffi)
:serial t
:components
((:file "src/packages")
(:module "transcendental"
:serial t
:components ((:file "package")))
(:file "src/cffi-types")
(:file "src/generate-interface/generate-interface")))
| true |
;;;; magical-gen.asd
;;;;
;;;; Author: PI:NAME:<NAME>END_PI
(asdf:defsystem #:magicl-gen
:license "BSD 3-Clause (See LICENSE.txt)"
:description "Generate MAGICL interfaces"
:maintainer "Rigetti Computing"
:author "Rigetti Computing"
:depends-on (#:cffi
#:cffi-libffi)
:serial t
:components
((:file "src/packages")
(:module "transcendental"
:serial t
:components ((:file "package")))
(:file "src/cffi-types")
(:file "src/generate-interface/generate-interface")))
|
[
{
"context": "indent-tabs-mode: nil -*-\n\n;;; Copyright (C) 2017, Dmitry Ignatiev <lovesan.ru at gmail.com>\n\n;;; Permission is here",
"end": 87,
"score": 0.9998639225959778,
"start": 72,
"tag": "NAME",
"value": "Dmitry Ignatiev"
},
{
"context": "nil -*-\n\n;;; Copyright (C) 2017, Dmitry Ignatiev <lovesan.ru at gmail.com>\n\n;;; Permission is hereby granted, ",
"end": 99,
"score": 0.7576206922531128,
"start": 89,
"tag": "EMAIL",
"value": "lovesan.ru"
},
{
"context": "pyright (C) 2017, Dmitry Ignatiev <lovesan.ru at gmail.com>\n\n;;; Permission is hereby granted, free of charg",
"end": 112,
"score": 0.8128933906555176,
"start": 104,
"tag": "EMAIL",
"value": "mail.com"
}
] |
src/types.lisp
|
easye/clave
| 17 |
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;; Copyright (C) 2017, Dmitry Ignatiev <lovesan.ru at gmail.com>
;;; 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 #:clave)
(defstruct (packet (:constructor %packet (ptr))
(:conc-name %packet-)
(:copier nil)
(:predicate packetp))
(ptr (null-pointer) :type foreign-pointer))
(defstruct (frame (:constructor %frame (ptr))
(:conc-name %frame-)
(:copier nil)
(:predicate framep))
(ptr (null-pointer) :type foreign-pointer))
(defstruct (codec (:constructor %codec (ptr))
(:conc-name %codec-)
(:copier nul)
(:predicate codecp))
(ptr (null-pointer) :type foreign-pointer))
(defstruct (io-format (:constructor %io-format (ptr input))
(:conc-name %io-format-)
(:copier nil)
(:predicate io-format-p))
(ptr (null-pointer) :type foreign-pointer)
(input nil :type boolean))
(defstruct (io-context (:constructor %io-context (ptr token-ptr opened &optional icb buf rcb wcb scb))
(:conc-name %io-context-)
(:copier nil)
(:predicate io-context-p))
(ptr (null-pointer) :type foreign-pointer)
(token-ptr (null-pointer) :type foreign-pointer)
(opened nil :type boolean)
(icb nil :type (or null (function () t) symbol))
(buf (make-array 1 :element-type 'uint8) :type (simple-array uint8 (*)))
(rcb nil :type (or null function symbol))
(wcb nil :type (or null function symbol))
(scb nil :type (or null function symbol)))
(defstruct (format-context (:constructor %format-context (ptr input &optional io icb))
(:conc-name %format-context-)
(:copier nil)
(:predicate format-context-p))
(ptr (null-pointer) :type foreign-pointer)
input
(io nil :type (or null io-context))
(icb nil :type (or null symbol function)))
(defstruct (media-stream (:constructor %media-stream (ptr source))
(:conc-name %media-stream-)
(:copier nil)
(:predicate media-stream-p))
source
(ptr (null-pointer) :type foreign-pointer))
(defstruct (codec-parameters (:constructor %codec-parameters (ptr &optional source))
(:conc-name %codec-parameters-)
(:copier nil)
(:predicate codec-parameters-p))
source
(ptr (null-pointer) :type foreign-pointer))
(defstruct (codec-context (:constructor %codec-context (ptr))
(:conc-name %codec-context-)
(:copier nil)
(:predicate codec-context-p))
(ptr (null-pointer) :type foreign-pointer))
(defstruct (resample-context (:constructor %resample-context (ptr))
(:conc-name %resample-context-)
(:copier nil)
(:predicate resample-context-p))
(ptr (null-pointer) :type foreign-pointer))
(defstruct (scale-context (:constructor %scale-context (ptr))
(:conc-name %scale-context)
(:copier nil)
(:predicate scale-context-p))
(ptr (null-pointer) :type foreign-pointer))
(defstruct (codec-profile (:constructor %codec-profile (id name))
(:conc-name %codec-profile-)
(:copier nil)
(:predicate codec-profile-p))
(id 0 :type (signed-byte 32))
(name "" :type (vector character)))
(defcstruct (av-rational :class av-rational)
(num :int)
(denom :int))
(defmethod translate-from-foreign (ptr (type av-rational))
(with-foreign-slots ((num denom) ptr (:struct av-rational))
(if (zerop denom) 0 (/ num denom))))
(defmethod expand-from-foreign (ptr (type av-rational))
`(with-foreign-slots ((num denom) ,ptr (:struct av-rational))
(let ((d denom))
(if (zerop d) 0 (/ num d)))))
(defmethod translate-into-foreign-memory (value (type av-rational) ptr)
(with-foreign-slots ((num denom) ptr (:struct av-rational))
(setf num (numerator value)
num (denominator value))))
(defmethod expand-into-foreign-memory (value (type av-rational) ptr)
(print value)
`(with-foreign-slots ((num denom) ,ptr (:struct av-rational))
(setf num (numerator ,value)
denom (denominator ,value))))
;; vim: ft=lisp et
|
48338
|
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;; Copyright (C) 2017, <NAME> <<EMAIL> at g<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.
(in-package #:clave)
(defstruct (packet (:constructor %packet (ptr))
(:conc-name %packet-)
(:copier nil)
(:predicate packetp))
(ptr (null-pointer) :type foreign-pointer))
(defstruct (frame (:constructor %frame (ptr))
(:conc-name %frame-)
(:copier nil)
(:predicate framep))
(ptr (null-pointer) :type foreign-pointer))
(defstruct (codec (:constructor %codec (ptr))
(:conc-name %codec-)
(:copier nul)
(:predicate codecp))
(ptr (null-pointer) :type foreign-pointer))
(defstruct (io-format (:constructor %io-format (ptr input))
(:conc-name %io-format-)
(:copier nil)
(:predicate io-format-p))
(ptr (null-pointer) :type foreign-pointer)
(input nil :type boolean))
(defstruct (io-context (:constructor %io-context (ptr token-ptr opened &optional icb buf rcb wcb scb))
(:conc-name %io-context-)
(:copier nil)
(:predicate io-context-p))
(ptr (null-pointer) :type foreign-pointer)
(token-ptr (null-pointer) :type foreign-pointer)
(opened nil :type boolean)
(icb nil :type (or null (function () t) symbol))
(buf (make-array 1 :element-type 'uint8) :type (simple-array uint8 (*)))
(rcb nil :type (or null function symbol))
(wcb nil :type (or null function symbol))
(scb nil :type (or null function symbol)))
(defstruct (format-context (:constructor %format-context (ptr input &optional io icb))
(:conc-name %format-context-)
(:copier nil)
(:predicate format-context-p))
(ptr (null-pointer) :type foreign-pointer)
input
(io nil :type (or null io-context))
(icb nil :type (or null symbol function)))
(defstruct (media-stream (:constructor %media-stream (ptr source))
(:conc-name %media-stream-)
(:copier nil)
(:predicate media-stream-p))
source
(ptr (null-pointer) :type foreign-pointer))
(defstruct (codec-parameters (:constructor %codec-parameters (ptr &optional source))
(:conc-name %codec-parameters-)
(:copier nil)
(:predicate codec-parameters-p))
source
(ptr (null-pointer) :type foreign-pointer))
(defstruct (codec-context (:constructor %codec-context (ptr))
(:conc-name %codec-context-)
(:copier nil)
(:predicate codec-context-p))
(ptr (null-pointer) :type foreign-pointer))
(defstruct (resample-context (:constructor %resample-context (ptr))
(:conc-name %resample-context-)
(:copier nil)
(:predicate resample-context-p))
(ptr (null-pointer) :type foreign-pointer))
(defstruct (scale-context (:constructor %scale-context (ptr))
(:conc-name %scale-context)
(:copier nil)
(:predicate scale-context-p))
(ptr (null-pointer) :type foreign-pointer))
(defstruct (codec-profile (:constructor %codec-profile (id name))
(:conc-name %codec-profile-)
(:copier nil)
(:predicate codec-profile-p))
(id 0 :type (signed-byte 32))
(name "" :type (vector character)))
(defcstruct (av-rational :class av-rational)
(num :int)
(denom :int))
(defmethod translate-from-foreign (ptr (type av-rational))
(with-foreign-slots ((num denom) ptr (:struct av-rational))
(if (zerop denom) 0 (/ num denom))))
(defmethod expand-from-foreign (ptr (type av-rational))
`(with-foreign-slots ((num denom) ,ptr (:struct av-rational))
(let ((d denom))
(if (zerop d) 0 (/ num d)))))
(defmethod translate-into-foreign-memory (value (type av-rational) ptr)
(with-foreign-slots ((num denom) ptr (:struct av-rational))
(setf num (numerator value)
num (denominator value))))
(defmethod expand-into-foreign-memory (value (type av-rational) ptr)
(print value)
`(with-foreign-slots ((num denom) ,ptr (:struct av-rational))
(setf num (numerator ,value)
denom (denominator ,value))))
;; vim: ft=lisp et
| true |
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;; Copyright (C) 2017, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI at gPI: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.
(in-package #:clave)
(defstruct (packet (:constructor %packet (ptr))
(:conc-name %packet-)
(:copier nil)
(:predicate packetp))
(ptr (null-pointer) :type foreign-pointer))
(defstruct (frame (:constructor %frame (ptr))
(:conc-name %frame-)
(:copier nil)
(:predicate framep))
(ptr (null-pointer) :type foreign-pointer))
(defstruct (codec (:constructor %codec (ptr))
(:conc-name %codec-)
(:copier nul)
(:predicate codecp))
(ptr (null-pointer) :type foreign-pointer))
(defstruct (io-format (:constructor %io-format (ptr input))
(:conc-name %io-format-)
(:copier nil)
(:predicate io-format-p))
(ptr (null-pointer) :type foreign-pointer)
(input nil :type boolean))
(defstruct (io-context (:constructor %io-context (ptr token-ptr opened &optional icb buf rcb wcb scb))
(:conc-name %io-context-)
(:copier nil)
(:predicate io-context-p))
(ptr (null-pointer) :type foreign-pointer)
(token-ptr (null-pointer) :type foreign-pointer)
(opened nil :type boolean)
(icb nil :type (or null (function () t) symbol))
(buf (make-array 1 :element-type 'uint8) :type (simple-array uint8 (*)))
(rcb nil :type (or null function symbol))
(wcb nil :type (or null function symbol))
(scb nil :type (or null function symbol)))
(defstruct (format-context (:constructor %format-context (ptr input &optional io icb))
(:conc-name %format-context-)
(:copier nil)
(:predicate format-context-p))
(ptr (null-pointer) :type foreign-pointer)
input
(io nil :type (or null io-context))
(icb nil :type (or null symbol function)))
(defstruct (media-stream (:constructor %media-stream (ptr source))
(:conc-name %media-stream-)
(:copier nil)
(:predicate media-stream-p))
source
(ptr (null-pointer) :type foreign-pointer))
(defstruct (codec-parameters (:constructor %codec-parameters (ptr &optional source))
(:conc-name %codec-parameters-)
(:copier nil)
(:predicate codec-parameters-p))
source
(ptr (null-pointer) :type foreign-pointer))
(defstruct (codec-context (:constructor %codec-context (ptr))
(:conc-name %codec-context-)
(:copier nil)
(:predicate codec-context-p))
(ptr (null-pointer) :type foreign-pointer))
(defstruct (resample-context (:constructor %resample-context (ptr))
(:conc-name %resample-context-)
(:copier nil)
(:predicate resample-context-p))
(ptr (null-pointer) :type foreign-pointer))
(defstruct (scale-context (:constructor %scale-context (ptr))
(:conc-name %scale-context)
(:copier nil)
(:predicate scale-context-p))
(ptr (null-pointer) :type foreign-pointer))
(defstruct (codec-profile (:constructor %codec-profile (id name))
(:conc-name %codec-profile-)
(:copier nil)
(:predicate codec-profile-p))
(id 0 :type (signed-byte 32))
(name "" :type (vector character)))
(defcstruct (av-rational :class av-rational)
(num :int)
(denom :int))
(defmethod translate-from-foreign (ptr (type av-rational))
(with-foreign-slots ((num denom) ptr (:struct av-rational))
(if (zerop denom) 0 (/ num denom))))
(defmethod expand-from-foreign (ptr (type av-rational))
`(with-foreign-slots ((num denom) ,ptr (:struct av-rational))
(let ((d denom))
(if (zerop d) 0 (/ num d)))))
(defmethod translate-into-foreign-memory (value (type av-rational) ptr)
(with-foreign-slots ((num denom) ptr (:struct av-rational))
(setf num (numerator value)
num (denominator value))))
(defmethod expand-into-foreign-memory (value (type av-rational) ptr)
(print value)
`(with-foreign-slots ((num denom) ,ptr (:struct av-rational))
(setf num (numerator ,value)
denom (denominator ,value))))
;; vim: ft=lisp et
|
[
{
"context": "ense. See the file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;",
"end": 232,
"score": 0.9996373653411865,
"start": 222,
"tag": "NAME",
"value": "Eric Smith"
},
{
"context": " file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 256,
"score": 0.9999332427978516,
"start": 234,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/kestrel/axe/tries.lisp
|
mayankmanj/acl2
| 305 |
; A datatype for counting rewrite attempts.
;
; Copyright (C) 2019-2020 Kestrel Institute
; Copyright (C) 2019-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")
;; A datatype for counting how many times rewrite rules are tried. Either nil
;; (meaning we are not counting tries), or a natural number. We keep triesp
;; disabled to avoid case splits in proofs.
(defund triesp (x)
(declare (xargs :guard t))
(or (natp x)
(null x)))
(defthm triesp-forward
(implies (triesp x)
(or (natp x)
(null x)))
:rule-classes :forward-chaining
:hints (("Goal" :in-theory (enable triesp))))
(defmacro zero-tries () 0)
(defund-inline increment-tries (tries)
(declare (xargs :guard (and (triesp tries)
tries)))
(+ 1 tries))
(defthm triesp-of-increment-tries
(implies (triesp x)
(triesp (increment-tries x)))
:hints (("Goal" :in-theory (enable triesp increment-tries))))
(defund-inline sub-tries (tries1 tries2)
(declare (xargs :guard (and (triesp tries1)
(triesp tries2))))
(if (and tries1
tries2)
(- tries1 tries2)
0))
(defthm integerp-of-sub-tries-type
(implies (and (triesp tries1)
(triesp tries2))
(integerp (sub-tries tries1 tries2)))
:rule-classes :type-prescription
:hints (("Goal" :in-theory (enable sub-tries))))
(defthmd integerp-of-sub-tries
(implies (and (triesp tries1)
(triesp tries2))
(integerp (sub-tries tries1 tries2)))
:hints (("Goal" :in-theory (enable sub-tries))))
|
34795
|
; A datatype for counting rewrite attempts.
;
; Copyright (C) 2019-2020 Kestrel Institute
; Copyright (C) 2019-2020 Kestrel Technology, LLC
;
; License: A 3-clause BSD license. See the file books/3BSD-mod.txt.
;
; Author: <NAME> (<EMAIL>)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
;; A datatype for counting how many times rewrite rules are tried. Either nil
;; (meaning we are not counting tries), or a natural number. We keep triesp
;; disabled to avoid case splits in proofs.
(defund triesp (x)
(declare (xargs :guard t))
(or (natp x)
(null x)))
(defthm triesp-forward
(implies (triesp x)
(or (natp x)
(null x)))
:rule-classes :forward-chaining
:hints (("Goal" :in-theory (enable triesp))))
(defmacro zero-tries () 0)
(defund-inline increment-tries (tries)
(declare (xargs :guard (and (triesp tries)
tries)))
(+ 1 tries))
(defthm triesp-of-increment-tries
(implies (triesp x)
(triesp (increment-tries x)))
:hints (("Goal" :in-theory (enable triesp increment-tries))))
(defund-inline sub-tries (tries1 tries2)
(declare (xargs :guard (and (triesp tries1)
(triesp tries2))))
(if (and tries1
tries2)
(- tries1 tries2)
0))
(defthm integerp-of-sub-tries-type
(implies (and (triesp tries1)
(triesp tries2))
(integerp (sub-tries tries1 tries2)))
:rule-classes :type-prescription
:hints (("Goal" :in-theory (enable sub-tries))))
(defthmd integerp-of-sub-tries
(implies (and (triesp tries1)
(triesp tries2))
(integerp (sub-tries tries1 tries2)))
:hints (("Goal" :in-theory (enable sub-tries))))
| true |
; A datatype for counting rewrite attempts.
;
; Copyright (C) 2019-2020 Kestrel Institute
; Copyright (C) 2019-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")
;; A datatype for counting how many times rewrite rules are tried. Either nil
;; (meaning we are not counting tries), or a natural number. We keep triesp
;; disabled to avoid case splits in proofs.
(defund triesp (x)
(declare (xargs :guard t))
(or (natp x)
(null x)))
(defthm triesp-forward
(implies (triesp x)
(or (natp x)
(null x)))
:rule-classes :forward-chaining
:hints (("Goal" :in-theory (enable triesp))))
(defmacro zero-tries () 0)
(defund-inline increment-tries (tries)
(declare (xargs :guard (and (triesp tries)
tries)))
(+ 1 tries))
(defthm triesp-of-increment-tries
(implies (triesp x)
(triesp (increment-tries x)))
:hints (("Goal" :in-theory (enable triesp increment-tries))))
(defund-inline sub-tries (tries1 tries2)
(declare (xargs :guard (and (triesp tries1)
(triesp tries2))))
(if (and tries1
tries2)
(- tries1 tries2)
0))
(defthm integerp-of-sub-tries-type
(implies (and (triesp tries1)
(triesp tries2))
(integerp (sub-tries tries1 tries2)))
:rule-classes :type-prescription
:hints (("Goal" :in-theory (enable sub-tries))))
(defthmd integerp-of-sub-tries
(implies (and (triesp tries1)
(triesp tries2))
(integerp (sub-tries tries1 tries2)))
:hints (("Goal" :in-theory (enable sub-tries))))
|
[
{
"context": "ons for\n;;; creating SIN/COS tables.\n;;;\n;;; Bishop Brock and Calvin Harrison\n;;; Computational Logic, I",
"end": 423,
"score": 0.999862790107727,
"start": 411,
"tag": "NAME",
"value": "Bishop Brock"
},
{
"context": "eating SIN/COS tables.\n;;;\n;;; Bishop Brock and Calvin Harrison\n;;; Computational Logic, Inc.\n;;; 1717 West",
"end": 443,
"score": 0.9998703002929688,
"start": 428,
"tag": "NAME",
"value": "Calvin Harrison"
},
{
"context": "treet, Suite 290\n;;; Austin, Texas 78703\n;;; [email protected]\n;;;\n;;;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~",
"end": 563,
"score": 0.9999287128448486,
"start": 550,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/misc/sin-cos.lisp
|
ragerdl/acl2-defthm-rc2
| 1 |
; sin-cos.lisp -- series approximations to SIN and COS
; Copyright (C) 1997 Computational Logic, Inc.
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;;;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
;;;
;;; sin-cos.lisp
;;;
;;; Unlimited series approximations to SIN and COS, plus functions for
;;; creating SIN/COS tables.
;;;
;;; Bishop Brock and Calvin Harrison
;;; Computational Logic, Inc.
;;; 1717 West 6th Street, Suite 290
;;; Austin, Texas 78703
;;; [email protected]
;;;
;;;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
;;;****************************************************************************
;;;
;;; Environment
;;;
;;;****************************************************************************
(in-package "ACL2")
(deflabel sin-cos
:doc ":doc-section miscellaneous
SIN/COS approximations.
~/~/~/")
;;;****************************************************************************
;;;
;;; Series approximations of sin/cos.
;;;
;;;****************************************************************************
(defun compute-series (x parity ex fact num itr ans)
":doc-section sin-cos
Series approximation to SIN/COS.
~/~/
This function is used to calculate the following Maclaurin series:
To compute SIN:
x - (x^3/3!) + (x^5/5!) - (x^7/7!) + ....
To compute COS:
1- (x^2/2!) + (x^4/4!) - (x^6/6!) + ....
Arguments:
x -- x
parity -- T to add the new term, NIL to subtract the new term.
ex -- x^num
fact -- num!
itr -- Number of iterations
ans -- Accumulated answer.
~/"
(declare (xargs :guard (and (rationalp x)
(booleanp parity)
(rationalp ex)
(integerp fact)
(> fact 0)
(integerp num)
(>= num 0)
(integerp itr)
(>= itr 0)
(rationalp ans))))
(if (zp itr)
ans
(compute-series x (not parity) (* x x ex) (* (+ 2 num) (+ 1 num) fact)
(+ 2 num) (1- itr) (if parity
(+ ans (/ ex fact))
(- ans (/ ex fact))))))
(local
(defthm type-of-compute-series
(implies
(and (rationalp x)
(rationalp ex)
(integerp fact)
(integerp num)
(rationalp ans))
(rationalp (compute-series x parity ex fact num itr ans)))
:rule-classes :type-prescription))
(defun fast-compute-series
(num-x^2 denom-x^2 num-x^n num-sum denom-sum n parity itr)
":doc-section sin-cos
Efficient series approximation to SIN/COS.
~/~/
This function is used to calculate the following Maclaurin series:
To compute SIN:
x - (x^3/3!) + (x^5/5!) - (x^7/7!) + ....
To compute COS:
1- (x^2/2!) + (x^4/4!) - (x^6/6!) + ....
Rather than accumulating each term as shown, we instead compute the
numerator and denominator of the sum, and return these two values. This
avoids the necessity of reducing each rational as it is accumulated. On
one set of examples this procudure was almost an order of magnitude faster
than the simple summation given by COMPUTE-SERIES.
Given x^2 as num-x^2/denom-x^2, and a partial sum num-sum/denom-sum,
we compute the next partial sum as:
num-sum denom-x^2 (n + 1) (n + 2) num-x^n num-x^2
--------- * ------------------------- + --------------------------
denom-sum denom-x^2 (n + 1) (n + 2) denom-x^2 (n + 1) (n + 2)
Again, the rationals are not actually computed, and instead we simply return
the numerator and denominator of the answer.
Arguments:
num-x^2 -- (Numerator of x)^2.
denom-x^2 -- (Denominator of x)^2.
num-x^n -- (num-x)^n
num-sum -- Numerator of partial sum.
denom-sum -- Denominator of partial sum.
n -- n
parity -- T to add next term, NIL to subtract next term.
itr -- Number of iterations to perform.
~/"
(declare (xargs :guard (and (integerp num-x^2)
(integerp denom-x^2)
(not (= denom-x^2 0))
(integerp num-x^n)
(integerp num-sum)
(integerp denom-sum)
(not (= denom-sum 0))
(integerp n)
(<= 0 n)
(booleanp parity)
(integerp itr)
(<= 0 itr))
:guard-hints (("Goal" :in-theory (disable DISTRIBUTIVITY)))))
(if (zp itr)
(mv num-sum denom-sum)
(let*
((n+1*n+2 (* (+ n 1) (+ n 2)))
(multiplier (* denom-x^2 n+1*n+2))
(new-denom-sum (* denom-sum multiplier))
(adjusted-num-sum (* num-sum multiplier))
(new-num-x^n (* num-x^n num-x^2))
(new-num-sum (if parity
(+ adjusted-num-sum new-num-x^n)
(- adjusted-num-sum new-num-x^n))))
(fast-compute-series num-x^2 denom-x^2 new-num-x^n
new-num-sum new-denom-sum
(+ 2 n) (not parity) (1- itr)))))
(local
(defthm type-of-fast-compute-series
(implies
(and (integerp num-x^2)
(integerp denom-x^2)
(not (= denom-x^2 0))
(integerp num-x^n)
(integerp num-sum)
(integerp denom-sum)
(not (= denom-sum 0))
(integerp n)
(<= 0 n)
(booleanp parity)
(integerp itr)
(<= 0 itr))
(and
(integerp
(mv-nth 0 (fast-compute-series num-x^2 denom-x^2 num-x^n num-sum denom-sum
n parity itr)))
(integerp
(mv-nth 1 (fast-compute-series num-x^2 denom-x^2 num-x^n num-sum denom-sum
n parity itr)))
(not
(equal
(mv-nth 1
(fast-compute-series num-x^2 denom-x^2 num-x^n num-sum denom-sum
n parity itr))
0))))
:rule-classes
((:type-prescription
:corollary
(implies
(and (integerp num-x^2)
(integerp denom-x^2)
(not (= denom-x^2 0))
(integerp num-x^n)
(integerp num-sum)
(integerp denom-sum)
(not (= denom-sum 0))
(integerp n)
(<= 0 n)
(booleanp parity)
(integerp itr)
(<= 0 itr))
(integerp
(mv-nth 0
(fast-compute-series num-x^2 denom-x^2 num-x^n num-sum denom-sum
n parity itr)))))
(:type-prescription
:corollary
(implies
(and (integerp num-x^2)
(integerp denom-x^2)
(not (= denom-x^2 0))
(integerp num-x^n)
(integerp num-sum)
(integerp denom-sum)
(not (= denom-sum 0))
(integerp n)
(<= 0 n)
(booleanp parity)
(integerp itr)
(<= 0 itr))
(and
(integerp
(mv-nth 1
(fast-compute-series num-x^2 denom-x^2 num-x^n num-sum denom-sum
n parity itr)))
(not
(equal
(mv-nth 1
(fast-compute-series num-x^2 denom-x^2 num-x^n
num-sum denom-sum n parity itr))
0))))))
:hints
(("Goal"
:in-theory (disable distributivity))))) ;Too slow
(defun fast-compute-cos (x itr)
":doc-section sin-cos
This function returns the numerator and denominator of a rational
approximation to cos(x) (in radians) by itr iterations of
FAST-COMPUTE-SERIES.
~/~/~/"
(declare (xargs :guard (and (rationalp x)
(integerp itr)
(>= itr 0))))
(fast-compute-series (* (numerator x) (numerator x))
(* (denominator x) (denominator x))
1 1 1 0 nil itr))
(defun fast-compute-sin (x itr)
":doc-section sin-cos
This function returns the numerator and denominator of a rational
approximation to sin(x) (in radians) by itr iterations of
FAST-COMPUTE-SERIES.
~/~/~/"
(declare (xargs :guard (and (rationalp x)
(integerp itr)
(>= itr 0))))
(fast-compute-series (* (numerator x) (numerator x))
(* (denominator x) (denominator x))
(numerator x) (numerator x) (denominator x) 1 nil itr))
(defun truncated-integer-cos (x itr scale)
":doc-section sin-cos
Integer approximation to cos(x) * scale.
~/~/
A rational approximation to cos(x), scaled up by scale, and then TRUNCATED
to an integer.~/"
(declare (xargs :guard (and (rationalp x)
(integerp itr)
(<= 0 itr)
(rationalp scale))
:guard-hints
(("Goal"
:in-theory (disable mv-nth)))))
(mv-let (num denom) (fast-compute-cos x itr)
(truncate (* num scale) denom)))
(defun truncated-integer-sin (x itr scale)
":doc-section sin-cos
Integer approximation to sin(x) * scale.
~/~/
A rational approximation to cos(x), scaled up by scale, and then TRUNCATED
to an integer.~/"
(declare (xargs :guard (and (rationalp x)
(integerp itr)
(<= 0 itr)
(rationalp scale))
:guard-hints
(("Goal"
:in-theory (disable mv-nth)))))
(mv-let (num denom) (fast-compute-sin x itr)
(truncate (* num scale) denom)))
(defun truncated-integer-sin/cos-table-fn (sin/cos i n pie itr scale)
":doc-section sin-cos
Helper for SIN/COS-TABLE-FN
~/~/
Note that this function has special code for 0, pi/2, pi, and (3/2)pi.
The convergence of the series at these points is problematic in the
context of truncation (vs. rounding).~/"
(declare (xargs :guard (and (or (eq sin/cos :SIN) (eq sin/cos :COS))
(integerp i)
(<= 0 i)
(integerp n)
(<= 0 n)
(<= i n)
(rationalp pie)
(integerp itr)
(<= 0 itr)
(rationalp scale))
:measure (ifix (if (<= n i) 0 (- n i)))))
(cond
((zp (- n i)) nil)
(t (let ((i/n (/ i n)))
(cons
(cons i (case sin/cos
(:sin
(case i/n
((0 1/2) 0) ;0, pi
(1/4 (truncate scale 1)) ;pi/2
(3/4 (truncate scale -1)) ;(3/2)pi
(t
(truncated-integer-sin (* 2 pie i/n) itr scale))))
(t
(case i/n
(0 (truncate scale 1)) ;0
((1/4 3/4) 0) ;pi/2, (3/2)pi
(1/2 (truncate scale -1)) ;pi
(t
(truncated-integer-cos (* 2 pie i/n) itr scale))))))
(truncated-integer-sin/cos-table-fn
sin/cos (1+ i) n pie itr scale))))))
(defun truncated-integer-sin/cos-table (sin/cos n pie itr scale)
":doc-section sin-cos
Create a scaled, truncated integer sin/cos table from 0 to 2*pi.
~/~/
This function creates a table of approximations to
sin[cos]( (2 pi i)/n ) * scale, i = 0,...,n-1.
The result is an alist ( ... (i . sin[cos](i) ) ... ).
Arguments:
sin/cos -- :SIN or :COS.
n -- Total number of table entries
pie -- An approximation to pi sufficiently accurate for the user's
purposes.
itr -- Required number of iterations of FAST-COMPUTE-SIN[COS]
sufficient for user's accuracy.
scale -- Scale factor.
~/"
(declare (xargs :guard (and (or (eq sin/cos :SIN) (eq sin/cos :COS))
(integerp n)
(<= 0 n)
(rationalp pie)
(integerp itr)
(<= 0 itr)
(rationalp scale))))
(truncated-integer-sin/cos-table-fn sin/cos 0 n pie itr scale))
|
65423
|
; sin-cos.lisp -- series approximations to SIN and COS
; Copyright (C) 1997 Computational Logic, Inc.
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;;;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
;;;
;;; sin-cos.lisp
;;;
;;; Unlimited series approximations to SIN and COS, plus functions for
;;; creating SIN/COS tables.
;;;
;;; <NAME> and <NAME>
;;; Computational Logic, Inc.
;;; 1717 West 6th Street, Suite 290
;;; Austin, Texas 78703
;;; <EMAIL>
;;;
;;;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
;;;****************************************************************************
;;;
;;; Environment
;;;
;;;****************************************************************************
(in-package "ACL2")
(deflabel sin-cos
:doc ":doc-section miscellaneous
SIN/COS approximations.
~/~/~/")
;;;****************************************************************************
;;;
;;; Series approximations of sin/cos.
;;;
;;;****************************************************************************
(defun compute-series (x parity ex fact num itr ans)
":doc-section sin-cos
Series approximation to SIN/COS.
~/~/
This function is used to calculate the following Maclaurin series:
To compute SIN:
x - (x^3/3!) + (x^5/5!) - (x^7/7!) + ....
To compute COS:
1- (x^2/2!) + (x^4/4!) - (x^6/6!) + ....
Arguments:
x -- x
parity -- T to add the new term, NIL to subtract the new term.
ex -- x^num
fact -- num!
itr -- Number of iterations
ans -- Accumulated answer.
~/"
(declare (xargs :guard (and (rationalp x)
(booleanp parity)
(rationalp ex)
(integerp fact)
(> fact 0)
(integerp num)
(>= num 0)
(integerp itr)
(>= itr 0)
(rationalp ans))))
(if (zp itr)
ans
(compute-series x (not parity) (* x x ex) (* (+ 2 num) (+ 1 num) fact)
(+ 2 num) (1- itr) (if parity
(+ ans (/ ex fact))
(- ans (/ ex fact))))))
(local
(defthm type-of-compute-series
(implies
(and (rationalp x)
(rationalp ex)
(integerp fact)
(integerp num)
(rationalp ans))
(rationalp (compute-series x parity ex fact num itr ans)))
:rule-classes :type-prescription))
(defun fast-compute-series
(num-x^2 denom-x^2 num-x^n num-sum denom-sum n parity itr)
":doc-section sin-cos
Efficient series approximation to SIN/COS.
~/~/
This function is used to calculate the following Maclaurin series:
To compute SIN:
x - (x^3/3!) + (x^5/5!) - (x^7/7!) + ....
To compute COS:
1- (x^2/2!) + (x^4/4!) - (x^6/6!) + ....
Rather than accumulating each term as shown, we instead compute the
numerator and denominator of the sum, and return these two values. This
avoids the necessity of reducing each rational as it is accumulated. On
one set of examples this procudure was almost an order of magnitude faster
than the simple summation given by COMPUTE-SERIES.
Given x^2 as num-x^2/denom-x^2, and a partial sum num-sum/denom-sum,
we compute the next partial sum as:
num-sum denom-x^2 (n + 1) (n + 2) num-x^n num-x^2
--------- * ------------------------- + --------------------------
denom-sum denom-x^2 (n + 1) (n + 2) denom-x^2 (n + 1) (n + 2)
Again, the rationals are not actually computed, and instead we simply return
the numerator and denominator of the answer.
Arguments:
num-x^2 -- (Numerator of x)^2.
denom-x^2 -- (Denominator of x)^2.
num-x^n -- (num-x)^n
num-sum -- Numerator of partial sum.
denom-sum -- Denominator of partial sum.
n -- n
parity -- T to add next term, NIL to subtract next term.
itr -- Number of iterations to perform.
~/"
(declare (xargs :guard (and (integerp num-x^2)
(integerp denom-x^2)
(not (= denom-x^2 0))
(integerp num-x^n)
(integerp num-sum)
(integerp denom-sum)
(not (= denom-sum 0))
(integerp n)
(<= 0 n)
(booleanp parity)
(integerp itr)
(<= 0 itr))
:guard-hints (("Goal" :in-theory (disable DISTRIBUTIVITY)))))
(if (zp itr)
(mv num-sum denom-sum)
(let*
((n+1*n+2 (* (+ n 1) (+ n 2)))
(multiplier (* denom-x^2 n+1*n+2))
(new-denom-sum (* denom-sum multiplier))
(adjusted-num-sum (* num-sum multiplier))
(new-num-x^n (* num-x^n num-x^2))
(new-num-sum (if parity
(+ adjusted-num-sum new-num-x^n)
(- adjusted-num-sum new-num-x^n))))
(fast-compute-series num-x^2 denom-x^2 new-num-x^n
new-num-sum new-denom-sum
(+ 2 n) (not parity) (1- itr)))))
(local
(defthm type-of-fast-compute-series
(implies
(and (integerp num-x^2)
(integerp denom-x^2)
(not (= denom-x^2 0))
(integerp num-x^n)
(integerp num-sum)
(integerp denom-sum)
(not (= denom-sum 0))
(integerp n)
(<= 0 n)
(booleanp parity)
(integerp itr)
(<= 0 itr))
(and
(integerp
(mv-nth 0 (fast-compute-series num-x^2 denom-x^2 num-x^n num-sum denom-sum
n parity itr)))
(integerp
(mv-nth 1 (fast-compute-series num-x^2 denom-x^2 num-x^n num-sum denom-sum
n parity itr)))
(not
(equal
(mv-nth 1
(fast-compute-series num-x^2 denom-x^2 num-x^n num-sum denom-sum
n parity itr))
0))))
:rule-classes
((:type-prescription
:corollary
(implies
(and (integerp num-x^2)
(integerp denom-x^2)
(not (= denom-x^2 0))
(integerp num-x^n)
(integerp num-sum)
(integerp denom-sum)
(not (= denom-sum 0))
(integerp n)
(<= 0 n)
(booleanp parity)
(integerp itr)
(<= 0 itr))
(integerp
(mv-nth 0
(fast-compute-series num-x^2 denom-x^2 num-x^n num-sum denom-sum
n parity itr)))))
(:type-prescription
:corollary
(implies
(and (integerp num-x^2)
(integerp denom-x^2)
(not (= denom-x^2 0))
(integerp num-x^n)
(integerp num-sum)
(integerp denom-sum)
(not (= denom-sum 0))
(integerp n)
(<= 0 n)
(booleanp parity)
(integerp itr)
(<= 0 itr))
(and
(integerp
(mv-nth 1
(fast-compute-series num-x^2 denom-x^2 num-x^n num-sum denom-sum
n parity itr)))
(not
(equal
(mv-nth 1
(fast-compute-series num-x^2 denom-x^2 num-x^n
num-sum denom-sum n parity itr))
0))))))
:hints
(("Goal"
:in-theory (disable distributivity))))) ;Too slow
(defun fast-compute-cos (x itr)
":doc-section sin-cos
This function returns the numerator and denominator of a rational
approximation to cos(x) (in radians) by itr iterations of
FAST-COMPUTE-SERIES.
~/~/~/"
(declare (xargs :guard (and (rationalp x)
(integerp itr)
(>= itr 0))))
(fast-compute-series (* (numerator x) (numerator x))
(* (denominator x) (denominator x))
1 1 1 0 nil itr))
(defun fast-compute-sin (x itr)
":doc-section sin-cos
This function returns the numerator and denominator of a rational
approximation to sin(x) (in radians) by itr iterations of
FAST-COMPUTE-SERIES.
~/~/~/"
(declare (xargs :guard (and (rationalp x)
(integerp itr)
(>= itr 0))))
(fast-compute-series (* (numerator x) (numerator x))
(* (denominator x) (denominator x))
(numerator x) (numerator x) (denominator x) 1 nil itr))
(defun truncated-integer-cos (x itr scale)
":doc-section sin-cos
Integer approximation to cos(x) * scale.
~/~/
A rational approximation to cos(x), scaled up by scale, and then TRUNCATED
to an integer.~/"
(declare (xargs :guard (and (rationalp x)
(integerp itr)
(<= 0 itr)
(rationalp scale))
:guard-hints
(("Goal"
:in-theory (disable mv-nth)))))
(mv-let (num denom) (fast-compute-cos x itr)
(truncate (* num scale) denom)))
(defun truncated-integer-sin (x itr scale)
":doc-section sin-cos
Integer approximation to sin(x) * scale.
~/~/
A rational approximation to cos(x), scaled up by scale, and then TRUNCATED
to an integer.~/"
(declare (xargs :guard (and (rationalp x)
(integerp itr)
(<= 0 itr)
(rationalp scale))
:guard-hints
(("Goal"
:in-theory (disable mv-nth)))))
(mv-let (num denom) (fast-compute-sin x itr)
(truncate (* num scale) denom)))
(defun truncated-integer-sin/cos-table-fn (sin/cos i n pie itr scale)
":doc-section sin-cos
Helper for SIN/COS-TABLE-FN
~/~/
Note that this function has special code for 0, pi/2, pi, and (3/2)pi.
The convergence of the series at these points is problematic in the
context of truncation (vs. rounding).~/"
(declare (xargs :guard (and (or (eq sin/cos :SIN) (eq sin/cos :COS))
(integerp i)
(<= 0 i)
(integerp n)
(<= 0 n)
(<= i n)
(rationalp pie)
(integerp itr)
(<= 0 itr)
(rationalp scale))
:measure (ifix (if (<= n i) 0 (- n i)))))
(cond
((zp (- n i)) nil)
(t (let ((i/n (/ i n)))
(cons
(cons i (case sin/cos
(:sin
(case i/n
((0 1/2) 0) ;0, pi
(1/4 (truncate scale 1)) ;pi/2
(3/4 (truncate scale -1)) ;(3/2)pi
(t
(truncated-integer-sin (* 2 pie i/n) itr scale))))
(t
(case i/n
(0 (truncate scale 1)) ;0
((1/4 3/4) 0) ;pi/2, (3/2)pi
(1/2 (truncate scale -1)) ;pi
(t
(truncated-integer-cos (* 2 pie i/n) itr scale))))))
(truncated-integer-sin/cos-table-fn
sin/cos (1+ i) n pie itr scale))))))
(defun truncated-integer-sin/cos-table (sin/cos n pie itr scale)
":doc-section sin-cos
Create a scaled, truncated integer sin/cos table from 0 to 2*pi.
~/~/
This function creates a table of approximations to
sin[cos]( (2 pi i)/n ) * scale, i = 0,...,n-1.
The result is an alist ( ... (i . sin[cos](i) ) ... ).
Arguments:
sin/cos -- :SIN or :COS.
n -- Total number of table entries
pie -- An approximation to pi sufficiently accurate for the user's
purposes.
itr -- Required number of iterations of FAST-COMPUTE-SIN[COS]
sufficient for user's accuracy.
scale -- Scale factor.
~/"
(declare (xargs :guard (and (or (eq sin/cos :SIN) (eq sin/cos :COS))
(integerp n)
(<= 0 n)
(rationalp pie)
(integerp itr)
(<= 0 itr)
(rationalp scale))))
(truncated-integer-sin/cos-table-fn sin/cos 0 n pie itr scale))
| true |
; sin-cos.lisp -- series approximations to SIN and COS
; Copyright (C) 1997 Computational Logic, Inc.
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;;;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
;;;
;;; sin-cos.lisp
;;;
;;; Unlimited series approximations to SIN and COS, plus functions for
;;; creating SIN/COS tables.
;;;
;;; PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI
;;; Computational Logic, Inc.
;;; 1717 West 6th Street, Suite 290
;;; Austin, Texas 78703
;;; PI:EMAIL:<EMAIL>END_PI
;;;
;;;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
;;;****************************************************************************
;;;
;;; Environment
;;;
;;;****************************************************************************
(in-package "ACL2")
(deflabel sin-cos
:doc ":doc-section miscellaneous
SIN/COS approximations.
~/~/~/")
;;;****************************************************************************
;;;
;;; Series approximations of sin/cos.
;;;
;;;****************************************************************************
(defun compute-series (x parity ex fact num itr ans)
":doc-section sin-cos
Series approximation to SIN/COS.
~/~/
This function is used to calculate the following Maclaurin series:
To compute SIN:
x - (x^3/3!) + (x^5/5!) - (x^7/7!) + ....
To compute COS:
1- (x^2/2!) + (x^4/4!) - (x^6/6!) + ....
Arguments:
x -- x
parity -- T to add the new term, NIL to subtract the new term.
ex -- x^num
fact -- num!
itr -- Number of iterations
ans -- Accumulated answer.
~/"
(declare (xargs :guard (and (rationalp x)
(booleanp parity)
(rationalp ex)
(integerp fact)
(> fact 0)
(integerp num)
(>= num 0)
(integerp itr)
(>= itr 0)
(rationalp ans))))
(if (zp itr)
ans
(compute-series x (not parity) (* x x ex) (* (+ 2 num) (+ 1 num) fact)
(+ 2 num) (1- itr) (if parity
(+ ans (/ ex fact))
(- ans (/ ex fact))))))
(local
(defthm type-of-compute-series
(implies
(and (rationalp x)
(rationalp ex)
(integerp fact)
(integerp num)
(rationalp ans))
(rationalp (compute-series x parity ex fact num itr ans)))
:rule-classes :type-prescription))
(defun fast-compute-series
(num-x^2 denom-x^2 num-x^n num-sum denom-sum n parity itr)
":doc-section sin-cos
Efficient series approximation to SIN/COS.
~/~/
This function is used to calculate the following Maclaurin series:
To compute SIN:
x - (x^3/3!) + (x^5/5!) - (x^7/7!) + ....
To compute COS:
1- (x^2/2!) + (x^4/4!) - (x^6/6!) + ....
Rather than accumulating each term as shown, we instead compute the
numerator and denominator of the sum, and return these two values. This
avoids the necessity of reducing each rational as it is accumulated. On
one set of examples this procudure was almost an order of magnitude faster
than the simple summation given by COMPUTE-SERIES.
Given x^2 as num-x^2/denom-x^2, and a partial sum num-sum/denom-sum,
we compute the next partial sum as:
num-sum denom-x^2 (n + 1) (n + 2) num-x^n num-x^2
--------- * ------------------------- + --------------------------
denom-sum denom-x^2 (n + 1) (n + 2) denom-x^2 (n + 1) (n + 2)
Again, the rationals are not actually computed, and instead we simply return
the numerator and denominator of the answer.
Arguments:
num-x^2 -- (Numerator of x)^2.
denom-x^2 -- (Denominator of x)^2.
num-x^n -- (num-x)^n
num-sum -- Numerator of partial sum.
denom-sum -- Denominator of partial sum.
n -- n
parity -- T to add next term, NIL to subtract next term.
itr -- Number of iterations to perform.
~/"
(declare (xargs :guard (and (integerp num-x^2)
(integerp denom-x^2)
(not (= denom-x^2 0))
(integerp num-x^n)
(integerp num-sum)
(integerp denom-sum)
(not (= denom-sum 0))
(integerp n)
(<= 0 n)
(booleanp parity)
(integerp itr)
(<= 0 itr))
:guard-hints (("Goal" :in-theory (disable DISTRIBUTIVITY)))))
(if (zp itr)
(mv num-sum denom-sum)
(let*
((n+1*n+2 (* (+ n 1) (+ n 2)))
(multiplier (* denom-x^2 n+1*n+2))
(new-denom-sum (* denom-sum multiplier))
(adjusted-num-sum (* num-sum multiplier))
(new-num-x^n (* num-x^n num-x^2))
(new-num-sum (if parity
(+ adjusted-num-sum new-num-x^n)
(- adjusted-num-sum new-num-x^n))))
(fast-compute-series num-x^2 denom-x^2 new-num-x^n
new-num-sum new-denom-sum
(+ 2 n) (not parity) (1- itr)))))
(local
(defthm type-of-fast-compute-series
(implies
(and (integerp num-x^2)
(integerp denom-x^2)
(not (= denom-x^2 0))
(integerp num-x^n)
(integerp num-sum)
(integerp denom-sum)
(not (= denom-sum 0))
(integerp n)
(<= 0 n)
(booleanp parity)
(integerp itr)
(<= 0 itr))
(and
(integerp
(mv-nth 0 (fast-compute-series num-x^2 denom-x^2 num-x^n num-sum denom-sum
n parity itr)))
(integerp
(mv-nth 1 (fast-compute-series num-x^2 denom-x^2 num-x^n num-sum denom-sum
n parity itr)))
(not
(equal
(mv-nth 1
(fast-compute-series num-x^2 denom-x^2 num-x^n num-sum denom-sum
n parity itr))
0))))
:rule-classes
((:type-prescription
:corollary
(implies
(and (integerp num-x^2)
(integerp denom-x^2)
(not (= denom-x^2 0))
(integerp num-x^n)
(integerp num-sum)
(integerp denom-sum)
(not (= denom-sum 0))
(integerp n)
(<= 0 n)
(booleanp parity)
(integerp itr)
(<= 0 itr))
(integerp
(mv-nth 0
(fast-compute-series num-x^2 denom-x^2 num-x^n num-sum denom-sum
n parity itr)))))
(:type-prescription
:corollary
(implies
(and (integerp num-x^2)
(integerp denom-x^2)
(not (= denom-x^2 0))
(integerp num-x^n)
(integerp num-sum)
(integerp denom-sum)
(not (= denom-sum 0))
(integerp n)
(<= 0 n)
(booleanp parity)
(integerp itr)
(<= 0 itr))
(and
(integerp
(mv-nth 1
(fast-compute-series num-x^2 denom-x^2 num-x^n num-sum denom-sum
n parity itr)))
(not
(equal
(mv-nth 1
(fast-compute-series num-x^2 denom-x^2 num-x^n
num-sum denom-sum n parity itr))
0))))))
:hints
(("Goal"
:in-theory (disable distributivity))))) ;Too slow
(defun fast-compute-cos (x itr)
":doc-section sin-cos
This function returns the numerator and denominator of a rational
approximation to cos(x) (in radians) by itr iterations of
FAST-COMPUTE-SERIES.
~/~/~/"
(declare (xargs :guard (and (rationalp x)
(integerp itr)
(>= itr 0))))
(fast-compute-series (* (numerator x) (numerator x))
(* (denominator x) (denominator x))
1 1 1 0 nil itr))
(defun fast-compute-sin (x itr)
":doc-section sin-cos
This function returns the numerator and denominator of a rational
approximation to sin(x) (in radians) by itr iterations of
FAST-COMPUTE-SERIES.
~/~/~/"
(declare (xargs :guard (and (rationalp x)
(integerp itr)
(>= itr 0))))
(fast-compute-series (* (numerator x) (numerator x))
(* (denominator x) (denominator x))
(numerator x) (numerator x) (denominator x) 1 nil itr))
(defun truncated-integer-cos (x itr scale)
":doc-section sin-cos
Integer approximation to cos(x) * scale.
~/~/
A rational approximation to cos(x), scaled up by scale, and then TRUNCATED
to an integer.~/"
(declare (xargs :guard (and (rationalp x)
(integerp itr)
(<= 0 itr)
(rationalp scale))
:guard-hints
(("Goal"
:in-theory (disable mv-nth)))))
(mv-let (num denom) (fast-compute-cos x itr)
(truncate (* num scale) denom)))
(defun truncated-integer-sin (x itr scale)
":doc-section sin-cos
Integer approximation to sin(x) * scale.
~/~/
A rational approximation to cos(x), scaled up by scale, and then TRUNCATED
to an integer.~/"
(declare (xargs :guard (and (rationalp x)
(integerp itr)
(<= 0 itr)
(rationalp scale))
:guard-hints
(("Goal"
:in-theory (disable mv-nth)))))
(mv-let (num denom) (fast-compute-sin x itr)
(truncate (* num scale) denom)))
(defun truncated-integer-sin/cos-table-fn (sin/cos i n pie itr scale)
":doc-section sin-cos
Helper for SIN/COS-TABLE-FN
~/~/
Note that this function has special code for 0, pi/2, pi, and (3/2)pi.
The convergence of the series at these points is problematic in the
context of truncation (vs. rounding).~/"
(declare (xargs :guard (and (or (eq sin/cos :SIN) (eq sin/cos :COS))
(integerp i)
(<= 0 i)
(integerp n)
(<= 0 n)
(<= i n)
(rationalp pie)
(integerp itr)
(<= 0 itr)
(rationalp scale))
:measure (ifix (if (<= n i) 0 (- n i)))))
(cond
((zp (- n i)) nil)
(t (let ((i/n (/ i n)))
(cons
(cons i (case sin/cos
(:sin
(case i/n
((0 1/2) 0) ;0, pi
(1/4 (truncate scale 1)) ;pi/2
(3/4 (truncate scale -1)) ;(3/2)pi
(t
(truncated-integer-sin (* 2 pie i/n) itr scale))))
(t
(case i/n
(0 (truncate scale 1)) ;0
((1/4 3/4) 0) ;pi/2, (3/2)pi
(1/2 (truncate scale -1)) ;pi
(t
(truncated-integer-cos (* 2 pie i/n) itr scale))))))
(truncated-integer-sin/cos-table-fn
sin/cos (1+ i) n pie itr scale))))))
(defun truncated-integer-sin/cos-table (sin/cos n pie itr scale)
":doc-section sin-cos
Create a scaled, truncated integer sin/cos table from 0 to 2*pi.
~/~/
This function creates a table of approximations to
sin[cos]( (2 pi i)/n ) * scale, i = 0,...,n-1.
The result is an alist ( ... (i . sin[cos](i) ) ... ).
Arguments:
sin/cos -- :SIN or :COS.
n -- Total number of table entries
pie -- An approximation to pi sufficiently accurate for the user's
purposes.
itr -- Required number of iterations of FAST-COMPUTE-SIN[COS]
sufficient for user's accuracy.
scale -- Scale factor.
~/"
(declare (xargs :guard (and (or (eq sin/cos :SIN) (eq sin/cos :COS))
(integerp n)
(<= 0 n)
(rationalp pie)
(integerp itr)
(<= 0 itr)
(rationalp scale))))
(truncated-integer-sin/cos-table-fn sin/cos 0 n pie itr scale))
|
[
{
"context": "\n;;; express or implied warranty.\n;;;\n;;; Authors: Delmar Hager, James Dutton, Teri Crowe\n;;; Contributors: Kerry",
"end": 628,
"score": 0.9998683929443359,
"start": 616,
"tag": "NAME",
"value": "Delmar Hager"
},
{
"context": "r implied warranty.\n;;;\n;;; Authors: Delmar Hager, James Dutton, Teri Crowe\n;;; Contributors: Kerry Kimbrough, Pa",
"end": 642,
"score": 0.99983811378479,
"start": 630,
"tag": "NAME",
"value": "James Dutton"
},
{
"context": "anty.\n;;;\n;;; Authors: Delmar Hager, James Dutton, Teri Crowe\n;;; Contributors: Kerry Kimbrough, Patrick Hogan,",
"end": 654,
"score": 0.9998494982719421,
"start": 644,
"tag": "NAME",
"value": "Teri Crowe"
},
{
"context": " Hager, James Dutton, Teri Crowe\n;;; Contributors: Kerry Kimbrough, Patrick Hogan, Eric Mielke\n\n(in-package \"PICTURE",
"end": 688,
"score": 0.9998577833175659,
"start": 673,
"tag": "NAME",
"value": "Kerry Kimbrough"
},
{
"context": "ton, Teri Crowe\n;;; Contributors: Kerry Kimbrough, Patrick Hogan, Eric Mielke\n\n(in-package \"PICTURES\")\n\n\n(export '",
"end": 703,
"score": 0.9998511075973511,
"start": 690,
"tag": "NAME",
"value": "Patrick Hogan"
},
{
"context": "\n;;; Contributors: Kerry Kimbrough, Patrick Hogan, Eric Mielke\n\n(in-package \"PICTURES\")\n\n\n(export '(\n\t circle-c",
"end": 716,
"score": 0.9998319745063782,
"start": 705,
"tag": "NAME",
"value": "Eric Mielke"
}
] |
src/gui/clue/pictures/circle.lisp
|
sbwhitecap/clocc-hg
| 0 |
;;;-*- Mode:Lisp; Package:PICTURES; Base:10 -*-
;;;
;;;
;;;
;;; TEXAS INSTRUMENTS INCORPORATED
;;; P.O. BOX 149149
;;; AUSTIN, TEXAS 78714-9149
;;;
;;; Copyright (C)1987,1988,1989,1990 Texas Instruments Incorporated.
;;;
;;; Permission is granted to any individual or institution to use, copy, modify,
;;; and distribute this software, provided that this complete copyright and
;;; permission notice is maintained, intact, in all copies and supporting
;;; documentation.
;;;
;;; Texas Instruments Incorporated provides this software "as is" without
;;; express or implied warranty.
;;;
;;; Authors: Delmar Hager, James Dutton, Teri Crowe
;;; Contributors: Kerry Kimbrough, Patrick Hogan, Eric Mielke
(in-package "PICTURES")
(export '(
circle-center-x
circle-center-y
circle-radius
circle-center
make-circle
make-filled-circle
make-filled-circle-edge
circle
filled-circle-edge
filled-circle
)
'pictures)
;Circle Class Definition:
(defclass circle (extent-cache graphic)
(
(center-x :type wcoord
:initarg :center-x
:accessor circle-center-x
:documentation "x-coordinate of the center")
(center-y :type wcoord
:initarg :center-y
:accessor circle-center-y
:documentation "y-coordinate of the center")
(radius :type wcoord
:initarg :radius
:accessor circle-radius
:documentation "Radius of the circle")
)
(:documentation "A graphic that represents a circle in object coordinates"))
;Filled-Circle Class Definition:
(defclass filled-circle ( circle)
()
(:documentation "Filled circle class in pictures"))
;Filled-Circle-Edge Class Definition:
(defclass filled-circle-edge ( circle edge)
()
(:documentation "Filled circle edge class in pictures"))
;Function: make-circle
; Return a new circle object with the given CENTER and RADIUS.
(defun make-circle (center-x center-y radius
&rest options
)
"Make a circle with the center coordinate of (CENTER-X CENTER-Y) and RADIUS.
The following keyword OPTIONS are allowed:
GSTATE PARENT SENESITIVITY TRANSFORM PLIST"
(declare (type wcoord center-x center-y radius))
(apply #'make-instance 'circle
:center-x center-x
:center-y center-y
:radius radius
options)
)
;Function: make-filled-circle
; Return a new filled-circle object with the given CENTER and RADIUS.
(defun make-filled-circle (center-x center-y radius
&rest options
)
"Make a filled-circle with the center coordinate of
(CENTER-X CENTER-Y) and RADIUS.
The following keyword OPTIONS are allowed:
GSTATE PARENT SENESITIVITY TRANSFORM PLIST"
(declare (type wcoord center-x center-y radius))
(apply #'make-instance 'filled-circle
:center-x center-x
:center-y center-y
:radius radius
options))
;Function: make-filled-circle-edge
; Return a new filled-circle-edge object with the given CENTER and RADIUS.
(defun make-filled-circle-edge (center-x center-y radius &rest options)
"Make a filled-circle with the center coordinate of
(CENTER-X CENTER-Y) and RADIUS.
The following keyword OPTIONS are allowed:
GSTATE PARENT SENESITIVITY TRANSFORM PLIST"
(declare (type wcoord center-x center-y radius))
(apply #'make-instance 'filled-circle-edge
:center-x center-x
:center-y center-y
:radius radius
options))
;Method: circle-radius
; Returns or changes the object coordinates for the radius of the CIRCLE.
(defmethod (setf circle-radius) :after (new-radius (circle circle))
(declare (ignore new-radius))
(extent-changed circle))
;Method: circle-center
; Returns or changes the object coordinates of the center of the CIRCLE.
(defmethod circle-center ((circle circle))
(with-slots (center-x center-y) circle
(values center-x center-y)))
(defmethod (SETF circle-center-x) :after (new-center-x (circle circle))
(declare (ignore new-center-x))
(extent-changed circle))
(defmethod (setf circle-center-y) :after (new-center-y (circle circle))
(declare (ignore new-center-y))
(extent-changed circle))
; Graphic methods for circle graphics
;Method: extent-compute
; Compute the extent rectangle for the CIRCLE.
; Note: A graphic's extent rectangle is defined in the object coordinate
; system. This means that each graphic should apply its own transform to
; its computed extent before returning it.
(defmethod extent-compute ((circle circle))
(with-slots (center-x center-y radius transform) circle
(let (new-center-x new-center-y new-radius-x new-radius-y new-radius)
(multiple-value-setq
(new-center-x new-center-y) ; Transform circle center
(transform-point transform center-x center-y))
(multiple-value-setq
(new-radius-x new-radius-y) ; Transform circle radius
(scale-point transform radius radius))
(setf new-radius
(min new-radius-x new-radius-y)) ; Use the smaller scale factor
(let ((xmin (- new-center-x new-radius))
(ymin (- new-center-y new-radius))
(xmax (+ new-center-x new-radius))
(ymax (+ new-center-y new-radius)))
(with-coercion ((xmin ymin xmax ymax) extent-element)
(make-extent-rect ; Build the extent square
:xmin xmin
:ymin ymin
:xmax xmax
:ymax ymax
:valid t))))))
;Method: draw-graphic
; Draw the CIRCLE object in the given VIEW. If MIN-X, MIN-Y, WIDTH, and
; HEIGHT are given, then only parts of the object that lie within the
; given rectangle need to be drawn.
(defmethod draw-graphic ((circle circle) (view view)
&optional min-x min-y width height)
(declare (type (or null wcoord) min-x min-y width height))
(with-slots (extent) circle
(WHEN (visible-p circle)
(multiple-value-bind (xmin ymin diameter)
(square-bounding-circle circle)
(view-draw-arc
view ; Draw the circle
xmin
ymin
diameter
diameter
0
(* 2 pi)
(graphic-gstate circle)) ; Pass the combined gstate
))))
;Method: draw-graphic Draw the FILLED-CIRCLE object in the given VIEW. If
;MIN-X, MIN-Y, WIDTH, and HEIGHT are given, then only parts of the object
;that lie within the given rectangle need to be drawn.
(defmethod draw-graphic ((circle filled-circle) (view view)
&optional min-x min-y width height)
(declare (type (or null wcoord) min-x min-y width height))
(with-slots (extent) circle
(WHEN (visible-p circle)
(multiple-value-bind (xmin ymin diameter)
(square-bounding-circle circle)
(view-draw-filled-arc
view ; Draw the circle
xmin
ymin
diameter
diameter
0
(* 2 pi)
(graphic-gstate circle)) ; Pass the combined gstate
))))
;Method: draw-graphic
; Draw the FILLED-CIRCLE-EDGE object by first drawing the interior and
; then boundary. If MIN-X, MIN-Y, WIDTH, and HEIGHT are given, then only
; parts of the object that lie within the given rectangle need to be
; drawn.
(defmethod draw-graphic ((circle filled-circle-edge) (view view)
&optional min-x min-y width height)
(declare (type (or null wcoord) min-x min-y width height))
(with-slots (extent) circle
(WHEN (visible-p circle)
(with-slots (edge-gstate) circle
; Use global temp buffer
(multiple-value-bind (xmin ymin diameter)
(square-bounding-circle circle)
(view-draw-filled-arc
view ; Draw the circle's interior
xmin
ymin
diameter
diameter
0
(* 2 pi)
(graphic-gstate circle)) ; Pass the combined gstate
(view-draw-arc
view ; Draw the circle's boundary
xmin
ymin
diameter
diameter
0
(* 2 pi)
(edge-gstate circle)) ; Pass the combined edge gstate
)))))
;Method: normalize-graphic
; Normalize the CIRCLE by applying its transform
; to its geometry, changing it accordingly, and then setting its transform
; to nil (the identity transform). Nothing of value is returned.
(defmethod normalize-graphic :before ((circle circle))
(with-slots (center-x center-y radius transform) circle
(multiple-value-setq (center-x center-y) ; Transform the center
(transform-point transform center-x center-y))
(let (radius-x radius-y)
(multiple-value-setq (radius-x radius-y) ; Transform the radius
(scale-point transform radius radius))
(setf radius (min radius-x radius-y))))) ; Use the smaller scale factor
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Private Function: square-bounding-circle
; Return the southwest corner and the width of the square in which the
; given CIRCLE is inscribed.
(defun square-bounding-circle (circle)
(with-slots (center-x center-y radius) circle
(let (new-center-x new-center-y new-radius-x new-radius-y new-radius)
(multiple-value-setq (new-center-x new-center-y) ; Transform circle center
(transform-point (graphic-world-transform circle) center-x center-y))
(multiple-value-setq (new-radius-x new-radius-y) ; Transform circle radius
(scale-point (graphic-world-transform circle) radius radius))
(setf new-radius (min new-radius-x new-radius-y)) ; Use the smaller scale factor
(values (- new-center-x new-radius)
(- new-center-y new-radius)
(* 2 new-radius)))))
|
48057
|
;;;-*- Mode:Lisp; Package:PICTURES; Base:10 -*-
;;;
;;;
;;;
;;; TEXAS INSTRUMENTS INCORPORATED
;;; P.O. BOX 149149
;;; AUSTIN, TEXAS 78714-9149
;;;
;;; Copyright (C)1987,1988,1989,1990 Texas Instruments Incorporated.
;;;
;;; Permission is granted to any individual or institution to use, copy, modify,
;;; and distribute this software, provided that this complete copyright and
;;; permission notice is maintained, intact, in all copies and supporting
;;; documentation.
;;;
;;; Texas Instruments Incorporated provides this software "as is" without
;;; express or implied warranty.
;;;
;;; Authors: <NAME>, <NAME>, <NAME>
;;; Contributors: <NAME>, <NAME>, <NAME>
(in-package "PICTURES")
(export '(
circle-center-x
circle-center-y
circle-radius
circle-center
make-circle
make-filled-circle
make-filled-circle-edge
circle
filled-circle-edge
filled-circle
)
'pictures)
;Circle Class Definition:
(defclass circle (extent-cache graphic)
(
(center-x :type wcoord
:initarg :center-x
:accessor circle-center-x
:documentation "x-coordinate of the center")
(center-y :type wcoord
:initarg :center-y
:accessor circle-center-y
:documentation "y-coordinate of the center")
(radius :type wcoord
:initarg :radius
:accessor circle-radius
:documentation "Radius of the circle")
)
(:documentation "A graphic that represents a circle in object coordinates"))
;Filled-Circle Class Definition:
(defclass filled-circle ( circle)
()
(:documentation "Filled circle class in pictures"))
;Filled-Circle-Edge Class Definition:
(defclass filled-circle-edge ( circle edge)
()
(:documentation "Filled circle edge class in pictures"))
;Function: make-circle
; Return a new circle object with the given CENTER and RADIUS.
(defun make-circle (center-x center-y radius
&rest options
)
"Make a circle with the center coordinate of (CENTER-X CENTER-Y) and RADIUS.
The following keyword OPTIONS are allowed:
GSTATE PARENT SENESITIVITY TRANSFORM PLIST"
(declare (type wcoord center-x center-y radius))
(apply #'make-instance 'circle
:center-x center-x
:center-y center-y
:radius radius
options)
)
;Function: make-filled-circle
; Return a new filled-circle object with the given CENTER and RADIUS.
(defun make-filled-circle (center-x center-y radius
&rest options
)
"Make a filled-circle with the center coordinate of
(CENTER-X CENTER-Y) and RADIUS.
The following keyword OPTIONS are allowed:
GSTATE PARENT SENESITIVITY TRANSFORM PLIST"
(declare (type wcoord center-x center-y radius))
(apply #'make-instance 'filled-circle
:center-x center-x
:center-y center-y
:radius radius
options))
;Function: make-filled-circle-edge
; Return a new filled-circle-edge object with the given CENTER and RADIUS.
(defun make-filled-circle-edge (center-x center-y radius &rest options)
"Make a filled-circle with the center coordinate of
(CENTER-X CENTER-Y) and RADIUS.
The following keyword OPTIONS are allowed:
GSTATE PARENT SENESITIVITY TRANSFORM PLIST"
(declare (type wcoord center-x center-y radius))
(apply #'make-instance 'filled-circle-edge
:center-x center-x
:center-y center-y
:radius radius
options))
;Method: circle-radius
; Returns or changes the object coordinates for the radius of the CIRCLE.
(defmethod (setf circle-radius) :after (new-radius (circle circle))
(declare (ignore new-radius))
(extent-changed circle))
;Method: circle-center
; Returns or changes the object coordinates of the center of the CIRCLE.
(defmethod circle-center ((circle circle))
(with-slots (center-x center-y) circle
(values center-x center-y)))
(defmethod (SETF circle-center-x) :after (new-center-x (circle circle))
(declare (ignore new-center-x))
(extent-changed circle))
(defmethod (setf circle-center-y) :after (new-center-y (circle circle))
(declare (ignore new-center-y))
(extent-changed circle))
; Graphic methods for circle graphics
;Method: extent-compute
; Compute the extent rectangle for the CIRCLE.
; Note: A graphic's extent rectangle is defined in the object coordinate
; system. This means that each graphic should apply its own transform to
; its computed extent before returning it.
(defmethod extent-compute ((circle circle))
(with-slots (center-x center-y radius transform) circle
(let (new-center-x new-center-y new-radius-x new-radius-y new-radius)
(multiple-value-setq
(new-center-x new-center-y) ; Transform circle center
(transform-point transform center-x center-y))
(multiple-value-setq
(new-radius-x new-radius-y) ; Transform circle radius
(scale-point transform radius radius))
(setf new-radius
(min new-radius-x new-radius-y)) ; Use the smaller scale factor
(let ((xmin (- new-center-x new-radius))
(ymin (- new-center-y new-radius))
(xmax (+ new-center-x new-radius))
(ymax (+ new-center-y new-radius)))
(with-coercion ((xmin ymin xmax ymax) extent-element)
(make-extent-rect ; Build the extent square
:xmin xmin
:ymin ymin
:xmax xmax
:ymax ymax
:valid t))))))
;Method: draw-graphic
; Draw the CIRCLE object in the given VIEW. If MIN-X, MIN-Y, WIDTH, and
; HEIGHT are given, then only parts of the object that lie within the
; given rectangle need to be drawn.
(defmethod draw-graphic ((circle circle) (view view)
&optional min-x min-y width height)
(declare (type (or null wcoord) min-x min-y width height))
(with-slots (extent) circle
(WHEN (visible-p circle)
(multiple-value-bind (xmin ymin diameter)
(square-bounding-circle circle)
(view-draw-arc
view ; Draw the circle
xmin
ymin
diameter
diameter
0
(* 2 pi)
(graphic-gstate circle)) ; Pass the combined gstate
))))
;Method: draw-graphic Draw the FILLED-CIRCLE object in the given VIEW. If
;MIN-X, MIN-Y, WIDTH, and HEIGHT are given, then only parts of the object
;that lie within the given rectangle need to be drawn.
(defmethod draw-graphic ((circle filled-circle) (view view)
&optional min-x min-y width height)
(declare (type (or null wcoord) min-x min-y width height))
(with-slots (extent) circle
(WHEN (visible-p circle)
(multiple-value-bind (xmin ymin diameter)
(square-bounding-circle circle)
(view-draw-filled-arc
view ; Draw the circle
xmin
ymin
diameter
diameter
0
(* 2 pi)
(graphic-gstate circle)) ; Pass the combined gstate
))))
;Method: draw-graphic
; Draw the FILLED-CIRCLE-EDGE object by first drawing the interior and
; then boundary. If MIN-X, MIN-Y, WIDTH, and HEIGHT are given, then only
; parts of the object that lie within the given rectangle need to be
; drawn.
(defmethod draw-graphic ((circle filled-circle-edge) (view view)
&optional min-x min-y width height)
(declare (type (or null wcoord) min-x min-y width height))
(with-slots (extent) circle
(WHEN (visible-p circle)
(with-slots (edge-gstate) circle
; Use global temp buffer
(multiple-value-bind (xmin ymin diameter)
(square-bounding-circle circle)
(view-draw-filled-arc
view ; Draw the circle's interior
xmin
ymin
diameter
diameter
0
(* 2 pi)
(graphic-gstate circle)) ; Pass the combined gstate
(view-draw-arc
view ; Draw the circle's boundary
xmin
ymin
diameter
diameter
0
(* 2 pi)
(edge-gstate circle)) ; Pass the combined edge gstate
)))))
;Method: normalize-graphic
; Normalize the CIRCLE by applying its transform
; to its geometry, changing it accordingly, and then setting its transform
; to nil (the identity transform). Nothing of value is returned.
(defmethod normalize-graphic :before ((circle circle))
(with-slots (center-x center-y radius transform) circle
(multiple-value-setq (center-x center-y) ; Transform the center
(transform-point transform center-x center-y))
(let (radius-x radius-y)
(multiple-value-setq (radius-x radius-y) ; Transform the radius
(scale-point transform radius radius))
(setf radius (min radius-x radius-y))))) ; Use the smaller scale factor
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Private Function: square-bounding-circle
; Return the southwest corner and the width of the square in which the
; given CIRCLE is inscribed.
(defun square-bounding-circle (circle)
(with-slots (center-x center-y radius) circle
(let (new-center-x new-center-y new-radius-x new-radius-y new-radius)
(multiple-value-setq (new-center-x new-center-y) ; Transform circle center
(transform-point (graphic-world-transform circle) center-x center-y))
(multiple-value-setq (new-radius-x new-radius-y) ; Transform circle radius
(scale-point (graphic-world-transform circle) radius radius))
(setf new-radius (min new-radius-x new-radius-y)) ; Use the smaller scale factor
(values (- new-center-x new-radius)
(- new-center-y new-radius)
(* 2 new-radius)))))
| true |
;;;-*- Mode:Lisp; Package:PICTURES; Base:10 -*-
;;;
;;;
;;;
;;; TEXAS INSTRUMENTS INCORPORATED
;;; P.O. BOX 149149
;;; AUSTIN, TEXAS 78714-9149
;;;
;;; Copyright (C)1987,1988,1989,1990 Texas Instruments Incorporated.
;;;
;;; Permission is granted to any individual or institution to use, copy, modify,
;;; and distribute this software, provided that this complete copyright and
;;; permission notice is maintained, intact, in all copies and supporting
;;; documentation.
;;;
;;; Texas Instruments Incorporated provides this software "as is" without
;;; express or implied warranty.
;;;
;;; Authors: PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
;;; Contributors: PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
(in-package "PICTURES")
(export '(
circle-center-x
circle-center-y
circle-radius
circle-center
make-circle
make-filled-circle
make-filled-circle-edge
circle
filled-circle-edge
filled-circle
)
'pictures)
;Circle Class Definition:
(defclass circle (extent-cache graphic)
(
(center-x :type wcoord
:initarg :center-x
:accessor circle-center-x
:documentation "x-coordinate of the center")
(center-y :type wcoord
:initarg :center-y
:accessor circle-center-y
:documentation "y-coordinate of the center")
(radius :type wcoord
:initarg :radius
:accessor circle-radius
:documentation "Radius of the circle")
)
(:documentation "A graphic that represents a circle in object coordinates"))
;Filled-Circle Class Definition:
(defclass filled-circle ( circle)
()
(:documentation "Filled circle class in pictures"))
;Filled-Circle-Edge Class Definition:
(defclass filled-circle-edge ( circle edge)
()
(:documentation "Filled circle edge class in pictures"))
;Function: make-circle
; Return a new circle object with the given CENTER and RADIUS.
(defun make-circle (center-x center-y radius
&rest options
)
"Make a circle with the center coordinate of (CENTER-X CENTER-Y) and RADIUS.
The following keyword OPTIONS are allowed:
GSTATE PARENT SENESITIVITY TRANSFORM PLIST"
(declare (type wcoord center-x center-y radius))
(apply #'make-instance 'circle
:center-x center-x
:center-y center-y
:radius radius
options)
)
;Function: make-filled-circle
; Return a new filled-circle object with the given CENTER and RADIUS.
(defun make-filled-circle (center-x center-y radius
&rest options
)
"Make a filled-circle with the center coordinate of
(CENTER-X CENTER-Y) and RADIUS.
The following keyword OPTIONS are allowed:
GSTATE PARENT SENESITIVITY TRANSFORM PLIST"
(declare (type wcoord center-x center-y radius))
(apply #'make-instance 'filled-circle
:center-x center-x
:center-y center-y
:radius radius
options))
;Function: make-filled-circle-edge
; Return a new filled-circle-edge object with the given CENTER and RADIUS.
(defun make-filled-circle-edge (center-x center-y radius &rest options)
"Make a filled-circle with the center coordinate of
(CENTER-X CENTER-Y) and RADIUS.
The following keyword OPTIONS are allowed:
GSTATE PARENT SENESITIVITY TRANSFORM PLIST"
(declare (type wcoord center-x center-y radius))
(apply #'make-instance 'filled-circle-edge
:center-x center-x
:center-y center-y
:radius radius
options))
;Method: circle-radius
; Returns or changes the object coordinates for the radius of the CIRCLE.
(defmethod (setf circle-radius) :after (new-radius (circle circle))
(declare (ignore new-radius))
(extent-changed circle))
;Method: circle-center
; Returns or changes the object coordinates of the center of the CIRCLE.
(defmethod circle-center ((circle circle))
(with-slots (center-x center-y) circle
(values center-x center-y)))
(defmethod (SETF circle-center-x) :after (new-center-x (circle circle))
(declare (ignore new-center-x))
(extent-changed circle))
(defmethod (setf circle-center-y) :after (new-center-y (circle circle))
(declare (ignore new-center-y))
(extent-changed circle))
; Graphic methods for circle graphics
;Method: extent-compute
; Compute the extent rectangle for the CIRCLE.
; Note: A graphic's extent rectangle is defined in the object coordinate
; system. This means that each graphic should apply its own transform to
; its computed extent before returning it.
(defmethod extent-compute ((circle circle))
(with-slots (center-x center-y radius transform) circle
(let (new-center-x new-center-y new-radius-x new-radius-y new-radius)
(multiple-value-setq
(new-center-x new-center-y) ; Transform circle center
(transform-point transform center-x center-y))
(multiple-value-setq
(new-radius-x new-radius-y) ; Transform circle radius
(scale-point transform radius radius))
(setf new-radius
(min new-radius-x new-radius-y)) ; Use the smaller scale factor
(let ((xmin (- new-center-x new-radius))
(ymin (- new-center-y new-radius))
(xmax (+ new-center-x new-radius))
(ymax (+ new-center-y new-radius)))
(with-coercion ((xmin ymin xmax ymax) extent-element)
(make-extent-rect ; Build the extent square
:xmin xmin
:ymin ymin
:xmax xmax
:ymax ymax
:valid t))))))
;Method: draw-graphic
; Draw the CIRCLE object in the given VIEW. If MIN-X, MIN-Y, WIDTH, and
; HEIGHT are given, then only parts of the object that lie within the
; given rectangle need to be drawn.
(defmethod draw-graphic ((circle circle) (view view)
&optional min-x min-y width height)
(declare (type (or null wcoord) min-x min-y width height))
(with-slots (extent) circle
(WHEN (visible-p circle)
(multiple-value-bind (xmin ymin diameter)
(square-bounding-circle circle)
(view-draw-arc
view ; Draw the circle
xmin
ymin
diameter
diameter
0
(* 2 pi)
(graphic-gstate circle)) ; Pass the combined gstate
))))
;Method: draw-graphic Draw the FILLED-CIRCLE object in the given VIEW. If
;MIN-X, MIN-Y, WIDTH, and HEIGHT are given, then only parts of the object
;that lie within the given rectangle need to be drawn.
(defmethod draw-graphic ((circle filled-circle) (view view)
&optional min-x min-y width height)
(declare (type (or null wcoord) min-x min-y width height))
(with-slots (extent) circle
(WHEN (visible-p circle)
(multiple-value-bind (xmin ymin diameter)
(square-bounding-circle circle)
(view-draw-filled-arc
view ; Draw the circle
xmin
ymin
diameter
diameter
0
(* 2 pi)
(graphic-gstate circle)) ; Pass the combined gstate
))))
;Method: draw-graphic
; Draw the FILLED-CIRCLE-EDGE object by first drawing the interior and
; then boundary. If MIN-X, MIN-Y, WIDTH, and HEIGHT are given, then only
; parts of the object that lie within the given rectangle need to be
; drawn.
(defmethod draw-graphic ((circle filled-circle-edge) (view view)
&optional min-x min-y width height)
(declare (type (or null wcoord) min-x min-y width height))
(with-slots (extent) circle
(WHEN (visible-p circle)
(with-slots (edge-gstate) circle
; Use global temp buffer
(multiple-value-bind (xmin ymin diameter)
(square-bounding-circle circle)
(view-draw-filled-arc
view ; Draw the circle's interior
xmin
ymin
diameter
diameter
0
(* 2 pi)
(graphic-gstate circle)) ; Pass the combined gstate
(view-draw-arc
view ; Draw the circle's boundary
xmin
ymin
diameter
diameter
0
(* 2 pi)
(edge-gstate circle)) ; Pass the combined edge gstate
)))))
;Method: normalize-graphic
; Normalize the CIRCLE by applying its transform
; to its geometry, changing it accordingly, and then setting its transform
; to nil (the identity transform). Nothing of value is returned.
(defmethod normalize-graphic :before ((circle circle))
(with-slots (center-x center-y radius transform) circle
(multiple-value-setq (center-x center-y) ; Transform the center
(transform-point transform center-x center-y))
(let (radius-x radius-y)
(multiple-value-setq (radius-x radius-y) ; Transform the radius
(scale-point transform radius radius))
(setf radius (min radius-x radius-y))))) ; Use the smaller scale factor
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;Private Function: square-bounding-circle
; Return the southwest corner and the width of the square in which the
; given CIRCLE is inscribed.
(defun square-bounding-circle (circle)
(with-slots (center-x center-y radius) circle
(let (new-center-x new-center-y new-radius-x new-radius-y new-radius)
(multiple-value-setq (new-center-x new-center-y) ; Transform circle center
(transform-point (graphic-world-transform circle) center-x center-y))
(multiple-value-setq (new-radius-x new-radius-y) ; Transform circle radius
(scale-point (graphic-world-transform circle) radius radius))
(setf new-radius (min new-radius-x new-radius-y)) ; Use the smaller scale factor
(values (- new-center-x new-radius)
(- new-center-y new-radius)
(* 2 new-radius)))))
|
[
{
"context": ";;;; by Nikodemus Siivola <[email protected]>, 2009.\n;;;;\n;;;; Per",
"end": 25,
"score": 0.9998915195465088,
"start": 8,
"tag": "NAME",
"value": "Nikodemus Siivola"
},
{
"context": ";;;; by Nikodemus Siivola <[email protected]>, 2009.\n;;;;\n;;;; Permission is hereby granted, f",
"end": 53,
"score": 0.999932587146759,
"start": 27,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
objects/sphere.lisp
|
nikodemus/raylisp
| 6 |
;;;; by Nikodemus Siivola <[email protected]>, 2009.
;;;;
;;;; 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 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 :raylisp)
(defclass sphere (scene-object)
((radius
:initform 1.0 :initarg :radius :reader radius-of)
(location
:initform +origin+ :initarg :location
:reader location-of)))
(defun sphere-matrix (sphere)
(let ((r (radius-of sphere)))
(matrix* (translate (location-of sphere))
(scale* r r r))))
(defmethod compute-object-properties ((sphere sphere) scene transform &key shading-object)
(multiple-value-bind (inverse adjunct/inverse)
(inverse-and-adjunct/inverse-matrix (matrix* transform (sphere-matrix sphere)))
(list
:intersection
(unless shading-object
(sb-int:named-lambda sphere-intersection (ray)
(declare (optimize speed))
(let* ((o2 (transform-point (ray-origin ray) inverse))
(d2 (transform-direction (ray-direction ray) inverse))
(limit +epsilon+))
(declare (dynamic-extent o2 d2))
(let ((t1 (quadratic-roots-above limit
(dot-product d2 d2)
(* 2.0 (dot-product d2 o2))
(- (dot-product o2 o2) 1.0))))
(when (< limit t1 (ray-extent ray))
(setf (ray-extent ray) t1)
t)))))
:normal
(lambda (point)
(let ((p (transform-point point adjunct/inverse)))
(%normalize p p))))))
(defmethod compute-object-extents ((sphere sphere) transform)
(transform-bounds (vec -1.0 -1.0 -1.0)
(vec 1.0 1.0 1.0)
(matrix* transform (sphere-matrix sphere))))
(defmethod compute-csg-properties ((sphere sphere) scene transform)
(let* ((inverse (inverse-matrix (matrix* transform (sphere-matrix sphere))))
(compiled (compile-scene-object sphere scene transform :shading-object sphere)))
(list
;; FIXME: To reduce consing even further: stack allocate
;; the csg-interactions and pass a continuation in here.
;; ...alternatively, pre-allocate a csg-intersection buffer.
:all-intersections
(sb-int:named-lambda sphere-all-intersections (origin direction)
(declare (optimize speed))
(let ((o (transform-point origin inverse))
(d (transform-direction direction inverse))
(limit +epsilon+))
(declare (dynamic-extent o d))
(multiple-value-bind (r1 r2)
(quadratic-roots-above limit
(dot-product d d)
(* 2.0 (dot-product d o))
(- (dot-product o o) 1.0))
(cond ((= limit r1)
#())
((= limit r2)
(simple-vector (make-csg-intersection :distance r1 :object compiled)))
(t
(simple-vector (make-csg-intersection :distance r1 :object compiled)
(make-csg-intersection :distance r2 :object compiled)))))))
:inside
(lambda (point)
(> (+ 1.0 +epsilon+)
(let ((p (transform-point point inverse)))
(declare (dynamic-extent p))
(vec-length p)))))))
|
47473
|
;;;; by <NAME> <<EMAIL>>, 2009.
;;;;
;;;; 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 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 :raylisp)
(defclass sphere (scene-object)
((radius
:initform 1.0 :initarg :radius :reader radius-of)
(location
:initform +origin+ :initarg :location
:reader location-of)))
(defun sphere-matrix (sphere)
(let ((r (radius-of sphere)))
(matrix* (translate (location-of sphere))
(scale* r r r))))
(defmethod compute-object-properties ((sphere sphere) scene transform &key shading-object)
(multiple-value-bind (inverse adjunct/inverse)
(inverse-and-adjunct/inverse-matrix (matrix* transform (sphere-matrix sphere)))
(list
:intersection
(unless shading-object
(sb-int:named-lambda sphere-intersection (ray)
(declare (optimize speed))
(let* ((o2 (transform-point (ray-origin ray) inverse))
(d2 (transform-direction (ray-direction ray) inverse))
(limit +epsilon+))
(declare (dynamic-extent o2 d2))
(let ((t1 (quadratic-roots-above limit
(dot-product d2 d2)
(* 2.0 (dot-product d2 o2))
(- (dot-product o2 o2) 1.0))))
(when (< limit t1 (ray-extent ray))
(setf (ray-extent ray) t1)
t)))))
:normal
(lambda (point)
(let ((p (transform-point point adjunct/inverse)))
(%normalize p p))))))
(defmethod compute-object-extents ((sphere sphere) transform)
(transform-bounds (vec -1.0 -1.0 -1.0)
(vec 1.0 1.0 1.0)
(matrix* transform (sphere-matrix sphere))))
(defmethod compute-csg-properties ((sphere sphere) scene transform)
(let* ((inverse (inverse-matrix (matrix* transform (sphere-matrix sphere))))
(compiled (compile-scene-object sphere scene transform :shading-object sphere)))
(list
;; FIXME: To reduce consing even further: stack allocate
;; the csg-interactions and pass a continuation in here.
;; ...alternatively, pre-allocate a csg-intersection buffer.
:all-intersections
(sb-int:named-lambda sphere-all-intersections (origin direction)
(declare (optimize speed))
(let ((o (transform-point origin inverse))
(d (transform-direction direction inverse))
(limit +epsilon+))
(declare (dynamic-extent o d))
(multiple-value-bind (r1 r2)
(quadratic-roots-above limit
(dot-product d d)
(* 2.0 (dot-product d o))
(- (dot-product o o) 1.0))
(cond ((= limit r1)
#())
((= limit r2)
(simple-vector (make-csg-intersection :distance r1 :object compiled)))
(t
(simple-vector (make-csg-intersection :distance r1 :object compiled)
(make-csg-intersection :distance r2 :object compiled)))))))
:inside
(lambda (point)
(> (+ 1.0 +epsilon+)
(let ((p (transform-point point inverse)))
(declare (dynamic-extent p))
(vec-length p)))))))
| true |
;;;; by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>, 2009.
;;;;
;;;; 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 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 :raylisp)
(defclass sphere (scene-object)
((radius
:initform 1.0 :initarg :radius :reader radius-of)
(location
:initform +origin+ :initarg :location
:reader location-of)))
(defun sphere-matrix (sphere)
(let ((r (radius-of sphere)))
(matrix* (translate (location-of sphere))
(scale* r r r))))
(defmethod compute-object-properties ((sphere sphere) scene transform &key shading-object)
(multiple-value-bind (inverse adjunct/inverse)
(inverse-and-adjunct/inverse-matrix (matrix* transform (sphere-matrix sphere)))
(list
:intersection
(unless shading-object
(sb-int:named-lambda sphere-intersection (ray)
(declare (optimize speed))
(let* ((o2 (transform-point (ray-origin ray) inverse))
(d2 (transform-direction (ray-direction ray) inverse))
(limit +epsilon+))
(declare (dynamic-extent o2 d2))
(let ((t1 (quadratic-roots-above limit
(dot-product d2 d2)
(* 2.0 (dot-product d2 o2))
(- (dot-product o2 o2) 1.0))))
(when (< limit t1 (ray-extent ray))
(setf (ray-extent ray) t1)
t)))))
:normal
(lambda (point)
(let ((p (transform-point point adjunct/inverse)))
(%normalize p p))))))
(defmethod compute-object-extents ((sphere sphere) transform)
(transform-bounds (vec -1.0 -1.0 -1.0)
(vec 1.0 1.0 1.0)
(matrix* transform (sphere-matrix sphere))))
(defmethod compute-csg-properties ((sphere sphere) scene transform)
(let* ((inverse (inverse-matrix (matrix* transform (sphere-matrix sphere))))
(compiled (compile-scene-object sphere scene transform :shading-object sphere)))
(list
;; FIXME: To reduce consing even further: stack allocate
;; the csg-interactions and pass a continuation in here.
;; ...alternatively, pre-allocate a csg-intersection buffer.
:all-intersections
(sb-int:named-lambda sphere-all-intersections (origin direction)
(declare (optimize speed))
(let ((o (transform-point origin inverse))
(d (transform-direction direction inverse))
(limit +epsilon+))
(declare (dynamic-extent o d))
(multiple-value-bind (r1 r2)
(quadratic-roots-above limit
(dot-product d d)
(* 2.0 (dot-product d o))
(- (dot-product o o) 1.0))
(cond ((= limit r1)
#())
((= limit r2)
(simple-vector (make-csg-intersection :distance r1 :object compiled)))
(t
(simple-vector (make-csg-intersection :distance r1 :object compiled)
(make-csg-intersection :distance r2 :object compiled)))))))
:inside
(lambda (point)
(> (+ 1.0 +epsilon+)
(let ((p (transform-point point inverse)))
(declare (dynamic-extent p))
(vec-length p)))))))
|
[
{
"context": "he LICENSE file distributed with ACL2.\n;\n; Author: Alessandro Coglio ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 202,
"score": 0.999870777130127,
"start": 185,
"tag": "NAME",
"value": "Alessandro Coglio"
},
{
"context": "ributed with ACL2.\n;\n; Author: Alessandro Coglio ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 222,
"score": 0.9999299645423889,
"start": 204,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/kestrel/std/system/check-mv-let-call.lisp
|
KestrelInstitute/acl2
| 305 |
; Standard System Library
;
; Copyright (C) 2021 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 "dumb-occur-var-open")
(include-book "remove-trivial-vars")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define check-mv-let-call ((term pseudo-termp))
:returns (mv (yes/no booleanp)
(mv-var symbolp :hyp :guard)
(vars symbol-listp :hyp :guard)
(indices nat-listp)
(hides boolean-listp)
(mv-term pseudo-termp :hyp :guard)
(body-term pseudo-termp :hyp :guard))
:parents (std/system/term-queries)
:short "Check if a term is a (translated) call of @(tsee mv-let)."
:long
(xdoc::topstring
(xdoc::p
"In translated form, @('(mv-let (var1 ... varn) mv-term body-term)') is")
(xdoc::codeblock
"((lambda (mv)"
" ((lambda (var1 ... varn) body-term-trans)"
" (mv-nth '0 mv)"
" ..."
" (mv-nth 'n-1 mv)))"
" mv-term-trans)")
(xdoc::p
"where @('mv-term-trans') and @('body-term-trans') are
the translations of @('mv-term') and @('body-term').")
(xdoc::p
"This utility checks if a translated term has the form above;
it also checks that @('mv') does not occur free in @('body-term')
(via @(tsee dumb-occur-var-open) for greater flexibility).
If all these checks pass, it returns @('t') as first result,
and additionally the variable @('mv'),
the list @('(var1 ... varn)'),
the term @('mv-term-trans'),
and the term @('body-term-trans').
If the input term does not have that form,
this utility returns @('nil') for each result.")
(xdoc::p
"If the input term has the form above,
it is not necessarily the result of translating @(tsee mv-let).
It could be the translation of
@('(let ((mv mv-term))
(let ((var1 (mv-nth 0 mv)) ... (varn (mv-nth n-1 mv)))
mv-body))')
instead;
it depends on whether @('mv-term') is single-valued or multi-valued,
and also on whether the term is translated for execution or not.
However, the result of translating @(tsee mv-let)
necessarily has the form above.")
(xdoc::p
"Note, however, that lambda expressions are always closed
in translated terms directly obtained from untranslated terms.
ACL2 accomplishes this closure
by adding formal paramaters to the lambda expressions
for the otherwise free variables,
and adding actual arguments identical to those variables;
see @(tsee remove-trivial-vars).
This means that the lambda expressions above may have extra variables.
To ``correct'' for this, before examining the two lambda expressions,
we remove all their formal parameters
that are identical to the corresponding arguments,
via @(tsee remove-trivial-vars)'s auxiliary function
@(tsee remove-equal-formals-actuals), which does exactly that.
We do not use @(tsee remove-trivial-vars) because that one
removes the trivial variables at all levels,
while here we only want to remove the ones
from the two lambda expressions being examined.")
(xdoc::p
"Note also that, due to this lambda expression closure,
the @('mv') variable is not always the symbol `@('mv')':
if that symbol happens to be a free variable,
ACL2's translation picks a different symbol
for the first formal argument of the outer lambda expression above.
For instance,")
(xdoc::codeblock
":trans (let ((mv 0)) (mv-let (x y) (f mv) (list x y mv)))")
(xdoc::p
"produces a translated term with the symbol `@('mv0')'
as the variable bound to the multiple value.
This is why this utility returns this variable
as one of its results.")
(xdoc::p
"In translated terms directly obtained from untranslated terms,
@(tsee mv-let)s always have @('(mv-nth i ...)') calls
for all contiguous indices @('i') from 0 to
the number of @(tsee mv-let)-bound variables minus 1,
corresponding to all the bound variables (0-based).
However, if a term is subjected to
transformations like @(tsee remove-unused-vars),
some of those @(tsee mv-nth) calls may disappear
(if they are not used in the body of the @(tsee mv-let)).
Thus, for wider usability,
this utility does not require all the @(tsee mv-nth) calls to be present.
It only requires calls with strictly increasing indices, allowing gaps.
The ordered list of indices actually present is returned,
so that a caller can indipendently check that there are no gaps,
if the term is not supposed to have any such gaps.")
(xdoc::p
"An additional complication derives from the fact that @(tsee mv-let)
allows the declaration of ignored variables within, e.g.
@('(mv-let (x y z) (mv 1 2 3) (declare (ignore x y)) z)').
In translated terms, this manifests in the addition of @(tsee hide)
around the @(tsee mv-nth) terms, which in this example is")
(xdoc::codeblock
"((lambda (mv)"
" ((lambda (x y z) z)"
" (hide (mv-nth '0 mv))"
" (hide (mv-nth '1 mv))"
" (mv-nth '2 mv)))"
" (cons '1 (cons '2 (cons '3 'nil))))")
(xdoc::p
"This utility takes this possibility into account,
and returns, as an additional result,
a list of booleans, of the same length as variables and indices,
that says whether the corresponding @(tsee mv-nth)
is wrapped by @(tsee hide) or not.
This way, the utility returns all the information about the term,
which the caller may use as desired.")
(xdoc::p
"@(tsee mv-let) also support the declaration of ignorable variables.
But these declarations do not introduce any @(tsee hide) wrapper
or other change into the translated term.")
(xdoc::p
"This utility is a left inverse of @(tsee make-mv-let-call)."))
(b* (((when (variablep term)) (mv nil nil nil nil nil nil nil))
((when (fquotep term)) (mv nil nil nil nil nil nil nil))
((unless (flambda-applicationp term)) (mv nil nil nil nil nil nil nil))
(outer-lambda-expr (ffn-symb term))
(formals (lambda-formals outer-lambda-expr))
(actuals (fargs term))
((mv list-mv list-mv-term)
(remove-equal-formals-actuals formals actuals))
((unless (and (consp list-mv)
(not (consp (cdr list-mv)))))
(mv nil nil nil nil nil nil nil))
(mv-var (car list-mv))
((unless (and (consp list-mv-term)
(not (consp (cdr list-mv-term)))))
(mv nil nil nil nil nil nil nil))
(mv-term (car list-mv-term))
(inner-lambda-expr-call (lambda-body outer-lambda-expr))
((when (variablep inner-lambda-expr-call))
(mv nil nil nil nil nil nil nil))
((when (fquotep inner-lambda-expr-call))
(mv nil nil nil nil nil nil nil))
((unless (flambda-applicationp inner-lambda-expr-call))
(mv nil nil nil nil nil nil nil))
(inner-lambda-expr (ffn-symb inner-lambda-expr-call))
(formals (lambda-formals inner-lambda-expr))
(actuals (fargs inner-lambda-expr-call))
((mv vars mv-nths) (remove-equal-formals-actuals formals actuals))
(body-term (lambda-body inner-lambda-expr))
((when (dumb-occur-var-open mv-var body-term))
(mv nil nil nil nil nil nil nil))
((mv okp indices hides) (check-mv-let-call-aux mv-nths 0 mv-var))
((unless okp) (mv nil nil nil nil nil nil nil)))
(mv t mv-var vars indices hides mv-term body-term))
:prepwork
((define check-mv-let-call-aux ((terms pseudo-term-listp)
(min-index natp)
(mv-var symbolp))
:returns (mv (yes/no booleanp) (indices nat-listp) (hides boolean-listp))
(b* (((when (endp terms)) (mv t nil nil))
(term (car terms))
((mv hide term)
(if (and (true-listp term)
(consp term)
(consp (cdr term))
(atom (cddr term))
(eq (car term) 'hide))
(mv t (cadr term))
(mv nil term)))
((unless (and (true-listp term)
(consp term)
(consp (cdr term))
(consp (cddr term))
(atom (cdddr term))))
(mv nil nil nil))
((unless (eq (car term) 'mv-nth)) (mv nil nil nil))
(index-term (cadr term))
((unless (eq (caddr term) mv-var)) (mv nil nil nil))
((unless (quotep index-term)) (mv nil nil nil))
(index (unquote index-term))
((unless (natp index)) (mv nil nil nil))
((unless (>= index min-index)) (mv nil nil nil))
((mv yes/no indices hides) (check-mv-let-call-aux (cdr terms)
(1+ index)
mv-var))
((unless yes/no) (mv nil nil nil)))
(mv t (cons index indices) (cons hide hides)))
///
(defret len-of-check-mv-let-call-aux.indices
(implies yes/no
(equal (len indices)
(len terms))))
(defret len-of-check-mv-let-call-aux.hides
(implies yes/no
(equal (len hides)
(len terms)))))
(local (include-book "std/typed-lists/symbol-listp" :dir :system))
(local (include-book "std/typed-lists/pseudo-term-listp" :dir :system)))
///
(defret len-of-check-mv-let-call.indices/vars
(implies yes/no
(equal (len indices)
(len vars)))
:hyp :guard
:hints (("Goal" :in-theory (enable remove-equal-formals-actuals-same-len))))
(defret len-of-check-mv-let-call.hides/vars
(implies yes/no
(equal (len hides)
(len vars)))
:hyp :guard
:hints (("Goal" :in-theory (enable remove-equal-formals-actuals-same-len))))
(in-theory (disable len-of-check-mv-let-call.indices/vars
len-of-check-mv-let-call.hides/vars))
(local
(defthm acl2-count-of-check-mv-let-call.mv-term-lemma
(implies (consp x)
(< (acl2-count (car x))
(acl2-count x)))
:rule-classes :linear))
(defret acl2-count-of-check-mv-let-call.mv-term
(implies yes/no
(< (acl2-count mv-term)
(acl2-count term)))
:rule-classes :linear)
(defret acl2-count-of-check-mv-let-call.body-term
(implies yes/no
(< (acl2-count body-term)
(acl2-count term)))
:rule-classes :linear))
|
95769
|
; Standard System 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 "ACL2")
(include-book "dumb-occur-var-open")
(include-book "remove-trivial-vars")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define check-mv-let-call ((term pseudo-termp))
:returns (mv (yes/no booleanp)
(mv-var symbolp :hyp :guard)
(vars symbol-listp :hyp :guard)
(indices nat-listp)
(hides boolean-listp)
(mv-term pseudo-termp :hyp :guard)
(body-term pseudo-termp :hyp :guard))
:parents (std/system/term-queries)
:short "Check if a term is a (translated) call of @(tsee mv-let)."
:long
(xdoc::topstring
(xdoc::p
"In translated form, @('(mv-let (var1 ... varn) mv-term body-term)') is")
(xdoc::codeblock
"((lambda (mv)"
" ((lambda (var1 ... varn) body-term-trans)"
" (mv-nth '0 mv)"
" ..."
" (mv-nth 'n-1 mv)))"
" mv-term-trans)")
(xdoc::p
"where @('mv-term-trans') and @('body-term-trans') are
the translations of @('mv-term') and @('body-term').")
(xdoc::p
"This utility checks if a translated term has the form above;
it also checks that @('mv') does not occur free in @('body-term')
(via @(tsee dumb-occur-var-open) for greater flexibility).
If all these checks pass, it returns @('t') as first result,
and additionally the variable @('mv'),
the list @('(var1 ... varn)'),
the term @('mv-term-trans'),
and the term @('body-term-trans').
If the input term does not have that form,
this utility returns @('nil') for each result.")
(xdoc::p
"If the input term has the form above,
it is not necessarily the result of translating @(tsee mv-let).
It could be the translation of
@('(let ((mv mv-term))
(let ((var1 (mv-nth 0 mv)) ... (varn (mv-nth n-1 mv)))
mv-body))')
instead;
it depends on whether @('mv-term') is single-valued or multi-valued,
and also on whether the term is translated for execution or not.
However, the result of translating @(tsee mv-let)
necessarily has the form above.")
(xdoc::p
"Note, however, that lambda expressions are always closed
in translated terms directly obtained from untranslated terms.
ACL2 accomplishes this closure
by adding formal paramaters to the lambda expressions
for the otherwise free variables,
and adding actual arguments identical to those variables;
see @(tsee remove-trivial-vars).
This means that the lambda expressions above may have extra variables.
To ``correct'' for this, before examining the two lambda expressions,
we remove all their formal parameters
that are identical to the corresponding arguments,
via @(tsee remove-trivial-vars)'s auxiliary function
@(tsee remove-equal-formals-actuals), which does exactly that.
We do not use @(tsee remove-trivial-vars) because that one
removes the trivial variables at all levels,
while here we only want to remove the ones
from the two lambda expressions being examined.")
(xdoc::p
"Note also that, due to this lambda expression closure,
the @('mv') variable is not always the symbol `@('mv')':
if that symbol happens to be a free variable,
ACL2's translation picks a different symbol
for the first formal argument of the outer lambda expression above.
For instance,")
(xdoc::codeblock
":trans (let ((mv 0)) (mv-let (x y) (f mv) (list x y mv)))")
(xdoc::p
"produces a translated term with the symbol `@('mv0')'
as the variable bound to the multiple value.
This is why this utility returns this variable
as one of its results.")
(xdoc::p
"In translated terms directly obtained from untranslated terms,
@(tsee mv-let)s always have @('(mv-nth i ...)') calls
for all contiguous indices @('i') from 0 to
the number of @(tsee mv-let)-bound variables minus 1,
corresponding to all the bound variables (0-based).
However, if a term is subjected to
transformations like @(tsee remove-unused-vars),
some of those @(tsee mv-nth) calls may disappear
(if they are not used in the body of the @(tsee mv-let)).
Thus, for wider usability,
this utility does not require all the @(tsee mv-nth) calls to be present.
It only requires calls with strictly increasing indices, allowing gaps.
The ordered list of indices actually present is returned,
so that a caller can indipendently check that there are no gaps,
if the term is not supposed to have any such gaps.")
(xdoc::p
"An additional complication derives from the fact that @(tsee mv-let)
allows the declaration of ignored variables within, e.g.
@('(mv-let (x y z) (mv 1 2 3) (declare (ignore x y)) z)').
In translated terms, this manifests in the addition of @(tsee hide)
around the @(tsee mv-nth) terms, which in this example is")
(xdoc::codeblock
"((lambda (mv)"
" ((lambda (x y z) z)"
" (hide (mv-nth '0 mv))"
" (hide (mv-nth '1 mv))"
" (mv-nth '2 mv)))"
" (cons '1 (cons '2 (cons '3 'nil))))")
(xdoc::p
"This utility takes this possibility into account,
and returns, as an additional result,
a list of booleans, of the same length as variables and indices,
that says whether the corresponding @(tsee mv-nth)
is wrapped by @(tsee hide) or not.
This way, the utility returns all the information about the term,
which the caller may use as desired.")
(xdoc::p
"@(tsee mv-let) also support the declaration of ignorable variables.
But these declarations do not introduce any @(tsee hide) wrapper
or other change into the translated term.")
(xdoc::p
"This utility is a left inverse of @(tsee make-mv-let-call)."))
(b* (((when (variablep term)) (mv nil nil nil nil nil nil nil))
((when (fquotep term)) (mv nil nil nil nil nil nil nil))
((unless (flambda-applicationp term)) (mv nil nil nil nil nil nil nil))
(outer-lambda-expr (ffn-symb term))
(formals (lambda-formals outer-lambda-expr))
(actuals (fargs term))
((mv list-mv list-mv-term)
(remove-equal-formals-actuals formals actuals))
((unless (and (consp list-mv)
(not (consp (cdr list-mv)))))
(mv nil nil nil nil nil nil nil))
(mv-var (car list-mv))
((unless (and (consp list-mv-term)
(not (consp (cdr list-mv-term)))))
(mv nil nil nil nil nil nil nil))
(mv-term (car list-mv-term))
(inner-lambda-expr-call (lambda-body outer-lambda-expr))
((when (variablep inner-lambda-expr-call))
(mv nil nil nil nil nil nil nil))
((when (fquotep inner-lambda-expr-call))
(mv nil nil nil nil nil nil nil))
((unless (flambda-applicationp inner-lambda-expr-call))
(mv nil nil nil nil nil nil nil))
(inner-lambda-expr (ffn-symb inner-lambda-expr-call))
(formals (lambda-formals inner-lambda-expr))
(actuals (fargs inner-lambda-expr-call))
((mv vars mv-nths) (remove-equal-formals-actuals formals actuals))
(body-term (lambda-body inner-lambda-expr))
((when (dumb-occur-var-open mv-var body-term))
(mv nil nil nil nil nil nil nil))
((mv okp indices hides) (check-mv-let-call-aux mv-nths 0 mv-var))
((unless okp) (mv nil nil nil nil nil nil nil)))
(mv t mv-var vars indices hides mv-term body-term))
:prepwork
((define check-mv-let-call-aux ((terms pseudo-term-listp)
(min-index natp)
(mv-var symbolp))
:returns (mv (yes/no booleanp) (indices nat-listp) (hides boolean-listp))
(b* (((when (endp terms)) (mv t nil nil))
(term (car terms))
((mv hide term)
(if (and (true-listp term)
(consp term)
(consp (cdr term))
(atom (cddr term))
(eq (car term) 'hide))
(mv t (cadr term))
(mv nil term)))
((unless (and (true-listp term)
(consp term)
(consp (cdr term))
(consp (cddr term))
(atom (cdddr term))))
(mv nil nil nil))
((unless (eq (car term) 'mv-nth)) (mv nil nil nil))
(index-term (cadr term))
((unless (eq (caddr term) mv-var)) (mv nil nil nil))
((unless (quotep index-term)) (mv nil nil nil))
(index (unquote index-term))
((unless (natp index)) (mv nil nil nil))
((unless (>= index min-index)) (mv nil nil nil))
((mv yes/no indices hides) (check-mv-let-call-aux (cdr terms)
(1+ index)
mv-var))
((unless yes/no) (mv nil nil nil)))
(mv t (cons index indices) (cons hide hides)))
///
(defret len-of-check-mv-let-call-aux.indices
(implies yes/no
(equal (len indices)
(len terms))))
(defret len-of-check-mv-let-call-aux.hides
(implies yes/no
(equal (len hides)
(len terms)))))
(local (include-book "std/typed-lists/symbol-listp" :dir :system))
(local (include-book "std/typed-lists/pseudo-term-listp" :dir :system)))
///
(defret len-of-check-mv-let-call.indices/vars
(implies yes/no
(equal (len indices)
(len vars)))
:hyp :guard
:hints (("Goal" :in-theory (enable remove-equal-formals-actuals-same-len))))
(defret len-of-check-mv-let-call.hides/vars
(implies yes/no
(equal (len hides)
(len vars)))
:hyp :guard
:hints (("Goal" :in-theory (enable remove-equal-formals-actuals-same-len))))
(in-theory (disable len-of-check-mv-let-call.indices/vars
len-of-check-mv-let-call.hides/vars))
(local
(defthm acl2-count-of-check-mv-let-call.mv-term-lemma
(implies (consp x)
(< (acl2-count (car x))
(acl2-count x)))
:rule-classes :linear))
(defret acl2-count-of-check-mv-let-call.mv-term
(implies yes/no
(< (acl2-count mv-term)
(acl2-count term)))
:rule-classes :linear)
(defret acl2-count-of-check-mv-let-call.body-term
(implies yes/no
(< (acl2-count body-term)
(acl2-count term)))
:rule-classes :linear))
| true |
; Standard System 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 "ACL2")
(include-book "dumb-occur-var-open")
(include-book "remove-trivial-vars")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define check-mv-let-call ((term pseudo-termp))
:returns (mv (yes/no booleanp)
(mv-var symbolp :hyp :guard)
(vars symbol-listp :hyp :guard)
(indices nat-listp)
(hides boolean-listp)
(mv-term pseudo-termp :hyp :guard)
(body-term pseudo-termp :hyp :guard))
:parents (std/system/term-queries)
:short "Check if a term is a (translated) call of @(tsee mv-let)."
:long
(xdoc::topstring
(xdoc::p
"In translated form, @('(mv-let (var1 ... varn) mv-term body-term)') is")
(xdoc::codeblock
"((lambda (mv)"
" ((lambda (var1 ... varn) body-term-trans)"
" (mv-nth '0 mv)"
" ..."
" (mv-nth 'n-1 mv)))"
" mv-term-trans)")
(xdoc::p
"where @('mv-term-trans') and @('body-term-trans') are
the translations of @('mv-term') and @('body-term').")
(xdoc::p
"This utility checks if a translated term has the form above;
it also checks that @('mv') does not occur free in @('body-term')
(via @(tsee dumb-occur-var-open) for greater flexibility).
If all these checks pass, it returns @('t') as first result,
and additionally the variable @('mv'),
the list @('(var1 ... varn)'),
the term @('mv-term-trans'),
and the term @('body-term-trans').
If the input term does not have that form,
this utility returns @('nil') for each result.")
(xdoc::p
"If the input term has the form above,
it is not necessarily the result of translating @(tsee mv-let).
It could be the translation of
@('(let ((mv mv-term))
(let ((var1 (mv-nth 0 mv)) ... (varn (mv-nth n-1 mv)))
mv-body))')
instead;
it depends on whether @('mv-term') is single-valued or multi-valued,
and also on whether the term is translated for execution or not.
However, the result of translating @(tsee mv-let)
necessarily has the form above.")
(xdoc::p
"Note, however, that lambda expressions are always closed
in translated terms directly obtained from untranslated terms.
ACL2 accomplishes this closure
by adding formal paramaters to the lambda expressions
for the otherwise free variables,
and adding actual arguments identical to those variables;
see @(tsee remove-trivial-vars).
This means that the lambda expressions above may have extra variables.
To ``correct'' for this, before examining the two lambda expressions,
we remove all their formal parameters
that are identical to the corresponding arguments,
via @(tsee remove-trivial-vars)'s auxiliary function
@(tsee remove-equal-formals-actuals), which does exactly that.
We do not use @(tsee remove-trivial-vars) because that one
removes the trivial variables at all levels,
while here we only want to remove the ones
from the two lambda expressions being examined.")
(xdoc::p
"Note also that, due to this lambda expression closure,
the @('mv') variable is not always the symbol `@('mv')':
if that symbol happens to be a free variable,
ACL2's translation picks a different symbol
for the first formal argument of the outer lambda expression above.
For instance,")
(xdoc::codeblock
":trans (let ((mv 0)) (mv-let (x y) (f mv) (list x y mv)))")
(xdoc::p
"produces a translated term with the symbol `@('mv0')'
as the variable bound to the multiple value.
This is why this utility returns this variable
as one of its results.")
(xdoc::p
"In translated terms directly obtained from untranslated terms,
@(tsee mv-let)s always have @('(mv-nth i ...)') calls
for all contiguous indices @('i') from 0 to
the number of @(tsee mv-let)-bound variables minus 1,
corresponding to all the bound variables (0-based).
However, if a term is subjected to
transformations like @(tsee remove-unused-vars),
some of those @(tsee mv-nth) calls may disappear
(if they are not used in the body of the @(tsee mv-let)).
Thus, for wider usability,
this utility does not require all the @(tsee mv-nth) calls to be present.
It only requires calls with strictly increasing indices, allowing gaps.
The ordered list of indices actually present is returned,
so that a caller can indipendently check that there are no gaps,
if the term is not supposed to have any such gaps.")
(xdoc::p
"An additional complication derives from the fact that @(tsee mv-let)
allows the declaration of ignored variables within, e.g.
@('(mv-let (x y z) (mv 1 2 3) (declare (ignore x y)) z)').
In translated terms, this manifests in the addition of @(tsee hide)
around the @(tsee mv-nth) terms, which in this example is")
(xdoc::codeblock
"((lambda (mv)"
" ((lambda (x y z) z)"
" (hide (mv-nth '0 mv))"
" (hide (mv-nth '1 mv))"
" (mv-nth '2 mv)))"
" (cons '1 (cons '2 (cons '3 'nil))))")
(xdoc::p
"This utility takes this possibility into account,
and returns, as an additional result,
a list of booleans, of the same length as variables and indices,
that says whether the corresponding @(tsee mv-nth)
is wrapped by @(tsee hide) or not.
This way, the utility returns all the information about the term,
which the caller may use as desired.")
(xdoc::p
"@(tsee mv-let) also support the declaration of ignorable variables.
But these declarations do not introduce any @(tsee hide) wrapper
or other change into the translated term.")
(xdoc::p
"This utility is a left inverse of @(tsee make-mv-let-call)."))
(b* (((when (variablep term)) (mv nil nil nil nil nil nil nil))
((when (fquotep term)) (mv nil nil nil nil nil nil nil))
((unless (flambda-applicationp term)) (mv nil nil nil nil nil nil nil))
(outer-lambda-expr (ffn-symb term))
(formals (lambda-formals outer-lambda-expr))
(actuals (fargs term))
((mv list-mv list-mv-term)
(remove-equal-formals-actuals formals actuals))
((unless (and (consp list-mv)
(not (consp (cdr list-mv)))))
(mv nil nil nil nil nil nil nil))
(mv-var (car list-mv))
((unless (and (consp list-mv-term)
(not (consp (cdr list-mv-term)))))
(mv nil nil nil nil nil nil nil))
(mv-term (car list-mv-term))
(inner-lambda-expr-call (lambda-body outer-lambda-expr))
((when (variablep inner-lambda-expr-call))
(mv nil nil nil nil nil nil nil))
((when (fquotep inner-lambda-expr-call))
(mv nil nil nil nil nil nil nil))
((unless (flambda-applicationp inner-lambda-expr-call))
(mv nil nil nil nil nil nil nil))
(inner-lambda-expr (ffn-symb inner-lambda-expr-call))
(formals (lambda-formals inner-lambda-expr))
(actuals (fargs inner-lambda-expr-call))
((mv vars mv-nths) (remove-equal-formals-actuals formals actuals))
(body-term (lambda-body inner-lambda-expr))
((when (dumb-occur-var-open mv-var body-term))
(mv nil nil nil nil nil nil nil))
((mv okp indices hides) (check-mv-let-call-aux mv-nths 0 mv-var))
((unless okp) (mv nil nil nil nil nil nil nil)))
(mv t mv-var vars indices hides mv-term body-term))
:prepwork
((define check-mv-let-call-aux ((terms pseudo-term-listp)
(min-index natp)
(mv-var symbolp))
:returns (mv (yes/no booleanp) (indices nat-listp) (hides boolean-listp))
(b* (((when (endp terms)) (mv t nil nil))
(term (car terms))
((mv hide term)
(if (and (true-listp term)
(consp term)
(consp (cdr term))
(atom (cddr term))
(eq (car term) 'hide))
(mv t (cadr term))
(mv nil term)))
((unless (and (true-listp term)
(consp term)
(consp (cdr term))
(consp (cddr term))
(atom (cdddr term))))
(mv nil nil nil))
((unless (eq (car term) 'mv-nth)) (mv nil nil nil))
(index-term (cadr term))
((unless (eq (caddr term) mv-var)) (mv nil nil nil))
((unless (quotep index-term)) (mv nil nil nil))
(index (unquote index-term))
((unless (natp index)) (mv nil nil nil))
((unless (>= index min-index)) (mv nil nil nil))
((mv yes/no indices hides) (check-mv-let-call-aux (cdr terms)
(1+ index)
mv-var))
((unless yes/no) (mv nil nil nil)))
(mv t (cons index indices) (cons hide hides)))
///
(defret len-of-check-mv-let-call-aux.indices
(implies yes/no
(equal (len indices)
(len terms))))
(defret len-of-check-mv-let-call-aux.hides
(implies yes/no
(equal (len hides)
(len terms)))))
(local (include-book "std/typed-lists/symbol-listp" :dir :system))
(local (include-book "std/typed-lists/pseudo-term-listp" :dir :system)))
///
(defret len-of-check-mv-let-call.indices/vars
(implies yes/no
(equal (len indices)
(len vars)))
:hyp :guard
:hints (("Goal" :in-theory (enable remove-equal-formals-actuals-same-len))))
(defret len-of-check-mv-let-call.hides/vars
(implies yes/no
(equal (len hides)
(len vars)))
:hyp :guard
:hints (("Goal" :in-theory (enable remove-equal-formals-actuals-same-len))))
(in-theory (disable len-of-check-mv-let-call.indices/vars
len-of-check-mv-let-call.hides/vars))
(local
(defthm acl2-count-of-check-mv-let-call.mv-term-lemma
(implies (consp x)
(< (acl2-count (car x))
(acl2-count x)))
:rule-classes :linear))
(defret acl2-count-of-check-mv-let-call.mv-term
(implies yes/no
(< (acl2-count mv-term)
(acl2-count term)))
:rule-classes :linear)
(defret acl2-count-of-check-mv-let-call.body-term
(implies yes/no
(< (acl2-count body-term)
(acl2-count term)))
:rule-classes :linear))
|
[
{
"context": "\t - Collecting lists forwards\n;; Author\t - Tim Bradshaw (tfb at lostwithiel)\n;; Created On\t - 1989\n;;",
"end": 189,
"score": 0.9999028444290161,
"start": 177,
"tag": "NAME",
"value": "Tim Bradshaw"
},
{
"context": " - Wed May 2 13:50:03 2012\n;; Last Modified By - Tim Bradshaw (tfb at kingston.local)\n;; Update Count\t - 13",
"end": 320,
"score": 0.9998489618301392,
"start": 308,
"tag": "NAME",
"value": "Tim Bradshaw"
},
{
"context": "pyrighting, but are copyright\n;;; 1989-2012 by me, Tim Bradshaw, and may be used for any purpose\n;;; whatsoever b",
"end": 977,
"score": 0.999894917011261,
"start": 965,
"tag": "NAME",
"value": "Tim Bradshaw"
}
] |
collecting.lisp
|
tfeb/interim-lisp
| 4 |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -*- Mode: Lisp -*- ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; File - collecting.lisp
;; Description - Collecting lists forwards
;; Author - Tim Bradshaw (tfb at lostwithiel)
;; Created On - 1989
;; Last Modified On - Wed May 2 13:50:03 2012
;; Last Modified By - Tim Bradshaw (tfb at kingston.local)
;; Update Count - 13
;; Status - Unknown
;;
;; $Id: //depot/www-tfeb-org/before-2013-prune/www-tfeb-org/html/programs/lisp/collecting.lisp#1 $
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Collecting lists forwards
;;; This is an old macro cleaned up a bit
;;;
;;; 2012: I have changed this to use local functions rather than macros,
;;; on the assumption that implementations can optimize this pretty well now
;;; and local functions are much semantically nicer than macros.
;;;
;;; These macros hardly seem worth copyrighting, but are copyright
;;; 1989-2012 by me, Tim Bradshaw, and may be used for any purpose
;;; whatsoever by anyone. There is no warranty whatsoever. I would
;;; appreciate acknowledgement if you use this in anger, and I would
;;; also very much appreciate any feedback or bug fixes.
(provide :org.tfeb.hax.collecting)
(eval-when (:compile-toplevel :load-toplevel :execute)
(when (not (find-package ':org.tfeb.hax))
(make-package ':org.tfeb.hax)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(export '(org.tfeb.hax::collecting
org.tfeb.hax::collect
org.tfeb.hax::with-collectors)
(find-package ':org.tfeb.hax)))
(in-package :org.tfeb.hax)
(defmacro collecting (&body forms)
;; Collect some random stuff into a list by keeping a tail-pointer
;; to it, return the collected list. This now uses a local function
;; rather than a macro.
"Collect things into a list forwards. Within the body of this macro
The form `(COLLECT THING)' will collect THING into the list returned by
COLLECTING. COLLECT is a local function so can be passed as an argument,
or returned. Uses a tail pointer -> efficient."
(let ((cn (make-symbol "C")) (tn (make-symbol "CT")))
`(let ((,cn '()) (,tn nil))
(flet ((collect (it)
(if ,cn
(setf (cdr ,tn) (list it)
,tn (cdr ,tn))
(setf ,tn (list it)
,cn ,tn))
it))
(declare (inline collect))
,@forms)
,cn)))
(defmacro with-collectors ((&rest collectors) &body forms)
;; multiple-collector version of COLLECTING.
"Collect some things into lists forwards.
The names in COLLECTORS are defined as local functions, which each collect into a
separate list. Returns as many values as there are collectors."
(let ((cvns (mapcar #'(lambda (c)
(make-symbol (concatenate 'string
(symbol-name c) "-VAR")))
collectors))
(ctns (mapcar #'(lambda (c)
(make-symbol (concatenate 'string
(symbol-name c) "-TAIL")))
collectors)))
`(let (,@cvns ,@ctns)
(flet ,(mapcar (lambda (cn cvn ctn)
`(,cn (it)
(if ,cvn
(setf (cdr ,ctn) (list it)
,ctn (cdr ,ctn))
(setf ,ctn (list it)
,cvn ,ctn))
it))
collectors cvns ctns)
(declare (inline ,@collectors))
,@forms)
(values ,@cvns))))
|
82007
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -*- Mode: Lisp -*- ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; File - collecting.lisp
;; Description - Collecting lists forwards
;; Author - <NAME> (tfb at lostwithiel)
;; Created On - 1989
;; Last Modified On - Wed May 2 13:50:03 2012
;; Last Modified By - <NAME> (tfb at kingston.local)
;; Update Count - 13
;; Status - Unknown
;;
;; $Id: //depot/www-tfeb-org/before-2013-prune/www-tfeb-org/html/programs/lisp/collecting.lisp#1 $
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Collecting lists forwards
;;; This is an old macro cleaned up a bit
;;;
;;; 2012: I have changed this to use local functions rather than macros,
;;; on the assumption that implementations can optimize this pretty well now
;;; and local functions are much semantically nicer than macros.
;;;
;;; These macros hardly seem worth copyrighting, but are copyright
;;; 1989-2012 by me, <NAME>, and may be used for any purpose
;;; whatsoever by anyone. There is no warranty whatsoever. I would
;;; appreciate acknowledgement if you use this in anger, and I would
;;; also very much appreciate any feedback or bug fixes.
(provide :org.tfeb.hax.collecting)
(eval-when (:compile-toplevel :load-toplevel :execute)
(when (not (find-package ':org.tfeb.hax))
(make-package ':org.tfeb.hax)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(export '(org.tfeb.hax::collecting
org.tfeb.hax::collect
org.tfeb.hax::with-collectors)
(find-package ':org.tfeb.hax)))
(in-package :org.tfeb.hax)
(defmacro collecting (&body forms)
;; Collect some random stuff into a list by keeping a tail-pointer
;; to it, return the collected list. This now uses a local function
;; rather than a macro.
"Collect things into a list forwards. Within the body of this macro
The form `(COLLECT THING)' will collect THING into the list returned by
COLLECTING. COLLECT is a local function so can be passed as an argument,
or returned. Uses a tail pointer -> efficient."
(let ((cn (make-symbol "C")) (tn (make-symbol "CT")))
`(let ((,cn '()) (,tn nil))
(flet ((collect (it)
(if ,cn
(setf (cdr ,tn) (list it)
,tn (cdr ,tn))
(setf ,tn (list it)
,cn ,tn))
it))
(declare (inline collect))
,@forms)
,cn)))
(defmacro with-collectors ((&rest collectors) &body forms)
;; multiple-collector version of COLLECTING.
"Collect some things into lists forwards.
The names in COLLECTORS are defined as local functions, which each collect into a
separate list. Returns as many values as there are collectors."
(let ((cvns (mapcar #'(lambda (c)
(make-symbol (concatenate 'string
(symbol-name c) "-VAR")))
collectors))
(ctns (mapcar #'(lambda (c)
(make-symbol (concatenate 'string
(symbol-name c) "-TAIL")))
collectors)))
`(let (,@cvns ,@ctns)
(flet ,(mapcar (lambda (cn cvn ctn)
`(,cn (it)
(if ,cvn
(setf (cdr ,ctn) (list it)
,ctn (cdr ,ctn))
(setf ,ctn (list it)
,cvn ,ctn))
it))
collectors cvns ctns)
(declare (inline ,@collectors))
,@forms)
(values ,@cvns))))
| true |
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -*- Mode: Lisp -*- ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; File - collecting.lisp
;; Description - Collecting lists forwards
;; Author - PI:NAME:<NAME>END_PI (tfb at lostwithiel)
;; Created On - 1989
;; Last Modified On - Wed May 2 13:50:03 2012
;; Last Modified By - PI:NAME:<NAME>END_PI (tfb at kingston.local)
;; Update Count - 13
;; Status - Unknown
;;
;; $Id: //depot/www-tfeb-org/before-2013-prune/www-tfeb-org/html/programs/lisp/collecting.lisp#1 $
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Collecting lists forwards
;;; This is an old macro cleaned up a bit
;;;
;;; 2012: I have changed this to use local functions rather than macros,
;;; on the assumption that implementations can optimize this pretty well now
;;; and local functions are much semantically nicer than macros.
;;;
;;; These macros hardly seem worth copyrighting, but are copyright
;;; 1989-2012 by me, PI:NAME:<NAME>END_PI, and may be used for any purpose
;;; whatsoever by anyone. There is no warranty whatsoever. I would
;;; appreciate acknowledgement if you use this in anger, and I would
;;; also very much appreciate any feedback or bug fixes.
(provide :org.tfeb.hax.collecting)
(eval-when (:compile-toplevel :load-toplevel :execute)
(when (not (find-package ':org.tfeb.hax))
(make-package ':org.tfeb.hax)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(export '(org.tfeb.hax::collecting
org.tfeb.hax::collect
org.tfeb.hax::with-collectors)
(find-package ':org.tfeb.hax)))
(in-package :org.tfeb.hax)
(defmacro collecting (&body forms)
;; Collect some random stuff into a list by keeping a tail-pointer
;; to it, return the collected list. This now uses a local function
;; rather than a macro.
"Collect things into a list forwards. Within the body of this macro
The form `(COLLECT THING)' will collect THING into the list returned by
COLLECTING. COLLECT is a local function so can be passed as an argument,
or returned. Uses a tail pointer -> efficient."
(let ((cn (make-symbol "C")) (tn (make-symbol "CT")))
`(let ((,cn '()) (,tn nil))
(flet ((collect (it)
(if ,cn
(setf (cdr ,tn) (list it)
,tn (cdr ,tn))
(setf ,tn (list it)
,cn ,tn))
it))
(declare (inline collect))
,@forms)
,cn)))
(defmacro with-collectors ((&rest collectors) &body forms)
;; multiple-collector version of COLLECTING.
"Collect some things into lists forwards.
The names in COLLECTORS are defined as local functions, which each collect into a
separate list. Returns as many values as there are collectors."
(let ((cvns (mapcar #'(lambda (c)
(make-symbol (concatenate 'string
(symbol-name c) "-VAR")))
collectors))
(ctns (mapcar #'(lambda (c)
(make-symbol (concatenate 'string
(symbol-name c) "-TAIL")))
collectors)))
`(let (,@cvns ,@ctns)
(flet ,(mapcar (lambda (cn cvn ctn)
`(,cn (it)
(if ,cvn
(setf (cdr ,ctn) (list it)
,ctn (cdr ,ctn))
(setf ,ctn (list it)
,cvn ,ctn))
it))
collectors cvns ctns)
(declare (inline ,@collectors))
,@forms)
(values ,@cvns))))
|
[
{
"context": "(defparameter *table-A* '((27 \"Jonah\") (18 \"Alan\") (28 \"Glory\") (18 \"Popeye\") (28 \"Ala",
"end": 36,
"score": 0.9996354579925537,
"start": 31,
"tag": "NAME",
"value": "Jonah"
},
{
"context": "(defparameter *table-A* '((27 \"Jonah\") (18 \"Alan\") (28 \"Glory\") (18 \"Popeye\") (28 \"Alan\")))\n\n(defp",
"end": 48,
"score": 0.9993734359741211,
"start": 44,
"tag": "NAME",
"value": "Alan"
},
{
"context": "rameter *table-A* '((27 \"Jonah\") (18 \"Alan\") (28 \"Glory\") (18 \"Popeye\") (28 \"Alan\")))\n\n(defparameter *tab",
"end": 61,
"score": 0.9990929961204529,
"start": 56,
"tag": "NAME",
"value": "Glory"
},
{
"context": "e-A* '((27 \"Jonah\") (18 \"Alan\") (28 \"Glory\") (18 \"Popeye\") (28 \"Alan\")))\n\n(defparameter *table-B* '((\"Jona",
"end": 75,
"score": 0.9828484058380127,
"start": 69,
"tag": "NAME",
"value": "Popeye"
},
{
"context": "nah\") (18 \"Alan\") (28 \"Glory\") (18 \"Popeye\") (28 \"Alan\")))\n\n(defparameter *table-B* '((\"Jonah\" \"Whales\")",
"end": 87,
"score": 0.9973119497299194,
"start": 83,
"tag": "NAME",
"value": "Alan"
},
{
"context": "peye\") (28 \"Alan\")))\n\n(defparameter *table-B* '((\"Jonah\" \"Whales\") (\"Jonah\" \"Spiders\") (\"Alan\" \"Ghosts\") ",
"end": 126,
"score": 0.9997639060020447,
"start": 121,
"tag": "NAME",
"value": "Jonah"
},
{
"context": "28 \"Alan\")))\n\n(defparameter *table-B* '((\"Jonah\" \"Whales\") (\"Jonah\" \"Spiders\") (\"Alan\" \"Ghosts\") (\"Alan\" \"",
"end": 135,
"score": 0.9996433258056641,
"start": 129,
"tag": "NAME",
"value": "Whales"
},
{
"context": ")\n\n(defparameter *table-B* '((\"Jonah\" \"Whales\") (\"Jonah\" \"Spiders\") (\"Alan\" \"Ghosts\") (\"Alan\" \"Zombies\") ",
"end": 145,
"score": 0.9997284412384033,
"start": 140,
"tag": "NAME",
"value": "Jonah"
},
{
"context": "arameter *table-B* '((\"Jonah\" \"Whales\") (\"Jonah\" \"Spiders\") (\"Alan\" \"Ghosts\") (\"Alan\" \"Zombies\") (\"Glory\" \"",
"end": 155,
"score": 0.9964516162872314,
"start": 148,
"tag": "NAME",
"value": "Spiders"
},
{
"context": "ble-B* '((\"Jonah\" \"Whales\") (\"Jonah\" \"Spiders\") (\"Alan\" \"Ghosts\") (\"Alan\" \"Zombies\") (\"Glory\" \"Buffy\")))",
"end": 164,
"score": 0.9996461868286133,
"start": 160,
"tag": "NAME",
"value": "Alan"
},
{
"context": "'((\"Jonah\" \"Whales\") (\"Jonah\" \"Spiders\") (\"Alan\" \"Ghosts\") (\"Alan\" \"Zombies\") (\"Glory\" \"Buffy\")))\n\n;; Hash",
"end": 173,
"score": 0.9940847158432007,
"start": 167,
"tag": "NAME",
"value": "Ghosts"
},
{
"context": "\"Whales\") (\"Jonah\" \"Spiders\") (\"Alan\" \"Ghosts\") (\"Alan\" \"Zombies\") (\"Glory\" \"Buffy\")))\n\n;; Hash phase\n(d",
"end": 182,
"score": 0.9995455741882324,
"start": 178,
"tag": "NAME",
"value": "Alan"
},
{
"context": "\") (\"Jonah\" \"Spiders\") (\"Alan\" \"Ghosts\") (\"Alan\" \"Zombies\") (\"Glory\" \"Buffy\")))\n\n;; Hash phase\n(defparamete",
"end": 192,
"score": 0.9923050999641418,
"start": 185,
"tag": "NAME",
"value": "Zombies"
},
{
"context": "\"Spiders\") (\"Alan\" \"Ghosts\") (\"Alan\" \"Zombies\") (\"Glory\" \"Buffy\")))\n\n;; Hash phase\n(defparameter *hash-ta",
"end": 202,
"score": 0.9994295239448547,
"start": 197,
"tag": "NAME",
"value": "Glory"
},
{
"context": "\") (\"Alan\" \"Ghosts\") (\"Alan\" \"Zombies\") (\"Glory\" \"Buffy\")))\n\n;; Hash phase\n(defparameter *hash-table* (ma",
"end": 210,
"score": 0.9809240102767944,
"start": 205,
"tag": "NAME",
"value": "Buffy"
}
] |
Task/Hash-join/Common-Lisp/hash-join.lisp
|
LaudateCorpus1/RosettaCodeData
| 1 |
(defparameter *table-A* '((27 "Jonah") (18 "Alan") (28 "Glory") (18 "Popeye") (28 "Alan")))
(defparameter *table-B* '(("Jonah" "Whales") ("Jonah" "Spiders") ("Alan" "Ghosts") ("Alan" "Zombies") ("Glory" "Buffy")))
;; Hash phase
(defparameter *hash-table* (make-hash-table :test #'equal))
(loop for (i r) in *table-A*
for value = (gethash r *hash-table* (list nil)) do
(setf (gethash r *hash-table*) value)
(push (list i r) (first value)))
;; Join phase
(loop for (i r) in *table-B* do
(let ((val (car (gethash i *hash-table*))))
(loop for (a b) in val do
(format t "{~a ~a} {~a ~a}~%" a b i r))))
|
70991
|
(defparameter *table-A* '((27 "<NAME>") (18 "<NAME>") (28 "<NAME>") (18 "<NAME>") (28 "<NAME>")))
(defparameter *table-B* '(("<NAME>" "<NAME>") ("<NAME>" "<NAME>") ("<NAME>" "<NAME>") ("<NAME>" "<NAME>") ("<NAME>" "<NAME>")))
;; Hash phase
(defparameter *hash-table* (make-hash-table :test #'equal))
(loop for (i r) in *table-A*
for value = (gethash r *hash-table* (list nil)) do
(setf (gethash r *hash-table*) value)
(push (list i r) (first value)))
;; Join phase
(loop for (i r) in *table-B* do
(let ((val (car (gethash i *hash-table*))))
(loop for (a b) in val do
(format t "{~a ~a} {~a ~a}~%" a b i r))))
| true |
(defparameter *table-A* '((27 "PI:NAME:<NAME>END_PI") (18 "PI:NAME:<NAME>END_PI") (28 "PI:NAME:<NAME>END_PI") (18 "PI:NAME:<NAME>END_PI") (28 "PI:NAME:<NAME>END_PI")))
(defparameter *table-B* '(("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") ("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI")))
;; Hash phase
(defparameter *hash-table* (make-hash-table :test #'equal))
(loop for (i r) in *table-A*
for value = (gethash r *hash-table* (list nil)) do
(setf (gethash r *hash-table*) value)
(push (list i r) (first value)))
;; Join phase
(loop for (i r) in *table-B* do
(let ((val (car (gethash i *hash-table*))))
(loop for (a b) in val do
(format t "{~a ~a} {~a ~a}~%" a b i r))))
|
[
{
"context": "\n \"\n> a\n\n>> b\n\"))\n\n\n;;;;;\n\n\n;; test example from [email protected]\n(addtest (test-snippets)\n header-paragraph-embed",
"end": 5805,
"score": 0.9999265670776367,
"start": 5783,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " and some following text.\"))\n\n;; test example from [email protected]\n(addtest (test-snippets)\n header-paragraph-embed",
"end": 6013,
"score": 0.9999294281005859,
"start": 5991,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "wing text.\n* Another item\"))\n\n;; test example from [email protected]\n(addtest (test-snippets)\n headers-and-lists\n (c",
"end": 6243,
"score": 0.9999269843101501,
"start": 6221,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
unit-tests/test-snippets.lisp
|
gwkkwg/cl-markdown
| 23 |
(in-package #:cl-markdown-test)
#|
Could use something like the form below to test the structure of the output
and thereby differentiate between parsing problems and output problems
(collect-elements
(chunks d)
:transform
(lambda (chunk)
(list (started-by chunk) (ended-by chunk)
(level chunk) (markup-class chunk)))
:filter (lambda (chunk) (not (ignore? chunk))))
|#
(deftestsuite test-escapes (test-snippets)
())
(addtest (test-escapes)
catch-markdown-ones
(check-output "\\\\ \\` \\* \\_ \\[ \\] \\( \\) \\# \\. \\! \\>"))
(addtest (test-escapes)
catch-markdown-ones-2
(ensure-cases (var)
'(("\\") ("`") ("*") ("_")
("[") ("]") ("(") (")")
("#") (".") ("!")
(">"))
(check-output (format nil "hi \\~a dude" var))))
(addtest (test-escapes :expected-failure "Problem in test suite... Markdown output is bad")
catch-markdown-ones-<
(check-output "\\<"))
(addtest (test-escapes)
code-and-escapes
(check-output "`\\*hi\\*`"))
(addtest (test-escapes)
star-and-escapes
(check-output "*\\*hi\\**"))
(deftestsuite test-lists-and-paragraphs (test-snippets)
())
(addtest (test-lists-and-paragraphs)
list-item-with-paragraph-1
(check-output "
* List item
with another paragraph
and some code
* Another item
this ends the list and starts a paragraph."))
(addtest (test-lists-and-paragraphs)
mingling-text-and-code
(check-output "
para
code
para
code
"))
#+(or)
(markdown
"
* List item
with another paragraph
and some code
* Another item
this ends the list and starts a paragraph.")
(addtest (test-lists-and-paragraphs)
list-item-with-paragraph-2
(check-output
"
* List item
and some code
"))
(addtest (test-lists-and-paragraphs)
list-item-with-paragraph-3
(check-output "
* Another item
paragraph "))
(addtest (test-lists-and-paragraphs)
list-item-with-paragraph-4
(check-output "
* Item 1
paragraph 1
* Item 2
paragraph 2
The end"))
(addtest (test-lists-and-paragraphs
:expected-failure "Markdown views treats the 1. as a *.")
list-item-with-paragraph-5
(check-output "
* Item 1
1. paragraph 1"))
(addtest (test-lists-and-paragraphs)
nested-lists-1
(check-output "
* Item 1
* Item A"))
;;?? Paragraph logic reversed?
(addtest (test-lists-and-paragraphs)
nested-lists-2
(check-output "
* Item 1
* Item A
* Item 2"))
(addtest (test-lists-and-paragraphs)
nested-lists-3
(check-output "
* a
* b
* c
* d
"))
(addtest (test-lists-and-paragraphs)
nested-lists-4
(check-output "
* a
* b
* c
* d
"))
(addtest (test-lists-and-paragraphs)
nested-lists-with-hard-returns
(check-output "
* Item 1
is spunky
* Item A
"))
(addtest (test-lists-and-paragraphs)
lists-and-code-1
(ensure-same
(nth-value 1
(cl-markdown:markdown
"
* The select form rewrites... If we add another line.
(select (?x)
(q ?x !property node))
"))
(nth-value 1
(cl-markdown:markdown
"
* The select form rewrites...
If we add another line.
(select (?x)
(q ?x !property node))
")) :test 'string=))
(addtest (test-lists-and-paragraphs
:expected-failure "paragraphs")
lists-and-blockquote
(check-output "paragraph 1
> ok
* item 1
q2. I thiought I had this one
ok"))
;;;;;
(deftestsuite test-break (test-snippets)
()
(:tests
(no-spaces (check-output "hello
there"))
(one-space (check-output "hello
there"))
(two-spaces (check-output "hello
there"))
(three-spaces (check-output "hello
there"))))
;; NOTE: markdown doesn't add the <br /> unless there is content _after_
;; line that ends with two spaces...
(addtest (test-break)
rest-of-line
(check-output "this is **strong**
ok?"))
(addtest (test-break)
rest-of-line-2
(check-output "this _is_ **strong**
ok?"))
(addtest (test-break :expected-failure "markdown doesn't add the <br /> unless there is content _after_ line that ends with two spaces...")
rest-of-line-3
(check-output "this _is_ **strong** "))
;;;;;
(deftestsuite entity-snippets (test-snippets)
())
(addtest (entity-snippets)
entity-check-1
(check-output "AT&T puts the amp in & >boss<"))
(addtest (entity-snippets)
entity-check-2
(check-output "The AT&T is AT & T, not AT&T or AT &T"))
(addtest (entity-snippets)
entity-check-3
(check-output "
Never forget AT
&T"))
;;;;
(deftestsuite numbered-lists (test-snippets)
())
(addtest (numbered-lists)
at-margin
(check-output "
1. hi
2. there
"))
(addtest (numbered-lists)
indented
(check-output "
1. hi
2. there
"))
(addtest (numbered-lists)
nospace
(check-output "
1.hi
2.there
"))
(addtest (numbered-lists
:expected-failure "Looks like a markdown bug")
nocontents
(check-output "
1.
2.
"))
;;;;
(deftestsuite test-horizontal-rules (test-snippets)
())
(addtest (test-horizontal-rules)
horizontal-rules-1
(check-output
"Here are some rules.
I hope you like 'em.
---
***
- - -
** ** **
_ _ _____ _ _
Did you like them?"))
(addtest (test-horizontal-rules)
horizontal-rules-2
(ensure (search
"this is code"
(nth-value 1 (markdown:markdown
"Here is an example:
this is code
- - - -
" :stream nil)) :test 'char=)))
;;;;
(deftestsuite test-nested-lists (test-snippets)
())
(addtest (test-nested-lists)
three-deep
(check-output
"
* a
* b
* c"))
(deftestsuite test-blockquotes (test-snippets)
())
(addtest (test-blockquotes)
nested-1
(check-output
"
> a
> b
"))
(addtest (test-blockquotes)
nested-2
(check-output
"
> a
> b
"))
(addtest (test-blockquotes)
nested-3
(check-output
"
> a
>> b
"))
;;;;;
;; test example from [email protected]
(addtest (test-snippets)
header-paragraph-embedded-link
(check-output
"## Common Lisp
* An item with a link [link](link.html) and some following text."))
;; test example from [email protected]
(addtest (test-snippets)
header-paragraph-embedded-link-in-list
(check-output
"## Common Lisp
* An item with a link [link](link.html) and some following text.
* Another item"))
;; test example from [email protected]
(addtest (test-snippets)
headers-and-lists
(check-output
"## Common Lisp
* An item with a link [link](link.html) and some following text.
## A second level heading
* Another item"))
(addtest (test-snippets)
header-in-list
(check-output
"* ok
# eh"))
(addtest (test-snippets)
reference-link-text-with-line-breaks
(check-output
"Hi this [is
so][is-so] cool.
[is-so]: http://a.c.c/"))
#+(or)
(markdown
"* ok
# eh")
(addtest (test-snippets)
list-item-with-hard-return
(check-output
"* A first list item
with a hard return
* A second list item
"))
(addtest (test-snippets)
list-items-and-paragraphs-1
(check-output
"* first line
second line"))
(addtest (test-snippets)
list-items-and-paragraphs-2
(check-output
"* first line
* second line"))
(addtest (test-snippets)
list-items-and-paragraphs-3
(check-output
"* first line
* second line"))
(addtest (test-snippets)
list-items-and-paragraphs-4
(check-output
"* first line
second line"))
(addtest (test-snippets)
inline-html-1
(check-output "`<div>foo</div>`"))
(addtest (test-snippets)
inline-html-2
(check-output "Simple block on one line:
<div>foo</div>
"))
|
86031
|
(in-package #:cl-markdown-test)
#|
Could use something like the form below to test the structure of the output
and thereby differentiate between parsing problems and output problems
(collect-elements
(chunks d)
:transform
(lambda (chunk)
(list (started-by chunk) (ended-by chunk)
(level chunk) (markup-class chunk)))
:filter (lambda (chunk) (not (ignore? chunk))))
|#
(deftestsuite test-escapes (test-snippets)
())
(addtest (test-escapes)
catch-markdown-ones
(check-output "\\\\ \\` \\* \\_ \\[ \\] \\( \\) \\# \\. \\! \\>"))
(addtest (test-escapes)
catch-markdown-ones-2
(ensure-cases (var)
'(("\\") ("`") ("*") ("_")
("[") ("]") ("(") (")")
("#") (".") ("!")
(">"))
(check-output (format nil "hi \\~a dude" var))))
(addtest (test-escapes :expected-failure "Problem in test suite... Markdown output is bad")
catch-markdown-ones-<
(check-output "\\<"))
(addtest (test-escapes)
code-and-escapes
(check-output "`\\*hi\\*`"))
(addtest (test-escapes)
star-and-escapes
(check-output "*\\*hi\\**"))
(deftestsuite test-lists-and-paragraphs (test-snippets)
())
(addtest (test-lists-and-paragraphs)
list-item-with-paragraph-1
(check-output "
* List item
with another paragraph
and some code
* Another item
this ends the list and starts a paragraph."))
(addtest (test-lists-and-paragraphs)
mingling-text-and-code
(check-output "
para
code
para
code
"))
#+(or)
(markdown
"
* List item
with another paragraph
and some code
* Another item
this ends the list and starts a paragraph.")
(addtest (test-lists-and-paragraphs)
list-item-with-paragraph-2
(check-output
"
* List item
and some code
"))
(addtest (test-lists-and-paragraphs)
list-item-with-paragraph-3
(check-output "
* Another item
paragraph "))
(addtest (test-lists-and-paragraphs)
list-item-with-paragraph-4
(check-output "
* Item 1
paragraph 1
* Item 2
paragraph 2
The end"))
(addtest (test-lists-and-paragraphs
:expected-failure "Markdown views treats the 1. as a *.")
list-item-with-paragraph-5
(check-output "
* Item 1
1. paragraph 1"))
(addtest (test-lists-and-paragraphs)
nested-lists-1
(check-output "
* Item 1
* Item A"))
;;?? Paragraph logic reversed?
(addtest (test-lists-and-paragraphs)
nested-lists-2
(check-output "
* Item 1
* Item A
* Item 2"))
(addtest (test-lists-and-paragraphs)
nested-lists-3
(check-output "
* a
* b
* c
* d
"))
(addtest (test-lists-and-paragraphs)
nested-lists-4
(check-output "
* a
* b
* c
* d
"))
(addtest (test-lists-and-paragraphs)
nested-lists-with-hard-returns
(check-output "
* Item 1
is spunky
* Item A
"))
(addtest (test-lists-and-paragraphs)
lists-and-code-1
(ensure-same
(nth-value 1
(cl-markdown:markdown
"
* The select form rewrites... If we add another line.
(select (?x)
(q ?x !property node))
"))
(nth-value 1
(cl-markdown:markdown
"
* The select form rewrites...
If we add another line.
(select (?x)
(q ?x !property node))
")) :test 'string=))
(addtest (test-lists-and-paragraphs
:expected-failure "paragraphs")
lists-and-blockquote
(check-output "paragraph 1
> ok
* item 1
q2. I thiought I had this one
ok"))
;;;;;
(deftestsuite test-break (test-snippets)
()
(:tests
(no-spaces (check-output "hello
there"))
(one-space (check-output "hello
there"))
(two-spaces (check-output "hello
there"))
(three-spaces (check-output "hello
there"))))
;; NOTE: markdown doesn't add the <br /> unless there is content _after_
;; line that ends with two spaces...
(addtest (test-break)
rest-of-line
(check-output "this is **strong**
ok?"))
(addtest (test-break)
rest-of-line-2
(check-output "this _is_ **strong**
ok?"))
(addtest (test-break :expected-failure "markdown doesn't add the <br /> unless there is content _after_ line that ends with two spaces...")
rest-of-line-3
(check-output "this _is_ **strong** "))
;;;;;
(deftestsuite entity-snippets (test-snippets)
())
(addtest (entity-snippets)
entity-check-1
(check-output "AT&T puts the amp in & >boss<"))
(addtest (entity-snippets)
entity-check-2
(check-output "The AT&T is AT & T, not AT&T or AT &T"))
(addtest (entity-snippets)
entity-check-3
(check-output "
Never forget AT
&T"))
;;;;
(deftestsuite numbered-lists (test-snippets)
())
(addtest (numbered-lists)
at-margin
(check-output "
1. hi
2. there
"))
(addtest (numbered-lists)
indented
(check-output "
1. hi
2. there
"))
(addtest (numbered-lists)
nospace
(check-output "
1.hi
2.there
"))
(addtest (numbered-lists
:expected-failure "Looks like a markdown bug")
nocontents
(check-output "
1.
2.
"))
;;;;
(deftestsuite test-horizontal-rules (test-snippets)
())
(addtest (test-horizontal-rules)
horizontal-rules-1
(check-output
"Here are some rules.
I hope you like 'em.
---
***
- - -
** ** **
_ _ _____ _ _
Did you like them?"))
(addtest (test-horizontal-rules)
horizontal-rules-2
(ensure (search
"this is code"
(nth-value 1 (markdown:markdown
"Here is an example:
this is code
- - - -
" :stream nil)) :test 'char=)))
;;;;
(deftestsuite test-nested-lists (test-snippets)
())
(addtest (test-nested-lists)
three-deep
(check-output
"
* a
* b
* c"))
(deftestsuite test-blockquotes (test-snippets)
())
(addtest (test-blockquotes)
nested-1
(check-output
"
> a
> b
"))
(addtest (test-blockquotes)
nested-2
(check-output
"
> a
> b
"))
(addtest (test-blockquotes)
nested-3
(check-output
"
> a
>> b
"))
;;;;;
;; test example from <EMAIL>
(addtest (test-snippets)
header-paragraph-embedded-link
(check-output
"## Common Lisp
* An item with a link [link](link.html) and some following text."))
;; test example from <EMAIL>
(addtest (test-snippets)
header-paragraph-embedded-link-in-list
(check-output
"## Common Lisp
* An item with a link [link](link.html) and some following text.
* Another item"))
;; test example from <EMAIL>
(addtest (test-snippets)
headers-and-lists
(check-output
"## Common Lisp
* An item with a link [link](link.html) and some following text.
## A second level heading
* Another item"))
(addtest (test-snippets)
header-in-list
(check-output
"* ok
# eh"))
(addtest (test-snippets)
reference-link-text-with-line-breaks
(check-output
"Hi this [is
so][is-so] cool.
[is-so]: http://a.c.c/"))
#+(or)
(markdown
"* ok
# eh")
(addtest (test-snippets)
list-item-with-hard-return
(check-output
"* A first list item
with a hard return
* A second list item
"))
(addtest (test-snippets)
list-items-and-paragraphs-1
(check-output
"* first line
second line"))
(addtest (test-snippets)
list-items-and-paragraphs-2
(check-output
"* first line
* second line"))
(addtest (test-snippets)
list-items-and-paragraphs-3
(check-output
"* first line
* second line"))
(addtest (test-snippets)
list-items-and-paragraphs-4
(check-output
"* first line
second line"))
(addtest (test-snippets)
inline-html-1
(check-output "`<div>foo</div>`"))
(addtest (test-snippets)
inline-html-2
(check-output "Simple block on one line:
<div>foo</div>
"))
| true |
(in-package #:cl-markdown-test)
#|
Could use something like the form below to test the structure of the output
and thereby differentiate between parsing problems and output problems
(collect-elements
(chunks d)
:transform
(lambda (chunk)
(list (started-by chunk) (ended-by chunk)
(level chunk) (markup-class chunk)))
:filter (lambda (chunk) (not (ignore? chunk))))
|#
(deftestsuite test-escapes (test-snippets)
())
(addtest (test-escapes)
catch-markdown-ones
(check-output "\\\\ \\` \\* \\_ \\[ \\] \\( \\) \\# \\. \\! \\>"))
(addtest (test-escapes)
catch-markdown-ones-2
(ensure-cases (var)
'(("\\") ("`") ("*") ("_")
("[") ("]") ("(") (")")
("#") (".") ("!")
(">"))
(check-output (format nil "hi \\~a dude" var))))
(addtest (test-escapes :expected-failure "Problem in test suite... Markdown output is bad")
catch-markdown-ones-<
(check-output "\\<"))
(addtest (test-escapes)
code-and-escapes
(check-output "`\\*hi\\*`"))
(addtest (test-escapes)
star-and-escapes
(check-output "*\\*hi\\**"))
(deftestsuite test-lists-and-paragraphs (test-snippets)
())
(addtest (test-lists-and-paragraphs)
list-item-with-paragraph-1
(check-output "
* List item
with another paragraph
and some code
* Another item
this ends the list and starts a paragraph."))
(addtest (test-lists-and-paragraphs)
mingling-text-and-code
(check-output "
para
code
para
code
"))
#+(or)
(markdown
"
* List item
with another paragraph
and some code
* Another item
this ends the list and starts a paragraph.")
(addtest (test-lists-and-paragraphs)
list-item-with-paragraph-2
(check-output
"
* List item
and some code
"))
(addtest (test-lists-and-paragraphs)
list-item-with-paragraph-3
(check-output "
* Another item
paragraph "))
(addtest (test-lists-and-paragraphs)
list-item-with-paragraph-4
(check-output "
* Item 1
paragraph 1
* Item 2
paragraph 2
The end"))
(addtest (test-lists-and-paragraphs
:expected-failure "Markdown views treats the 1. as a *.")
list-item-with-paragraph-5
(check-output "
* Item 1
1. paragraph 1"))
(addtest (test-lists-and-paragraphs)
nested-lists-1
(check-output "
* Item 1
* Item A"))
;;?? Paragraph logic reversed?
(addtest (test-lists-and-paragraphs)
nested-lists-2
(check-output "
* Item 1
* Item A
* Item 2"))
(addtest (test-lists-and-paragraphs)
nested-lists-3
(check-output "
* a
* b
* c
* d
"))
(addtest (test-lists-and-paragraphs)
nested-lists-4
(check-output "
* a
* b
* c
* d
"))
(addtest (test-lists-and-paragraphs)
nested-lists-with-hard-returns
(check-output "
* Item 1
is spunky
* Item A
"))
(addtest (test-lists-and-paragraphs)
lists-and-code-1
(ensure-same
(nth-value 1
(cl-markdown:markdown
"
* The select form rewrites... If we add another line.
(select (?x)
(q ?x !property node))
"))
(nth-value 1
(cl-markdown:markdown
"
* The select form rewrites...
If we add another line.
(select (?x)
(q ?x !property node))
")) :test 'string=))
(addtest (test-lists-and-paragraphs
:expected-failure "paragraphs")
lists-and-blockquote
(check-output "paragraph 1
> ok
* item 1
q2. I thiought I had this one
ok"))
;;;;;
(deftestsuite test-break (test-snippets)
()
(:tests
(no-spaces (check-output "hello
there"))
(one-space (check-output "hello
there"))
(two-spaces (check-output "hello
there"))
(three-spaces (check-output "hello
there"))))
;; NOTE: markdown doesn't add the <br /> unless there is content _after_
;; line that ends with two spaces...
(addtest (test-break)
rest-of-line
(check-output "this is **strong**
ok?"))
(addtest (test-break)
rest-of-line-2
(check-output "this _is_ **strong**
ok?"))
(addtest (test-break :expected-failure "markdown doesn't add the <br /> unless there is content _after_ line that ends with two spaces...")
rest-of-line-3
(check-output "this _is_ **strong** "))
;;;;;
(deftestsuite entity-snippets (test-snippets)
())
(addtest (entity-snippets)
entity-check-1
(check-output "AT&T puts the amp in & >boss<"))
(addtest (entity-snippets)
entity-check-2
(check-output "The AT&T is AT & T, not AT&T or AT &T"))
(addtest (entity-snippets)
entity-check-3
(check-output "
Never forget AT
&T"))
;;;;
(deftestsuite numbered-lists (test-snippets)
())
(addtest (numbered-lists)
at-margin
(check-output "
1. hi
2. there
"))
(addtest (numbered-lists)
indented
(check-output "
1. hi
2. there
"))
(addtest (numbered-lists)
nospace
(check-output "
1.hi
2.there
"))
(addtest (numbered-lists
:expected-failure "Looks like a markdown bug")
nocontents
(check-output "
1.
2.
"))
;;;;
(deftestsuite test-horizontal-rules (test-snippets)
())
(addtest (test-horizontal-rules)
horizontal-rules-1
(check-output
"Here are some rules.
I hope you like 'em.
---
***
- - -
** ** **
_ _ _____ _ _
Did you like them?"))
(addtest (test-horizontal-rules)
horizontal-rules-2
(ensure (search
"this is code"
(nth-value 1 (markdown:markdown
"Here is an example:
this is code
- - - -
" :stream nil)) :test 'char=)))
;;;;
(deftestsuite test-nested-lists (test-snippets)
())
(addtest (test-nested-lists)
three-deep
(check-output
"
* a
* b
* c"))
(deftestsuite test-blockquotes (test-snippets)
())
(addtest (test-blockquotes)
nested-1
(check-output
"
> a
> b
"))
(addtest (test-blockquotes)
nested-2
(check-output
"
> a
> b
"))
(addtest (test-blockquotes)
nested-3
(check-output
"
> a
>> b
"))
;;;;;
;; test example from PI:EMAIL:<EMAIL>END_PI
(addtest (test-snippets)
header-paragraph-embedded-link
(check-output
"## Common Lisp
* An item with a link [link](link.html) and some following text."))
;; test example from PI:EMAIL:<EMAIL>END_PI
(addtest (test-snippets)
header-paragraph-embedded-link-in-list
(check-output
"## Common Lisp
* An item with a link [link](link.html) and some following text.
* Another item"))
;; test example from PI:EMAIL:<EMAIL>END_PI
(addtest (test-snippets)
headers-and-lists
(check-output
"## Common Lisp
* An item with a link [link](link.html) and some following text.
## A second level heading
* Another item"))
(addtest (test-snippets)
header-in-list
(check-output
"* ok
# eh"))
(addtest (test-snippets)
reference-link-text-with-line-breaks
(check-output
"Hi this [is
so][is-so] cool.
[is-so]: http://a.c.c/"))
#+(or)
(markdown
"* ok
# eh")
(addtest (test-snippets)
list-item-with-hard-return
(check-output
"* A first list item
with a hard return
* A second list item
"))
(addtest (test-snippets)
list-items-and-paragraphs-1
(check-output
"* first line
second line"))
(addtest (test-snippets)
list-items-and-paragraphs-2
(check-output
"* first line
* second line"))
(addtest (test-snippets)
list-items-and-paragraphs-3
(check-output
"* first line
* second line"))
(addtest (test-snippets)
list-items-and-paragraphs-4
(check-output
"* first line
second line"))
(addtest (test-snippets)
inline-html-1
(check-output "`<div>foo</div>`"))
(addtest (test-snippets)
inline-html-2
(check-output "Simple block on one line:
<div>foo</div>
"))
|
[
{
"context": "er/inspector of Movitz images.\n;;;; Author: Frode Vatvedt Fjeld <[email protected]>\n;;;; Created at: Thu Jun 14 1",
"end": 402,
"score": 0.9998744130134583,
"start": 383,
"tag": "NAME",
"value": "Frode Vatvedt Fjeld"
},
{
"context": " images.\n;;;; Author: Frode Vatvedt Fjeld <[email protected]>\n;;;; Created at: Thu Jun 14 15:14:35 2001\n;;;",
"end": 418,
"score": 0.9999197125434875,
"start": 404,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
browser.lisp
|
russell/movitz
| 4 |
;;;;------------------------------------------------------------------
;;;;
;;;; Copyright (C) 2001-2002, 2004,
;;;; Department of Computer Science, University of Tromso, Norway.
;;;;
;;;; For distribution policy, see the accompanying file COPYING.
;;;;
;;;; Filename: browser.lisp
;;;; Description: A CLIM browser/inspector of Movitz images.
;;;; Author: Frode Vatvedt Fjeld <[email protected]>
;;;; Created at: Thu Jun 14 15:14:35 2001
;;;;
;;;; $Id$
;;;;
;;;;------------------------------------------------------------------
(eval-when (:compile-toplevel :load-toplevel)
#+allegro (require :climxm))
(defpackage movitz-browser
(:use clim clim-lisp movitz binary-types)
(:export browse-file
browse-pid
browse-word
browser))
(in-package movitz-browser)
(define-command-table browser-file-commands
:menu (("Print" :command print-graph)
("Print preview" :command print-graph-preview)
("" :divider :line)
("Quit" :command quit)))
(define-command-table browser-tree-commands
:menu (("Set NIL as root" :command (read-and-set-root nil))
("Enter word" :command set-root-word)))
(define-command quit ()
(frame-exit *application-frame*))
(define-command print-graph ()
(multiple-value-call #'warn
"print!: ~S :"
(select-file *application-frame*)))
(define-command print-graph-preview ()
(let ((temp-name (sys:make-temp-file-name "browser-graph-preview")))
(with-open-file (temp-file temp-name :direction :output)
(with-output-to-postscript-stream (ps-stream temp-file)
(display-graph *application-frame* ps-stream)))
(excl:run-shell-command (format nil "gv -resize ~S; rm ~S" temp-name temp-name) :wait nil)))
(define-application-frame browser ()
((root-tuple
:initarg :root-tuple
:accessor browser-root-tuple))
(:menu-bar t)
(:pointer-documentation t)
(:command-table (browser
:menu (("File" :menu browser-file-commands)
("Tree" :menu browser-tree-commands))
:inherit-from (browser-file-commands browser-tree-commands)))
(:panes
(graph
:application
;; :label "Object Graph"
;; :scroll-bars nil
:initial-cursor-visibility nil
:display-function 'display-graph))
(:layouts
(default (horizontally ()
graph))))
(defstruct graph-tuple
tree
object
parent
slot-name)
(define-presentation-type graph-tuple () :inherit-from t)
(defun display-graph (browser *standard-output*)
(format-graph-from-root (browser-root-tuple browser)
;; printer
#'(lambda (tuple *standard-output*)
(with-output-as-presentation (t tuple 'graph-tuple)
(with-slots (object slot-name) tuple
(formatting-table ()
(formatting-column ()
(when slot-name
(formatting-cell (t :align-x :center)
(display-child-spec slot-name)))
(formatting-cell (t :align-x :center)
(present object)))))))
;; child-producer
#'(lambda (tuple)
(with-slots (tree object parent slot-name) tuple
;; (warn "child-of: ~S" (type-of object))
(mapcar #'(lambda (child-slot-name)
(make-graph-tuple
:tree tree
:object (browser-child object child-slot-name)
:parent object
:slot-name child-slot-name))
(browser-open-slots tree object parent slot-name))))
:graph-type :digraph
:within-generation-separation 2
:maximize-generations nil
:generation-separation 60
:store-objects t
:center-nodes nil
:orientation :horizontal ;; :vertical
;; :duplicate-key #'cdr
;; :duplicate-test #'equalp
:merge-duplicates t
:cutoff-depth 50))
(defun display-child-spec (spec)
(case (first spec)
(slot-value
(with-drawing-options (t :ink +green+ :size :small)
(princ (string-downcase (format nil "~A" (second spec))))))
(otherwise
(princ spec))))
(defmethod movitz-object-browser-properties ((object t)) nil)
(defmethod browser-child ((object movitz-heap-object) child-spec)
(ecase (car child-spec)
(slot-value
(slot-value object (second child-spec)))))
(defclass browser-array ()
((type
:initarg :type
:reader browser-array-type)
(elements
:initarg :elements
:reader browser-array-elements)))
(define-presentation-type browser-array ())
(defmethod browser-child ((object movitz-vector) child-spec)
(destructuring-bind (operator &rest operands)
child-spec
(case operator
(aref
(nth (first operands)
(movitz-vector-symbolic-data object)))
(array
(make-instance 'browser-array
:type (movitz-vector-element-type object)
:elements (movitz-vector-symbolic-data object)))
(t (call-next-method object child-spec)))))
(defmethod browser-child ((object movitz-struct) child-spec)
(destructuring-bind (operator &rest operands)
child-spec
(case operator
(struct-ref
(nth (first operands)
(movitz-struct-slot-values object)))
(t (call-next-method)))))
(defun browser-slot-value (object slot-name)
(case (binary-slot-type (type-of object) slot-name)
(word (movitz-word (binary-slot-value object slot-name)))
(t (if (slot-boundp object slot-name)
(slot-value object slot-name)
(make-symbol "[UNBOUND]")))))
(defun browser-all-slots (object)
(mapcar #'(lambda (slot-name) (list 'slot-value slot-name))
(binary-record-slot-names (type-of object))))
(defmethod browser-default-open-slots ((object movitz-heap-object))
(reverse (set-difference (browser-all-slots object)
'((slot-value movitz::type))
:key #'second)))
(defmethod browser-default-open-slots ((object movitz-vector))
(assert (= (length (movitz-vector-symbolic-data object))
(movitz-vector-num-elements object)))
(append (remove 'movitz::data (call-next-method object) :key #'second)
(case (movitz-vector-element-type object)
(:any-t
;; merge EQ elements..
(loop for (value next-value) on (movitz-vector-symbolic-data object)
as i upfrom 0
with start-index = 0
unless (and next-value
(= (movitz-intern value)
(movitz-intern next-value)))
collect `(aref ,start-index ,@(unless (= i start-index) (list i)))
and do (setf start-index (1+ i))))
(t (list `(array ,(movitz-vector-num-elements object)))))))
(defmethod browser-default-open-slots ((object movitz-struct))
(append (remove 'movitz::slot0 (call-next-method object) :key #'second)
(loop for x from 0 below (movitz-struct-length object)
collect `(struct-ref ,x))))
(defun browse-image (*image* &key (root (make-graph-tuple
:object (movitz-word (movitz-read-and-intern nil 'word))
:tree (gensym))))
(let ((*endian* :little-endian)
(*print-radix* t)
(*print-base* 16))
(run-frame-top-level
(make-application-frame 'browser
:width 700
:height 700
:root-tuple root))))
(defun browse-word (word)
(browse-image movitz::*image*
:root (make-graph-tuple :object (movitz-word word)
:tree (gensym))))
(defun browser ()
(multiprocessing:process-run-function "browser" #'browse-image *i*))
(defun browse-pid (pid)
(flet ((do-browse-pid (pid)
(with-procfs-image (pid)
(browse-image *image*))))
(multiprocessing:process-run-function
`(:name "browser")
#'do-browse-pid
pid)))
(defun browse-file (&key (threadp t) (path *default-image-file*)
(offset (- 512 #x100000)) (direction :input))
(flet ((do-browse-path (path offset direction)
(with-binary-file (stream path :direction direction)
(browse-image (make-instance 'stream-image
:stream stream
:offset offset)))))
(if threadp
(multiprocessing:process-run-function "browser" #'do-browse-path
path offset direction)
(do-browse-path path offset direction))))
(define-presentation-type movitz-object ())
(define-presentation-method present (object (type movitz-object)
*standard-output*
(view textual-view) &key)
(formatting-table ()
(formatting-column ()
(formatting-cell (t :align-x :center)
(with-drawing-options (t :size :small)
(browser-print-safely object)))
(formatting-cell (t :align-x :center)
(format t "#x~8,'0X" (movitz-intern object))))))
(define-presentation-method present
(object (type movitz-object) *standard-output* (view textual-menu-view) &key)
(format t "#x~8,'0X" (movitz-intern object)))
(define-presentation-method present
(object (type graph-tuple) *standard-output* (view textual-menu-view) &key)
(format t "#x~8,'0X" (movitz-intern (graph-tuple-object object))))
(define-presentation-method present (object (type movitz-character)
*standard-output*
(view textual-view) &key)
(write (movitz-char object)))
(define-presentation-method present
(object (type movitz-symbol) *standard-output* (view textual-view) &key)
(format t "#x~8,'0X: |~A|" (movitz-intern object) (browser-print-safely object)))
(define-presentation-method present
(object (type movitz-vector) *standard-output* (view textual-view) &key)
(if (not (eq :character (movitz-vector-element-type object)))
(call-next-method)
(format t "#x~8,'0X: \"~A\"" (movitz-intern object) (browser-print-safely object))))
(defun browser-print-safely (object)
(handler-case
(movitz::movitz-print object)
(error ()
(write-string (string-downcase (symbol-name (type-of object)))))))
(define-presentation-method present (object (type browser-array)
*standard-output*
(view textual-view) &key)
(let ((rows-per-col (typecase (length (browser-array-elements object))
((integer 0 15) 1)
((integer 16 47) 2)
((integer 48 127) 4)
(t 8))))
(formatting-table ()
(loop for row on (browser-array-elements object) by #'(lambda (x) (nthcdr rows-per-col x))
as i upfrom 0 by rows-per-col
do (formatting-row ()
(formatting-cell (t :align-x :right)
(format t "~D:" i))
(loop for r from 1 to rows-per-col
as element in row
do (formatting-cell ()
(case (browser-array-type object)
(:u32 (format t "#x~8,'0X" element))
((:u8 :code) (format t "#x~2,'0X" element))
(t #+ignore(warn "unk: ~S" (browser-array-type object))
(write element))))))))))
(define-browser-command read-and-set-root ((object 't))
(set-root (movitz-word (movitz-read-and-intern object 'word))))
(define-browser-command toggle ((tuple 'graph-tuple))
(with-slots (tree object parent slot-name) tuple
(cond
((null (browser-open-slots tree object parent slot-name))
(setf (browser-open-slots tree object parent slot-name)
(browser-default-open-slots object)))
;; (warn "now open: ~S" (browser-open-slots tree object parent slot-name)))
(t
(setf (browser-open-slots tree object parent slot-name)
nil)))))
(define-presentation-to-command-translator toggle
(graph-tuple
toggle
browser
:gesture :select
:tester ((object)
(typep (graph-tuple-object object) 'movitz-heap-object)))
(object)
(list object))
(define-browser-command set-root ((object 'movitz-object))
(setf (browser-root-tuple *application-frame*)
(make-graph-tuple :tree (gensym) :object object)))
(define-presentation-to-command-translator set-root-tuple
(graph-tuple set-root browser)
(object)
(list (graph-tuple-object object)))
(define-browser-command new-browser ((object 'movitz-object))
(browse-image *image* :root (make-graph-tuple :tree (gensym)
:object object)))
(define-presentation-to-command-translator new-browser-tuple
(graph-tuple new-browser browser)
(object)
(list (graph-tuple-object object)))
(defun (setf browser-open-slots) (value tree object parent slot-name)
(let ((old-slot (assoc-if #'(lambda (x) (and (eq (car x) parent) (eq (cdr x) slot-name)))
(getf (movitz-object-browser-properties object) tree))))
(if old-slot
(setf (cdr old-slot) value)
(setf (getf (movitz-object-browser-properties object) tree)
(acons (cons parent slot-name)
value
(getf (movitz-object-browser-properties object) tree)))))
value)
(defun browser-open-slots (tree object parent slot-name)
(cdr (assoc-if #'(lambda (x) (and (eq (car x) parent) (eq (cdr x) slot-name)))
(getf (movitz-object-browser-properties object) tree))))
(define-browser-command set-root-word ()
(let ((word (accepting-values (t :own-window t)
(accept '((integer 0 #xffffffff) :base 16)))))
(when word
(set-root (movitz-word word)))))
|
18690
|
;;;;------------------------------------------------------------------
;;;;
;;;; Copyright (C) 2001-2002, 2004,
;;;; Department of Computer Science, University of Tromso, Norway.
;;;;
;;;; For distribution policy, see the accompanying file COPYING.
;;;;
;;;; Filename: browser.lisp
;;;; Description: A CLIM browser/inspector of Movitz images.
;;;; Author: <NAME> <<EMAIL>>
;;;; Created at: Thu Jun 14 15:14:35 2001
;;;;
;;;; $Id$
;;;;
;;;;------------------------------------------------------------------
(eval-when (:compile-toplevel :load-toplevel)
#+allegro (require :climxm))
(defpackage movitz-browser
(:use clim clim-lisp movitz binary-types)
(:export browse-file
browse-pid
browse-word
browser))
(in-package movitz-browser)
(define-command-table browser-file-commands
:menu (("Print" :command print-graph)
("Print preview" :command print-graph-preview)
("" :divider :line)
("Quit" :command quit)))
(define-command-table browser-tree-commands
:menu (("Set NIL as root" :command (read-and-set-root nil))
("Enter word" :command set-root-word)))
(define-command quit ()
(frame-exit *application-frame*))
(define-command print-graph ()
(multiple-value-call #'warn
"print!: ~S :"
(select-file *application-frame*)))
(define-command print-graph-preview ()
(let ((temp-name (sys:make-temp-file-name "browser-graph-preview")))
(with-open-file (temp-file temp-name :direction :output)
(with-output-to-postscript-stream (ps-stream temp-file)
(display-graph *application-frame* ps-stream)))
(excl:run-shell-command (format nil "gv -resize ~S; rm ~S" temp-name temp-name) :wait nil)))
(define-application-frame browser ()
((root-tuple
:initarg :root-tuple
:accessor browser-root-tuple))
(:menu-bar t)
(:pointer-documentation t)
(:command-table (browser
:menu (("File" :menu browser-file-commands)
("Tree" :menu browser-tree-commands))
:inherit-from (browser-file-commands browser-tree-commands)))
(:panes
(graph
:application
;; :label "Object Graph"
;; :scroll-bars nil
:initial-cursor-visibility nil
:display-function 'display-graph))
(:layouts
(default (horizontally ()
graph))))
(defstruct graph-tuple
tree
object
parent
slot-name)
(define-presentation-type graph-tuple () :inherit-from t)
(defun display-graph (browser *standard-output*)
(format-graph-from-root (browser-root-tuple browser)
;; printer
#'(lambda (tuple *standard-output*)
(with-output-as-presentation (t tuple 'graph-tuple)
(with-slots (object slot-name) tuple
(formatting-table ()
(formatting-column ()
(when slot-name
(formatting-cell (t :align-x :center)
(display-child-spec slot-name)))
(formatting-cell (t :align-x :center)
(present object)))))))
;; child-producer
#'(lambda (tuple)
(with-slots (tree object parent slot-name) tuple
;; (warn "child-of: ~S" (type-of object))
(mapcar #'(lambda (child-slot-name)
(make-graph-tuple
:tree tree
:object (browser-child object child-slot-name)
:parent object
:slot-name child-slot-name))
(browser-open-slots tree object parent slot-name))))
:graph-type :digraph
:within-generation-separation 2
:maximize-generations nil
:generation-separation 60
:store-objects t
:center-nodes nil
:orientation :horizontal ;; :vertical
;; :duplicate-key #'cdr
;; :duplicate-test #'equalp
:merge-duplicates t
:cutoff-depth 50))
(defun display-child-spec (spec)
(case (first spec)
(slot-value
(with-drawing-options (t :ink +green+ :size :small)
(princ (string-downcase (format nil "~A" (second spec))))))
(otherwise
(princ spec))))
(defmethod movitz-object-browser-properties ((object t)) nil)
(defmethod browser-child ((object movitz-heap-object) child-spec)
(ecase (car child-spec)
(slot-value
(slot-value object (second child-spec)))))
(defclass browser-array ()
((type
:initarg :type
:reader browser-array-type)
(elements
:initarg :elements
:reader browser-array-elements)))
(define-presentation-type browser-array ())
(defmethod browser-child ((object movitz-vector) child-spec)
(destructuring-bind (operator &rest operands)
child-spec
(case operator
(aref
(nth (first operands)
(movitz-vector-symbolic-data object)))
(array
(make-instance 'browser-array
:type (movitz-vector-element-type object)
:elements (movitz-vector-symbolic-data object)))
(t (call-next-method object child-spec)))))
(defmethod browser-child ((object movitz-struct) child-spec)
(destructuring-bind (operator &rest operands)
child-spec
(case operator
(struct-ref
(nth (first operands)
(movitz-struct-slot-values object)))
(t (call-next-method)))))
(defun browser-slot-value (object slot-name)
(case (binary-slot-type (type-of object) slot-name)
(word (movitz-word (binary-slot-value object slot-name)))
(t (if (slot-boundp object slot-name)
(slot-value object slot-name)
(make-symbol "[UNBOUND]")))))
(defun browser-all-slots (object)
(mapcar #'(lambda (slot-name) (list 'slot-value slot-name))
(binary-record-slot-names (type-of object))))
(defmethod browser-default-open-slots ((object movitz-heap-object))
(reverse (set-difference (browser-all-slots object)
'((slot-value movitz::type))
:key #'second)))
(defmethod browser-default-open-slots ((object movitz-vector))
(assert (= (length (movitz-vector-symbolic-data object))
(movitz-vector-num-elements object)))
(append (remove 'movitz::data (call-next-method object) :key #'second)
(case (movitz-vector-element-type object)
(:any-t
;; merge EQ elements..
(loop for (value next-value) on (movitz-vector-symbolic-data object)
as i upfrom 0
with start-index = 0
unless (and next-value
(= (movitz-intern value)
(movitz-intern next-value)))
collect `(aref ,start-index ,@(unless (= i start-index) (list i)))
and do (setf start-index (1+ i))))
(t (list `(array ,(movitz-vector-num-elements object)))))))
(defmethod browser-default-open-slots ((object movitz-struct))
(append (remove 'movitz::slot0 (call-next-method object) :key #'second)
(loop for x from 0 below (movitz-struct-length object)
collect `(struct-ref ,x))))
(defun browse-image (*image* &key (root (make-graph-tuple
:object (movitz-word (movitz-read-and-intern nil 'word))
:tree (gensym))))
(let ((*endian* :little-endian)
(*print-radix* t)
(*print-base* 16))
(run-frame-top-level
(make-application-frame 'browser
:width 700
:height 700
:root-tuple root))))
(defun browse-word (word)
(browse-image movitz::*image*
:root (make-graph-tuple :object (movitz-word word)
:tree (gensym))))
(defun browser ()
(multiprocessing:process-run-function "browser" #'browse-image *i*))
(defun browse-pid (pid)
(flet ((do-browse-pid (pid)
(with-procfs-image (pid)
(browse-image *image*))))
(multiprocessing:process-run-function
`(:name "browser")
#'do-browse-pid
pid)))
(defun browse-file (&key (threadp t) (path *default-image-file*)
(offset (- 512 #x100000)) (direction :input))
(flet ((do-browse-path (path offset direction)
(with-binary-file (stream path :direction direction)
(browse-image (make-instance 'stream-image
:stream stream
:offset offset)))))
(if threadp
(multiprocessing:process-run-function "browser" #'do-browse-path
path offset direction)
(do-browse-path path offset direction))))
(define-presentation-type movitz-object ())
(define-presentation-method present (object (type movitz-object)
*standard-output*
(view textual-view) &key)
(formatting-table ()
(formatting-column ()
(formatting-cell (t :align-x :center)
(with-drawing-options (t :size :small)
(browser-print-safely object)))
(formatting-cell (t :align-x :center)
(format t "#x~8,'0X" (movitz-intern object))))))
(define-presentation-method present
(object (type movitz-object) *standard-output* (view textual-menu-view) &key)
(format t "#x~8,'0X" (movitz-intern object)))
(define-presentation-method present
(object (type graph-tuple) *standard-output* (view textual-menu-view) &key)
(format t "#x~8,'0X" (movitz-intern (graph-tuple-object object))))
(define-presentation-method present (object (type movitz-character)
*standard-output*
(view textual-view) &key)
(write (movitz-char object)))
(define-presentation-method present
(object (type movitz-symbol) *standard-output* (view textual-view) &key)
(format t "#x~8,'0X: |~A|" (movitz-intern object) (browser-print-safely object)))
(define-presentation-method present
(object (type movitz-vector) *standard-output* (view textual-view) &key)
(if (not (eq :character (movitz-vector-element-type object)))
(call-next-method)
(format t "#x~8,'0X: \"~A\"" (movitz-intern object) (browser-print-safely object))))
(defun browser-print-safely (object)
(handler-case
(movitz::movitz-print object)
(error ()
(write-string (string-downcase (symbol-name (type-of object)))))))
(define-presentation-method present (object (type browser-array)
*standard-output*
(view textual-view) &key)
(let ((rows-per-col (typecase (length (browser-array-elements object))
((integer 0 15) 1)
((integer 16 47) 2)
((integer 48 127) 4)
(t 8))))
(formatting-table ()
(loop for row on (browser-array-elements object) by #'(lambda (x) (nthcdr rows-per-col x))
as i upfrom 0 by rows-per-col
do (formatting-row ()
(formatting-cell (t :align-x :right)
(format t "~D:" i))
(loop for r from 1 to rows-per-col
as element in row
do (formatting-cell ()
(case (browser-array-type object)
(:u32 (format t "#x~8,'0X" element))
((:u8 :code) (format t "#x~2,'0X" element))
(t #+ignore(warn "unk: ~S" (browser-array-type object))
(write element))))))))))
(define-browser-command read-and-set-root ((object 't))
(set-root (movitz-word (movitz-read-and-intern object 'word))))
(define-browser-command toggle ((tuple 'graph-tuple))
(with-slots (tree object parent slot-name) tuple
(cond
((null (browser-open-slots tree object parent slot-name))
(setf (browser-open-slots tree object parent slot-name)
(browser-default-open-slots object)))
;; (warn "now open: ~S" (browser-open-slots tree object parent slot-name)))
(t
(setf (browser-open-slots tree object parent slot-name)
nil)))))
(define-presentation-to-command-translator toggle
(graph-tuple
toggle
browser
:gesture :select
:tester ((object)
(typep (graph-tuple-object object) 'movitz-heap-object)))
(object)
(list object))
(define-browser-command set-root ((object 'movitz-object))
(setf (browser-root-tuple *application-frame*)
(make-graph-tuple :tree (gensym) :object object)))
(define-presentation-to-command-translator set-root-tuple
(graph-tuple set-root browser)
(object)
(list (graph-tuple-object object)))
(define-browser-command new-browser ((object 'movitz-object))
(browse-image *image* :root (make-graph-tuple :tree (gensym)
:object object)))
(define-presentation-to-command-translator new-browser-tuple
(graph-tuple new-browser browser)
(object)
(list (graph-tuple-object object)))
(defun (setf browser-open-slots) (value tree object parent slot-name)
(let ((old-slot (assoc-if #'(lambda (x) (and (eq (car x) parent) (eq (cdr x) slot-name)))
(getf (movitz-object-browser-properties object) tree))))
(if old-slot
(setf (cdr old-slot) value)
(setf (getf (movitz-object-browser-properties object) tree)
(acons (cons parent slot-name)
value
(getf (movitz-object-browser-properties object) tree)))))
value)
(defun browser-open-slots (tree object parent slot-name)
(cdr (assoc-if #'(lambda (x) (and (eq (car x) parent) (eq (cdr x) slot-name)))
(getf (movitz-object-browser-properties object) tree))))
(define-browser-command set-root-word ()
(let ((word (accepting-values (t :own-window t)
(accept '((integer 0 #xffffffff) :base 16)))))
(when word
(set-root (movitz-word word)))))
| true |
;;;;------------------------------------------------------------------
;;;;
;;;; Copyright (C) 2001-2002, 2004,
;;;; Department of Computer Science, University of Tromso, Norway.
;;;;
;;;; For distribution policy, see the accompanying file COPYING.
;;;;
;;;; Filename: browser.lisp
;;;; Description: A CLIM browser/inspector of Movitz images.
;;;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;;; Created at: Thu Jun 14 15:14:35 2001
;;;;
;;;; $Id$
;;;;
;;;;------------------------------------------------------------------
(eval-when (:compile-toplevel :load-toplevel)
#+allegro (require :climxm))
(defpackage movitz-browser
(:use clim clim-lisp movitz binary-types)
(:export browse-file
browse-pid
browse-word
browser))
(in-package movitz-browser)
(define-command-table browser-file-commands
:menu (("Print" :command print-graph)
("Print preview" :command print-graph-preview)
("" :divider :line)
("Quit" :command quit)))
(define-command-table browser-tree-commands
:menu (("Set NIL as root" :command (read-and-set-root nil))
("Enter word" :command set-root-word)))
(define-command quit ()
(frame-exit *application-frame*))
(define-command print-graph ()
(multiple-value-call #'warn
"print!: ~S :"
(select-file *application-frame*)))
(define-command print-graph-preview ()
(let ((temp-name (sys:make-temp-file-name "browser-graph-preview")))
(with-open-file (temp-file temp-name :direction :output)
(with-output-to-postscript-stream (ps-stream temp-file)
(display-graph *application-frame* ps-stream)))
(excl:run-shell-command (format nil "gv -resize ~S; rm ~S" temp-name temp-name) :wait nil)))
(define-application-frame browser ()
((root-tuple
:initarg :root-tuple
:accessor browser-root-tuple))
(:menu-bar t)
(:pointer-documentation t)
(:command-table (browser
:menu (("File" :menu browser-file-commands)
("Tree" :menu browser-tree-commands))
:inherit-from (browser-file-commands browser-tree-commands)))
(:panes
(graph
:application
;; :label "Object Graph"
;; :scroll-bars nil
:initial-cursor-visibility nil
:display-function 'display-graph))
(:layouts
(default (horizontally ()
graph))))
(defstruct graph-tuple
tree
object
parent
slot-name)
(define-presentation-type graph-tuple () :inherit-from t)
(defun display-graph (browser *standard-output*)
(format-graph-from-root (browser-root-tuple browser)
;; printer
#'(lambda (tuple *standard-output*)
(with-output-as-presentation (t tuple 'graph-tuple)
(with-slots (object slot-name) tuple
(formatting-table ()
(formatting-column ()
(when slot-name
(formatting-cell (t :align-x :center)
(display-child-spec slot-name)))
(formatting-cell (t :align-x :center)
(present object)))))))
;; child-producer
#'(lambda (tuple)
(with-slots (tree object parent slot-name) tuple
;; (warn "child-of: ~S" (type-of object))
(mapcar #'(lambda (child-slot-name)
(make-graph-tuple
:tree tree
:object (browser-child object child-slot-name)
:parent object
:slot-name child-slot-name))
(browser-open-slots tree object parent slot-name))))
:graph-type :digraph
:within-generation-separation 2
:maximize-generations nil
:generation-separation 60
:store-objects t
:center-nodes nil
:orientation :horizontal ;; :vertical
;; :duplicate-key #'cdr
;; :duplicate-test #'equalp
:merge-duplicates t
:cutoff-depth 50))
(defun display-child-spec (spec)
(case (first spec)
(slot-value
(with-drawing-options (t :ink +green+ :size :small)
(princ (string-downcase (format nil "~A" (second spec))))))
(otherwise
(princ spec))))
(defmethod movitz-object-browser-properties ((object t)) nil)
(defmethod browser-child ((object movitz-heap-object) child-spec)
(ecase (car child-spec)
(slot-value
(slot-value object (second child-spec)))))
(defclass browser-array ()
((type
:initarg :type
:reader browser-array-type)
(elements
:initarg :elements
:reader browser-array-elements)))
(define-presentation-type browser-array ())
(defmethod browser-child ((object movitz-vector) child-spec)
(destructuring-bind (operator &rest operands)
child-spec
(case operator
(aref
(nth (first operands)
(movitz-vector-symbolic-data object)))
(array
(make-instance 'browser-array
:type (movitz-vector-element-type object)
:elements (movitz-vector-symbolic-data object)))
(t (call-next-method object child-spec)))))
(defmethod browser-child ((object movitz-struct) child-spec)
(destructuring-bind (operator &rest operands)
child-spec
(case operator
(struct-ref
(nth (first operands)
(movitz-struct-slot-values object)))
(t (call-next-method)))))
(defun browser-slot-value (object slot-name)
(case (binary-slot-type (type-of object) slot-name)
(word (movitz-word (binary-slot-value object slot-name)))
(t (if (slot-boundp object slot-name)
(slot-value object slot-name)
(make-symbol "[UNBOUND]")))))
(defun browser-all-slots (object)
(mapcar #'(lambda (slot-name) (list 'slot-value slot-name))
(binary-record-slot-names (type-of object))))
(defmethod browser-default-open-slots ((object movitz-heap-object))
(reverse (set-difference (browser-all-slots object)
'((slot-value movitz::type))
:key #'second)))
(defmethod browser-default-open-slots ((object movitz-vector))
(assert (= (length (movitz-vector-symbolic-data object))
(movitz-vector-num-elements object)))
(append (remove 'movitz::data (call-next-method object) :key #'second)
(case (movitz-vector-element-type object)
(:any-t
;; merge EQ elements..
(loop for (value next-value) on (movitz-vector-symbolic-data object)
as i upfrom 0
with start-index = 0
unless (and next-value
(= (movitz-intern value)
(movitz-intern next-value)))
collect `(aref ,start-index ,@(unless (= i start-index) (list i)))
and do (setf start-index (1+ i))))
(t (list `(array ,(movitz-vector-num-elements object)))))))
(defmethod browser-default-open-slots ((object movitz-struct))
(append (remove 'movitz::slot0 (call-next-method object) :key #'second)
(loop for x from 0 below (movitz-struct-length object)
collect `(struct-ref ,x))))
(defun browse-image (*image* &key (root (make-graph-tuple
:object (movitz-word (movitz-read-and-intern nil 'word))
:tree (gensym))))
(let ((*endian* :little-endian)
(*print-radix* t)
(*print-base* 16))
(run-frame-top-level
(make-application-frame 'browser
:width 700
:height 700
:root-tuple root))))
(defun browse-word (word)
(browse-image movitz::*image*
:root (make-graph-tuple :object (movitz-word word)
:tree (gensym))))
(defun browser ()
(multiprocessing:process-run-function "browser" #'browse-image *i*))
(defun browse-pid (pid)
(flet ((do-browse-pid (pid)
(with-procfs-image (pid)
(browse-image *image*))))
(multiprocessing:process-run-function
`(:name "browser")
#'do-browse-pid
pid)))
(defun browse-file (&key (threadp t) (path *default-image-file*)
(offset (- 512 #x100000)) (direction :input))
(flet ((do-browse-path (path offset direction)
(with-binary-file (stream path :direction direction)
(browse-image (make-instance 'stream-image
:stream stream
:offset offset)))))
(if threadp
(multiprocessing:process-run-function "browser" #'do-browse-path
path offset direction)
(do-browse-path path offset direction))))
(define-presentation-type movitz-object ())
(define-presentation-method present (object (type movitz-object)
*standard-output*
(view textual-view) &key)
(formatting-table ()
(formatting-column ()
(formatting-cell (t :align-x :center)
(with-drawing-options (t :size :small)
(browser-print-safely object)))
(formatting-cell (t :align-x :center)
(format t "#x~8,'0X" (movitz-intern object))))))
(define-presentation-method present
(object (type movitz-object) *standard-output* (view textual-menu-view) &key)
(format t "#x~8,'0X" (movitz-intern object)))
(define-presentation-method present
(object (type graph-tuple) *standard-output* (view textual-menu-view) &key)
(format t "#x~8,'0X" (movitz-intern (graph-tuple-object object))))
(define-presentation-method present (object (type movitz-character)
*standard-output*
(view textual-view) &key)
(write (movitz-char object)))
(define-presentation-method present
(object (type movitz-symbol) *standard-output* (view textual-view) &key)
(format t "#x~8,'0X: |~A|" (movitz-intern object) (browser-print-safely object)))
(define-presentation-method present
(object (type movitz-vector) *standard-output* (view textual-view) &key)
(if (not (eq :character (movitz-vector-element-type object)))
(call-next-method)
(format t "#x~8,'0X: \"~A\"" (movitz-intern object) (browser-print-safely object))))
(defun browser-print-safely (object)
(handler-case
(movitz::movitz-print object)
(error ()
(write-string (string-downcase (symbol-name (type-of object)))))))
(define-presentation-method present (object (type browser-array)
*standard-output*
(view textual-view) &key)
(let ((rows-per-col (typecase (length (browser-array-elements object))
((integer 0 15) 1)
((integer 16 47) 2)
((integer 48 127) 4)
(t 8))))
(formatting-table ()
(loop for row on (browser-array-elements object) by #'(lambda (x) (nthcdr rows-per-col x))
as i upfrom 0 by rows-per-col
do (formatting-row ()
(formatting-cell (t :align-x :right)
(format t "~D:" i))
(loop for r from 1 to rows-per-col
as element in row
do (formatting-cell ()
(case (browser-array-type object)
(:u32 (format t "#x~8,'0X" element))
((:u8 :code) (format t "#x~2,'0X" element))
(t #+ignore(warn "unk: ~S" (browser-array-type object))
(write element))))))))))
(define-browser-command read-and-set-root ((object 't))
(set-root (movitz-word (movitz-read-and-intern object 'word))))
(define-browser-command toggle ((tuple 'graph-tuple))
(with-slots (tree object parent slot-name) tuple
(cond
((null (browser-open-slots tree object parent slot-name))
(setf (browser-open-slots tree object parent slot-name)
(browser-default-open-slots object)))
;; (warn "now open: ~S" (browser-open-slots tree object parent slot-name)))
(t
(setf (browser-open-slots tree object parent slot-name)
nil)))))
(define-presentation-to-command-translator toggle
(graph-tuple
toggle
browser
:gesture :select
:tester ((object)
(typep (graph-tuple-object object) 'movitz-heap-object)))
(object)
(list object))
(define-browser-command set-root ((object 'movitz-object))
(setf (browser-root-tuple *application-frame*)
(make-graph-tuple :tree (gensym) :object object)))
(define-presentation-to-command-translator set-root-tuple
(graph-tuple set-root browser)
(object)
(list (graph-tuple-object object)))
(define-browser-command new-browser ((object 'movitz-object))
(browse-image *image* :root (make-graph-tuple :tree (gensym)
:object object)))
(define-presentation-to-command-translator new-browser-tuple
(graph-tuple new-browser browser)
(object)
(list (graph-tuple-object object)))
(defun (setf browser-open-slots) (value tree object parent slot-name)
(let ((old-slot (assoc-if #'(lambda (x) (and (eq (car x) parent) (eq (cdr x) slot-name)))
(getf (movitz-object-browser-properties object) tree))))
(if old-slot
(setf (cdr old-slot) value)
(setf (getf (movitz-object-browser-properties object) tree)
(acons (cons parent slot-name)
value
(getf (movitz-object-browser-properties object) tree)))))
value)
(defun browser-open-slots (tree object parent slot-name)
(cdr (assoc-if #'(lambda (x) (and (eq (car x) parent) (eq (cdr x) slot-name)))
(getf (movitz-object-browser-properties object) tree))))
(define-browser-command set-root-word ()
(let ((word (accepting-values (t :own-window t)
(accept '((integer 0 #xffffffff) :base 16)))))
(when word
(set-root (movitz-word word)))))
|
[
{
"context": "isp\n\n;;;; Copyright (c) 2012 -- 2014 \"the Phoeron\" Colin J.E. Lupton <//thephoeron.com>\n;;;; See LICENSE for additiona",
"end": 169,
"score": 0.9998682737350464,
"start": 152,
"tag": "NAME",
"value": "Colin J.E. Lupton"
}
] |
redshiftnet.lisp
|
thephoeron/REDSHIFTNET
| 2 |
;;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: REDSHIFTNET; Base: 10 -*-
;;;; file: redshiftnet.lisp
;;;; Copyright (c) 2012 -- 2014 "the Phoeron" Colin J.E. Lupton <//thephoeron.com>
;;;; See LICENSE for additional information.
(in-package :redshiftnet)
;;; REDSHIFTNET SERVER
(defun rsn-start (&key (www-port 8080) (ssl-port 8090))
"Server Start function for REDSHIFTNET"
(ensure-directories-exist *www-acc-log*)
(ensure-directories-exist *www-msg-log*)
(ensure-directories-exist *ssl-acc-log*)
(ensure-directories-exist *ssl-msg-log*)
;(postmodern:connect-toplevel *primary-db* *primary-db-user* *primary-db-pass* *primary-db-host*)
(setf (port vhost-web) www-port
(port vhost-ssl) ssl-port)
(hunchentoot:start vhost-web)
(hunchentoot:start vhost-ssl)
(format t "~%REDSHIFTNET Started and Running:~% WEB: ~W~% SSL: ~W" vhost-web vhost-ssl))
(defun rsn-stop ()
"Server Stop function for REDSHIFTNET"
(when (or vhost-web vhost-ssl)
;(postmodern:disconnect-toplevel)
(format t "~%REDSHIFTNET running on acceptors ~W and ~W" (hunchentoot:stop vhost-web) (hunchentoot:stop vhost-ssl)))
(format t "~%REDSHIFTNET Stopped successfully..."))
(defun rsn-restart (&key (www-port 8080) (ssl-port 8090))
"Restart Server function for REDSHIFTNET. Caveat programmer: Assumes SBCL environment and Quicklisp installed."
(rsn-stop)
(ql:quickload "redshiftnet")
(rsn-start :www-port www-port :ssl-port ssl-port)
(sb-ext:gc :full t)
(format t "~%REDSHIFTNET Restarted successfully..."))
;; EOF
|
68853
|
;;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: REDSHIFTNET; Base: 10 -*-
;;;; file: redshiftnet.lisp
;;;; Copyright (c) 2012 -- 2014 "the Phoeron" <NAME> <//thephoeron.com>
;;;; See LICENSE for additional information.
(in-package :redshiftnet)
;;; REDSHIFTNET SERVER
(defun rsn-start (&key (www-port 8080) (ssl-port 8090))
"Server Start function for REDSHIFTNET"
(ensure-directories-exist *www-acc-log*)
(ensure-directories-exist *www-msg-log*)
(ensure-directories-exist *ssl-acc-log*)
(ensure-directories-exist *ssl-msg-log*)
;(postmodern:connect-toplevel *primary-db* *primary-db-user* *primary-db-pass* *primary-db-host*)
(setf (port vhost-web) www-port
(port vhost-ssl) ssl-port)
(hunchentoot:start vhost-web)
(hunchentoot:start vhost-ssl)
(format t "~%REDSHIFTNET Started and Running:~% WEB: ~W~% SSL: ~W" vhost-web vhost-ssl))
(defun rsn-stop ()
"Server Stop function for REDSHIFTNET"
(when (or vhost-web vhost-ssl)
;(postmodern:disconnect-toplevel)
(format t "~%REDSHIFTNET running on acceptors ~W and ~W" (hunchentoot:stop vhost-web) (hunchentoot:stop vhost-ssl)))
(format t "~%REDSHIFTNET Stopped successfully..."))
(defun rsn-restart (&key (www-port 8080) (ssl-port 8090))
"Restart Server function for REDSHIFTNET. Caveat programmer: Assumes SBCL environment and Quicklisp installed."
(rsn-stop)
(ql:quickload "redshiftnet")
(rsn-start :www-port www-port :ssl-port ssl-port)
(sb-ext:gc :full t)
(format t "~%REDSHIFTNET Restarted successfully..."))
;; EOF
| true |
;;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: REDSHIFTNET; Base: 10 -*-
;;;; file: redshiftnet.lisp
;;;; Copyright (c) 2012 -- 2014 "the Phoeron" PI:NAME:<NAME>END_PI <//thephoeron.com>
;;;; See LICENSE for additional information.
(in-package :redshiftnet)
;;; REDSHIFTNET SERVER
(defun rsn-start (&key (www-port 8080) (ssl-port 8090))
"Server Start function for REDSHIFTNET"
(ensure-directories-exist *www-acc-log*)
(ensure-directories-exist *www-msg-log*)
(ensure-directories-exist *ssl-acc-log*)
(ensure-directories-exist *ssl-msg-log*)
;(postmodern:connect-toplevel *primary-db* *primary-db-user* *primary-db-pass* *primary-db-host*)
(setf (port vhost-web) www-port
(port vhost-ssl) ssl-port)
(hunchentoot:start vhost-web)
(hunchentoot:start vhost-ssl)
(format t "~%REDSHIFTNET Started and Running:~% WEB: ~W~% SSL: ~W" vhost-web vhost-ssl))
(defun rsn-stop ()
"Server Stop function for REDSHIFTNET"
(when (or vhost-web vhost-ssl)
;(postmodern:disconnect-toplevel)
(format t "~%REDSHIFTNET running on acceptors ~W and ~W" (hunchentoot:stop vhost-web) (hunchentoot:stop vhost-ssl)))
(format t "~%REDSHIFTNET Stopped successfully..."))
(defun rsn-restart (&key (www-port 8080) (ssl-port 8090))
"Restart Server function for REDSHIFTNET. Caveat programmer: Assumes SBCL environment and Quicklisp installed."
(rsn-stop)
(ql:quickload "redshiftnet")
(rsn-start :www-port www-port :ssl-port ssl-port)
(sb-ext:gc :full t)
(format t "~%REDSHIFTNET Restarted successfully..."))
;; EOF
|
[
{
"context": "ra\")\n (is (connection-spec-password spec) \"apass\")\n (is (connection-spec-host spec) \"hoast\"",
"end": 2417,
"score": 0.9990525245666504,
"start": 2412,
"tag": "PASSWORD",
"value": "apass"
},
{
"context": "uest\")\n (is (connection-spec-host spec) \"::1\")\n (is (connection-spec-port spec) 5672)\n ",
"end": 8469,
"score": 0.7855584621429443,
"start": 8468,
"tag": "IP_ADDRESS",
"value": "1"
},
{
"context": "er\")\n (is (connection-spec-password spec) \"pass\")\n (is (connection-spec-host spec) \"host\")",
"end": 9095,
"score": 0.9776199460029602,
"start": 9091,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": "er\")\n (is (connection-spec-password spec) \"pass\")\n (is (connection-spec-host spec) \"host\")",
"end": 10071,
"score": 0.8746400475502014,
"start": 10067,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": " :password \"pass\"\n ",
"end": 11471,
"score": 0.9995365142822266,
"start": 11467,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": "er\")\n (is (connection-spec-password spec) \"pass\")\n (is (connection-spec-host spec) \"host\")",
"end": 12092,
"score": 0.6837843060493469,
"start": 12088,
"tag": "PASSWORD",
"value": "pass"
}
] |
t/unit/connection-spec.lisp
|
jeosol/cl-bunny
| 17 |
(in-package :cl-bunny.test)
(plan 2)
(subtest "Connection spec tests"
(subtest "Parser helpers"
(subtest "check-unit-paramter"
(is-error (bunny::check-uint-parameter '(("frame-max" . "qwe")) "frame-max") 'error) ;; TODO: specialize error
(is-error (bunny::check-uint-parameter '(("frame-max" . "-2")) "frame-max") 'error) ;; TODO: specialize error
(is (bunny::check-uint-parameter '(("frame-max" . "256")) "frame-max") 256))
(subtest "check-connection-parameters"
(is-error (bunny::check-connection-parameters "frame-max=wer") 'error)
(is-error (bunny::check-connection-parameters "frame-max=-2") 'error)
(is-values (bunny::check-connection-parameters "frame-max=256") '(#.bunny::+channel-max+ 256 #.bunny::+heartbeat-interval+ t t :default))
(is-values (bunny::check-connection-parameters "qwe=qwe&frame-max=256") '(#.bunny::+channel-max+ 256 #.bunny::+heartbeat-interval+ t t :default))
(is-values (bunny::check-connection-parameters "heartbeat-interval=34&frame-max=256&channel-max=0") '(0 256 34 t t :default))))
(subtest "Connection string parser tests [without additional params]"
;; this should comply with https://www.rabbitmq.com/uri-spec.html
;; tests based on Apendix A
(subtest "amqp://user:pass@host:10000/vhost"
(let ((spec (bunny::make-connection-spec "amqp://user:pass@host:10000/vhost")))
(is (connection-spec-login spec) "user")
(is (connection-spec-password spec) "pass")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 10000)
(is (connection-spec-vhost spec) "vhost")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (connection-spec-channel-max spec) bunny::+channel-max+ "Channel max is default")
(is (connection-spec-frame-max spec) bunny::+frame-max+ "Frame max is default")
(is (connection-spec-heartbeat-interval spec) bunny::+heartbeat-interval+ "Heartbeat interval is default")
(is (print-amqp-object-to-string spec) "amqp://user:pass@host:10000/vhost")))
(subtest "amqp://user%61:%61pass@ho%61st:10000/v%2fhost"
(let ((spec (bunny::make-connection-spec "amqp://user%61:%61pass@ho%61st:10000/v%2fhost")))
(is (connection-spec-login spec) "usera")
(is (connection-spec-password spec) "apass")
(is (connection-spec-host spec) "hoast")
(is (connection-spec-port spec) 10000)
(is (connection-spec-vhost spec) "v/host")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://usera:apass@hoast:10000/v%2Fhost")))
(subtest "amqp://"
(let ((spec (bunny::make-connection-spec "amqp://")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://")))
(subtest "amqps://"
(let ((spec (bunny::make-connection-spec "amqps://")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5671)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) t "Do use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqps://")))
(subtest "amqp://:@/"
(let ((spec (bunny::make-connection-spec "amqp://:@/")))
(is (connection-spec-login spec) "")
(is (connection-spec-password spec) "")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://:@/")))
(subtest "amqp://user@"
(let ((spec (bunny::make-connection-spec "amqp://user@")))
(is (connection-spec-login spec) "user")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://user@")))
(subtest "amqp://user:pass@"
(let ((spec (bunny::make-connection-spec "amqp://user:pass@")))
(is (connection-spec-login spec) "user")
(is (connection-spec-password spec) "pass")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://user:pass@")))
(subtest "amqp://host"
(let ((spec (bunny::make-connection-spec "amqp://host")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://host")))
(subtest "amqp://:10000"
(let ((spec (bunny::make-connection-spec "amqp://:10000")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 10000)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://:10000")))
(subtest "amqp:///vhost"
(let ((spec (bunny::make-connection-spec "amqp:///vhost")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "vhost")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp:///vhost")))
(subtest "amqp://host/"
(let ((spec (bunny::make-connection-spec "amqp://host/")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://host/")))
(subtest "amqp://host/%2f"
(let ((spec (bunny::make-connection-spec "amqp://host/%2f")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://host")))
(subtest "amqp://[::1]"
(let ((spec (bunny::make-connection-spec "amqp://[::1]")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "::1")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) t "Address is IPv6")
(is (print-amqp-object-to-string spec) "amqp://[::1]"))))
(subtest "Connection string parser tests [with additional params]"
(subtest "amqp://user:pass@host:10000/vhost?frame-max=256"
(let ((spec (bunny::make-connection-spec "amqp://user:pass@host:10000/vhost?frame-max=256")))
(is (connection-spec-login spec) "user")
(is (connection-spec-password spec) "pass")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 10000)
(is (connection-spec-vhost spec) "vhost")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (connection-spec-channel-max spec) bunny::+channel-max+ "Channel max is default")
(is (connection-spec-frame-max spec) 256 "Frame max is 256")
(is (connection-spec-heartbeat-interval spec) bunny::+heartbeat-interval+ "Heartbeat interval is default")
(is (print-amqp-object-to-string spec) "amqp://user:pass@host:10000/vhost?frame-max=256")))
(subtest "amqp://user:pass@host:10000/vhost?heartbeat-interval=30&channel-max=256"
(let ((spec (bunny::make-connection-spec "amqp://user:pass@host:10000/vhost?heartbeat-interval=30&channel-max=256")))
(is (connection-spec-login spec) "user")
(is (connection-spec-password spec) "pass")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 10000)
(is (connection-spec-vhost spec) "vhost")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (connection-spec-channel-max spec) 256 "Channel max is 256")
(is (connection-spec-frame-max spec) bunny::+frame-max+ "Frame max is default")
(is (connection-spec-heartbeat-interval spec) 30 "Heartbeat interval is 30")
(is (print-amqp-object-to-string spec) "amqp://user:pass@host:10000/vhost?channel-max=256&heartbeat-interval=30"))))
(subtest "Connection list parser tests [without additional params]"
(subtest "NIL"
(let ((spec (bunny::make-connection-spec nil)))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://")))
(subtest "PLIST"
(let ((spec (bunny::make-connection-spec '(:login "user"
:password "pass"
:host "host"
:port 10000
:vhost "vhost"
:use-tls-p t
:use-ipv6-p nil
:channel-max 256
:frame-max 4096
:heartbeat-interval 30))))
(is (connection-spec-login spec) "user")
(is (connection-spec-password spec) "pass")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 10000)
(is (connection-spec-vhost spec) "vhost" "Use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (connection-spec-channel-max spec) 256 "Channel max is 256")
(is (connection-spec-frame-max spec) 4096 "Frame max is 4096")
(is (connection-spec-heartbeat-interval spec) 30 "Heartbeat interval is 30")
(is (print-amqp-object-to-string spec) "amqps://user:pass@host:10000/vhost?channel-max=256&frame-max=4096&heartbeat-interval=30"))))
(let ((spec (bunny::make-connection-spec "amqp://")))
(is (bunny::make-connection-spec spec) spec "Make-connection-spec returns the same connection spec")))
(finalize)
|
1953
|
(in-package :cl-bunny.test)
(plan 2)
(subtest "Connection spec tests"
(subtest "Parser helpers"
(subtest "check-unit-paramter"
(is-error (bunny::check-uint-parameter '(("frame-max" . "qwe")) "frame-max") 'error) ;; TODO: specialize error
(is-error (bunny::check-uint-parameter '(("frame-max" . "-2")) "frame-max") 'error) ;; TODO: specialize error
(is (bunny::check-uint-parameter '(("frame-max" . "256")) "frame-max") 256))
(subtest "check-connection-parameters"
(is-error (bunny::check-connection-parameters "frame-max=wer") 'error)
(is-error (bunny::check-connection-parameters "frame-max=-2") 'error)
(is-values (bunny::check-connection-parameters "frame-max=256") '(#.bunny::+channel-max+ 256 #.bunny::+heartbeat-interval+ t t :default))
(is-values (bunny::check-connection-parameters "qwe=qwe&frame-max=256") '(#.bunny::+channel-max+ 256 #.bunny::+heartbeat-interval+ t t :default))
(is-values (bunny::check-connection-parameters "heartbeat-interval=34&frame-max=256&channel-max=0") '(0 256 34 t t :default))))
(subtest "Connection string parser tests [without additional params]"
;; this should comply with https://www.rabbitmq.com/uri-spec.html
;; tests based on Apendix A
(subtest "amqp://user:pass@host:10000/vhost"
(let ((spec (bunny::make-connection-spec "amqp://user:pass@host:10000/vhost")))
(is (connection-spec-login spec) "user")
(is (connection-spec-password spec) "pass")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 10000)
(is (connection-spec-vhost spec) "vhost")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (connection-spec-channel-max spec) bunny::+channel-max+ "Channel max is default")
(is (connection-spec-frame-max spec) bunny::+frame-max+ "Frame max is default")
(is (connection-spec-heartbeat-interval spec) bunny::+heartbeat-interval+ "Heartbeat interval is default")
(is (print-amqp-object-to-string spec) "amqp://user:pass@host:10000/vhost")))
(subtest "amqp://user%61:%61pass@ho%61st:10000/v%2fhost"
(let ((spec (bunny::make-connection-spec "amqp://user%61:%61pass@ho%61st:10000/v%2fhost")))
(is (connection-spec-login spec) "usera")
(is (connection-spec-password spec) "<PASSWORD>")
(is (connection-spec-host spec) "hoast")
(is (connection-spec-port spec) 10000)
(is (connection-spec-vhost spec) "v/host")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://usera:apass@hoast:10000/v%2Fhost")))
(subtest "amqp://"
(let ((spec (bunny::make-connection-spec "amqp://")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://")))
(subtest "amqps://"
(let ((spec (bunny::make-connection-spec "amqps://")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5671)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) t "Do use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqps://")))
(subtest "amqp://:@/"
(let ((spec (bunny::make-connection-spec "amqp://:@/")))
(is (connection-spec-login spec) "")
(is (connection-spec-password spec) "")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://:@/")))
(subtest "amqp://user@"
(let ((spec (bunny::make-connection-spec "amqp://user@")))
(is (connection-spec-login spec) "user")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://user@")))
(subtest "amqp://user:pass@"
(let ((spec (bunny::make-connection-spec "amqp://user:pass@")))
(is (connection-spec-login spec) "user")
(is (connection-spec-password spec) "pass")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://user:pass@")))
(subtest "amqp://host"
(let ((spec (bunny::make-connection-spec "amqp://host")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://host")))
(subtest "amqp://:10000"
(let ((spec (bunny::make-connection-spec "amqp://:10000")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 10000)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://:10000")))
(subtest "amqp:///vhost"
(let ((spec (bunny::make-connection-spec "amqp:///vhost")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "vhost")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp:///vhost")))
(subtest "amqp://host/"
(let ((spec (bunny::make-connection-spec "amqp://host/")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://host/")))
(subtest "amqp://host/%2f"
(let ((spec (bunny::make-connection-spec "amqp://host/%2f")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://host")))
(subtest "amqp://[::1]"
(let ((spec (bunny::make-connection-spec "amqp://[::1]")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "::1")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) t "Address is IPv6")
(is (print-amqp-object-to-string spec) "amqp://[::1]"))))
(subtest "Connection string parser tests [with additional params]"
(subtest "amqp://user:pass@host:10000/vhost?frame-max=256"
(let ((spec (bunny::make-connection-spec "amqp://user:pass@host:10000/vhost?frame-max=256")))
(is (connection-spec-login spec) "user")
(is (connection-spec-password spec) "<PASSWORD>")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 10000)
(is (connection-spec-vhost spec) "vhost")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (connection-spec-channel-max spec) bunny::+channel-max+ "Channel max is default")
(is (connection-spec-frame-max spec) 256 "Frame max is 256")
(is (connection-spec-heartbeat-interval spec) bunny::+heartbeat-interval+ "Heartbeat interval is default")
(is (print-amqp-object-to-string spec) "amqp://user:pass@host:10000/vhost?frame-max=256")))
(subtest "amqp://user:pass@host:10000/vhost?heartbeat-interval=30&channel-max=256"
(let ((spec (bunny::make-connection-spec "amqp://user:pass@host:10000/vhost?heartbeat-interval=30&channel-max=256")))
(is (connection-spec-login spec) "user")
(is (connection-spec-password spec) "<PASSWORD>")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 10000)
(is (connection-spec-vhost spec) "vhost")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (connection-spec-channel-max spec) 256 "Channel max is 256")
(is (connection-spec-frame-max spec) bunny::+frame-max+ "Frame max is default")
(is (connection-spec-heartbeat-interval spec) 30 "Heartbeat interval is 30")
(is (print-amqp-object-to-string spec) "amqp://user:pass@host:10000/vhost?channel-max=256&heartbeat-interval=30"))))
(subtest "Connection list parser tests [without additional params]"
(subtest "NIL"
(let ((spec (bunny::make-connection-spec nil)))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://")))
(subtest "PLIST"
(let ((spec (bunny::make-connection-spec '(:login "user"
:password "<PASSWORD>"
:host "host"
:port 10000
:vhost "vhost"
:use-tls-p t
:use-ipv6-p nil
:channel-max 256
:frame-max 4096
:heartbeat-interval 30))))
(is (connection-spec-login spec) "user")
(is (connection-spec-password spec) "<PASSWORD>")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 10000)
(is (connection-spec-vhost spec) "vhost" "Use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (connection-spec-channel-max spec) 256 "Channel max is 256")
(is (connection-spec-frame-max spec) 4096 "Frame max is 4096")
(is (connection-spec-heartbeat-interval spec) 30 "Heartbeat interval is 30")
(is (print-amqp-object-to-string spec) "amqps://user:pass@host:10000/vhost?channel-max=256&frame-max=4096&heartbeat-interval=30"))))
(let ((spec (bunny::make-connection-spec "amqp://")))
(is (bunny::make-connection-spec spec) spec "Make-connection-spec returns the same connection spec")))
(finalize)
| true |
(in-package :cl-bunny.test)
(plan 2)
(subtest "Connection spec tests"
(subtest "Parser helpers"
(subtest "check-unit-paramter"
(is-error (bunny::check-uint-parameter '(("frame-max" . "qwe")) "frame-max") 'error) ;; TODO: specialize error
(is-error (bunny::check-uint-parameter '(("frame-max" . "-2")) "frame-max") 'error) ;; TODO: specialize error
(is (bunny::check-uint-parameter '(("frame-max" . "256")) "frame-max") 256))
(subtest "check-connection-parameters"
(is-error (bunny::check-connection-parameters "frame-max=wer") 'error)
(is-error (bunny::check-connection-parameters "frame-max=-2") 'error)
(is-values (bunny::check-connection-parameters "frame-max=256") '(#.bunny::+channel-max+ 256 #.bunny::+heartbeat-interval+ t t :default))
(is-values (bunny::check-connection-parameters "qwe=qwe&frame-max=256") '(#.bunny::+channel-max+ 256 #.bunny::+heartbeat-interval+ t t :default))
(is-values (bunny::check-connection-parameters "heartbeat-interval=34&frame-max=256&channel-max=0") '(0 256 34 t t :default))))
(subtest "Connection string parser tests [without additional params]"
;; this should comply with https://www.rabbitmq.com/uri-spec.html
;; tests based on Apendix A
(subtest "amqp://user:pass@host:10000/vhost"
(let ((spec (bunny::make-connection-spec "amqp://user:pass@host:10000/vhost")))
(is (connection-spec-login spec) "user")
(is (connection-spec-password spec) "pass")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 10000)
(is (connection-spec-vhost spec) "vhost")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (connection-spec-channel-max spec) bunny::+channel-max+ "Channel max is default")
(is (connection-spec-frame-max spec) bunny::+frame-max+ "Frame max is default")
(is (connection-spec-heartbeat-interval spec) bunny::+heartbeat-interval+ "Heartbeat interval is default")
(is (print-amqp-object-to-string spec) "amqp://user:pass@host:10000/vhost")))
(subtest "amqp://user%61:%61pass@ho%61st:10000/v%2fhost"
(let ((spec (bunny::make-connection-spec "amqp://user%61:%61pass@ho%61st:10000/v%2fhost")))
(is (connection-spec-login spec) "usera")
(is (connection-spec-password spec) "PI:PASSWORD:<PASSWORD>END_PI")
(is (connection-spec-host spec) "hoast")
(is (connection-spec-port spec) 10000)
(is (connection-spec-vhost spec) "v/host")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://usera:apass@hoast:10000/v%2Fhost")))
(subtest "amqp://"
(let ((spec (bunny::make-connection-spec "amqp://")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://")))
(subtest "amqps://"
(let ((spec (bunny::make-connection-spec "amqps://")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5671)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) t "Do use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqps://")))
(subtest "amqp://:@/"
(let ((spec (bunny::make-connection-spec "amqp://:@/")))
(is (connection-spec-login spec) "")
(is (connection-spec-password spec) "")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://:@/")))
(subtest "amqp://user@"
(let ((spec (bunny::make-connection-spec "amqp://user@")))
(is (connection-spec-login spec) "user")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://user@")))
(subtest "amqp://user:pass@"
(let ((spec (bunny::make-connection-spec "amqp://user:pass@")))
(is (connection-spec-login spec) "user")
(is (connection-spec-password spec) "pass")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://user:pass@")))
(subtest "amqp://host"
(let ((spec (bunny::make-connection-spec "amqp://host")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://host")))
(subtest "amqp://:10000"
(let ((spec (bunny::make-connection-spec "amqp://:10000")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 10000)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://:10000")))
(subtest "amqp:///vhost"
(let ((spec (bunny::make-connection-spec "amqp:///vhost")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "vhost")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp:///vhost")))
(subtest "amqp://host/"
(let ((spec (bunny::make-connection-spec "amqp://host/")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://host/")))
(subtest "amqp://host/%2f"
(let ((spec (bunny::make-connection-spec "amqp://host/%2f")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://host")))
(subtest "amqp://[::1]"
(let ((spec (bunny::make-connection-spec "amqp://[::1]")))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "::1")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) t "Address is IPv6")
(is (print-amqp-object-to-string spec) "amqp://[::1]"))))
(subtest "Connection string parser tests [with additional params]"
(subtest "amqp://user:pass@host:10000/vhost?frame-max=256"
(let ((spec (bunny::make-connection-spec "amqp://user:pass@host:10000/vhost?frame-max=256")))
(is (connection-spec-login spec) "user")
(is (connection-spec-password spec) "PI:PASSWORD:<PASSWORD>END_PI")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 10000)
(is (connection-spec-vhost spec) "vhost")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (connection-spec-channel-max spec) bunny::+channel-max+ "Channel max is default")
(is (connection-spec-frame-max spec) 256 "Frame max is 256")
(is (connection-spec-heartbeat-interval spec) bunny::+heartbeat-interval+ "Heartbeat interval is default")
(is (print-amqp-object-to-string spec) "amqp://user:pass@host:10000/vhost?frame-max=256")))
(subtest "amqp://user:pass@host:10000/vhost?heartbeat-interval=30&channel-max=256"
(let ((spec (bunny::make-connection-spec "amqp://user:pass@host:10000/vhost?heartbeat-interval=30&channel-max=256")))
(is (connection-spec-login spec) "user")
(is (connection-spec-password spec) "PI:PASSWORD:<PASSWORD>END_PI")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 10000)
(is (connection-spec-vhost spec) "vhost")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (connection-spec-channel-max spec) 256 "Channel max is 256")
(is (connection-spec-frame-max spec) bunny::+frame-max+ "Frame max is default")
(is (connection-spec-heartbeat-interval spec) 30 "Heartbeat interval is 30")
(is (print-amqp-object-to-string spec) "amqp://user:pass@host:10000/vhost?channel-max=256&heartbeat-interval=30"))))
(subtest "Connection list parser tests [without additional params]"
(subtest "NIL"
(let ((spec (bunny::make-connection-spec nil)))
(is (connection-spec-login spec) "guest")
(is (connection-spec-password spec) "guest")
(is (connection-spec-host spec) "localhost")
(is (connection-spec-port spec) 5672)
(is (connection-spec-vhost spec) "/")
(is (connection-spec-use-tls-p spec) nil "Do not use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (print-amqp-object-to-string spec) "amqp://")))
(subtest "PLIST"
(let ((spec (bunny::make-connection-spec '(:login "user"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:host "host"
:port 10000
:vhost "vhost"
:use-tls-p t
:use-ipv6-p nil
:channel-max 256
:frame-max 4096
:heartbeat-interval 30))))
(is (connection-spec-login spec) "user")
(is (connection-spec-password spec) "PI:PASSWORD:<PASSWORD>END_PI")
(is (connection-spec-host spec) "host")
(is (connection-spec-port spec) 10000)
(is (connection-spec-vhost spec) "vhost" "Use TLS")
(is (connection-spec-use-ipv6-p spec) nil "Address is not IPv6")
(is (connection-spec-channel-max spec) 256 "Channel max is 256")
(is (connection-spec-frame-max spec) 4096 "Frame max is 4096")
(is (connection-spec-heartbeat-interval spec) 30 "Heartbeat interval is 30")
(is (print-amqp-object-to-string spec) "amqps://user:pass@host:10000/vhost?channel-max=256&frame-max=4096&heartbeat-interval=30"))))
(let ((spec (bunny::make-connection-spec "amqp://")))
(is (bunny::make-connection-spec spec) spec "Make-connection-spec returns the same connection spec")))
(finalize)
|
[
{
"context": "5, 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.9997319579124451,
"start": 70,
"tag": "NAME",
"value": "Matt Kaufmann"
}
] |
books/kestrel/apt/simplify-defun-sk-tests.lisp
|
ragerdl/acl2
| 1 |
; Copyright (C) 2015, Regents of the University of Texas
; Written by Matt Kaufmann
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
; Since the official transformation is simplify, most of the tests here call
; simplify even though this file is about simplifying defun-sk forms, not defun
; forms. We let a few of the initial ones call simplify-defun-sk just to test
; that simplify-defun-sk continues to work.
(in-package "ACL2")
(include-book "simplify")
(include-book "std/testing/must-be-redundant" :dir :system)
(include-book "std/testing/must-fail" :dir :system)
(include-book "kestrel/utilities/deftest" :dir :system)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Simplify-defun-sk tests
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun fix-true-listp (lst)
(if (consp lst)
(cons (car lst)
(fix-true-listp (cdr lst)))
nil))
(defthm member-fix-true-listp
(iff (member a (fix-true-listp lst))
(member a lst)))
; Basic exists test for one bound variable
(deftest
(defun-sk foo (lst)
(exists x (member-equal x (fix-true-listp lst))))
(simplify-defun-sk foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(EXISTS (X) (MEMBER-EQUAL X LST))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST)))))
; As above, but with member, which introduces a LET. We can probably live with
; that. NOTE: We are blowing away prog2$ here; otherwise this test fails.
(deftest
(defun-sk foo (lst)
(exists x (member x (fix-true-listp lst))))
(simplify-defun-sk foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(EXISTS (X)
(MEMBER-EQUAL X LST))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST)))))
; Basic exists test for more than one bound variable
(deftest
(defun-sk foo (lst)
(exists (x y) (member-equal (cons x y) (fix-true-listp lst))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(EXISTS (X Y)
(MEMBER-EQUAL (CONS X Y) LST))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST)))))
; Basic forall test for one bound variable
(deftest
(defun-sk foo (lst)
(forall x (not (member-equal x (fix-true-listp lst)))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(FORALL (X) (NOT (MEMBER-EQUAL X LST)))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST)))))
; Basic forall test for more than one bound variable
(deftest
(defun-sk foo (lst)
(forall (x y) (not (member-equal (cons x y) (fix-true-listp lst)))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(FORALL (X Y)
(NOT (MEMBER-EQUAL (CONS X Y) LST)))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST)))))
; Test for empty formals.
(deftest
(defun-sk foo ()
(forall (x y) (not (member-equal (cons x y) (fix-true-listp y)))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 ()
(FORALL (X Y)
(NOT (MEMBER-EQUAL (CONS X Y) Y)))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO) (FOO$1)))))
; Test for more than one formal; also tests that UNTRANSLATE is called with IFF
; flag, so that result uses OR.
(deftest
(defun-sk foo (u v)
(exists (x y) (or (member-equal (cons x y) (fix-true-listp u))
(member-equal (cons x y) (fix-true-listp v)))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (U V)
(EXISTS (X Y)
(OR (MEMBER-EQUAL (CONS X Y) U)
(MEMBER-EQUAL (CONS X Y) V)))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO U V) (FOO$1 U V)))))
; Test of pattern for :simplify-body
(deftest
(defun-sk foo (u v)
(exists (x y) (or (member-equal (cons x y) (fix-true-listp u))
(member-equal (cons x y) (fix-true-listp v)))))
(simplify foo
:simplify-body (or _ @))
(must-be-redundant
(DEFUN-SK FOO$1 (U V)
(EXISTS (X Y)
(OR (MEMBER-EQUAL (CONS X Y) (FIX-TRUE-LISTP U))
(MEMBER-EQUAL (CONS X Y) V)))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO U V) (FOO$1 U V)))))
; Test some options
(deftest
(defun-sk foo (lst)
(forall x (not (member-equal x (fix-true-listp lst))))
:strengthen t
:rewrite :direct
:witness-dcls ((declare (xargs :non-executable nil))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(FORALL (X) (NOT (MEMBER-EQUAL X LST)))
:QUANT-OK T
:WITNESS-DCLS ((DECLARE (XARGS :NON-EXECUTABLE NIL)))
:STRENGTHEN T
:REWRITE :DIRECT)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST)))))
; Test of :new-enable
(deftest
(defun-sk foo (lst)
(exists x (member-equal x (fix-true-listp lst))))
(simplify foo)
(assert-event (not (disabledp '(:definition foo$1))))
(simplify foo :new-enable nil)
(assert-event (disabledp '(:definition foo$2)))
(simplify foo :new-enable t)
(assert-event (not (disabledp '(:definition foo$3)))))
(deftest
(defun-sk foo (lst)
(exists x (member-equal x (fix-true-listp lst))))
(in-theory (disable foo))
(simplify foo)
(assert-event (disabledp '(:definition foo$1)))
(simplify foo :new-enable t)
(assert-event (not (disabledp '(:definition foo$2))))
(simplify foo :new-enable nil)
(assert-event (disabledp '(:definition foo$3))))
; Test of :guard-hints.
(deftest
(defun-sk foo (lst)
(exists x (member-equal x (fix-true-listp lst))))
(verify-guards fix-true-listp)
(verify-guards foo)
(defun my-true-listp (x)
(declare (xargs :guard t))
(true-listp x))
(in-theory (disable my-true-listp (tau-system)))
(must-fail
; This test is only of interest for its output. To see the output, submit it
; without the surrounding call of must-fail. The output should consist of the
; following clean and succinct error message.
#||
ACL2 Error in event processing: Guard verification has failed for
FOO$1. See :DOC apt::simplify-failure for some ways to address this
failure.
||#
(simplify foo
:guard (my-true-listp lst)))
(simplify foo
:guard (my-true-listp lst)
:guard-hints (("Goal" :in-theory (enable my-true-listp))))
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(EXISTS (X) (MEMBER-EQUAL X LST))
:QUANT-OK T
:WITNESS-DCLS ((DECLARE (XARGS :GUARD (MY-TRUE-LISTP LST)
:VERIFY-GUARDS NIL)))))
(assert-event (eq (symbol-class 'foo$1 (w state)) :common-lisp-compliant)))
; Tests for more than one match
(deftest
(defstub stub0 (x y z) t)
(defun-sk foo (x y)
(exists z
(equal (list (list (list
(* 3 (+ 1 (+ 1 x)))
(* 3 (+ 1 (+ 1 x)))
(* 4 5 (+ 1 (+ 1 y))))))
(stub0 x y z))))
; Underscore variables other than _ must be distinct for matches to different
; terms:
(must-fail (simplify foo
:simplify-body (list (* 3 @1)
_a
(* _a 5 @2))))
; @-variables other than @ must be distinct for matches to different terms:
(must-fail (simplify foo
:simplify-body (list (* 3 @a)
@a
_)))
; This one is fine.
(simplify foo
:simplify-body (list @1
_1
(* _2 5 @2)))
; So is this.
(simplify foo
:simplify-body (list @
_
(* _ 5 @)))
(must-be-redundant
(DEFUN-SK FOO$1 (X Y)
(EXISTS (Z)
(EQUAL (LIST (LIST (LIST (+ 6 (* 3 X))
(* 3 (+ 1 (+ 1 X)))
(* 4 5 (+ 2 Y)))))
(STUB0 X Y Z)))
:QUANT-OK T))
(must-be-redundant
(DEFUN-SK FOO$2 (X Y)
(EXISTS (Z)
(EQUAL (LIST (LIST (LIST (+ 6 (* 3 X))
(* 3 (+ 1 (+ 1 X)))
(* 4 5 (+ 2 Y)))))
(STUB0 X Y Z)))
:QUANT-OK T)))
; Test the use of directed-untranslate.
(deftest
(defun-sk foo (lst)
(exists x (if (consp x)
(member-equal x (fix-true-listp lst))
nil)))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(EXISTS (X) (IF (CONSP X)
(MEMBER-EQUAL X LST)
NIL))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST))))
(defun-sk foo2a (lst)
(exists x (if (consp x)
(member-equal x (fix-true-listp lst))
nil)))
(simplify foo2a)
(must-be-redundant
(DEFUN-SK FOO2A$1 (LST)
(EXISTS (X) (IF (CONSP X)
(MEMBER-EQUAL X LST)
NIL))
:QUANT-OK T)
(DEFTHM FOO2A-BECOMES-FOO2A$1
(IFF (FOO2A LST) (FOO2A$1 LST))))
(defun-sk foo2b (lst) ; same as foo2a
(exists x (if (consp x)
(member-equal x (fix-true-listp lst))
nil)))
(simplify foo2b :untranslate t)
(must-be-redundant
(DEFUN-SK FOO2B$1 (LST)
(EXISTS (X) (AND (CONSP X) (MEMBER-EQUAL X LST)))
:QUANT-OK T)
(DEFTHM FOO2B-BECOMES-FOO2B$1
(IFF (FOO2B LST) (FOO2B$1 LST)))))
;;; Test :untranslate hint.
;;; NOTE: We are blowing away prog2$ here; otherwise this test fails.
(deftest
(defun-sk g1 (lst)
(exists x (car (cdr (or (member 3 lst)
(member x lst))))))
(simplify g1)
(must-be-redundant
(DEFUN-SK G1$1 (LST)
(EXISTS (X)
(CAR (CDR (OR (MEMBER-EQUAL 3 LST)
(MEMBER-EQUAL X LST)))))
:QUANT-OK T))
(defun-sk g2 (lst)
(exists x (car (cdr (or (member 3 lst)
(member x lst))))))
(simplify g2 :untranslate t)
(must-be-redundant
(DEFUN-SK G2$1 (LST)
(EXISTS (X)
(CADR (OR (MEMBER-EQUAL 3 LST)
(MEMBER-EQUAL X LST))))
:QUANT-OK T))
(defun-sk g3 (lst)
(exists x (car (cdr (or (member 3 lst)
(member x lst))))))
(simplify g3 :untranslate nil)
(must-be-redundant
(DEFUN-SK G3$1 (LST)
(EXISTS (X)
(CAR (CDR (IF (MEMBER-EQUAL '3 LST)
(MEMBER-EQUAL '3 LST)
(MEMBER-EQUAL X LST)))))
:QUANT-OK T)))
;;; Test :expand hints
(deftest
(defun-sk foo (y z)
(exists x (equal (append y z)
(append z x y))))
(simplify foo :expand (append y z))
(must-be-redundant
(DEFUN-SK FOO$1 (Y Z)
(EXISTS (X)
(EQUAL (IF (CONSP Y)
(CONS (CAR Y) (APPEND (CDR Y) Z))
Z)
(APPEND Z X Y)))
:QUANT-OK T)))
; Same as above but slightly different :expand syntax.
(deftest
(defun-sk foo (y z)
(exists x (equal (append y z)
(append z x y))))
(simplify foo :expand ((append y z)))
(must-be-redundant
(DEFUN-SK FOO$1 (Y Z)
(EXISTS (X)
(EQUAL (IF (CONSP Y)
(CONS (CAR Y) (APPEND (CDR Y) Z))
Z)
(APPEND Z X Y)))
:QUANT-OK T)))
; Same as above but wilder :expand hint.
(deftest
(defun-sk foo (y z)
(exists x (equal (append y z)
(append z x y))))
(simplify foo :expand ((:free (z) (append y z))))
(must-be-redundant
(DEFUN-SK FOO$1 (Y Z)
(EXISTS (X)
(EQUAL (IF (CONSP Y)
(CONS (CAR Y) (APPEND (CDR Y) Z))
Z)
(APPEND Z X Y)))
:QUANT-OK T)))
;;; Test :must-simplify
(deftest
(defun-sk foo (y)
(exists x (member-equal x y)))
(must-fail (simplify foo))
(must-fail (simplify foo :must-simplify t))
(simplify foo :must-simplify nil)
(must-be-redundant
(DEFUN-SK FOO$1 (Y)
(EXISTS (X) (MEMBER-EQUAL X Y))
:QUANT-OK T)))
;;; The following test fails without the use of :extra-bindings-ok in the
;;; computed hint that proves F-BECOMES-F$1 from F-BECOMES-F$1-LEMMA. This
;;; problem cannot arise for defun (as opposed to defun-sk), because the
;;; implementation of simplify-defun does not generate any uses of :instance.
(deftest
(defund foo (a)
(declare (xargs :guard t))
(list a))
(defthm member-equal-foo
(member-equal a (foo a))
:hints (("Goal" :in-theory (enable foo))))
(defun my-equiv (x y)
(declare (xargs :guard t))
(equal x y))
(defequiv my-equiv)
(defun my-if (x y z)
(declare (xargs :guard t))
(if x y z))
(defthm iff-implies-equal-my-if-1
(implies (iff x x-equiv)
(equal (my-if x y z) (my-if x-equiv y z)))
:rule-classes (:congruence))
(defthm my-equiv-implies-equal-my-if-1
(implies (my-equiv x x-equiv)
(equal (my-if x y z) (my-if x-equiv y z)))
:rule-classes (:congruence))
(defun-sk f (x y)
(forall a (my-if (member-equal a (foo a)) x y)))
(simplify f
:simplify-body (my-if @ _ _))
(must-fail
; I initially wrote the following incorrectly. The error message was wrong --
; ACL2 complained that the error message isn't an embedded event form. This is
; actually a problem with defun-sk, with a fix expected in April 2018. Adding
; this must-fail form actually does no good in regression testing, since
; failure is silent; that is, the must-fail form succeeded quietly even before
; fixing the complaint. But we include it here as a reminder, and in case one
; wants to test manually.
(DEFUN-SK F$1 (A)
(FORALL (A) (MY-IF T X Y))
:QUANT-OK T))
(must-be-redundant
(DEFUN-SK F$1 (X Y)
(FORALL (A) (MY-IF T X Y))
:QUANT-OK T))
)
; Test of preserving prog2$ and cw.
(deftest
(local (in-theory (disable prog2$-fn))) ; avoid blowing away prog2$
(defun-sk foo (x)
(exists y (equal (cons x y)
(cons (prog2$ (cw "Hello ~x0 ~x1" x y) (car y))
y))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (X)
(EXISTS (Y)
(EQUAL X
(PROG2$ (CW "Hello ~x0 ~x1" X Y)
(CAR Y))))
:QUANT-OK T)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Simplify-defun-sk2 tests
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(deftest
(include-book ; newline to break possible dependency (probably unnecessary)
"kestrel/soft/top" :dir :system)
(defunvar ?f1 (* *) => *)
(defun-sk2 g1[?f1] (x y)
(forall z
(equal (cdr (cons 3 (?f1 x z)))
(?f1 y z))))
(simplify g1[?f1])
(MUST-BE-REDUNDANT
(DEFUN-SK2 G1[?F1]$1 (X Y)
(FORALL (Z)
(EQUAL (?F1 X Z)
(?F1 Y Z)))
:QUANT-OK T)))
|
4463
|
; Copyright (C) 2015, Regents of the University of Texas
; Written by <NAME>
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
; Since the official transformation is simplify, most of the tests here call
; simplify even though this file is about simplifying defun-sk forms, not defun
; forms. We let a few of the initial ones call simplify-defun-sk just to test
; that simplify-defun-sk continues to work.
(in-package "ACL2")
(include-book "simplify")
(include-book "std/testing/must-be-redundant" :dir :system)
(include-book "std/testing/must-fail" :dir :system)
(include-book "kestrel/utilities/deftest" :dir :system)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Simplify-defun-sk tests
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun fix-true-listp (lst)
(if (consp lst)
(cons (car lst)
(fix-true-listp (cdr lst)))
nil))
(defthm member-fix-true-listp
(iff (member a (fix-true-listp lst))
(member a lst)))
; Basic exists test for one bound variable
(deftest
(defun-sk foo (lst)
(exists x (member-equal x (fix-true-listp lst))))
(simplify-defun-sk foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(EXISTS (X) (MEMBER-EQUAL X LST))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST)))))
; As above, but with member, which introduces a LET. We can probably live with
; that. NOTE: We are blowing away prog2$ here; otherwise this test fails.
(deftest
(defun-sk foo (lst)
(exists x (member x (fix-true-listp lst))))
(simplify-defun-sk foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(EXISTS (X)
(MEMBER-EQUAL X LST))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST)))))
; Basic exists test for more than one bound variable
(deftest
(defun-sk foo (lst)
(exists (x y) (member-equal (cons x y) (fix-true-listp lst))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(EXISTS (X Y)
(MEMBER-EQUAL (CONS X Y) LST))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST)))))
; Basic forall test for one bound variable
(deftest
(defun-sk foo (lst)
(forall x (not (member-equal x (fix-true-listp lst)))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(FORALL (X) (NOT (MEMBER-EQUAL X LST)))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST)))))
; Basic forall test for more than one bound variable
(deftest
(defun-sk foo (lst)
(forall (x y) (not (member-equal (cons x y) (fix-true-listp lst)))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(FORALL (X Y)
(NOT (MEMBER-EQUAL (CONS X Y) LST)))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST)))))
; Test for empty formals.
(deftest
(defun-sk foo ()
(forall (x y) (not (member-equal (cons x y) (fix-true-listp y)))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 ()
(FORALL (X Y)
(NOT (MEMBER-EQUAL (CONS X Y) Y)))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO) (FOO$1)))))
; Test for more than one formal; also tests that UNTRANSLATE is called with IFF
; flag, so that result uses OR.
(deftest
(defun-sk foo (u v)
(exists (x y) (or (member-equal (cons x y) (fix-true-listp u))
(member-equal (cons x y) (fix-true-listp v)))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (U V)
(EXISTS (X Y)
(OR (MEMBER-EQUAL (CONS X Y) U)
(MEMBER-EQUAL (CONS X Y) V)))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO U V) (FOO$1 U V)))))
; Test of pattern for :simplify-body
(deftest
(defun-sk foo (u v)
(exists (x y) (or (member-equal (cons x y) (fix-true-listp u))
(member-equal (cons x y) (fix-true-listp v)))))
(simplify foo
:simplify-body (or _ @))
(must-be-redundant
(DEFUN-SK FOO$1 (U V)
(EXISTS (X Y)
(OR (MEMBER-EQUAL (CONS X Y) (FIX-TRUE-LISTP U))
(MEMBER-EQUAL (CONS X Y) V)))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO U V) (FOO$1 U V)))))
; Test some options
(deftest
(defun-sk foo (lst)
(forall x (not (member-equal x (fix-true-listp lst))))
:strengthen t
:rewrite :direct
:witness-dcls ((declare (xargs :non-executable nil))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(FORALL (X) (NOT (MEMBER-EQUAL X LST)))
:QUANT-OK T
:WITNESS-DCLS ((DECLARE (XARGS :NON-EXECUTABLE NIL)))
:STRENGTHEN T
:REWRITE :DIRECT)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST)))))
; Test of :new-enable
(deftest
(defun-sk foo (lst)
(exists x (member-equal x (fix-true-listp lst))))
(simplify foo)
(assert-event (not (disabledp '(:definition foo$1))))
(simplify foo :new-enable nil)
(assert-event (disabledp '(:definition foo$2)))
(simplify foo :new-enable t)
(assert-event (not (disabledp '(:definition foo$3)))))
(deftest
(defun-sk foo (lst)
(exists x (member-equal x (fix-true-listp lst))))
(in-theory (disable foo))
(simplify foo)
(assert-event (disabledp '(:definition foo$1)))
(simplify foo :new-enable t)
(assert-event (not (disabledp '(:definition foo$2))))
(simplify foo :new-enable nil)
(assert-event (disabledp '(:definition foo$3))))
; Test of :guard-hints.
(deftest
(defun-sk foo (lst)
(exists x (member-equal x (fix-true-listp lst))))
(verify-guards fix-true-listp)
(verify-guards foo)
(defun my-true-listp (x)
(declare (xargs :guard t))
(true-listp x))
(in-theory (disable my-true-listp (tau-system)))
(must-fail
; This test is only of interest for its output. To see the output, submit it
; without the surrounding call of must-fail. The output should consist of the
; following clean and succinct error message.
#||
ACL2 Error in event processing: Guard verification has failed for
FOO$1. See :DOC apt::simplify-failure for some ways to address this
failure.
||#
(simplify foo
:guard (my-true-listp lst)))
(simplify foo
:guard (my-true-listp lst)
:guard-hints (("Goal" :in-theory (enable my-true-listp))))
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(EXISTS (X) (MEMBER-EQUAL X LST))
:QUANT-OK T
:WITNESS-DCLS ((DECLARE (XARGS :GUARD (MY-TRUE-LISTP LST)
:VERIFY-GUARDS NIL)))))
(assert-event (eq (symbol-class 'foo$1 (w state)) :common-lisp-compliant)))
; Tests for more than one match
(deftest
(defstub stub0 (x y z) t)
(defun-sk foo (x y)
(exists z
(equal (list (list (list
(* 3 (+ 1 (+ 1 x)))
(* 3 (+ 1 (+ 1 x)))
(* 4 5 (+ 1 (+ 1 y))))))
(stub0 x y z))))
; Underscore variables other than _ must be distinct for matches to different
; terms:
(must-fail (simplify foo
:simplify-body (list (* 3 @1)
_a
(* _a 5 @2))))
; @-variables other than @ must be distinct for matches to different terms:
(must-fail (simplify foo
:simplify-body (list (* 3 @a)
@a
_)))
; This one is fine.
(simplify foo
:simplify-body (list @1
_1
(* _2 5 @2)))
; So is this.
(simplify foo
:simplify-body (list @
_
(* _ 5 @)))
(must-be-redundant
(DEFUN-SK FOO$1 (X Y)
(EXISTS (Z)
(EQUAL (LIST (LIST (LIST (+ 6 (* 3 X))
(* 3 (+ 1 (+ 1 X)))
(* 4 5 (+ 2 Y)))))
(STUB0 X Y Z)))
:QUANT-OK T))
(must-be-redundant
(DEFUN-SK FOO$2 (X Y)
(EXISTS (Z)
(EQUAL (LIST (LIST (LIST (+ 6 (* 3 X))
(* 3 (+ 1 (+ 1 X)))
(* 4 5 (+ 2 Y)))))
(STUB0 X Y Z)))
:QUANT-OK T)))
; Test the use of directed-untranslate.
(deftest
(defun-sk foo (lst)
(exists x (if (consp x)
(member-equal x (fix-true-listp lst))
nil)))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(EXISTS (X) (IF (CONSP X)
(MEMBER-EQUAL X LST)
NIL))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST))))
(defun-sk foo2a (lst)
(exists x (if (consp x)
(member-equal x (fix-true-listp lst))
nil)))
(simplify foo2a)
(must-be-redundant
(DEFUN-SK FOO2A$1 (LST)
(EXISTS (X) (IF (CONSP X)
(MEMBER-EQUAL X LST)
NIL))
:QUANT-OK T)
(DEFTHM FOO2A-BECOMES-FOO2A$1
(IFF (FOO2A LST) (FOO2A$1 LST))))
(defun-sk foo2b (lst) ; same as foo2a
(exists x (if (consp x)
(member-equal x (fix-true-listp lst))
nil)))
(simplify foo2b :untranslate t)
(must-be-redundant
(DEFUN-SK FOO2B$1 (LST)
(EXISTS (X) (AND (CONSP X) (MEMBER-EQUAL X LST)))
:QUANT-OK T)
(DEFTHM FOO2B-BECOMES-FOO2B$1
(IFF (FOO2B LST) (FOO2B$1 LST)))))
;;; Test :untranslate hint.
;;; NOTE: We are blowing away prog2$ here; otherwise this test fails.
(deftest
(defun-sk g1 (lst)
(exists x (car (cdr (or (member 3 lst)
(member x lst))))))
(simplify g1)
(must-be-redundant
(DEFUN-SK G1$1 (LST)
(EXISTS (X)
(CAR (CDR (OR (MEMBER-EQUAL 3 LST)
(MEMBER-EQUAL X LST)))))
:QUANT-OK T))
(defun-sk g2 (lst)
(exists x (car (cdr (or (member 3 lst)
(member x lst))))))
(simplify g2 :untranslate t)
(must-be-redundant
(DEFUN-SK G2$1 (LST)
(EXISTS (X)
(CADR (OR (MEMBER-EQUAL 3 LST)
(MEMBER-EQUAL X LST))))
:QUANT-OK T))
(defun-sk g3 (lst)
(exists x (car (cdr (or (member 3 lst)
(member x lst))))))
(simplify g3 :untranslate nil)
(must-be-redundant
(DEFUN-SK G3$1 (LST)
(EXISTS (X)
(CAR (CDR (IF (MEMBER-EQUAL '3 LST)
(MEMBER-EQUAL '3 LST)
(MEMBER-EQUAL X LST)))))
:QUANT-OK T)))
;;; Test :expand hints
(deftest
(defun-sk foo (y z)
(exists x (equal (append y z)
(append z x y))))
(simplify foo :expand (append y z))
(must-be-redundant
(DEFUN-SK FOO$1 (Y Z)
(EXISTS (X)
(EQUAL (IF (CONSP Y)
(CONS (CAR Y) (APPEND (CDR Y) Z))
Z)
(APPEND Z X Y)))
:QUANT-OK T)))
; Same as above but slightly different :expand syntax.
(deftest
(defun-sk foo (y z)
(exists x (equal (append y z)
(append z x y))))
(simplify foo :expand ((append y z)))
(must-be-redundant
(DEFUN-SK FOO$1 (Y Z)
(EXISTS (X)
(EQUAL (IF (CONSP Y)
(CONS (CAR Y) (APPEND (CDR Y) Z))
Z)
(APPEND Z X Y)))
:QUANT-OK T)))
; Same as above but wilder :expand hint.
(deftest
(defun-sk foo (y z)
(exists x (equal (append y z)
(append z x y))))
(simplify foo :expand ((:free (z) (append y z))))
(must-be-redundant
(DEFUN-SK FOO$1 (Y Z)
(EXISTS (X)
(EQUAL (IF (CONSP Y)
(CONS (CAR Y) (APPEND (CDR Y) Z))
Z)
(APPEND Z X Y)))
:QUANT-OK T)))
;;; Test :must-simplify
(deftest
(defun-sk foo (y)
(exists x (member-equal x y)))
(must-fail (simplify foo))
(must-fail (simplify foo :must-simplify t))
(simplify foo :must-simplify nil)
(must-be-redundant
(DEFUN-SK FOO$1 (Y)
(EXISTS (X) (MEMBER-EQUAL X Y))
:QUANT-OK T)))
;;; The following test fails without the use of :extra-bindings-ok in the
;;; computed hint that proves F-BECOMES-F$1 from F-BECOMES-F$1-LEMMA. This
;;; problem cannot arise for defun (as opposed to defun-sk), because the
;;; implementation of simplify-defun does not generate any uses of :instance.
(deftest
(defund foo (a)
(declare (xargs :guard t))
(list a))
(defthm member-equal-foo
(member-equal a (foo a))
:hints (("Goal" :in-theory (enable foo))))
(defun my-equiv (x y)
(declare (xargs :guard t))
(equal x y))
(defequiv my-equiv)
(defun my-if (x y z)
(declare (xargs :guard t))
(if x y z))
(defthm iff-implies-equal-my-if-1
(implies (iff x x-equiv)
(equal (my-if x y z) (my-if x-equiv y z)))
:rule-classes (:congruence))
(defthm my-equiv-implies-equal-my-if-1
(implies (my-equiv x x-equiv)
(equal (my-if x y z) (my-if x-equiv y z)))
:rule-classes (:congruence))
(defun-sk f (x y)
(forall a (my-if (member-equal a (foo a)) x y)))
(simplify f
:simplify-body (my-if @ _ _))
(must-fail
; I initially wrote the following incorrectly. The error message was wrong --
; ACL2 complained that the error message isn't an embedded event form. This is
; actually a problem with defun-sk, with a fix expected in April 2018. Adding
; this must-fail form actually does no good in regression testing, since
; failure is silent; that is, the must-fail form succeeded quietly even before
; fixing the complaint. But we include it here as a reminder, and in case one
; wants to test manually.
(DEFUN-SK F$1 (A)
(FORALL (A) (MY-IF T X Y))
:QUANT-OK T))
(must-be-redundant
(DEFUN-SK F$1 (X Y)
(FORALL (A) (MY-IF T X Y))
:QUANT-OK T))
)
; Test of preserving prog2$ and cw.
(deftest
(local (in-theory (disable prog2$-fn))) ; avoid blowing away prog2$
(defun-sk foo (x)
(exists y (equal (cons x y)
(cons (prog2$ (cw "Hello ~x0 ~x1" x y) (car y))
y))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (X)
(EXISTS (Y)
(EQUAL X
(PROG2$ (CW "Hello ~x0 ~x1" X Y)
(CAR Y))))
:QUANT-OK T)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Simplify-defun-sk2 tests
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(deftest
(include-book ; newline to break possible dependency (probably unnecessary)
"kestrel/soft/top" :dir :system)
(defunvar ?f1 (* *) => *)
(defun-sk2 g1[?f1] (x y)
(forall z
(equal (cdr (cons 3 (?f1 x z)))
(?f1 y z))))
(simplify g1[?f1])
(MUST-BE-REDUNDANT
(DEFUN-SK2 G1[?F1]$1 (X Y)
(FORALL (Z)
(EQUAL (?F1 X Z)
(?F1 Y Z)))
:QUANT-OK T)))
| true |
; Copyright (C) 2015, 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.
; Since the official transformation is simplify, most of the tests here call
; simplify even though this file is about simplifying defun-sk forms, not defun
; forms. We let a few of the initial ones call simplify-defun-sk just to test
; that simplify-defun-sk continues to work.
(in-package "ACL2")
(include-book "simplify")
(include-book "std/testing/must-be-redundant" :dir :system)
(include-book "std/testing/must-fail" :dir :system)
(include-book "kestrel/utilities/deftest" :dir :system)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Simplify-defun-sk tests
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun fix-true-listp (lst)
(if (consp lst)
(cons (car lst)
(fix-true-listp (cdr lst)))
nil))
(defthm member-fix-true-listp
(iff (member a (fix-true-listp lst))
(member a lst)))
; Basic exists test for one bound variable
(deftest
(defun-sk foo (lst)
(exists x (member-equal x (fix-true-listp lst))))
(simplify-defun-sk foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(EXISTS (X) (MEMBER-EQUAL X LST))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST)))))
; As above, but with member, which introduces a LET. We can probably live with
; that. NOTE: We are blowing away prog2$ here; otherwise this test fails.
(deftest
(defun-sk foo (lst)
(exists x (member x (fix-true-listp lst))))
(simplify-defun-sk foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(EXISTS (X)
(MEMBER-EQUAL X LST))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST)))))
; Basic exists test for more than one bound variable
(deftest
(defun-sk foo (lst)
(exists (x y) (member-equal (cons x y) (fix-true-listp lst))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(EXISTS (X Y)
(MEMBER-EQUAL (CONS X Y) LST))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST)))))
; Basic forall test for one bound variable
(deftest
(defun-sk foo (lst)
(forall x (not (member-equal x (fix-true-listp lst)))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(FORALL (X) (NOT (MEMBER-EQUAL X LST)))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST)))))
; Basic forall test for more than one bound variable
(deftest
(defun-sk foo (lst)
(forall (x y) (not (member-equal (cons x y) (fix-true-listp lst)))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(FORALL (X Y)
(NOT (MEMBER-EQUAL (CONS X Y) LST)))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST)))))
; Test for empty formals.
(deftest
(defun-sk foo ()
(forall (x y) (not (member-equal (cons x y) (fix-true-listp y)))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 ()
(FORALL (X Y)
(NOT (MEMBER-EQUAL (CONS X Y) Y)))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO) (FOO$1)))))
; Test for more than one formal; also tests that UNTRANSLATE is called with IFF
; flag, so that result uses OR.
(deftest
(defun-sk foo (u v)
(exists (x y) (or (member-equal (cons x y) (fix-true-listp u))
(member-equal (cons x y) (fix-true-listp v)))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (U V)
(EXISTS (X Y)
(OR (MEMBER-EQUAL (CONS X Y) U)
(MEMBER-EQUAL (CONS X Y) V)))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO U V) (FOO$1 U V)))))
; Test of pattern for :simplify-body
(deftest
(defun-sk foo (u v)
(exists (x y) (or (member-equal (cons x y) (fix-true-listp u))
(member-equal (cons x y) (fix-true-listp v)))))
(simplify foo
:simplify-body (or _ @))
(must-be-redundant
(DEFUN-SK FOO$1 (U V)
(EXISTS (X Y)
(OR (MEMBER-EQUAL (CONS X Y) (FIX-TRUE-LISTP U))
(MEMBER-EQUAL (CONS X Y) V)))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO U V) (FOO$1 U V)))))
; Test some options
(deftest
(defun-sk foo (lst)
(forall x (not (member-equal x (fix-true-listp lst))))
:strengthen t
:rewrite :direct
:witness-dcls ((declare (xargs :non-executable nil))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(FORALL (X) (NOT (MEMBER-EQUAL X LST)))
:QUANT-OK T
:WITNESS-DCLS ((DECLARE (XARGS :NON-EXECUTABLE NIL)))
:STRENGTHEN T
:REWRITE :DIRECT)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST)))))
; Test of :new-enable
(deftest
(defun-sk foo (lst)
(exists x (member-equal x (fix-true-listp lst))))
(simplify foo)
(assert-event (not (disabledp '(:definition foo$1))))
(simplify foo :new-enable nil)
(assert-event (disabledp '(:definition foo$2)))
(simplify foo :new-enable t)
(assert-event (not (disabledp '(:definition foo$3)))))
(deftest
(defun-sk foo (lst)
(exists x (member-equal x (fix-true-listp lst))))
(in-theory (disable foo))
(simplify foo)
(assert-event (disabledp '(:definition foo$1)))
(simplify foo :new-enable t)
(assert-event (not (disabledp '(:definition foo$2))))
(simplify foo :new-enable nil)
(assert-event (disabledp '(:definition foo$3))))
; Test of :guard-hints.
(deftest
(defun-sk foo (lst)
(exists x (member-equal x (fix-true-listp lst))))
(verify-guards fix-true-listp)
(verify-guards foo)
(defun my-true-listp (x)
(declare (xargs :guard t))
(true-listp x))
(in-theory (disable my-true-listp (tau-system)))
(must-fail
; This test is only of interest for its output. To see the output, submit it
; without the surrounding call of must-fail. The output should consist of the
; following clean and succinct error message.
#||
ACL2 Error in event processing: Guard verification has failed for
FOO$1. See :DOC apt::simplify-failure for some ways to address this
failure.
||#
(simplify foo
:guard (my-true-listp lst)))
(simplify foo
:guard (my-true-listp lst)
:guard-hints (("Goal" :in-theory (enable my-true-listp))))
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(EXISTS (X) (MEMBER-EQUAL X LST))
:QUANT-OK T
:WITNESS-DCLS ((DECLARE (XARGS :GUARD (MY-TRUE-LISTP LST)
:VERIFY-GUARDS NIL)))))
(assert-event (eq (symbol-class 'foo$1 (w state)) :common-lisp-compliant)))
; Tests for more than one match
(deftest
(defstub stub0 (x y z) t)
(defun-sk foo (x y)
(exists z
(equal (list (list (list
(* 3 (+ 1 (+ 1 x)))
(* 3 (+ 1 (+ 1 x)))
(* 4 5 (+ 1 (+ 1 y))))))
(stub0 x y z))))
; Underscore variables other than _ must be distinct for matches to different
; terms:
(must-fail (simplify foo
:simplify-body (list (* 3 @1)
_a
(* _a 5 @2))))
; @-variables other than @ must be distinct for matches to different terms:
(must-fail (simplify foo
:simplify-body (list (* 3 @a)
@a
_)))
; This one is fine.
(simplify foo
:simplify-body (list @1
_1
(* _2 5 @2)))
; So is this.
(simplify foo
:simplify-body (list @
_
(* _ 5 @)))
(must-be-redundant
(DEFUN-SK FOO$1 (X Y)
(EXISTS (Z)
(EQUAL (LIST (LIST (LIST (+ 6 (* 3 X))
(* 3 (+ 1 (+ 1 X)))
(* 4 5 (+ 2 Y)))))
(STUB0 X Y Z)))
:QUANT-OK T))
(must-be-redundant
(DEFUN-SK FOO$2 (X Y)
(EXISTS (Z)
(EQUAL (LIST (LIST (LIST (+ 6 (* 3 X))
(* 3 (+ 1 (+ 1 X)))
(* 4 5 (+ 2 Y)))))
(STUB0 X Y Z)))
:QUANT-OK T)))
; Test the use of directed-untranslate.
(deftest
(defun-sk foo (lst)
(exists x (if (consp x)
(member-equal x (fix-true-listp lst))
nil)))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (LST)
(EXISTS (X) (IF (CONSP X)
(MEMBER-EQUAL X LST)
NIL))
:QUANT-OK T)
(DEFTHM FOO-BECOMES-FOO$1
(IFF (FOO LST) (FOO$1 LST))))
(defun-sk foo2a (lst)
(exists x (if (consp x)
(member-equal x (fix-true-listp lst))
nil)))
(simplify foo2a)
(must-be-redundant
(DEFUN-SK FOO2A$1 (LST)
(EXISTS (X) (IF (CONSP X)
(MEMBER-EQUAL X LST)
NIL))
:QUANT-OK T)
(DEFTHM FOO2A-BECOMES-FOO2A$1
(IFF (FOO2A LST) (FOO2A$1 LST))))
(defun-sk foo2b (lst) ; same as foo2a
(exists x (if (consp x)
(member-equal x (fix-true-listp lst))
nil)))
(simplify foo2b :untranslate t)
(must-be-redundant
(DEFUN-SK FOO2B$1 (LST)
(EXISTS (X) (AND (CONSP X) (MEMBER-EQUAL X LST)))
:QUANT-OK T)
(DEFTHM FOO2B-BECOMES-FOO2B$1
(IFF (FOO2B LST) (FOO2B$1 LST)))))
;;; Test :untranslate hint.
;;; NOTE: We are blowing away prog2$ here; otherwise this test fails.
(deftest
(defun-sk g1 (lst)
(exists x (car (cdr (or (member 3 lst)
(member x lst))))))
(simplify g1)
(must-be-redundant
(DEFUN-SK G1$1 (LST)
(EXISTS (X)
(CAR (CDR (OR (MEMBER-EQUAL 3 LST)
(MEMBER-EQUAL X LST)))))
:QUANT-OK T))
(defun-sk g2 (lst)
(exists x (car (cdr (or (member 3 lst)
(member x lst))))))
(simplify g2 :untranslate t)
(must-be-redundant
(DEFUN-SK G2$1 (LST)
(EXISTS (X)
(CADR (OR (MEMBER-EQUAL 3 LST)
(MEMBER-EQUAL X LST))))
:QUANT-OK T))
(defun-sk g3 (lst)
(exists x (car (cdr (or (member 3 lst)
(member x lst))))))
(simplify g3 :untranslate nil)
(must-be-redundant
(DEFUN-SK G3$1 (LST)
(EXISTS (X)
(CAR (CDR (IF (MEMBER-EQUAL '3 LST)
(MEMBER-EQUAL '3 LST)
(MEMBER-EQUAL X LST)))))
:QUANT-OK T)))
;;; Test :expand hints
(deftest
(defun-sk foo (y z)
(exists x (equal (append y z)
(append z x y))))
(simplify foo :expand (append y z))
(must-be-redundant
(DEFUN-SK FOO$1 (Y Z)
(EXISTS (X)
(EQUAL (IF (CONSP Y)
(CONS (CAR Y) (APPEND (CDR Y) Z))
Z)
(APPEND Z X Y)))
:QUANT-OK T)))
; Same as above but slightly different :expand syntax.
(deftest
(defun-sk foo (y z)
(exists x (equal (append y z)
(append z x y))))
(simplify foo :expand ((append y z)))
(must-be-redundant
(DEFUN-SK FOO$1 (Y Z)
(EXISTS (X)
(EQUAL (IF (CONSP Y)
(CONS (CAR Y) (APPEND (CDR Y) Z))
Z)
(APPEND Z X Y)))
:QUANT-OK T)))
; Same as above but wilder :expand hint.
(deftest
(defun-sk foo (y z)
(exists x (equal (append y z)
(append z x y))))
(simplify foo :expand ((:free (z) (append y z))))
(must-be-redundant
(DEFUN-SK FOO$1 (Y Z)
(EXISTS (X)
(EQUAL (IF (CONSP Y)
(CONS (CAR Y) (APPEND (CDR Y) Z))
Z)
(APPEND Z X Y)))
:QUANT-OK T)))
;;; Test :must-simplify
(deftest
(defun-sk foo (y)
(exists x (member-equal x y)))
(must-fail (simplify foo))
(must-fail (simplify foo :must-simplify t))
(simplify foo :must-simplify nil)
(must-be-redundant
(DEFUN-SK FOO$1 (Y)
(EXISTS (X) (MEMBER-EQUAL X Y))
:QUANT-OK T)))
;;; The following test fails without the use of :extra-bindings-ok in the
;;; computed hint that proves F-BECOMES-F$1 from F-BECOMES-F$1-LEMMA. This
;;; problem cannot arise for defun (as opposed to defun-sk), because the
;;; implementation of simplify-defun does not generate any uses of :instance.
(deftest
(defund foo (a)
(declare (xargs :guard t))
(list a))
(defthm member-equal-foo
(member-equal a (foo a))
:hints (("Goal" :in-theory (enable foo))))
(defun my-equiv (x y)
(declare (xargs :guard t))
(equal x y))
(defequiv my-equiv)
(defun my-if (x y z)
(declare (xargs :guard t))
(if x y z))
(defthm iff-implies-equal-my-if-1
(implies (iff x x-equiv)
(equal (my-if x y z) (my-if x-equiv y z)))
:rule-classes (:congruence))
(defthm my-equiv-implies-equal-my-if-1
(implies (my-equiv x x-equiv)
(equal (my-if x y z) (my-if x-equiv y z)))
:rule-classes (:congruence))
(defun-sk f (x y)
(forall a (my-if (member-equal a (foo a)) x y)))
(simplify f
:simplify-body (my-if @ _ _))
(must-fail
; I initially wrote the following incorrectly. The error message was wrong --
; ACL2 complained that the error message isn't an embedded event form. This is
; actually a problem with defun-sk, with a fix expected in April 2018. Adding
; this must-fail form actually does no good in regression testing, since
; failure is silent; that is, the must-fail form succeeded quietly even before
; fixing the complaint. But we include it here as a reminder, and in case one
; wants to test manually.
(DEFUN-SK F$1 (A)
(FORALL (A) (MY-IF T X Y))
:QUANT-OK T))
(must-be-redundant
(DEFUN-SK F$1 (X Y)
(FORALL (A) (MY-IF T X Y))
:QUANT-OK T))
)
; Test of preserving prog2$ and cw.
(deftest
(local (in-theory (disable prog2$-fn))) ; avoid blowing away prog2$
(defun-sk foo (x)
(exists y (equal (cons x y)
(cons (prog2$ (cw "Hello ~x0 ~x1" x y) (car y))
y))))
(simplify foo)
(must-be-redundant
(DEFUN-SK FOO$1 (X)
(EXISTS (Y)
(EQUAL X
(PROG2$ (CW "Hello ~x0 ~x1" X Y)
(CAR Y))))
:QUANT-OK T)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Simplify-defun-sk2 tests
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(deftest
(include-book ; newline to break possible dependency (probably unnecessary)
"kestrel/soft/top" :dir :system)
(defunvar ?f1 (* *) => *)
(defun-sk2 g1[?f1] (x y)
(forall z
(equal (cdr (cons 3 (?f1 x z)))
(?f1 y z))))
(simplify g1[?f1])
(MUST-BE-REDUNDANT
(DEFUN-SK2 G1[?F1]$1 (X Y)
(FORALL (Z)
(EQUAL (?F1 X Z)
(?F1 Y Z)))
:QUANT-OK T)))
|
[
{
"context": "*********\nPRODIGY Version 2.01 \nCopyright 1989 by Steven Minton, Craig Knoblock, Dan Kuokka and Jaime Carbonell\n\n",
"end": 137,
"score": 0.9998752474784851,
"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.9998666644096375,
"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.9998593330383301,
"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.9998735189437866,
"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.9998723864555359,
"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.9998781085014343,
"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.9998735189437866,
"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.9998686909675598,
"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.9998568296432495,
"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.9998615384101868,
"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.9998652935028076,
"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.9998412132263184,
"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.999840497970581,
"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.9998558163642883,
"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.9998604655265808,
"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.9998547434806824,
"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.999862790107727,
"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.9999238848686218,
"start": 925,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "============================\n; This was written by dkahn in june and july 1989.\n; The user must be careful",
"end": 1522,
"score": 0.9972932934761047,
"start": 1517,
"tag": "USERNAME",
"value": "dkahn"
}
] |
algorithm/java-ml/UCI-small/prodigy/domains/frozenblocksworld/blocksgraph.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.
*******************************************************************************|#
;==========================================================================
; File: graphics.lisp Version: 0.0 Created: 3/2/88
;
; Locked by: none. Modified: 4/4/88
;
; Purpose: To standardize domain graphics for Prodigy.
;
;==========================================================================
; This was written by dkahn in june and july 1989.
; The user must be careful not to use more blocks in the domain then can fit
; on the graphics window, otherwise the graphics will not work well, although
; I don't think it will crash. The objects scale automatically to the width
; and height of the characters used to label them. The height is, of course,
; determined by the font used, but the width may be controlled by the user
; when writing the problems for the domain.
(require 'pg-system)
(use-package (symbol-name 'pg))
(proclaim
'(special *DOMAIN-WINDOW* *FINISH* *NODE-MSG-X* *NODE-MSG-Y*
*STATE-MSG-X* *STATE-MSG-Y* *START-STATE* *WIDTH*
*DOMAIN-STATE* *DOMAIN-NODE* *DOMAIN-GRAPHICS*))
(proclaim
'(special *GRAPHICS-INFO* *DOMAIN-CHAR-HEIGHT* *GRAPHICS-INFO*
*BLOCK-SEPARATION-X* *BLOCK-SEPARATION-Y*
*DOMAIN-HEIGHT* *DOMAIN-WIDTH* *HAND-LOC-X* *HAND-LOC-Y*
*DOMAIN-CHAR-WIDTH* *X-DIM* *Y-DIM* *START-X* *START-Y*
*BLOCK-WIDTH* *BLOCK-HEIGHT* *DOMAIN-LINES* *DOMAIN-COLS* ))
;==========================================================================
; Domain Dependent Functions
;==========================================================================
;; RESET-DOMAIN-GRAPHICS-PARAMETERS should be called when a new problem is
;; loaded. This function sets graphics variables to null. In particular,
;; the variables *NODE-MSG-X*, *NODE-MSG-Y*, which determine the location
;; of the node message in the graphics window and *STATE-MSG-X*, and
;; *STATE-MSG-Y* which determine the location of the state message in the
;; graphics window should be set to null in this function.
;;
(defun reset-domain-graphics-parameters ()
(psetq *NODE-MSG-X* NIL
*NODE-MSG-Y* NIL
*STATE-MSG-X* NIL
*STATE-MSG-Y* NIL
*WIDTH* NIL
*DOMAIN-CHAR-HEIGHT* NIL
*DOMAIN-CHAR-WIDTH* NIL ; MAXIMUM WIDTH OF an object
*GRAPHICS-INFO* NIL)
(mapcar #'makunbound '(*DOMAIN-HEIGHT* *DOMAIN-LINES* *DOMAIN-WIDTH*
*START-X* *START-Y* *BLOCK-WIDTH* *BLOCK-HEIGHT*
*BLOCK-SEPARATION-X* *BLOCK-SEPARATION-Y* *HALF-BLOCK*
*HAND-LOC-X* *HAND-LOC-Y* *HAND-DATA*))
)
;--------------------------------------------------------------------------
;; DETERMINE-DOMAIN-GRAPHICS-PARAMETERS SETS the variables used in drawing
;; the domain graphics for a given problem. This routine should also
;; determine the location of the node and state messages: i.e., set the
;; variables (*NODE-MSG-Y*, *NODE-MSG-X*, *STATE-MSG-X*, *STATE-MSG-Y*).
;;
(defun determine-domain-graphics-parameters (problem)
(setq *GRAPHICS-INFO* (init-a-list problem))
; (fill-in-graphics-info *start-state*)
(setq *WIDTH* 0
*DOMAIN-CHAR-HEIGHT* (pg-text-height *DOMAIN-WINDOW* "A")
*DOMAIN-HEIGHT* (pg-window-height *DOMAIN-WINDOW*)
*DOMAIN-WIDTH* (pg-window-width *DOMAIN-WINDOW*)
*DOMAIN-LINES* (truncate *DOMAIN-HEIGHT* *DOMAIN-CHAR-HEIGHT*)
*DOMAIN-CHAR-WIDTH* (pg-text-width *DOMAIN-WINDOW* "A")
*DOMAIN-COLS* (truncate *DOMAIN-WIDTH* *DOMAIN-CHAR-WIDTH*)
*X-DIM* (count-objects *STATIC-STATE-PREDS*)
*Y-DIM* *X-DIM*
*START-X* (truncate (* .05 *DOMAIN-WIDTH*)); to be added to
*START-Y* (- *DOMAIN-HEIGHT* (truncate (* .15 *DOMAIN-HEIGHT*)))
; to be subtracted from
*NODE-MSG-X* (+ *START-X* 10)
*NODE-MSG-Y* (- *DOMAIN-HEIGHT* 5 *DOMAIN-CHAR-HEIGHT*)
*STATE-MSG-X* (+ *START-X* 10)
*STATE-MSG-Y* (- *NODE-MSG-Y* 2 *DOMAIN-CHAR-HEIGHT*)
*BLOCK-WIDTH* (+ 10 (* *DOMAIN-CHAR-WIDTH* (max-char-in-label problem)))
*BLOCK-HEIGHT* (+ 6 *DOMAIN-CHAR-HEIGHT*)
*BLOCK-SEPARATION-X* 5
*BLOCK-SEPARATION-Y* 0
*HALF-BLOCK* (truncate *BLOCK-HEIGHT* 2)
*HAND-LOC-X* (truncate (* .6 *DOMAIN-WIDTH*))
*HAND-LOC-Y* (+ *BLOCK-HEIGHT* 20)
*HAND-DATA* `((,(- *HAND-LOC-X* 2) ,(- *HAND-LOC-Y* *HALF-BLOCK*)) ;start
(0 ,(- 0 *HALF-BLOCK* 4)) ;left side
(,(+ 2 (truncate *BLOCK-WIDTH* (/ .4))) 0) ; left top
(0 ,(- (+ *block-height* 5) *HAND-LOC-Y*)) ; up arm
(,(truncate *block-width* (/ .2)) 0) ; top of arm
(0 ,(- *HAND-LOC-Y* (+ *block-height* 5))); down arm
(,(+ 2 (truncate *BLOCK-WIDTH* (/ .4))) 0); right top
(0 ,(+ *HALF-BLOCK* 4)))
)
)
; MAX-CHAR-IN-LABEL moves through the initial state description
; and creates a list of numbers, 0 for each predicate that is not
; OBJECT and the length of the object name for each predicate that
; is OBJECT. It then returns the MAX of the list.
(defun max-char-in-label (preds)
(apply #'max (mapcar #'(lambda (x) (if (eq (car x) 'object)
(length (symbol-name (second x)))
0))
preds)
)
)
(defun last-el (lst)
(car (last lst)))
; In pos-data the x-pos and y-pos are the position of the
; object in space. rest-position is the value to give to x-pos
; when the object is on-table. Y-pos is 0 when the object is
; on-table. Unchanged-flag is used by add-domain-graphic-objects to
; keep track of which objects aren't in the updata list.
(defstruct pos-data
(x-pos nil)
(y-pos nil)
rest-pos
(in-arm-p nil)
(unchanged-flag nil)
)
(defun count-objects (static-preds)
(cond ((null static-preds) 0)
((eq 'object (caar static-preds))
(1+ (count-objects (cdr static-preds))))
(t (count-objects (cdr static-preds)))
)
)
; This sets up the assocation list for *GRAPICS-INFO*.
; It must set-up an assoc for each object instantiated in
; lst. It must then assign to the object a table position.
; x-pos is a counter that holds the table positions. It is
; incremented so that on two objects receive the same table postion.
(defun init-a-list (lst)
(do ((a-list nil) (x-pos 0)) ((null lst) a-list)
(cond ((eq (caar lst) 'object)
(setq a-list
(acons (cadar lst) (make-pos-data :rest-pos x-pos) a-list)
)
(setq x-pos (1+ x-pos))
(pop lst)
)
(t (pop lst)) ; if pred is not static-object
)
)
)
#|
(defun fill-in-graphics-info (lst)
(do () ((null lst) nil)
(setq lst (build-list lst))
)
)
; BUILD-LIST takes a list of initial state predicates
(defun build-list (lst)
(let ((pred (car lst)))
(cond ((null lst) nil)
((eq (car pred) 'on-table)
(update (last-el pred) (pos-data-rest-pos (cdr
(assoc (last-el pred)
*GRAPHICS-INFO*)));X
0); Y
(build-list (cdr lst)))
((eq (car pred) 'holding) (setf (pos-data-rest-pos (cdr
(assoc (last-el pred)
*GRAPHICS-INFO*)))
t))
((and (eq (car pred) 'on) (good-object-p (last-el pred)))
(update (cadr pred) (pos-data-x-pos (cdr
(assoc (last-el pred)
*GRAPHICS-INFO*)))
(1+ (pos-data-y-pos (cdr (assoc (last-el pred)
*GRAPHICS-INFO*)))))
(build-list (cdr lst)))
((eq (caar lst) 'on) (append (list pred) (build-list (cdr lst))))
(t (build-list (cdr LST)))
)
)
)
; GOOD-OBJECT-P is true of all the data in the struct are non-nil
;
(defun good-object-p (object)
(let ((struct (cdr (assoc object *GRAPHICS-INFO*))))
(and (pos-data-x-pos struct)
(pos-data-y-pos struct))
)
)
|#
(defmacro get-x-point (lst)
`(caar ,lst)
)
(defmacro get-y-point (lst)
`(cadar ,lst)
)
;--------------------------------------------------------------------------
;; DRAW-DOMAIN-BACKGROUND uses domain graphics parameters to draw the
;; rear plane for the given domain -- drawn before any domain objects
;; are added to the domain graphics window.
;;
(defun draw-domain-background ())
;--------------------------------------------------------------------------
;; DELETE-DOMAIN-GRAPHIC-OBJECTS erases objects from the domain window.
;; The argument to this function is a list containing predicates to delete.
;; The function must parse the relevant graphics predicates and devise some
;; method for removing them from the domain window.
;;
(defun delete-domain-graphic-objects (state-preds)
(unless (null state-preds)
(let ((pred (caar state-preds)))
(cond ((eq 'on-table pred) (erase-block (cadar state-preds)))
((eq 'on pred) (erase-block (cadar state-preds)))
((eq 'holding pred) (erase-block (cadar state-preds)))
(t nil)
)
)
(delete-domain-graphic-objects (cdr state-preds))
)
)
;--------------------------------------------------------------------------
;; ADD-DOMAIN-GRAPHIC-OBJECTS adds objects to the domain window. This
;; function is the complement of (delete-domain-graphic-objects). The
;; argument to this function may contain predicates irrelevant to graphics,
;; therefore the function must devise a method to parse relevant predicates
;; and add the appropriate objects to the domain window.
;;
; This function is yucky. The state-preds list can contain the relations of
; objects in an arbitrary order. Thus the ON predicate could occur before
; the ON-TABLE of the supporting object (i.e. the list could say A is on B
; before it says B is on the table. The following routine draws every object
; that it can in one pass through the outer loop. It then starts over again
; with a list containing all undone predicates.
; This would be much more elegant with circular lists, but I don't want to
; fool with them now.
(defun add-domain-graphic-objects (state-preds)
(do ((good-a-list nil)
(unchanged-a-list (flag-unchanged-objects state-preds))
(incvar)
(next-list state-preds incvar))
((null next-list))
(setq incvar
(do ((working-list next-list (cdr working-list))
(stack-var nil))
((null working-list) stack-var) ; return list of undone preds
;debug code (format t "here's working-list ~A~%" working-list)
(case (caar working-list)
('on-table (draw-on-table (car working-list))
(setq good-a-list (acons (get-ob working-list) t
good-a-list)))
('holding (draw-in-hand (cadar working-list)))
('on (cond ((good-object-II-p (get-sup working-list) good-a-list)
(setq good-a-list (acons (get-ob working-list)
t good-a-list))
(draw-on-box (car working-list)))
(t (push (car working-list) stack-var))))
) ; end case
)
) ; end setq
)
)
(defun flag-unchanged-objects (pred-list)
;reset all unchanged-flags
(do ((count (1- (length *GRAPHICS-INFO*)) (1- count)))
((minusp count))
(setf (pos-data-unchanged-flag
(cdr (nth count *GRAPHICS-INFO*))) t)
)
; now set to TRUE those that haven't changed.
(dolist (pred pred-list)
;debug code (format t "~%This is pred: ~A" pred)
(cond ((or (eq (car pred) 'on-table)
(eq (car pred) 'on))
(setf (pos-data-unchanged-flag
(cdr (assoc (second pred) *GRAPHICS-INFO*)))
nil)
)
)
)
)
; the following access functions act on a list of predicates the first of
; which should be an ON or an ON-TABLE predicate. get-sub returns the object
; that is underneath in an ON predicate. Get-ob returns the object that is
; being put on the table.
(defun get-sup (preds)
(caddar preds))
(defun get-ob (preds)
(cadar preds))
(defun good-object-II-p (object a-list)
(or (cdr (assoc object a-list))
(pos-data-unchanged-flag (cdr (assoc object *GRAPHICS-INFO*))))
)
#|
(defun good-object-II-p (pred-list good-a-list)
(let* ((pred-1 (car pred-list))
(object (third pred-1))) ; get the object name
(setq pred-list (cdr pred-list))
(cond ((null pred-list) t) ; object is good
((and (member (car pred-1) '(on holding on-table))
(eq object (cadar pred-list)))
; then
nil); bad object
(t (good-object-II-p (cons pred-1 (cdr pred-list))))
)
)
)
|#
;--------------------------------------------------------------------------
;; DRAW-DOMAIN-FOREGROUND uses domain graphics parameters to draw the
;; foremost plane of graphics -- drawn after the domain objects.
;;
(defun draw-domain-foreground ()
(pg-draw-line *DOMAIN-WINDOW* 5 *START-Y* (- *DOMAIN-WIDTH* 5)
*START-Y*)
(draw (get-x-point *HAND-DATA*) (get-y-point *HAND-DATA*) (cdr *HAND-DATA*))
; (terpri) (princ "Paused") (read-char)
)
(defun draw (X1 Y1 x-y-list)
(unless (null x-y-list)
(let ((X2 (+ X1 (get-x-point x-y-list)))
(Y2 (+ Y1 (get-y-point x-y-list))))
(pg-draw-line *DOMAIN-WINDOW* X1 Y1 X2 Y2)
(draw X2 Y2 (cdr x-y-list))
)
)
)
; ========================================================================
; Drawing functions for boxes
; ========================================================================
; DRAW-ON-TABLE draws the box listed in the predicate on the table.
; Each box will have a predetermined table position
(defun draw-on-table (pred)
(let ((info-ob (cdr (assoc (last-el pred) *graphics-info*))))
(draw-box-with-label (pos-data-rest-pos info-ob) 0 (last-el pred))
(update (last-el pred) (pos-data-rest-pos info-ob) 0)
)
)
; DRAW-ON-BOX draws an object on top of another one.
; It also updates the data on the upper box.
(defun draw-on-box (pred)
(let ((support-ob (cdr (assoc (third pred) *graphics-info*)))
;(resting-ob (car (assoc (third pred) *graphics-info*)))
)
(draw-box-with-label (pos-data-x-pos support-ob)
(1+ (pos-data-y-pos support-ob))
(cadr pred))
(update (cadr pred) (pos-data-x-pos support-ob)
(1+ (pos-data-y-pos support-ob)))
)
)
; DRAW-IN-HAND will draw a box in the hand of the robot.
; No update is nescessary.
(defun draw-in-hand (name)
(pg-with-window *DOMAIN-WINDOW*
(pg-frame-rect
*HAND-LOC-X*
(- *HAND-LOC-Y* *BLOCK-HEIGHT*)
(+ *HAND-LOC-X* *BLOCK-WIDTH*)
*HAND-LOC-Y*)
)
(pg-write-text *DOMAIN-WINDOW*
(+ *HAND-LOC-X* 5)
(- *HAND-LOC-Y* 5)
(symbol-name name)
)
(setf (pos-data-in-arm-p (cdr (assoc name *GRAPHICS-INFO*))) t)
)
; UPDATE changes the location var of the block.
;
;
(defun update (keyname X Y)
(let ((structure (cdr (assoc keyname *GRAPHICS-INFO*))))
(setf (pos-data-x-pos structure) X)
(setf (pos-data-y-pos structure) Y)
)
)
; DRAW-BOX-WITH-LABEL will draw a little box and then write the print
; name of the object inside it.
; location is a small integer indicating the blocks position in block-space.
; name is a symbol whose print name is going to be the label.
; The block-org-? are the lower left-hand points and
; the corner-? are the upper right-hand points.
(defun draw-box-with-label (x-pos y-pos name)
(let* ((block-org-x (calc-x-from-int x-pos))
(block-org-y (calc-y-from-int y-pos))
(corner-x (+ block-org-x *BLOCK-WIDTH*))
(corner-y (- block-org-y *BLOCK-HEIGHT*))
)
(pg-with-window *DOMAIN-WINDOW*
(pg-frame-rect
block-org-x
corner-y
corner-x
block-org-y)
)
(pg-write-text *DOMAIN-WINDOW*
(+ block-org-x 5)
(- block-org-y 5)
(symbol-name name)
)
)
)
; CALC-X-FROM-INT will return a pixel value give a grid value.
(defun calc-x-from-int (int)
(+ (* (+ *BLOCK-WIDTH* *BLOCK-SEPARATION-X*) int) *START-X*)
)
; CALC-Y-FROM-INT will return a pixel value give a grid value.
(defun calc-y-from-int (int)
(- *START-Y* (* (+ *BLOCK-HEIGHT* *BLOCK-SEPARATION-Y*) int))
)
(defun erase-block (name)
(let (x-pos y-pos block-org-x block-org-y)
(cond ((pos-data-in-arm-p (cdr (assoc name *GRAPHICS-INFO*)))
(setq block-org-x *HAND-LOC-X* block-org-y *HAND-LOC-Y*)
(setf (pos-data-in-arm-p (cdr (assoc name *GRAPHICS-INFO*))) nil)
)
(t (setq x-pos
(pos-data-x-pos (cdr (assoc name *GRAPHICS-INFO*)))
y-pos
(pos-data-y-pos (cdr (assoc name *GRAPHICS-INFO*))))
(setq block-org-x (calc-x-from-int x-pos))
(setq block-org-y (calc-y-from-int y-pos)))
)
(pg-with-window *DOMAIN-WINDOW*
(pg-erase-rect block-org-x
(- block-org-y *BLOCK-HEIGHT*)
(+ block-org-x *BLOCK-WIDTH*)
block-org-y)
)
)
)
(provide 'pg-state)
|
4315
|
#|
*******************************************************************************
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.
*******************************************************************************|#
;==========================================================================
; File: graphics.lisp Version: 0.0 Created: 3/2/88
;
; Locked by: none. Modified: 4/4/88
;
; Purpose: To standardize domain graphics for Prodigy.
;
;==========================================================================
; This was written by dkahn in june and july 1989.
; The user must be careful not to use more blocks in the domain then can fit
; on the graphics window, otherwise the graphics will not work well, although
; I don't think it will crash. The objects scale automatically to the width
; and height of the characters used to label them. The height is, of course,
; determined by the font used, but the width may be controlled by the user
; when writing the problems for the domain.
(require 'pg-system)
(use-package (symbol-name 'pg))
(proclaim
'(special *DOMAIN-WINDOW* *FINISH* *NODE-MSG-X* *NODE-MSG-Y*
*STATE-MSG-X* *STATE-MSG-Y* *START-STATE* *WIDTH*
*DOMAIN-STATE* *DOMAIN-NODE* *DOMAIN-GRAPHICS*))
(proclaim
'(special *GRAPHICS-INFO* *DOMAIN-CHAR-HEIGHT* *GRAPHICS-INFO*
*BLOCK-SEPARATION-X* *BLOCK-SEPARATION-Y*
*DOMAIN-HEIGHT* *DOMAIN-WIDTH* *HAND-LOC-X* *HAND-LOC-Y*
*DOMAIN-CHAR-WIDTH* *X-DIM* *Y-DIM* *START-X* *START-Y*
*BLOCK-WIDTH* *BLOCK-HEIGHT* *DOMAIN-LINES* *DOMAIN-COLS* ))
;==========================================================================
; Domain Dependent Functions
;==========================================================================
;; RESET-DOMAIN-GRAPHICS-PARAMETERS should be called when a new problem is
;; loaded. This function sets graphics variables to null. In particular,
;; the variables *NODE-MSG-X*, *NODE-MSG-Y*, which determine the location
;; of the node message in the graphics window and *STATE-MSG-X*, and
;; *STATE-MSG-Y* which determine the location of the state message in the
;; graphics window should be set to null in this function.
;;
(defun reset-domain-graphics-parameters ()
(psetq *NODE-MSG-X* NIL
*NODE-MSG-Y* NIL
*STATE-MSG-X* NIL
*STATE-MSG-Y* NIL
*WIDTH* NIL
*DOMAIN-CHAR-HEIGHT* NIL
*DOMAIN-CHAR-WIDTH* NIL ; MAXIMUM WIDTH OF an object
*GRAPHICS-INFO* NIL)
(mapcar #'makunbound '(*DOMAIN-HEIGHT* *DOMAIN-LINES* *DOMAIN-WIDTH*
*START-X* *START-Y* *BLOCK-WIDTH* *BLOCK-HEIGHT*
*BLOCK-SEPARATION-X* *BLOCK-SEPARATION-Y* *HALF-BLOCK*
*HAND-LOC-X* *HAND-LOC-Y* *HAND-DATA*))
)
;--------------------------------------------------------------------------
;; DETERMINE-DOMAIN-GRAPHICS-PARAMETERS SETS the variables used in drawing
;; the domain graphics for a given problem. This routine should also
;; determine the location of the node and state messages: i.e., set the
;; variables (*NODE-MSG-Y*, *NODE-MSG-X*, *STATE-MSG-X*, *STATE-MSG-Y*).
;;
(defun determine-domain-graphics-parameters (problem)
(setq *GRAPHICS-INFO* (init-a-list problem))
; (fill-in-graphics-info *start-state*)
(setq *WIDTH* 0
*DOMAIN-CHAR-HEIGHT* (pg-text-height *DOMAIN-WINDOW* "A")
*DOMAIN-HEIGHT* (pg-window-height *DOMAIN-WINDOW*)
*DOMAIN-WIDTH* (pg-window-width *DOMAIN-WINDOW*)
*DOMAIN-LINES* (truncate *DOMAIN-HEIGHT* *DOMAIN-CHAR-HEIGHT*)
*DOMAIN-CHAR-WIDTH* (pg-text-width *DOMAIN-WINDOW* "A")
*DOMAIN-COLS* (truncate *DOMAIN-WIDTH* *DOMAIN-CHAR-WIDTH*)
*X-DIM* (count-objects *STATIC-STATE-PREDS*)
*Y-DIM* *X-DIM*
*START-X* (truncate (* .05 *DOMAIN-WIDTH*)); to be added to
*START-Y* (- *DOMAIN-HEIGHT* (truncate (* .15 *DOMAIN-HEIGHT*)))
; to be subtracted from
*NODE-MSG-X* (+ *START-X* 10)
*NODE-MSG-Y* (- *DOMAIN-HEIGHT* 5 *DOMAIN-CHAR-HEIGHT*)
*STATE-MSG-X* (+ *START-X* 10)
*STATE-MSG-Y* (- *NODE-MSG-Y* 2 *DOMAIN-CHAR-HEIGHT*)
*BLOCK-WIDTH* (+ 10 (* *DOMAIN-CHAR-WIDTH* (max-char-in-label problem)))
*BLOCK-HEIGHT* (+ 6 *DOMAIN-CHAR-HEIGHT*)
*BLOCK-SEPARATION-X* 5
*BLOCK-SEPARATION-Y* 0
*HALF-BLOCK* (truncate *BLOCK-HEIGHT* 2)
*HAND-LOC-X* (truncate (* .6 *DOMAIN-WIDTH*))
*HAND-LOC-Y* (+ *BLOCK-HEIGHT* 20)
*HAND-DATA* `((,(- *HAND-LOC-X* 2) ,(- *HAND-LOC-Y* *HALF-BLOCK*)) ;start
(0 ,(- 0 *HALF-BLOCK* 4)) ;left side
(,(+ 2 (truncate *BLOCK-WIDTH* (/ .4))) 0) ; left top
(0 ,(- (+ *block-height* 5) *HAND-LOC-Y*)) ; up arm
(,(truncate *block-width* (/ .2)) 0) ; top of arm
(0 ,(- *HAND-LOC-Y* (+ *block-height* 5))); down arm
(,(+ 2 (truncate *BLOCK-WIDTH* (/ .4))) 0); right top
(0 ,(+ *HALF-BLOCK* 4)))
)
)
; MAX-CHAR-IN-LABEL moves through the initial state description
; and creates a list of numbers, 0 for each predicate that is not
; OBJECT and the length of the object name for each predicate that
; is OBJECT. It then returns the MAX of the list.
(defun max-char-in-label (preds)
(apply #'max (mapcar #'(lambda (x) (if (eq (car x) 'object)
(length (symbol-name (second x)))
0))
preds)
)
)
(defun last-el (lst)
(car (last lst)))
; In pos-data the x-pos and y-pos are the position of the
; object in space. rest-position is the value to give to x-pos
; when the object is on-table. Y-pos is 0 when the object is
; on-table. Unchanged-flag is used by add-domain-graphic-objects to
; keep track of which objects aren't in the updata list.
(defstruct pos-data
(x-pos nil)
(y-pos nil)
rest-pos
(in-arm-p nil)
(unchanged-flag nil)
)
(defun count-objects (static-preds)
(cond ((null static-preds) 0)
((eq 'object (caar static-preds))
(1+ (count-objects (cdr static-preds))))
(t (count-objects (cdr static-preds)))
)
)
; This sets up the assocation list for *GRAPICS-INFO*.
; It must set-up an assoc for each object instantiated in
; lst. It must then assign to the object a table position.
; x-pos is a counter that holds the table positions. It is
; incremented so that on two objects receive the same table postion.
(defun init-a-list (lst)
(do ((a-list nil) (x-pos 0)) ((null lst) a-list)
(cond ((eq (caar lst) 'object)
(setq a-list
(acons (cadar lst) (make-pos-data :rest-pos x-pos) a-list)
)
(setq x-pos (1+ x-pos))
(pop lst)
)
(t (pop lst)) ; if pred is not static-object
)
)
)
#|
(defun fill-in-graphics-info (lst)
(do () ((null lst) nil)
(setq lst (build-list lst))
)
)
; BUILD-LIST takes a list of initial state predicates
(defun build-list (lst)
(let ((pred (car lst)))
(cond ((null lst) nil)
((eq (car pred) 'on-table)
(update (last-el pred) (pos-data-rest-pos (cdr
(assoc (last-el pred)
*GRAPHICS-INFO*)));X
0); Y
(build-list (cdr lst)))
((eq (car pred) 'holding) (setf (pos-data-rest-pos (cdr
(assoc (last-el pred)
*GRAPHICS-INFO*)))
t))
((and (eq (car pred) 'on) (good-object-p (last-el pred)))
(update (cadr pred) (pos-data-x-pos (cdr
(assoc (last-el pred)
*GRAPHICS-INFO*)))
(1+ (pos-data-y-pos (cdr (assoc (last-el pred)
*GRAPHICS-INFO*)))))
(build-list (cdr lst)))
((eq (caar lst) 'on) (append (list pred) (build-list (cdr lst))))
(t (build-list (cdr LST)))
)
)
)
; GOOD-OBJECT-P is true of all the data in the struct are non-nil
;
(defun good-object-p (object)
(let ((struct (cdr (assoc object *GRAPHICS-INFO*))))
(and (pos-data-x-pos struct)
(pos-data-y-pos struct))
)
)
|#
(defmacro get-x-point (lst)
`(caar ,lst)
)
(defmacro get-y-point (lst)
`(cadar ,lst)
)
;--------------------------------------------------------------------------
;; DRAW-DOMAIN-BACKGROUND uses domain graphics parameters to draw the
;; rear plane for the given domain -- drawn before any domain objects
;; are added to the domain graphics window.
;;
(defun draw-domain-background ())
;--------------------------------------------------------------------------
;; DELETE-DOMAIN-GRAPHIC-OBJECTS erases objects from the domain window.
;; The argument to this function is a list containing predicates to delete.
;; The function must parse the relevant graphics predicates and devise some
;; method for removing them from the domain window.
;;
(defun delete-domain-graphic-objects (state-preds)
(unless (null state-preds)
(let ((pred (caar state-preds)))
(cond ((eq 'on-table pred) (erase-block (cadar state-preds)))
((eq 'on pred) (erase-block (cadar state-preds)))
((eq 'holding pred) (erase-block (cadar state-preds)))
(t nil)
)
)
(delete-domain-graphic-objects (cdr state-preds))
)
)
;--------------------------------------------------------------------------
;; ADD-DOMAIN-GRAPHIC-OBJECTS adds objects to the domain window. This
;; function is the complement of (delete-domain-graphic-objects). The
;; argument to this function may contain predicates irrelevant to graphics,
;; therefore the function must devise a method to parse relevant predicates
;; and add the appropriate objects to the domain window.
;;
; This function is yucky. The state-preds list can contain the relations of
; objects in an arbitrary order. Thus the ON predicate could occur before
; the ON-TABLE of the supporting object (i.e. the list could say A is on B
; before it says B is on the table. The following routine draws every object
; that it can in one pass through the outer loop. It then starts over again
; with a list containing all undone predicates.
; This would be much more elegant with circular lists, but I don't want to
; fool with them now.
(defun add-domain-graphic-objects (state-preds)
(do ((good-a-list nil)
(unchanged-a-list (flag-unchanged-objects state-preds))
(incvar)
(next-list state-preds incvar))
((null next-list))
(setq incvar
(do ((working-list next-list (cdr working-list))
(stack-var nil))
((null working-list) stack-var) ; return list of undone preds
;debug code (format t "here's working-list ~A~%" working-list)
(case (caar working-list)
('on-table (draw-on-table (car working-list))
(setq good-a-list (acons (get-ob working-list) t
good-a-list)))
('holding (draw-in-hand (cadar working-list)))
('on (cond ((good-object-II-p (get-sup working-list) good-a-list)
(setq good-a-list (acons (get-ob working-list)
t good-a-list))
(draw-on-box (car working-list)))
(t (push (car working-list) stack-var))))
) ; end case
)
) ; end setq
)
)
(defun flag-unchanged-objects (pred-list)
;reset all unchanged-flags
(do ((count (1- (length *GRAPHICS-INFO*)) (1- count)))
((minusp count))
(setf (pos-data-unchanged-flag
(cdr (nth count *GRAPHICS-INFO*))) t)
)
; now set to TRUE those that haven't changed.
(dolist (pred pred-list)
;debug code (format t "~%This is pred: ~A" pred)
(cond ((or (eq (car pred) 'on-table)
(eq (car pred) 'on))
(setf (pos-data-unchanged-flag
(cdr (assoc (second pred) *GRAPHICS-INFO*)))
nil)
)
)
)
)
; the following access functions act on a list of predicates the first of
; which should be an ON or an ON-TABLE predicate. get-sub returns the object
; that is underneath in an ON predicate. Get-ob returns the object that is
; being put on the table.
(defun get-sup (preds)
(caddar preds))
(defun get-ob (preds)
(cadar preds))
(defun good-object-II-p (object a-list)
(or (cdr (assoc object a-list))
(pos-data-unchanged-flag (cdr (assoc object *GRAPHICS-INFO*))))
)
#|
(defun good-object-II-p (pred-list good-a-list)
(let* ((pred-1 (car pred-list))
(object (third pred-1))) ; get the object name
(setq pred-list (cdr pred-list))
(cond ((null pred-list) t) ; object is good
((and (member (car pred-1) '(on holding on-table))
(eq object (cadar pred-list)))
; then
nil); bad object
(t (good-object-II-p (cons pred-1 (cdr pred-list))))
)
)
)
|#
;--------------------------------------------------------------------------
;; DRAW-DOMAIN-FOREGROUND uses domain graphics parameters to draw the
;; foremost plane of graphics -- drawn after the domain objects.
;;
(defun draw-domain-foreground ()
(pg-draw-line *DOMAIN-WINDOW* 5 *START-Y* (- *DOMAIN-WIDTH* 5)
*START-Y*)
(draw (get-x-point *HAND-DATA*) (get-y-point *HAND-DATA*) (cdr *HAND-DATA*))
; (terpri) (princ "Paused") (read-char)
)
(defun draw (X1 Y1 x-y-list)
(unless (null x-y-list)
(let ((X2 (+ X1 (get-x-point x-y-list)))
(Y2 (+ Y1 (get-y-point x-y-list))))
(pg-draw-line *DOMAIN-WINDOW* X1 Y1 X2 Y2)
(draw X2 Y2 (cdr x-y-list))
)
)
)
; ========================================================================
; Drawing functions for boxes
; ========================================================================
; DRAW-ON-TABLE draws the box listed in the predicate on the table.
; Each box will have a predetermined table position
(defun draw-on-table (pred)
(let ((info-ob (cdr (assoc (last-el pred) *graphics-info*))))
(draw-box-with-label (pos-data-rest-pos info-ob) 0 (last-el pred))
(update (last-el pred) (pos-data-rest-pos info-ob) 0)
)
)
; DRAW-ON-BOX draws an object on top of another one.
; It also updates the data on the upper box.
(defun draw-on-box (pred)
(let ((support-ob (cdr (assoc (third pred) *graphics-info*)))
;(resting-ob (car (assoc (third pred) *graphics-info*)))
)
(draw-box-with-label (pos-data-x-pos support-ob)
(1+ (pos-data-y-pos support-ob))
(cadr pred))
(update (cadr pred) (pos-data-x-pos support-ob)
(1+ (pos-data-y-pos support-ob)))
)
)
; DRAW-IN-HAND will draw a box in the hand of the robot.
; No update is nescessary.
(defun draw-in-hand (name)
(pg-with-window *DOMAIN-WINDOW*
(pg-frame-rect
*HAND-LOC-X*
(- *HAND-LOC-Y* *BLOCK-HEIGHT*)
(+ *HAND-LOC-X* *BLOCK-WIDTH*)
*HAND-LOC-Y*)
)
(pg-write-text *DOMAIN-WINDOW*
(+ *HAND-LOC-X* 5)
(- *HAND-LOC-Y* 5)
(symbol-name name)
)
(setf (pos-data-in-arm-p (cdr (assoc name *GRAPHICS-INFO*))) t)
)
; UPDATE changes the location var of the block.
;
;
(defun update (keyname X Y)
(let ((structure (cdr (assoc keyname *GRAPHICS-INFO*))))
(setf (pos-data-x-pos structure) X)
(setf (pos-data-y-pos structure) Y)
)
)
; DRAW-BOX-WITH-LABEL will draw a little box and then write the print
; name of the object inside it.
; location is a small integer indicating the blocks position in block-space.
; name is a symbol whose print name is going to be the label.
; The block-org-? are the lower left-hand points and
; the corner-? are the upper right-hand points.
(defun draw-box-with-label (x-pos y-pos name)
(let* ((block-org-x (calc-x-from-int x-pos))
(block-org-y (calc-y-from-int y-pos))
(corner-x (+ block-org-x *BLOCK-WIDTH*))
(corner-y (- block-org-y *BLOCK-HEIGHT*))
)
(pg-with-window *DOMAIN-WINDOW*
(pg-frame-rect
block-org-x
corner-y
corner-x
block-org-y)
)
(pg-write-text *DOMAIN-WINDOW*
(+ block-org-x 5)
(- block-org-y 5)
(symbol-name name)
)
)
)
; CALC-X-FROM-INT will return a pixel value give a grid value.
(defun calc-x-from-int (int)
(+ (* (+ *BLOCK-WIDTH* *BLOCK-SEPARATION-X*) int) *START-X*)
)
; CALC-Y-FROM-INT will return a pixel value give a grid value.
(defun calc-y-from-int (int)
(- *START-Y* (* (+ *BLOCK-HEIGHT* *BLOCK-SEPARATION-Y*) int))
)
(defun erase-block (name)
(let (x-pos y-pos block-org-x block-org-y)
(cond ((pos-data-in-arm-p (cdr (assoc name *GRAPHICS-INFO*)))
(setq block-org-x *HAND-LOC-X* block-org-y *HAND-LOC-Y*)
(setf (pos-data-in-arm-p (cdr (assoc name *GRAPHICS-INFO*))) nil)
)
(t (setq x-pos
(pos-data-x-pos (cdr (assoc name *GRAPHICS-INFO*)))
y-pos
(pos-data-y-pos (cdr (assoc name *GRAPHICS-INFO*))))
(setq block-org-x (calc-x-from-int x-pos))
(setq block-org-y (calc-y-from-int y-pos)))
)
(pg-with-window *DOMAIN-WINDOW*
(pg-erase-rect block-org-x
(- block-org-y *BLOCK-HEIGHT*)
(+ block-org-x *BLOCK-WIDTH*)
block-org-y)
)
)
)
(provide 'pg-state)
| 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.
*******************************************************************************|#
;==========================================================================
; File: graphics.lisp Version: 0.0 Created: 3/2/88
;
; Locked by: none. Modified: 4/4/88
;
; Purpose: To standardize domain graphics for Prodigy.
;
;==========================================================================
; This was written by dkahn in june and july 1989.
; The user must be careful not to use more blocks in the domain then can fit
; on the graphics window, otherwise the graphics will not work well, although
; I don't think it will crash. The objects scale automatically to the width
; and height of the characters used to label them. The height is, of course,
; determined by the font used, but the width may be controlled by the user
; when writing the problems for the domain.
(require 'pg-system)
(use-package (symbol-name 'pg))
(proclaim
'(special *DOMAIN-WINDOW* *FINISH* *NODE-MSG-X* *NODE-MSG-Y*
*STATE-MSG-X* *STATE-MSG-Y* *START-STATE* *WIDTH*
*DOMAIN-STATE* *DOMAIN-NODE* *DOMAIN-GRAPHICS*))
(proclaim
'(special *GRAPHICS-INFO* *DOMAIN-CHAR-HEIGHT* *GRAPHICS-INFO*
*BLOCK-SEPARATION-X* *BLOCK-SEPARATION-Y*
*DOMAIN-HEIGHT* *DOMAIN-WIDTH* *HAND-LOC-X* *HAND-LOC-Y*
*DOMAIN-CHAR-WIDTH* *X-DIM* *Y-DIM* *START-X* *START-Y*
*BLOCK-WIDTH* *BLOCK-HEIGHT* *DOMAIN-LINES* *DOMAIN-COLS* ))
;==========================================================================
; Domain Dependent Functions
;==========================================================================
;; RESET-DOMAIN-GRAPHICS-PARAMETERS should be called when a new problem is
;; loaded. This function sets graphics variables to null. In particular,
;; the variables *NODE-MSG-X*, *NODE-MSG-Y*, which determine the location
;; of the node message in the graphics window and *STATE-MSG-X*, and
;; *STATE-MSG-Y* which determine the location of the state message in the
;; graphics window should be set to null in this function.
;;
(defun reset-domain-graphics-parameters ()
(psetq *NODE-MSG-X* NIL
*NODE-MSG-Y* NIL
*STATE-MSG-X* NIL
*STATE-MSG-Y* NIL
*WIDTH* NIL
*DOMAIN-CHAR-HEIGHT* NIL
*DOMAIN-CHAR-WIDTH* NIL ; MAXIMUM WIDTH OF an object
*GRAPHICS-INFO* NIL)
(mapcar #'makunbound '(*DOMAIN-HEIGHT* *DOMAIN-LINES* *DOMAIN-WIDTH*
*START-X* *START-Y* *BLOCK-WIDTH* *BLOCK-HEIGHT*
*BLOCK-SEPARATION-X* *BLOCK-SEPARATION-Y* *HALF-BLOCK*
*HAND-LOC-X* *HAND-LOC-Y* *HAND-DATA*))
)
;--------------------------------------------------------------------------
;; DETERMINE-DOMAIN-GRAPHICS-PARAMETERS SETS the variables used in drawing
;; the domain graphics for a given problem. This routine should also
;; determine the location of the node and state messages: i.e., set the
;; variables (*NODE-MSG-Y*, *NODE-MSG-X*, *STATE-MSG-X*, *STATE-MSG-Y*).
;;
(defun determine-domain-graphics-parameters (problem)
(setq *GRAPHICS-INFO* (init-a-list problem))
; (fill-in-graphics-info *start-state*)
(setq *WIDTH* 0
*DOMAIN-CHAR-HEIGHT* (pg-text-height *DOMAIN-WINDOW* "A")
*DOMAIN-HEIGHT* (pg-window-height *DOMAIN-WINDOW*)
*DOMAIN-WIDTH* (pg-window-width *DOMAIN-WINDOW*)
*DOMAIN-LINES* (truncate *DOMAIN-HEIGHT* *DOMAIN-CHAR-HEIGHT*)
*DOMAIN-CHAR-WIDTH* (pg-text-width *DOMAIN-WINDOW* "A")
*DOMAIN-COLS* (truncate *DOMAIN-WIDTH* *DOMAIN-CHAR-WIDTH*)
*X-DIM* (count-objects *STATIC-STATE-PREDS*)
*Y-DIM* *X-DIM*
*START-X* (truncate (* .05 *DOMAIN-WIDTH*)); to be added to
*START-Y* (- *DOMAIN-HEIGHT* (truncate (* .15 *DOMAIN-HEIGHT*)))
; to be subtracted from
*NODE-MSG-X* (+ *START-X* 10)
*NODE-MSG-Y* (- *DOMAIN-HEIGHT* 5 *DOMAIN-CHAR-HEIGHT*)
*STATE-MSG-X* (+ *START-X* 10)
*STATE-MSG-Y* (- *NODE-MSG-Y* 2 *DOMAIN-CHAR-HEIGHT*)
*BLOCK-WIDTH* (+ 10 (* *DOMAIN-CHAR-WIDTH* (max-char-in-label problem)))
*BLOCK-HEIGHT* (+ 6 *DOMAIN-CHAR-HEIGHT*)
*BLOCK-SEPARATION-X* 5
*BLOCK-SEPARATION-Y* 0
*HALF-BLOCK* (truncate *BLOCK-HEIGHT* 2)
*HAND-LOC-X* (truncate (* .6 *DOMAIN-WIDTH*))
*HAND-LOC-Y* (+ *BLOCK-HEIGHT* 20)
*HAND-DATA* `((,(- *HAND-LOC-X* 2) ,(- *HAND-LOC-Y* *HALF-BLOCK*)) ;start
(0 ,(- 0 *HALF-BLOCK* 4)) ;left side
(,(+ 2 (truncate *BLOCK-WIDTH* (/ .4))) 0) ; left top
(0 ,(- (+ *block-height* 5) *HAND-LOC-Y*)) ; up arm
(,(truncate *block-width* (/ .2)) 0) ; top of arm
(0 ,(- *HAND-LOC-Y* (+ *block-height* 5))); down arm
(,(+ 2 (truncate *BLOCK-WIDTH* (/ .4))) 0); right top
(0 ,(+ *HALF-BLOCK* 4)))
)
)
; MAX-CHAR-IN-LABEL moves through the initial state description
; and creates a list of numbers, 0 for each predicate that is not
; OBJECT and the length of the object name for each predicate that
; is OBJECT. It then returns the MAX of the list.
(defun max-char-in-label (preds)
(apply #'max (mapcar #'(lambda (x) (if (eq (car x) 'object)
(length (symbol-name (second x)))
0))
preds)
)
)
(defun last-el (lst)
(car (last lst)))
; In pos-data the x-pos and y-pos are the position of the
; object in space. rest-position is the value to give to x-pos
; when the object is on-table. Y-pos is 0 when the object is
; on-table. Unchanged-flag is used by add-domain-graphic-objects to
; keep track of which objects aren't in the updata list.
(defstruct pos-data
(x-pos nil)
(y-pos nil)
rest-pos
(in-arm-p nil)
(unchanged-flag nil)
)
(defun count-objects (static-preds)
(cond ((null static-preds) 0)
((eq 'object (caar static-preds))
(1+ (count-objects (cdr static-preds))))
(t (count-objects (cdr static-preds)))
)
)
; This sets up the assocation list for *GRAPICS-INFO*.
; It must set-up an assoc for each object instantiated in
; lst. It must then assign to the object a table position.
; x-pos is a counter that holds the table positions. It is
; incremented so that on two objects receive the same table postion.
(defun init-a-list (lst)
(do ((a-list nil) (x-pos 0)) ((null lst) a-list)
(cond ((eq (caar lst) 'object)
(setq a-list
(acons (cadar lst) (make-pos-data :rest-pos x-pos) a-list)
)
(setq x-pos (1+ x-pos))
(pop lst)
)
(t (pop lst)) ; if pred is not static-object
)
)
)
#|
(defun fill-in-graphics-info (lst)
(do () ((null lst) nil)
(setq lst (build-list lst))
)
)
; BUILD-LIST takes a list of initial state predicates
(defun build-list (lst)
(let ((pred (car lst)))
(cond ((null lst) nil)
((eq (car pred) 'on-table)
(update (last-el pred) (pos-data-rest-pos (cdr
(assoc (last-el pred)
*GRAPHICS-INFO*)));X
0); Y
(build-list (cdr lst)))
((eq (car pred) 'holding) (setf (pos-data-rest-pos (cdr
(assoc (last-el pred)
*GRAPHICS-INFO*)))
t))
((and (eq (car pred) 'on) (good-object-p (last-el pred)))
(update (cadr pred) (pos-data-x-pos (cdr
(assoc (last-el pred)
*GRAPHICS-INFO*)))
(1+ (pos-data-y-pos (cdr (assoc (last-el pred)
*GRAPHICS-INFO*)))))
(build-list (cdr lst)))
((eq (caar lst) 'on) (append (list pred) (build-list (cdr lst))))
(t (build-list (cdr LST)))
)
)
)
; GOOD-OBJECT-P is true of all the data in the struct are non-nil
;
(defun good-object-p (object)
(let ((struct (cdr (assoc object *GRAPHICS-INFO*))))
(and (pos-data-x-pos struct)
(pos-data-y-pos struct))
)
)
|#
(defmacro get-x-point (lst)
`(caar ,lst)
)
(defmacro get-y-point (lst)
`(cadar ,lst)
)
;--------------------------------------------------------------------------
;; DRAW-DOMAIN-BACKGROUND uses domain graphics parameters to draw the
;; rear plane for the given domain -- drawn before any domain objects
;; are added to the domain graphics window.
;;
(defun draw-domain-background ())
;--------------------------------------------------------------------------
;; DELETE-DOMAIN-GRAPHIC-OBJECTS erases objects from the domain window.
;; The argument to this function is a list containing predicates to delete.
;; The function must parse the relevant graphics predicates and devise some
;; method for removing them from the domain window.
;;
(defun delete-domain-graphic-objects (state-preds)
(unless (null state-preds)
(let ((pred (caar state-preds)))
(cond ((eq 'on-table pred) (erase-block (cadar state-preds)))
((eq 'on pred) (erase-block (cadar state-preds)))
((eq 'holding pred) (erase-block (cadar state-preds)))
(t nil)
)
)
(delete-domain-graphic-objects (cdr state-preds))
)
)
;--------------------------------------------------------------------------
;; ADD-DOMAIN-GRAPHIC-OBJECTS adds objects to the domain window. This
;; function is the complement of (delete-domain-graphic-objects). The
;; argument to this function may contain predicates irrelevant to graphics,
;; therefore the function must devise a method to parse relevant predicates
;; and add the appropriate objects to the domain window.
;;
; This function is yucky. The state-preds list can contain the relations of
; objects in an arbitrary order. Thus the ON predicate could occur before
; the ON-TABLE of the supporting object (i.e. the list could say A is on B
; before it says B is on the table. The following routine draws every object
; that it can in one pass through the outer loop. It then starts over again
; with a list containing all undone predicates.
; This would be much more elegant with circular lists, but I don't want to
; fool with them now.
(defun add-domain-graphic-objects (state-preds)
(do ((good-a-list nil)
(unchanged-a-list (flag-unchanged-objects state-preds))
(incvar)
(next-list state-preds incvar))
((null next-list))
(setq incvar
(do ((working-list next-list (cdr working-list))
(stack-var nil))
((null working-list) stack-var) ; return list of undone preds
;debug code (format t "here's working-list ~A~%" working-list)
(case (caar working-list)
('on-table (draw-on-table (car working-list))
(setq good-a-list (acons (get-ob working-list) t
good-a-list)))
('holding (draw-in-hand (cadar working-list)))
('on (cond ((good-object-II-p (get-sup working-list) good-a-list)
(setq good-a-list (acons (get-ob working-list)
t good-a-list))
(draw-on-box (car working-list)))
(t (push (car working-list) stack-var))))
) ; end case
)
) ; end setq
)
)
(defun flag-unchanged-objects (pred-list)
;reset all unchanged-flags
(do ((count (1- (length *GRAPHICS-INFO*)) (1- count)))
((minusp count))
(setf (pos-data-unchanged-flag
(cdr (nth count *GRAPHICS-INFO*))) t)
)
; now set to TRUE those that haven't changed.
(dolist (pred pred-list)
;debug code (format t "~%This is pred: ~A" pred)
(cond ((or (eq (car pred) 'on-table)
(eq (car pred) 'on))
(setf (pos-data-unchanged-flag
(cdr (assoc (second pred) *GRAPHICS-INFO*)))
nil)
)
)
)
)
; the following access functions act on a list of predicates the first of
; which should be an ON or an ON-TABLE predicate. get-sub returns the object
; that is underneath in an ON predicate. Get-ob returns the object that is
; being put on the table.
(defun get-sup (preds)
(caddar preds))
(defun get-ob (preds)
(cadar preds))
(defun good-object-II-p (object a-list)
(or (cdr (assoc object a-list))
(pos-data-unchanged-flag (cdr (assoc object *GRAPHICS-INFO*))))
)
#|
(defun good-object-II-p (pred-list good-a-list)
(let* ((pred-1 (car pred-list))
(object (third pred-1))) ; get the object name
(setq pred-list (cdr pred-list))
(cond ((null pred-list) t) ; object is good
((and (member (car pred-1) '(on holding on-table))
(eq object (cadar pred-list)))
; then
nil); bad object
(t (good-object-II-p (cons pred-1 (cdr pred-list))))
)
)
)
|#
;--------------------------------------------------------------------------
;; DRAW-DOMAIN-FOREGROUND uses domain graphics parameters to draw the
;; foremost plane of graphics -- drawn after the domain objects.
;;
(defun draw-domain-foreground ()
(pg-draw-line *DOMAIN-WINDOW* 5 *START-Y* (- *DOMAIN-WIDTH* 5)
*START-Y*)
(draw (get-x-point *HAND-DATA*) (get-y-point *HAND-DATA*) (cdr *HAND-DATA*))
; (terpri) (princ "Paused") (read-char)
)
(defun draw (X1 Y1 x-y-list)
(unless (null x-y-list)
(let ((X2 (+ X1 (get-x-point x-y-list)))
(Y2 (+ Y1 (get-y-point x-y-list))))
(pg-draw-line *DOMAIN-WINDOW* X1 Y1 X2 Y2)
(draw X2 Y2 (cdr x-y-list))
)
)
)
; ========================================================================
; Drawing functions for boxes
; ========================================================================
; DRAW-ON-TABLE draws the box listed in the predicate on the table.
; Each box will have a predetermined table position
(defun draw-on-table (pred)
(let ((info-ob (cdr (assoc (last-el pred) *graphics-info*))))
(draw-box-with-label (pos-data-rest-pos info-ob) 0 (last-el pred))
(update (last-el pred) (pos-data-rest-pos info-ob) 0)
)
)
; DRAW-ON-BOX draws an object on top of another one.
; It also updates the data on the upper box.
(defun draw-on-box (pred)
(let ((support-ob (cdr (assoc (third pred) *graphics-info*)))
;(resting-ob (car (assoc (third pred) *graphics-info*)))
)
(draw-box-with-label (pos-data-x-pos support-ob)
(1+ (pos-data-y-pos support-ob))
(cadr pred))
(update (cadr pred) (pos-data-x-pos support-ob)
(1+ (pos-data-y-pos support-ob)))
)
)
; DRAW-IN-HAND will draw a box in the hand of the robot.
; No update is nescessary.
(defun draw-in-hand (name)
(pg-with-window *DOMAIN-WINDOW*
(pg-frame-rect
*HAND-LOC-X*
(- *HAND-LOC-Y* *BLOCK-HEIGHT*)
(+ *HAND-LOC-X* *BLOCK-WIDTH*)
*HAND-LOC-Y*)
)
(pg-write-text *DOMAIN-WINDOW*
(+ *HAND-LOC-X* 5)
(- *HAND-LOC-Y* 5)
(symbol-name name)
)
(setf (pos-data-in-arm-p (cdr (assoc name *GRAPHICS-INFO*))) t)
)
; UPDATE changes the location var of the block.
;
;
(defun update (keyname X Y)
(let ((structure (cdr (assoc keyname *GRAPHICS-INFO*))))
(setf (pos-data-x-pos structure) X)
(setf (pos-data-y-pos structure) Y)
)
)
; DRAW-BOX-WITH-LABEL will draw a little box and then write the print
; name of the object inside it.
; location is a small integer indicating the blocks position in block-space.
; name is a symbol whose print name is going to be the label.
; The block-org-? are the lower left-hand points and
; the corner-? are the upper right-hand points.
(defun draw-box-with-label (x-pos y-pos name)
(let* ((block-org-x (calc-x-from-int x-pos))
(block-org-y (calc-y-from-int y-pos))
(corner-x (+ block-org-x *BLOCK-WIDTH*))
(corner-y (- block-org-y *BLOCK-HEIGHT*))
)
(pg-with-window *DOMAIN-WINDOW*
(pg-frame-rect
block-org-x
corner-y
corner-x
block-org-y)
)
(pg-write-text *DOMAIN-WINDOW*
(+ block-org-x 5)
(- block-org-y 5)
(symbol-name name)
)
)
)
; CALC-X-FROM-INT will return a pixel value give a grid value.
(defun calc-x-from-int (int)
(+ (* (+ *BLOCK-WIDTH* *BLOCK-SEPARATION-X*) int) *START-X*)
)
; CALC-Y-FROM-INT will return a pixel value give a grid value.
(defun calc-y-from-int (int)
(- *START-Y* (* (+ *BLOCK-HEIGHT* *BLOCK-SEPARATION-Y*) int))
)
(defun erase-block (name)
(let (x-pos y-pos block-org-x block-org-y)
(cond ((pos-data-in-arm-p (cdr (assoc name *GRAPHICS-INFO*)))
(setq block-org-x *HAND-LOC-X* block-org-y *HAND-LOC-Y*)
(setf (pos-data-in-arm-p (cdr (assoc name *GRAPHICS-INFO*))) nil)
)
(t (setq x-pos
(pos-data-x-pos (cdr (assoc name *GRAPHICS-INFO*)))
y-pos
(pos-data-y-pos (cdr (assoc name *GRAPHICS-INFO*))))
(setq block-org-x (calc-x-from-int x-pos))
(setq block-org-y (calc-y-from-int y-pos)))
)
(pg-with-window *DOMAIN-WINDOW*
(pg-erase-rect block-org-x
(- block-org-y *BLOCK-HEIGHT*)
(+ block-org-x *BLOCK-WIDTH*)
block-org-y)
)
)
)
(provide 'pg-state)
|
[
{
"context": "ramming environment, TPTP translator.\"\n :author \"Fabricio Chalub <[email protected]> and Alexandre Rademaker <ale",
"end": 694,
"score": 0.9998823404312134,
"start": 679,
"tag": "NAME",
"value": "Fabricio Chalub"
},
{
"context": "nt, TPTP translator.\"\n :author \"Fabricio Chalub <[email protected]> and Alexandre Rademaker <[email protected]>\"\n ",
"end": 714,
"score": 0.9999338388442993,
"start": 696,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :author \"Fabricio Chalub <[email protected]> and Alexandre Rademaker <[email protected]>\"\n :license \"Apache 2.0\"\n :",
"end": 739,
"score": 0.9998785853385925,
"start": 720,
"tag": "NAME",
"value": "Alexandre Rademaker"
},
{
"context": "lub <[email protected]> and Alexandre Rademaker <[email protected]>\"\n :license \"Apache 2.0\"\n :depends-on (#:cl-fad",
"end": 759,
"score": 0.9999336004257202,
"start": 741,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
suo-kif.asd
|
TeamSPoon/wam_common_lisp_devel_workspace
| 4 |
;; Copyright 2016 IBM
;; 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.
(asdf:defsystem #:suo-kif
:description "SUO-KIF programming environment, TPTP translator."
:author "Fabricio Chalub <[email protected]> and Alexandre Rademaker <[email protected]>"
:license "Apache 2.0"
:depends-on (#:cl-fad
#:alexandria
#:cl-ppcre
#:optima
#:graph-algorithms
#:fare-memoization
#:fare-quasiquote-optima
#:fare-quasiquote-readtable
#:fiveam)
:serial t
:components ((:file "package")
(:file "utils")
(:file "tptp" :depends-on ("utils"))
(:file "prenex" :depends-on ("utils"))
(:file "tests")
(:file "graph" :depends-on ("utils"))
(:file "suo-kif" :depends-on ("utils" "prenex" "tptp"))))
|
11259
|
;; Copyright 2016 IBM
;; 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.
(asdf:defsystem #:suo-kif
:description "SUO-KIF programming environment, TPTP translator."
:author "<NAME> <<EMAIL>> and <NAME> <<EMAIL>>"
:license "Apache 2.0"
:depends-on (#:cl-fad
#:alexandria
#:cl-ppcre
#:optima
#:graph-algorithms
#:fare-memoization
#:fare-quasiquote-optima
#:fare-quasiquote-readtable
#:fiveam)
:serial t
:components ((:file "package")
(:file "utils")
(:file "tptp" :depends-on ("utils"))
(:file "prenex" :depends-on ("utils"))
(:file "tests")
(:file "graph" :depends-on ("utils"))
(:file "suo-kif" :depends-on ("utils" "prenex" "tptp"))))
| true |
;; Copyright 2016 IBM
;; 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.
(asdf:defsystem #:suo-kif
:description "SUO-KIF programming environment, TPTP translator."
:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> and PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:license "Apache 2.0"
:depends-on (#:cl-fad
#:alexandria
#:cl-ppcre
#:optima
#:graph-algorithms
#:fare-memoization
#:fare-quasiquote-optima
#:fare-quasiquote-readtable
#:fiveam)
:serial t
:components ((:file "package")
(:file "utils")
(:file "tptp" :depends-on ("utils"))
(:file "prenex" :depends-on ("utils"))
(:file "tests")
(:file "graph" :depends-on ("utils"))
(:file "suo-kif" :depends-on ("utils" "prenex" "tptp"))))
|
[
{
"context": "ther updates and finds avg temp in zipcode\n;;;\n;;; Kamil Shakirov <[email protected]>\n;;;\n\n(defpackage #:zguide.wu",
"end": 225,
"score": 0.9999001026153564,
"start": 211,
"tag": "NAME",
"value": "Kamil Shakirov"
},
{
"context": "finds avg temp in zipcode\n;;;\n;;; Kamil Shakirov <[email protected]>\n;;;\n\n(defpackage #:zguide.wuclient\n (:nicknames",
"end": 245,
"score": 0.9999211430549622,
"start": 227,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
ZeroMQ/filecode/examples/CL/wuclient.lisp
|
JailbreakFox/LightWeightRepository
| 2 |
;;; -*- Mode:Lisp; Syntax:ANSI-Common-Lisp; -*-
;;;
;;; Weather update client in Common Lisp
;;; Connects SUB socket to tcp://localhost:5556
;;; Collects weather updates and finds avg temp in zipcode
;;;
;;; Kamil Shakirov <[email protected]>
;;;
(defpackage #:zguide.wuclient
(:nicknames #:wuclient)
(:use #:cl #:zhelpers)
(:export #:main))
(in-package :zguide.wuclient)
(defun main ()
(zmq:with-context (context 1)
(message "Collecting updates from weather server...~%")
;; Socket to talk to server
(zmq:with-socket (subscriber context zmq:sub)
(zmq:connect subscriber "tcp://localhost:5556")
;; Subscribe to zipcode, default is NYC, 10001
(let ((filter (or (first (cmd-args)) "10001 ")))
(zmq:setsockopt subscriber zmq:subscribe filter)
;; Process 100 updates
(let ((number-updates 100)
(total-temp 0.0))
(loop :repeat number-updates :do
(let ((update (make-instance 'zmq:msg)))
(zmq:recv subscriber update)
(destructuring-bind (zipcode_ temperature relhumidity_)
(split-sequence:split-sequence #\Space (zmq:msg-data-as-string update))
(declare (ignore zipcode_ relhumidity_))
(incf total-temp (parse-integer temperature)))))
(message "Average temperature for zipcode ~A was ~FF~%"
filter (/ total-temp number-updates))))))
(cleanup))
|
51252
|
;;; -*- Mode:Lisp; Syntax:ANSI-Common-Lisp; -*-
;;;
;;; Weather update client in Common Lisp
;;; Connects SUB socket to tcp://localhost:5556
;;; Collects weather updates and finds avg temp in zipcode
;;;
;;; <NAME> <<EMAIL>>
;;;
(defpackage #:zguide.wuclient
(:nicknames #:wuclient)
(:use #:cl #:zhelpers)
(:export #:main))
(in-package :zguide.wuclient)
(defun main ()
(zmq:with-context (context 1)
(message "Collecting updates from weather server...~%")
;; Socket to talk to server
(zmq:with-socket (subscriber context zmq:sub)
(zmq:connect subscriber "tcp://localhost:5556")
;; Subscribe to zipcode, default is NYC, 10001
(let ((filter (or (first (cmd-args)) "10001 ")))
(zmq:setsockopt subscriber zmq:subscribe filter)
;; Process 100 updates
(let ((number-updates 100)
(total-temp 0.0))
(loop :repeat number-updates :do
(let ((update (make-instance 'zmq:msg)))
(zmq:recv subscriber update)
(destructuring-bind (zipcode_ temperature relhumidity_)
(split-sequence:split-sequence #\Space (zmq:msg-data-as-string update))
(declare (ignore zipcode_ relhumidity_))
(incf total-temp (parse-integer temperature)))))
(message "Average temperature for zipcode ~A was ~FF~%"
filter (/ total-temp number-updates))))))
(cleanup))
| true |
;;; -*- Mode:Lisp; Syntax:ANSI-Common-Lisp; -*-
;;;
;;; Weather update client in Common Lisp
;;; Connects SUB socket to tcp://localhost:5556
;;; Collects weather updates and finds avg temp in zipcode
;;;
;;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;;
(defpackage #:zguide.wuclient
(:nicknames #:wuclient)
(:use #:cl #:zhelpers)
(:export #:main))
(in-package :zguide.wuclient)
(defun main ()
(zmq:with-context (context 1)
(message "Collecting updates from weather server...~%")
;; Socket to talk to server
(zmq:with-socket (subscriber context zmq:sub)
(zmq:connect subscriber "tcp://localhost:5556")
;; Subscribe to zipcode, default is NYC, 10001
(let ((filter (or (first (cmd-args)) "10001 ")))
(zmq:setsockopt subscriber zmq:subscribe filter)
;; Process 100 updates
(let ((number-updates 100)
(total-temp 0.0))
(loop :repeat number-updates :do
(let ((update (make-instance 'zmq:msg)))
(zmq:recv subscriber update)
(destructuring-bind (zipcode_ temperature relhumidity_)
(split-sequence:split-sequence #\Space (zmq:msg-data-as-string update))
(declare (ignore zipcode_ relhumidity_))
(incf total-temp (parse-integer temperature)))))
(message "Average temperature for zipcode ~A was ~FF~%"
filter (/ total-temp number-updates))))))
(cleanup))
|
[
{
"context": "he LICENSE file distributed with ACL2.\n;\n; Author: Alessandro Coglio ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 239,
"score": 0.9998789429664612,
"start": 222,
"tag": "NAME",
"value": "Alessandro Coglio"
},
{
"context": "ributed with ACL2.\n;\n; Author: Alessandro Coglio ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 259,
"score": 0.9999303817749023,
"start": 241,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/kestrel/apt/tailrec-reference.lisp
|
solswords/acl2
| 0 |
; APT Tail Recursion Transformation -- Reference Documentation
;
; Copyright (C) 2017 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 "APT")
(include-book "xdoc/top" :dir :system)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc tailrec
:parents (reference)
:short "APT tail recursion transformation:
turn a recursive function that is not tail-recursive
into an equivalent tail-recursive function."
:long
"<h3>
Introduction
</h3>
<p>
Under certain conditions,
the computations performed by
a recursive function that is not tail-recursive
can be re-arranged so that they can be performed
by a tail-recursive function
whose arguments do not grow in the same way as the call stack
of the original function.
A tail-recursive function can be compiled into an imperative loop
that does not run out of space due to the call stack growth.
</p>
<h3>
General Form
</h3>
@({
(tailrec old
&key
:variant ; default :monoid
:domain ; default (lambda (x) t)
:new-name ; default :auto
:new-enable ; default :auto
:wrapper-name ; default :auto
:wrapper-enable ; default t
:thm-name ; default :auto
:thm-enable ; default t
:non-executable ; default :auto
:verify-guards ; default :auto
:hints ; default nil
:print ; default :result
:show-only ; default nil
)
})
<h3>
Inputs
</h3>
<p>
@('old')
</p>
<blockquote>
<p>
Denotes the target function to transform.
</p>
<p>
It must be the name of a function,
or a <see topic='@(url acl2::numbered-names)'>numbered name</see>
with a wildcard index that
<see topic='@(url resolve-numbered-name-wildcard)'>resolves</see>
to the name of a function.
In the rest of this documentation page, for expository convenience,
it is assumed that @('old') is the name of the denoted function.
</p>
<p>
@('old') must
be in logic mode,
be defined,
return a non-<see topic='@(url mv)'>multiple</see> value,
have no input or output <see topic='@(url acl2::stobj)'>stobjs</see>,
be singly (not mutually) recursive, and
not have a @(':?') measure.
If the @(':verify-guards') input is @('t'),
@('old') must be guard-verified.
</p>
<p>
With the body in <see topic='@(url acl2::term)'>translated</see> form,
and after expanding all lambda expressions (i.e. @(tsee let)s),
the function must have the form
</p>
@({
(defun old (x1 ... xn)
(if test<x1,...,xn>
base<x1,...,xn>
combine<nonrec<x1,...,xn>,
(old update-x1<x1,...,xn>
...
update-xn<x1,...,xn>)>))
})
<p>
where:
</p>
<ul>
<li>
The term @('test<x1,...,xn>') does not call @('old').
This term computes the exit test of the recursion.
</li>
<li>
The term @('base<x1,...,xn>') does not call @('old').
This term computes the base value of the recursion.
If the @(':variant') input is @(':monoid') or @(':monoid-alt'),
the term @('base<x1,...,xn>') must be ground,
i.e. actually not contain any of the @('xi') variables.
</li>
<li>
The term
@('combine<nonrec<x1,...,xn>,
(old update-x1<x1,...,xn> ... update-xn<x1,...,xn>)>')
contains one or more identical calls to @('old'),
namely @('(old update-x1<x1,...,xn> ... update-xn<x1,...,xn>)'),
where each @('update-xi<x1,...,xn>') is a term
that does not call @('old').
Let @('combine<nonrec<x1,...,xn>,r>') be the result of
replacing @('(old update-x1<x1,...,xn> ... update-xn<x1,...,xn>)')
with a fresh variable @('r').
</li>
<li>
The term @('combine<nonrec<x1,...,xn>,r>') is not just @('r')
(otherwise @('old') would already be tail-recursive).
</li>
<li>
The term @('combine<nonrec<x1,...,xn>,r>') does not call @(tsee if).
</li>
<li>
All the occurrences of @('x1'), ..., @('xn')
in @('combine<nonrec<x1,...,xn>,r>')
are within a subterm @('nonrec<x1,...,xn>') where @('r') does not occur.
This means that if @('combine<q,r>') is
the result of replacing all the occurrences of @('nonrec<x1,...,xn>')
with a fresh variable @('q'),
then no @('xi') occurs in @('combine<q,r>').
The term @('combine<q,r>') represents a binary operator
that combines @('nonrec<x1,...,xn>')
(which does not involve the recursive call to @('old'))
with the result of the recursive call to @('old').
The constraints just given may be satisfied
by multiple subterms @('nonrec<x1,...,xn>')
of @('combine<nonrec<x1,...,xn>,r>'):
the exact @('nonrec<x1,...,xn>') is determined
via the procedure described in
‘Decomposition of the Recursive Branch’ below.
</li>
</ul>
</blockquote>
<p>
@(':variant') — default @(':monoid')
</p>
<blockquote>
<p>
Indicates the variant of the transformation to use:
</p>
<ul>
<li>
@(':monoid'), for the monoidal variant,
where the applicability conditions below imply
the algebraic structure of a monoid (i.e. associativity and identity)
for the combination operator.
</li>
<li>
@(':monoid-alt'), for the alternative monoidal variant,
where the applicability conditions below also imply
the algebraic structure of a monoid (i.e. associativity and identity)
for the combination operator.
</li>
<li>
@(':assoc'), for the associative variant,
where the applicability conditions below imply
the algebraic structure of a semigroup (i.e. associativity only)
for the combination operator.
</li>
</ul>
<p>
The associative variant of the transformation is more widely applicable,
but the monoidal and alternative monoidal variants yield simpler functions.
The applicability conditions for the alternative monoidal variant
are neither stronger nor weaker than the ones for the monoidal variant,
so these two variants apply to different cases.
</p>
</blockquote>
<p>
@(':domain') — default @('(lambda (x) t)')
</p>
<blockquote>
<p>
Denotes the domain (i.e. predicate) @('domain')
over which the combination operator @('combine<q,r>')
must satisfy some of the applicability conditions below.
</p>
<p>
It must be one of the following:
</p>
<ul>
<li>
The name of a logic-mode unary function
that returns a non-<see topic='@(url mv)'>multiple</see> value
and that has no
input or output <see topic='@(url acl2::stobj)'>stobjs</see>.
If the generated functions are guard-verified
(which is determined by the @(':verify-guards') input; see below),
then the @(':domain') function must be guard-verified as well.
The @(':domain') function must be distinct from @('old').
</li>
<li>
A unary closed lambda expression
that only references logic-mode functions,
that returns a non-<see topic='@(url mv)'>multiple</see> value
and that has no
input or output <see topic='@(url acl2::stobj)'>stobjs</see>.
As an abbreviation, the name @('mac') of a macro stands for
the lambda expression @('(lambda (z1 z2 ...) (mac z1 z2 ...))'),
where @('z1'), @('z2'), ... are the required parameters of @('mac');
that is, a macro name abbreviates its eta-expansion
(considering only the macro's required parameters).
If the generated functions are guard-verified
(which is determined by the @(':verify-guards') input; see below),
then the body of the lambda expression
must only call guard-verified functions,
except possibly in the @(':logic') subterms of @(tsee mbe)s
and via @(tsee ec-call).
The lambda expression must not include any calls to @('old').
</li>
</ul>
<p>
The default domain consists of all values.
</p>
<p>
In the rest of this documentation page,
let @('domain') be the function or lambda expression.
</p>
</blockquote>
<p>
@(':new-name') — default @(':auto')
</p>
<blockquote>
<p>
Determines the name of the generated new function:
</p>
<ul>
<li>
@(':auto'),
to use the <see topic='@(url acl2::numbered-names)'>numbered name</see>
obtained by <see topic='@(url next-numbered-name)'>incrementing</see>
the index of @('old').
</li>
<li>
Any other symbol
(that is not in the main Lisp package and that is not a keyword),
to use as the name of the function.
</li>
</ul>
<p>
In the rest of this documentation page, let @('new') be this function.
</p>
</blockquote>
<p>
@(':new-enable') — default @(':auto')
</p>
<blockquote>
<p>
Determines whether @('new') is enabled:
</p>
<ul>
<li>
@('t'), to enable it.
</li>
<li>
@('nil'), to disable it.
</li>
<li>
@(':auto'), to enable it iff @('old') is enabled.
</li>
</ul>
</blockquote>
<p>
@(':wrapper-name') — default @(':auto')
</p>
<blockquote>
<p>
Determines the name of the generated wrapper function:
</p>
<ul>
<li>
@(':auto'),
to use the concatenation of the name of @('new') with @('-wrapper').
</li>
<li>
Any other symbol
(that is not in the main Lisp package and that is not a keyword),
to use as the name of the function.
</li>
</ul>
<p>
In the rest of this documentation page, let @('wrapper') be this function.
</p>
</blockquote>
<p>
@(':wrapper-enable') — default @('t')
</p>
<blockquote>
<p>
Determines whether @('wrapper') is enabled:
</p>
<ul>
<li>
@('t'), to enable it.
</li>
<li>
@('nil'), to disable it.
</li>
</ul>
</blockquote>
<p>
@(':thm-name') — default @(':auto')
</p>
<blockquote>
<p>
Determines the name of the theorem that relates @('old') to @('wrapper'):
</p>
<ul>
<li>
@(':auto'),
to use the <see topic='@(url acl2::paired-names)'>paired name</see>
obtaining by <see topic='@(url make-paired-name)'>pairing</see>
the name of @('old') and the name of @('new'),
putting the result into the same package as @('new').
</li>
<li>
Any other symbol
(that is not in the main Lisp package and that is not a keyword),
to use as the name of the theorem.
</li>
</ul>
<p>
In the rest of this documentation page,
let @('old-to-wrapper') be this theorem.
</p>
</blockquote>
<p>
@(':thm-enable') — default @('t')
</p>
<blockquote>
<p>
Determines whether @('old-to-wrapper') is enabled:
</p>
<ul>
<li>
@('t'), to enable it.
</li>
<li>
@('nil'), to disable it.
</li>
</ul>
</blockquote>
<p>
@(':non-executable') — default @(':auto')
</p>
<blockquote>
<p>
Determines whether @('new') and @('wrapper') are
<see topic='@(url acl2::non-executable)'>non-executable</see>:
</p>
<ul>
<li>
@('t'), to make them non-executable.
</li>
<li>
@('nil'), to not make them non-executable.
</li>
<li>
@(':auto'), to make them non-executable iff @('old') is non-executable.
</li>
</ul>
</blockquote>
<p>
@(':verify-guards') — default @(':auto')
</p>
<blockquote>
<p>
Determines whether @('new') and @('wrapper') are guard-verified:
</p>
<ul>
<li>
@('t'), to guard-verify them.
</li>
<li>
@('nil'), to not guard-verify them.
</li>
<li>
@(':auto'), to guard-verify them iff @('old') is guard-verified.
</li>
</ul>
</blockquote>
<p>
@(':hints') — default @('nil')
</p>
<blockquote>
<p>
Hints to prove the applicability conditions below.
</p>
<p>
It must be a
<see topic='@(url keyword-value-listp)'>keyword-value list</see>
@('(appcond1 hints1 ... appcondp hintsp)')
where each @('appcondk') is a keyword
that names one of the applicability conditions below,
and each @('hintsk') consists of hints as may appear
just after @(':hints') in a @(tsee defthm).
The hints @('hintsk') are used
to prove applicability condition @('appcondk').
</p>
<p>
The @('appcond1'), ..., @('appcondp') names must be all distinct.
</p>
<p>
An @('appcondk') is allowed in the @(':hints') input iff
the named applicability condition is present, as specified below.
</p>
</blockquote>
<p>
@(':print') — default @(':result')
</p>
<blockquote>
<p>
A <see topic='@(url print-specifier)'>print specifier</see>
to control the output printed on the screen.
</p>
</blockquote>
<p>
@(':show-only') — default @('nil')
</p>
<blockquote>
<p>
Determines whether the events generated by the transformation
should be submitted or only shown on the screen:
</p>
<ul>
<li>
@('nil'), to submit the events.
</li>
<li>
@('t'), to only show the events.
</li>
</ul>
</blockquote>
<h4>
Decomposition of the Recursive Branch
</h4>
<p>
Replace every occurrence of the recursive call
@('(old update-x1<x1,...,xn> ... update-xn<x1,...,xn>)')
in the recursive branch
@('combine<nonrec<x1,...,xn>,
(old update-x1<x1,...,xn> ... update-xn<x1,...,xn>)>')
of @('old')
with a fresh variable @('r'),
obtaining @('combine<nonrec<x1,...,xn>,r>').
</p>
<p>
Try to find the maximal and leftmost subterm @('nr')
of @('combine<nonrec<x1,...,xn>,r>')
such that @('r') does not occur in @('nr')
and such that all the occurrences of @('x1'), ..., @('xn')
in @('combine<nonrec<x1,...,xn>,r>')
occur within occurrences of @('nr') in @('combine<nonrec<x1,...,xn>,r>').
The latter constraint is equivalent to saying that
after replacing all the occurrences of @('nr')
in @('combine<nonrec<x1,...,xn>,r>')
with a fresh variable @('q'),
the resulting term will have only @('r') and @('q') as free variables.
</p>
<p>
If such a term @('nr') exists,
that term is @('nonrec<x1,...,xn>'),
and @('combine<q,r>') is the result of replacing
every occurrence of @('nonrec<x1,...,xn>')
in @('combine<nonrec<x1,...,xn>,r>')
with @('q').
</p>
<p>
If such a term @('nr') does not exist, decomposition fails.
</p>
<h3>
Applicability Conditions
</h3>
<p>
The following conditions must be proved
in order for the transformation to apply.
</p>
<p>
@(':domain-of-base')
</p>
<blockquote>
<p>
The base computation always returns values in the domain:
</p>
@({
(implies test<x1,...,xn>
(domain base<x1,...,xn>))
})
</blockquote>
<p>
@(':domain-of-nonrec')
</p>
<blockquote>
<p>
The non-recursive operand of the combination operator
always returns values in the domain,
when the exit test of the recursion fails:
</p>
@({
(implies (not test<x1,...,xn>)
(domain nonrec<x1,...,xn>))
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid') or @(':assoc').
</p>
</blockquote>
<p>
@(':domain-of-combine')
</p>
<blockquote>
<p>
The domain is closed under the combination operator:
</p>
@({
(implies (and (domain u)
(domain v))
(domain combine<u,v>))
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid') or @(':assoc').
</p>
</blockquote>
<p>
@(':domain-of-combine-uncond')
</p>
<blockquote>
<p>
The combination operator unconditionally returns values in the domain:
</p>
@({
(domain combine<u,v>)
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid-alt').
</p>
</blockquote>
<p>
@(':combine-associativity')
</p>
<blockquote>
<p>
The combination operator is associative over the domain:
</p>
@({
(implies (and (domain u)
(domain v)
(domain w))
(equal combine<u,combine<v,w>>
combine<combine<u,v>,w>))
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid') or @(':assoc').
</p>
</blockquote>
<p>
@(':combine-associativity-uncond')
</p>
<blockquote>
<p>
The combination operator is unconditionally associative:
</p>
@({
(equal combine<u,combine<v,w>>
combine<combine<u,v>,w>)
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid-alt').
</p>
</blockquote>
<p>
@(':combine-left-identity')
</p>
<blockquote>
<p>
The base value of the recursion
is left identity of the combination operator:
</p>
@({
(implies (and test<x1,...,xn>
(domain u))
(equal combine<base<x1...,xn>,u>
u))
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid') or @(':monoid-alt').
</p>
</blockquote>
<p>
@(':combine-right-identity')
</p>
<blockquote>
<p>
The base value of the recursion
is right identity of the combination operator:
</p>
@({
(implies (and test<x1,...,xn>
(domain u))
(equal combine<u,base<x1...,xn>>
u))
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid') or @(':monoid-alt').
</p>
</blockquote>
<p>
@(':domain-guard')
</p>
<blockquote>
<p>
The domain is well-defined (according to its guard) on every value:
</p>
@({
domain-guard<z>
})
<p>
where @('domain-guard<z>') is the guard term of @('domain')
if @('domain') is a function name,
while it is the guard obligation of @('domain')
if @('domain') is a lambda expression.
</p>
<p>
This applicability condition is present iff
the generated functions are guard-verified
(which is determined by the @(':verify-guards') input).
</p>
</blockquote>
<p>
@(':combine-guard')
</p>
<blockquote>
<p>
The combination operator is well-defined (according to its guard)
on every value in the domain:
</p>
@({
(implies (and (domain q)
(domain r))
combine-guard<q,r>)
})
<p>
where @('combine-guard<q,r>') is
the guard obligation of @('combine<q,r>').
</p>
<p>
This applicability condition is present iff
the generated functions are guard-verified
(which is determined by the @(':verify-guards') input).
</p>
</blockquote>
<p>
@(':domain-of-nonrec-when-guard')
</p>
<blockquote>
<p>
The non-recursive operand of the combination operator
returns values in the domain,
when the exit test of the recursion fails,
and under the guard of @('old'):
</p>
@({
(implies (and old-guard<x1,...,xn>
(not test<x1,...,xn>))
(domain nonrec<x1,...,xn>))
})
<p>
where @('old-guard<x1,...,xn>') is the guard term of @('old').
</p>
<p>
This applicability condition is present iff
the generated functions are guard-verified
(which is determined by the @(':verify-guards') input)
and the @(':variant') input is @(':monoid-alt').
</p>
</blockquote>
<p>
When present, @(':combine-left-identity') and @(':combine-right-identity'),
together with
either @(':combine-associativity') or @(':combine-associativity-uncond')
(one of them is always present),
and together with
either @(':domain-of-combine') or @(':domain-of-combine-uncond')
(one of them is always present),
mean that the domain has the algebraic structure of a monoid,
with the combination operator as the binary operator
and with the base value of the recursion as identity.
When @(':combine-left-identity') and @(':combine-right-identity') are absent,
the domain has the algebraic structure of a semigroup.
</p>
<h3>
Generated Functions and Theorems
</h3>
<p>
@('new')
</p>
<blockquote>
<p>
Tail-recursive equivalent of @('old'):
</p>
@({
;; when the :variant input is :monoid or :monoid-alt:
(defun new (x1 ... xn r)
(if test<x1,...,xn>
r
(new update-x1<x1,...,xn>
...
update-xn<x1,...,xn>
combine<r,nonrec<x1,...,xn>>)))
;; when the :variant input is :assoc:
(defun new (x1 ... xn r)
(if test<x1,...,xn>
combine<r,base<x1,...,xn>>
(new update-x1<x1,...,xn>
...
update-xn<x1,...,xn>
combine<r,nonrec<x1,...,xn>>)))
})
<p>
The measure term and well-founded relation of @('new')
are the same as @('old').
</p>
<p>
The guard is @('(and old-guard<x1,...,xn> (domain r))'),
where @('old-guard<x1,...,xn>') is the guard term of @('old').
</p>
</blockquote>
<p>
@('wrapper')
</p>
<blockquote>
<p>
Non-recursive wrapper of @('new'):
</p>
@({
;; when the :variant input is :monoid or :monoid-alt:
(defun wrapper (x1 ... xn)
(new x1 ... xn base<x1,...,xn>))
;; when the :variant input is :assoc:
(defun wrapper (x1 ... xn)
(if test<x1,...,xn>
base<x1,...,xn>
(new update-x1<x1,...,xn>
...
update-xn<x1,...,xn>
nonrec<x1,...,xn>)))
})
<p>
The guard is the same as @('old').
</p>
</blockquote>
<p>
@('old-to-wrapper')
</p>
<blockquote>
<p>
Theorem that relates @('old') to @('wrapper'):
</p>
@({
(defthm old-to-wrapper
(equal (old x1 ... xn)
(wrapper x1 ... xn)))
})
</blockquote>")
|
16740
|
; APT Tail Recursion Transformation -- Reference Documentation
;
; Copyright (C) 2017 Kestrel Institute (http://www.kestrel.edu)
;
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;
; Author: <NAME> (<EMAIL>)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "APT")
(include-book "xdoc/top" :dir :system)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc tailrec
:parents (reference)
:short "APT tail recursion transformation:
turn a recursive function that is not tail-recursive
into an equivalent tail-recursive function."
:long
"<h3>
Introduction
</h3>
<p>
Under certain conditions,
the computations performed by
a recursive function that is not tail-recursive
can be re-arranged so that they can be performed
by a tail-recursive function
whose arguments do not grow in the same way as the call stack
of the original function.
A tail-recursive function can be compiled into an imperative loop
that does not run out of space due to the call stack growth.
</p>
<h3>
General Form
</h3>
@({
(tailrec old
&key
:variant ; default :monoid
:domain ; default (lambda (x) t)
:new-name ; default :auto
:new-enable ; default :auto
:wrapper-name ; default :auto
:wrapper-enable ; default t
:thm-name ; default :auto
:thm-enable ; default t
:non-executable ; default :auto
:verify-guards ; default :auto
:hints ; default nil
:print ; default :result
:show-only ; default nil
)
})
<h3>
Inputs
</h3>
<p>
@('old')
</p>
<blockquote>
<p>
Denotes the target function to transform.
</p>
<p>
It must be the name of a function,
or a <see topic='@(url acl2::numbered-names)'>numbered name</see>
with a wildcard index that
<see topic='@(url resolve-numbered-name-wildcard)'>resolves</see>
to the name of a function.
In the rest of this documentation page, for expository convenience,
it is assumed that @('old') is the name of the denoted function.
</p>
<p>
@('old') must
be in logic mode,
be defined,
return a non-<see topic='@(url mv)'>multiple</see> value,
have no input or output <see topic='@(url acl2::stobj)'>stobjs</see>,
be singly (not mutually) recursive, and
not have a @(':?') measure.
If the @(':verify-guards') input is @('t'),
@('old') must be guard-verified.
</p>
<p>
With the body in <see topic='@(url acl2::term)'>translated</see> form,
and after expanding all lambda expressions (i.e. @(tsee let)s),
the function must have the form
</p>
@({
(defun old (x1 ... xn)
(if test<x1,...,xn>
base<x1,...,xn>
combine<nonrec<x1,...,xn>,
(old update-x1<x1,...,xn>
...
update-xn<x1,...,xn>)>))
})
<p>
where:
</p>
<ul>
<li>
The term @('test<x1,...,xn>') does not call @('old').
This term computes the exit test of the recursion.
</li>
<li>
The term @('base<x1,...,xn>') does not call @('old').
This term computes the base value of the recursion.
If the @(':variant') input is @(':monoid') or @(':monoid-alt'),
the term @('base<x1,...,xn>') must be ground,
i.e. actually not contain any of the @('xi') variables.
</li>
<li>
The term
@('combine<nonrec<x1,...,xn>,
(old update-x1<x1,...,xn> ... update-xn<x1,...,xn>)>')
contains one or more identical calls to @('old'),
namely @('(old update-x1<x1,...,xn> ... update-xn<x1,...,xn>)'),
where each @('update-xi<x1,...,xn>') is a term
that does not call @('old').
Let @('combine<nonrec<x1,...,xn>,r>') be the result of
replacing @('(old update-x1<x1,...,xn> ... update-xn<x1,...,xn>)')
with a fresh variable @('r').
</li>
<li>
The term @('combine<nonrec<x1,...,xn>,r>') is not just @('r')
(otherwise @('old') would already be tail-recursive).
</li>
<li>
The term @('combine<nonrec<x1,...,xn>,r>') does not call @(tsee if).
</li>
<li>
All the occurrences of @('x1'), ..., @('xn')
in @('combine<nonrec<x1,...,xn>,r>')
are within a subterm @('nonrec<x1,...,xn>') where @('r') does not occur.
This means that if @('combine<q,r>') is
the result of replacing all the occurrences of @('nonrec<x1,...,xn>')
with a fresh variable @('q'),
then no @('xi') occurs in @('combine<q,r>').
The term @('combine<q,r>') represents a binary operator
that combines @('nonrec<x1,...,xn>')
(which does not involve the recursive call to @('old'))
with the result of the recursive call to @('old').
The constraints just given may be satisfied
by multiple subterms @('nonrec<x1,...,xn>')
of @('combine<nonrec<x1,...,xn>,r>'):
the exact @('nonrec<x1,...,xn>') is determined
via the procedure described in
‘Decomposition of the Recursive Branch’ below.
</li>
</ul>
</blockquote>
<p>
@(':variant') — default @(':monoid')
</p>
<blockquote>
<p>
Indicates the variant of the transformation to use:
</p>
<ul>
<li>
@(':monoid'), for the monoidal variant,
where the applicability conditions below imply
the algebraic structure of a monoid (i.e. associativity and identity)
for the combination operator.
</li>
<li>
@(':monoid-alt'), for the alternative monoidal variant,
where the applicability conditions below also imply
the algebraic structure of a monoid (i.e. associativity and identity)
for the combination operator.
</li>
<li>
@(':assoc'), for the associative variant,
where the applicability conditions below imply
the algebraic structure of a semigroup (i.e. associativity only)
for the combination operator.
</li>
</ul>
<p>
The associative variant of the transformation is more widely applicable,
but the monoidal and alternative monoidal variants yield simpler functions.
The applicability conditions for the alternative monoidal variant
are neither stronger nor weaker than the ones for the monoidal variant,
so these two variants apply to different cases.
</p>
</blockquote>
<p>
@(':domain') — default @('(lambda (x) t)')
</p>
<blockquote>
<p>
Denotes the domain (i.e. predicate) @('domain')
over which the combination operator @('combine<q,r>')
must satisfy some of the applicability conditions below.
</p>
<p>
It must be one of the following:
</p>
<ul>
<li>
The name of a logic-mode unary function
that returns a non-<see topic='@(url mv)'>multiple</see> value
and that has no
input or output <see topic='@(url acl2::stobj)'>stobjs</see>.
If the generated functions are guard-verified
(which is determined by the @(':verify-guards') input; see below),
then the @(':domain') function must be guard-verified as well.
The @(':domain') function must be distinct from @('old').
</li>
<li>
A unary closed lambda expression
that only references logic-mode functions,
that returns a non-<see topic='@(url mv)'>multiple</see> value
and that has no
input or output <see topic='@(url acl2::stobj)'>stobjs</see>.
As an abbreviation, the name @('mac') of a macro stands for
the lambda expression @('(lambda (z1 z2 ...) (mac z1 z2 ...))'),
where @('z1'), @('z2'), ... are the required parameters of @('mac');
that is, a macro name abbreviates its eta-expansion
(considering only the macro's required parameters).
If the generated functions are guard-verified
(which is determined by the @(':verify-guards') input; see below),
then the body of the lambda expression
must only call guard-verified functions,
except possibly in the @(':logic') subterms of @(tsee mbe)s
and via @(tsee ec-call).
The lambda expression must not include any calls to @('old').
</li>
</ul>
<p>
The default domain consists of all values.
</p>
<p>
In the rest of this documentation page,
let @('domain') be the function or lambda expression.
</p>
</blockquote>
<p>
@(':new-name') — default @(':auto')
</p>
<blockquote>
<p>
Determines the name of the generated new function:
</p>
<ul>
<li>
@(':auto'),
to use the <see topic='@(url acl2::numbered-names)'>numbered name</see>
obtained by <see topic='@(url next-numbered-name)'>incrementing</see>
the index of @('old').
</li>
<li>
Any other symbol
(that is not in the main Lisp package and that is not a keyword),
to use as the name of the function.
</li>
</ul>
<p>
In the rest of this documentation page, let @('new') be this function.
</p>
</blockquote>
<p>
@(':new-enable') — default @(':auto')
</p>
<blockquote>
<p>
Determines whether @('new') is enabled:
</p>
<ul>
<li>
@('t'), to enable it.
</li>
<li>
@('nil'), to disable it.
</li>
<li>
@(':auto'), to enable it iff @('old') is enabled.
</li>
</ul>
</blockquote>
<p>
@(':wrapper-name') — default @(':auto')
</p>
<blockquote>
<p>
Determines the name of the generated wrapper function:
</p>
<ul>
<li>
@(':auto'),
to use the concatenation of the name of @('new') with @('-wrapper').
</li>
<li>
Any other symbol
(that is not in the main Lisp package and that is not a keyword),
to use as the name of the function.
</li>
</ul>
<p>
In the rest of this documentation page, let @('wrapper') be this function.
</p>
</blockquote>
<p>
@(':wrapper-enable') — default @('t')
</p>
<blockquote>
<p>
Determines whether @('wrapper') is enabled:
</p>
<ul>
<li>
@('t'), to enable it.
</li>
<li>
@('nil'), to disable it.
</li>
</ul>
</blockquote>
<p>
@(':thm-name') — default @(':auto')
</p>
<blockquote>
<p>
Determines the name of the theorem that relates @('old') to @('wrapper'):
</p>
<ul>
<li>
@(':auto'),
to use the <see topic='@(url acl2::paired-names)'>paired name</see>
obtaining by <see topic='@(url make-paired-name)'>pairing</see>
the name of @('old') and the name of @('new'),
putting the result into the same package as @('new').
</li>
<li>
Any other symbol
(that is not in the main Lisp package and that is not a keyword),
to use as the name of the theorem.
</li>
</ul>
<p>
In the rest of this documentation page,
let @('old-to-wrapper') be this theorem.
</p>
</blockquote>
<p>
@(':thm-enable') — default @('t')
</p>
<blockquote>
<p>
Determines whether @('old-to-wrapper') is enabled:
</p>
<ul>
<li>
@('t'), to enable it.
</li>
<li>
@('nil'), to disable it.
</li>
</ul>
</blockquote>
<p>
@(':non-executable') — default @(':auto')
</p>
<blockquote>
<p>
Determines whether @('new') and @('wrapper') are
<see topic='@(url acl2::non-executable)'>non-executable</see>:
</p>
<ul>
<li>
@('t'), to make them non-executable.
</li>
<li>
@('nil'), to not make them non-executable.
</li>
<li>
@(':auto'), to make them non-executable iff @('old') is non-executable.
</li>
</ul>
</blockquote>
<p>
@(':verify-guards') — default @(':auto')
</p>
<blockquote>
<p>
Determines whether @('new') and @('wrapper') are guard-verified:
</p>
<ul>
<li>
@('t'), to guard-verify them.
</li>
<li>
@('nil'), to not guard-verify them.
</li>
<li>
@(':auto'), to guard-verify them iff @('old') is guard-verified.
</li>
</ul>
</blockquote>
<p>
@(':hints') — default @('nil')
</p>
<blockquote>
<p>
Hints to prove the applicability conditions below.
</p>
<p>
It must be a
<see topic='@(url keyword-value-listp)'>keyword-value list</see>
@('(appcond1 hints1 ... appcondp hintsp)')
where each @('appcondk') is a keyword
that names one of the applicability conditions below,
and each @('hintsk') consists of hints as may appear
just after @(':hints') in a @(tsee defthm).
The hints @('hintsk') are used
to prove applicability condition @('appcondk').
</p>
<p>
The @('appcond1'), ..., @('appcondp') names must be all distinct.
</p>
<p>
An @('appcondk') is allowed in the @(':hints') input iff
the named applicability condition is present, as specified below.
</p>
</blockquote>
<p>
@(':print') — default @(':result')
</p>
<blockquote>
<p>
A <see topic='@(url print-specifier)'>print specifier</see>
to control the output printed on the screen.
</p>
</blockquote>
<p>
@(':show-only') — default @('nil')
</p>
<blockquote>
<p>
Determines whether the events generated by the transformation
should be submitted or only shown on the screen:
</p>
<ul>
<li>
@('nil'), to submit the events.
</li>
<li>
@('t'), to only show the events.
</li>
</ul>
</blockquote>
<h4>
Decomposition of the Recursive Branch
</h4>
<p>
Replace every occurrence of the recursive call
@('(old update-x1<x1,...,xn> ... update-xn<x1,...,xn>)')
in the recursive branch
@('combine<nonrec<x1,...,xn>,
(old update-x1<x1,...,xn> ... update-xn<x1,...,xn>)>')
of @('old')
with a fresh variable @('r'),
obtaining @('combine<nonrec<x1,...,xn>,r>').
</p>
<p>
Try to find the maximal and leftmost subterm @('nr')
of @('combine<nonrec<x1,...,xn>,r>')
such that @('r') does not occur in @('nr')
and such that all the occurrences of @('x1'), ..., @('xn')
in @('combine<nonrec<x1,...,xn>,r>')
occur within occurrences of @('nr') in @('combine<nonrec<x1,...,xn>,r>').
The latter constraint is equivalent to saying that
after replacing all the occurrences of @('nr')
in @('combine<nonrec<x1,...,xn>,r>')
with a fresh variable @('q'),
the resulting term will have only @('r') and @('q') as free variables.
</p>
<p>
If such a term @('nr') exists,
that term is @('nonrec<x1,...,xn>'),
and @('combine<q,r>') is the result of replacing
every occurrence of @('nonrec<x1,...,xn>')
in @('combine<nonrec<x1,...,xn>,r>')
with @('q').
</p>
<p>
If such a term @('nr') does not exist, decomposition fails.
</p>
<h3>
Applicability Conditions
</h3>
<p>
The following conditions must be proved
in order for the transformation to apply.
</p>
<p>
@(':domain-of-base')
</p>
<blockquote>
<p>
The base computation always returns values in the domain:
</p>
@({
(implies test<x1,...,xn>
(domain base<x1,...,xn>))
})
</blockquote>
<p>
@(':domain-of-nonrec')
</p>
<blockquote>
<p>
The non-recursive operand of the combination operator
always returns values in the domain,
when the exit test of the recursion fails:
</p>
@({
(implies (not test<x1,...,xn>)
(domain nonrec<x1,...,xn>))
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid') or @(':assoc').
</p>
</blockquote>
<p>
@(':domain-of-combine')
</p>
<blockquote>
<p>
The domain is closed under the combination operator:
</p>
@({
(implies (and (domain u)
(domain v))
(domain combine<u,v>))
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid') or @(':assoc').
</p>
</blockquote>
<p>
@(':domain-of-combine-uncond')
</p>
<blockquote>
<p>
The combination operator unconditionally returns values in the domain:
</p>
@({
(domain combine<u,v>)
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid-alt').
</p>
</blockquote>
<p>
@(':combine-associativity')
</p>
<blockquote>
<p>
The combination operator is associative over the domain:
</p>
@({
(implies (and (domain u)
(domain v)
(domain w))
(equal combine<u,combine<v,w>>
combine<combine<u,v>,w>))
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid') or @(':assoc').
</p>
</blockquote>
<p>
@(':combine-associativity-uncond')
</p>
<blockquote>
<p>
The combination operator is unconditionally associative:
</p>
@({
(equal combine<u,combine<v,w>>
combine<combine<u,v>,w>)
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid-alt').
</p>
</blockquote>
<p>
@(':combine-left-identity')
</p>
<blockquote>
<p>
The base value of the recursion
is left identity of the combination operator:
</p>
@({
(implies (and test<x1,...,xn>
(domain u))
(equal combine<base<x1...,xn>,u>
u))
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid') or @(':monoid-alt').
</p>
</blockquote>
<p>
@(':combine-right-identity')
</p>
<blockquote>
<p>
The base value of the recursion
is right identity of the combination operator:
</p>
@({
(implies (and test<x1,...,xn>
(domain u))
(equal combine<u,base<x1...,xn>>
u))
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid') or @(':monoid-alt').
</p>
</blockquote>
<p>
@(':domain-guard')
</p>
<blockquote>
<p>
The domain is well-defined (according to its guard) on every value:
</p>
@({
domain-guard<z>
})
<p>
where @('domain-guard<z>') is the guard term of @('domain')
if @('domain') is a function name,
while it is the guard obligation of @('domain')
if @('domain') is a lambda expression.
</p>
<p>
This applicability condition is present iff
the generated functions are guard-verified
(which is determined by the @(':verify-guards') input).
</p>
</blockquote>
<p>
@(':combine-guard')
</p>
<blockquote>
<p>
The combination operator is well-defined (according to its guard)
on every value in the domain:
</p>
@({
(implies (and (domain q)
(domain r))
combine-guard<q,r>)
})
<p>
where @('combine-guard<q,r>') is
the guard obligation of @('combine<q,r>').
</p>
<p>
This applicability condition is present iff
the generated functions are guard-verified
(which is determined by the @(':verify-guards') input).
</p>
</blockquote>
<p>
@(':domain-of-nonrec-when-guard')
</p>
<blockquote>
<p>
The non-recursive operand of the combination operator
returns values in the domain,
when the exit test of the recursion fails,
and under the guard of @('old'):
</p>
@({
(implies (and old-guard<x1,...,xn>
(not test<x1,...,xn>))
(domain nonrec<x1,...,xn>))
})
<p>
where @('old-guard<x1,...,xn>') is the guard term of @('old').
</p>
<p>
This applicability condition is present iff
the generated functions are guard-verified
(which is determined by the @(':verify-guards') input)
and the @(':variant') input is @(':monoid-alt').
</p>
</blockquote>
<p>
When present, @(':combine-left-identity') and @(':combine-right-identity'),
together with
either @(':combine-associativity') or @(':combine-associativity-uncond')
(one of them is always present),
and together with
either @(':domain-of-combine') or @(':domain-of-combine-uncond')
(one of them is always present),
mean that the domain has the algebraic structure of a monoid,
with the combination operator as the binary operator
and with the base value of the recursion as identity.
When @(':combine-left-identity') and @(':combine-right-identity') are absent,
the domain has the algebraic structure of a semigroup.
</p>
<h3>
Generated Functions and Theorems
</h3>
<p>
@('new')
</p>
<blockquote>
<p>
Tail-recursive equivalent of @('old'):
</p>
@({
;; when the :variant input is :monoid or :monoid-alt:
(defun new (x1 ... xn r)
(if test<x1,...,xn>
r
(new update-x1<x1,...,xn>
...
update-xn<x1,...,xn>
combine<r,nonrec<x1,...,xn>>)))
;; when the :variant input is :assoc:
(defun new (x1 ... xn r)
(if test<x1,...,xn>
combine<r,base<x1,...,xn>>
(new update-x1<x1,...,xn>
...
update-xn<x1,...,xn>
combine<r,nonrec<x1,...,xn>>)))
})
<p>
The measure term and well-founded relation of @('new')
are the same as @('old').
</p>
<p>
The guard is @('(and old-guard<x1,...,xn> (domain r))'),
where @('old-guard<x1,...,xn>') is the guard term of @('old').
</p>
</blockquote>
<p>
@('wrapper')
</p>
<blockquote>
<p>
Non-recursive wrapper of @('new'):
</p>
@({
;; when the :variant input is :monoid or :monoid-alt:
(defun wrapper (x1 ... xn)
(new x1 ... xn base<x1,...,xn>))
;; when the :variant input is :assoc:
(defun wrapper (x1 ... xn)
(if test<x1,...,xn>
base<x1,...,xn>
(new update-x1<x1,...,xn>
...
update-xn<x1,...,xn>
nonrec<x1,...,xn>)))
})
<p>
The guard is the same as @('old').
</p>
</blockquote>
<p>
@('old-to-wrapper')
</p>
<blockquote>
<p>
Theorem that relates @('old') to @('wrapper'):
</p>
@({
(defthm old-to-wrapper
(equal (old x1 ... xn)
(wrapper x1 ... xn)))
})
</blockquote>")
| true |
; APT Tail Recursion Transformation -- Reference Documentation
;
; Copyright (C) 2017 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 "APT")
(include-book "xdoc/top" :dir :system)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc tailrec
:parents (reference)
:short "APT tail recursion transformation:
turn a recursive function that is not tail-recursive
into an equivalent tail-recursive function."
:long
"<h3>
Introduction
</h3>
<p>
Under certain conditions,
the computations performed by
a recursive function that is not tail-recursive
can be re-arranged so that they can be performed
by a tail-recursive function
whose arguments do not grow in the same way as the call stack
of the original function.
A tail-recursive function can be compiled into an imperative loop
that does not run out of space due to the call stack growth.
</p>
<h3>
General Form
</h3>
@({
(tailrec old
&key
:variant ; default :monoid
:domain ; default (lambda (x) t)
:new-name ; default :auto
:new-enable ; default :auto
:wrapper-name ; default :auto
:wrapper-enable ; default t
:thm-name ; default :auto
:thm-enable ; default t
:non-executable ; default :auto
:verify-guards ; default :auto
:hints ; default nil
:print ; default :result
:show-only ; default nil
)
})
<h3>
Inputs
</h3>
<p>
@('old')
</p>
<blockquote>
<p>
Denotes the target function to transform.
</p>
<p>
It must be the name of a function,
or a <see topic='@(url acl2::numbered-names)'>numbered name</see>
with a wildcard index that
<see topic='@(url resolve-numbered-name-wildcard)'>resolves</see>
to the name of a function.
In the rest of this documentation page, for expository convenience,
it is assumed that @('old') is the name of the denoted function.
</p>
<p>
@('old') must
be in logic mode,
be defined,
return a non-<see topic='@(url mv)'>multiple</see> value,
have no input or output <see topic='@(url acl2::stobj)'>stobjs</see>,
be singly (not mutually) recursive, and
not have a @(':?') measure.
If the @(':verify-guards') input is @('t'),
@('old') must be guard-verified.
</p>
<p>
With the body in <see topic='@(url acl2::term)'>translated</see> form,
and after expanding all lambda expressions (i.e. @(tsee let)s),
the function must have the form
</p>
@({
(defun old (x1 ... xn)
(if test<x1,...,xn>
base<x1,...,xn>
combine<nonrec<x1,...,xn>,
(old update-x1<x1,...,xn>
...
update-xn<x1,...,xn>)>))
})
<p>
where:
</p>
<ul>
<li>
The term @('test<x1,...,xn>') does not call @('old').
This term computes the exit test of the recursion.
</li>
<li>
The term @('base<x1,...,xn>') does not call @('old').
This term computes the base value of the recursion.
If the @(':variant') input is @(':monoid') or @(':monoid-alt'),
the term @('base<x1,...,xn>') must be ground,
i.e. actually not contain any of the @('xi') variables.
</li>
<li>
The term
@('combine<nonrec<x1,...,xn>,
(old update-x1<x1,...,xn> ... update-xn<x1,...,xn>)>')
contains one or more identical calls to @('old'),
namely @('(old update-x1<x1,...,xn> ... update-xn<x1,...,xn>)'),
where each @('update-xi<x1,...,xn>') is a term
that does not call @('old').
Let @('combine<nonrec<x1,...,xn>,r>') be the result of
replacing @('(old update-x1<x1,...,xn> ... update-xn<x1,...,xn>)')
with a fresh variable @('r').
</li>
<li>
The term @('combine<nonrec<x1,...,xn>,r>') is not just @('r')
(otherwise @('old') would already be tail-recursive).
</li>
<li>
The term @('combine<nonrec<x1,...,xn>,r>') does not call @(tsee if).
</li>
<li>
All the occurrences of @('x1'), ..., @('xn')
in @('combine<nonrec<x1,...,xn>,r>')
are within a subterm @('nonrec<x1,...,xn>') where @('r') does not occur.
This means that if @('combine<q,r>') is
the result of replacing all the occurrences of @('nonrec<x1,...,xn>')
with a fresh variable @('q'),
then no @('xi') occurs in @('combine<q,r>').
The term @('combine<q,r>') represents a binary operator
that combines @('nonrec<x1,...,xn>')
(which does not involve the recursive call to @('old'))
with the result of the recursive call to @('old').
The constraints just given may be satisfied
by multiple subterms @('nonrec<x1,...,xn>')
of @('combine<nonrec<x1,...,xn>,r>'):
the exact @('nonrec<x1,...,xn>') is determined
via the procedure described in
‘Decomposition of the Recursive Branch’ below.
</li>
</ul>
</blockquote>
<p>
@(':variant') — default @(':monoid')
</p>
<blockquote>
<p>
Indicates the variant of the transformation to use:
</p>
<ul>
<li>
@(':monoid'), for the monoidal variant,
where the applicability conditions below imply
the algebraic structure of a monoid (i.e. associativity and identity)
for the combination operator.
</li>
<li>
@(':monoid-alt'), for the alternative monoidal variant,
where the applicability conditions below also imply
the algebraic structure of a monoid (i.e. associativity and identity)
for the combination operator.
</li>
<li>
@(':assoc'), for the associative variant,
where the applicability conditions below imply
the algebraic structure of a semigroup (i.e. associativity only)
for the combination operator.
</li>
</ul>
<p>
The associative variant of the transformation is more widely applicable,
but the monoidal and alternative monoidal variants yield simpler functions.
The applicability conditions for the alternative monoidal variant
are neither stronger nor weaker than the ones for the monoidal variant,
so these two variants apply to different cases.
</p>
</blockquote>
<p>
@(':domain') — default @('(lambda (x) t)')
</p>
<blockquote>
<p>
Denotes the domain (i.e. predicate) @('domain')
over which the combination operator @('combine<q,r>')
must satisfy some of the applicability conditions below.
</p>
<p>
It must be one of the following:
</p>
<ul>
<li>
The name of a logic-mode unary function
that returns a non-<see topic='@(url mv)'>multiple</see> value
and that has no
input or output <see topic='@(url acl2::stobj)'>stobjs</see>.
If the generated functions are guard-verified
(which is determined by the @(':verify-guards') input; see below),
then the @(':domain') function must be guard-verified as well.
The @(':domain') function must be distinct from @('old').
</li>
<li>
A unary closed lambda expression
that only references logic-mode functions,
that returns a non-<see topic='@(url mv)'>multiple</see> value
and that has no
input or output <see topic='@(url acl2::stobj)'>stobjs</see>.
As an abbreviation, the name @('mac') of a macro stands for
the lambda expression @('(lambda (z1 z2 ...) (mac z1 z2 ...))'),
where @('z1'), @('z2'), ... are the required parameters of @('mac');
that is, a macro name abbreviates its eta-expansion
(considering only the macro's required parameters).
If the generated functions are guard-verified
(which is determined by the @(':verify-guards') input; see below),
then the body of the lambda expression
must only call guard-verified functions,
except possibly in the @(':logic') subterms of @(tsee mbe)s
and via @(tsee ec-call).
The lambda expression must not include any calls to @('old').
</li>
</ul>
<p>
The default domain consists of all values.
</p>
<p>
In the rest of this documentation page,
let @('domain') be the function or lambda expression.
</p>
</blockquote>
<p>
@(':new-name') — default @(':auto')
</p>
<blockquote>
<p>
Determines the name of the generated new function:
</p>
<ul>
<li>
@(':auto'),
to use the <see topic='@(url acl2::numbered-names)'>numbered name</see>
obtained by <see topic='@(url next-numbered-name)'>incrementing</see>
the index of @('old').
</li>
<li>
Any other symbol
(that is not in the main Lisp package and that is not a keyword),
to use as the name of the function.
</li>
</ul>
<p>
In the rest of this documentation page, let @('new') be this function.
</p>
</blockquote>
<p>
@(':new-enable') — default @(':auto')
</p>
<blockquote>
<p>
Determines whether @('new') is enabled:
</p>
<ul>
<li>
@('t'), to enable it.
</li>
<li>
@('nil'), to disable it.
</li>
<li>
@(':auto'), to enable it iff @('old') is enabled.
</li>
</ul>
</blockquote>
<p>
@(':wrapper-name') — default @(':auto')
</p>
<blockquote>
<p>
Determines the name of the generated wrapper function:
</p>
<ul>
<li>
@(':auto'),
to use the concatenation of the name of @('new') with @('-wrapper').
</li>
<li>
Any other symbol
(that is not in the main Lisp package and that is not a keyword),
to use as the name of the function.
</li>
</ul>
<p>
In the rest of this documentation page, let @('wrapper') be this function.
</p>
</blockquote>
<p>
@(':wrapper-enable') — default @('t')
</p>
<blockquote>
<p>
Determines whether @('wrapper') is enabled:
</p>
<ul>
<li>
@('t'), to enable it.
</li>
<li>
@('nil'), to disable it.
</li>
</ul>
</blockquote>
<p>
@(':thm-name') — default @(':auto')
</p>
<blockquote>
<p>
Determines the name of the theorem that relates @('old') to @('wrapper'):
</p>
<ul>
<li>
@(':auto'),
to use the <see topic='@(url acl2::paired-names)'>paired name</see>
obtaining by <see topic='@(url make-paired-name)'>pairing</see>
the name of @('old') and the name of @('new'),
putting the result into the same package as @('new').
</li>
<li>
Any other symbol
(that is not in the main Lisp package and that is not a keyword),
to use as the name of the theorem.
</li>
</ul>
<p>
In the rest of this documentation page,
let @('old-to-wrapper') be this theorem.
</p>
</blockquote>
<p>
@(':thm-enable') — default @('t')
</p>
<blockquote>
<p>
Determines whether @('old-to-wrapper') is enabled:
</p>
<ul>
<li>
@('t'), to enable it.
</li>
<li>
@('nil'), to disable it.
</li>
</ul>
</blockquote>
<p>
@(':non-executable') — default @(':auto')
</p>
<blockquote>
<p>
Determines whether @('new') and @('wrapper') are
<see topic='@(url acl2::non-executable)'>non-executable</see>:
</p>
<ul>
<li>
@('t'), to make them non-executable.
</li>
<li>
@('nil'), to not make them non-executable.
</li>
<li>
@(':auto'), to make them non-executable iff @('old') is non-executable.
</li>
</ul>
</blockquote>
<p>
@(':verify-guards') — default @(':auto')
</p>
<blockquote>
<p>
Determines whether @('new') and @('wrapper') are guard-verified:
</p>
<ul>
<li>
@('t'), to guard-verify them.
</li>
<li>
@('nil'), to not guard-verify them.
</li>
<li>
@(':auto'), to guard-verify them iff @('old') is guard-verified.
</li>
</ul>
</blockquote>
<p>
@(':hints') — default @('nil')
</p>
<blockquote>
<p>
Hints to prove the applicability conditions below.
</p>
<p>
It must be a
<see topic='@(url keyword-value-listp)'>keyword-value list</see>
@('(appcond1 hints1 ... appcondp hintsp)')
where each @('appcondk') is a keyword
that names one of the applicability conditions below,
and each @('hintsk') consists of hints as may appear
just after @(':hints') in a @(tsee defthm).
The hints @('hintsk') are used
to prove applicability condition @('appcondk').
</p>
<p>
The @('appcond1'), ..., @('appcondp') names must be all distinct.
</p>
<p>
An @('appcondk') is allowed in the @(':hints') input iff
the named applicability condition is present, as specified below.
</p>
</blockquote>
<p>
@(':print') — default @(':result')
</p>
<blockquote>
<p>
A <see topic='@(url print-specifier)'>print specifier</see>
to control the output printed on the screen.
</p>
</blockquote>
<p>
@(':show-only') — default @('nil')
</p>
<blockquote>
<p>
Determines whether the events generated by the transformation
should be submitted or only shown on the screen:
</p>
<ul>
<li>
@('nil'), to submit the events.
</li>
<li>
@('t'), to only show the events.
</li>
</ul>
</blockquote>
<h4>
Decomposition of the Recursive Branch
</h4>
<p>
Replace every occurrence of the recursive call
@('(old update-x1<x1,...,xn> ... update-xn<x1,...,xn>)')
in the recursive branch
@('combine<nonrec<x1,...,xn>,
(old update-x1<x1,...,xn> ... update-xn<x1,...,xn>)>')
of @('old')
with a fresh variable @('r'),
obtaining @('combine<nonrec<x1,...,xn>,r>').
</p>
<p>
Try to find the maximal and leftmost subterm @('nr')
of @('combine<nonrec<x1,...,xn>,r>')
such that @('r') does not occur in @('nr')
and such that all the occurrences of @('x1'), ..., @('xn')
in @('combine<nonrec<x1,...,xn>,r>')
occur within occurrences of @('nr') in @('combine<nonrec<x1,...,xn>,r>').
The latter constraint is equivalent to saying that
after replacing all the occurrences of @('nr')
in @('combine<nonrec<x1,...,xn>,r>')
with a fresh variable @('q'),
the resulting term will have only @('r') and @('q') as free variables.
</p>
<p>
If such a term @('nr') exists,
that term is @('nonrec<x1,...,xn>'),
and @('combine<q,r>') is the result of replacing
every occurrence of @('nonrec<x1,...,xn>')
in @('combine<nonrec<x1,...,xn>,r>')
with @('q').
</p>
<p>
If such a term @('nr') does not exist, decomposition fails.
</p>
<h3>
Applicability Conditions
</h3>
<p>
The following conditions must be proved
in order for the transformation to apply.
</p>
<p>
@(':domain-of-base')
</p>
<blockquote>
<p>
The base computation always returns values in the domain:
</p>
@({
(implies test<x1,...,xn>
(domain base<x1,...,xn>))
})
</blockquote>
<p>
@(':domain-of-nonrec')
</p>
<blockquote>
<p>
The non-recursive operand of the combination operator
always returns values in the domain,
when the exit test of the recursion fails:
</p>
@({
(implies (not test<x1,...,xn>)
(domain nonrec<x1,...,xn>))
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid') or @(':assoc').
</p>
</blockquote>
<p>
@(':domain-of-combine')
</p>
<blockquote>
<p>
The domain is closed under the combination operator:
</p>
@({
(implies (and (domain u)
(domain v))
(domain combine<u,v>))
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid') or @(':assoc').
</p>
</blockquote>
<p>
@(':domain-of-combine-uncond')
</p>
<blockquote>
<p>
The combination operator unconditionally returns values in the domain:
</p>
@({
(domain combine<u,v>)
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid-alt').
</p>
</blockquote>
<p>
@(':combine-associativity')
</p>
<blockquote>
<p>
The combination operator is associative over the domain:
</p>
@({
(implies (and (domain u)
(domain v)
(domain w))
(equal combine<u,combine<v,w>>
combine<combine<u,v>,w>))
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid') or @(':assoc').
</p>
</blockquote>
<p>
@(':combine-associativity-uncond')
</p>
<blockquote>
<p>
The combination operator is unconditionally associative:
</p>
@({
(equal combine<u,combine<v,w>>
combine<combine<u,v>,w>)
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid-alt').
</p>
</blockquote>
<p>
@(':combine-left-identity')
</p>
<blockquote>
<p>
The base value of the recursion
is left identity of the combination operator:
</p>
@({
(implies (and test<x1,...,xn>
(domain u))
(equal combine<base<x1...,xn>,u>
u))
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid') or @(':monoid-alt').
</p>
</blockquote>
<p>
@(':combine-right-identity')
</p>
<blockquote>
<p>
The base value of the recursion
is right identity of the combination operator:
</p>
@({
(implies (and test<x1,...,xn>
(domain u))
(equal combine<u,base<x1...,xn>>
u))
})
<p>
This applicability condition is present iff
the @(':variant') input is @(':monoid') or @(':monoid-alt').
</p>
</blockquote>
<p>
@(':domain-guard')
</p>
<blockquote>
<p>
The domain is well-defined (according to its guard) on every value:
</p>
@({
domain-guard<z>
})
<p>
where @('domain-guard<z>') is the guard term of @('domain')
if @('domain') is a function name,
while it is the guard obligation of @('domain')
if @('domain') is a lambda expression.
</p>
<p>
This applicability condition is present iff
the generated functions are guard-verified
(which is determined by the @(':verify-guards') input).
</p>
</blockquote>
<p>
@(':combine-guard')
</p>
<blockquote>
<p>
The combination operator is well-defined (according to its guard)
on every value in the domain:
</p>
@({
(implies (and (domain q)
(domain r))
combine-guard<q,r>)
})
<p>
where @('combine-guard<q,r>') is
the guard obligation of @('combine<q,r>').
</p>
<p>
This applicability condition is present iff
the generated functions are guard-verified
(which is determined by the @(':verify-guards') input).
</p>
</blockquote>
<p>
@(':domain-of-nonrec-when-guard')
</p>
<blockquote>
<p>
The non-recursive operand of the combination operator
returns values in the domain,
when the exit test of the recursion fails,
and under the guard of @('old'):
</p>
@({
(implies (and old-guard<x1,...,xn>
(not test<x1,...,xn>))
(domain nonrec<x1,...,xn>))
})
<p>
where @('old-guard<x1,...,xn>') is the guard term of @('old').
</p>
<p>
This applicability condition is present iff
the generated functions are guard-verified
(which is determined by the @(':verify-guards') input)
and the @(':variant') input is @(':monoid-alt').
</p>
</blockquote>
<p>
When present, @(':combine-left-identity') and @(':combine-right-identity'),
together with
either @(':combine-associativity') or @(':combine-associativity-uncond')
(one of them is always present),
and together with
either @(':domain-of-combine') or @(':domain-of-combine-uncond')
(one of them is always present),
mean that the domain has the algebraic structure of a monoid,
with the combination operator as the binary operator
and with the base value of the recursion as identity.
When @(':combine-left-identity') and @(':combine-right-identity') are absent,
the domain has the algebraic structure of a semigroup.
</p>
<h3>
Generated Functions and Theorems
</h3>
<p>
@('new')
</p>
<blockquote>
<p>
Tail-recursive equivalent of @('old'):
</p>
@({
;; when the :variant input is :monoid or :monoid-alt:
(defun new (x1 ... xn r)
(if test<x1,...,xn>
r
(new update-x1<x1,...,xn>
...
update-xn<x1,...,xn>
combine<r,nonrec<x1,...,xn>>)))
;; when the :variant input is :assoc:
(defun new (x1 ... xn r)
(if test<x1,...,xn>
combine<r,base<x1,...,xn>>
(new update-x1<x1,...,xn>
...
update-xn<x1,...,xn>
combine<r,nonrec<x1,...,xn>>)))
})
<p>
The measure term and well-founded relation of @('new')
are the same as @('old').
</p>
<p>
The guard is @('(and old-guard<x1,...,xn> (domain r))'),
where @('old-guard<x1,...,xn>') is the guard term of @('old').
</p>
</blockquote>
<p>
@('wrapper')
</p>
<blockquote>
<p>
Non-recursive wrapper of @('new'):
</p>
@({
;; when the :variant input is :monoid or :monoid-alt:
(defun wrapper (x1 ... xn)
(new x1 ... xn base<x1,...,xn>))
;; when the :variant input is :assoc:
(defun wrapper (x1 ... xn)
(if test<x1,...,xn>
base<x1,...,xn>
(new update-x1<x1,...,xn>
...
update-xn<x1,...,xn>
nonrec<x1,...,xn>)))
})
<p>
The guard is the same as @('old').
</p>
</blockquote>
<p>
@('old-to-wrapper')
</p>
<blockquote>
<p>
Theorem that relates @('old') to @('wrapper'):
</p>
@({
(defthm old-to-wrapper
(equal (old x1 ... xn)
(wrapper x1 ... xn)))
})
</blockquote>")
|
[
{
"context": "#|\nCopyright (C) 2007, 2008 David Owen <[email protected]>\n\nThis program is free softwar",
"end": 39,
"score": 0.9997996687889099,
"start": 29,
"tag": "NAME",
"value": "David Owen"
},
{
"context": "#|\nCopyright (C) 2007, 2008 David Owen <[email protected]>\n\nThis program is free software: you can redistri",
"end": 58,
"score": 0.9999309182167053,
"start": 41,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
dso-lex-0.3.2/lex.lisp
|
timothyhinrichs/clicl
| 0 |
#|
Copyright (C) 2007, 2008 David Owen <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser Public License as published by
the Free Software Foundation, either version 3 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 Lesser Public License for more details.
You should have received a copy of the GNU Lesser Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
|#
(defpackage #:dso-lex
(:documentation "Allows the definition of lexers. See DEFLEXER.")
(:use #:cl #:cl-ppcre #:dso-util)
(:export #:deflexer #:make-lexer #:lex-all #:lex-inc))
(in-package #:dso-lex)
;;; regex manipulation
(defun anchor-and-mode (regex)
`(:sequence (:flags :single-line-mode-p) :start-anchor ,regex))
(defun wrap (regex) (anchor-and-mode `(:regex ,regex)))
(defun combine (regex-list)
(let ((mapped (mapcar
(lambda (regex) `(:register (:regex ,regex)))
regex-list)))
(when (rest mapped) (setq mapped `((:alternation ,@mapped))))
(anchor-and-mode (car mapped))))
;;; creating lexing forms
(defun break-defs (defs)
(let (regexs classes filters)
(dolist (d (reverse defs) (values regexs classes filters))
(destructuring-bind (regex class &optional filter) d
(push regex regexs)
(push class classes)
(push filter filters)))))
(defun greedy-lexer-form (input-var start-var defs)
(multiple-value-bind (regexs classes filters) (break-defs defs)
(setf regexs (mapcar 'wrap regexs))
`(let ((classes ,(coerce classes 'vector))
(filters ,(coerce filters 'vector))
max
at)
,@(mapcar
(lambda (i)
`(let ((end (nth-value 1 (scan ',(nth i regexs) ,input-var :start ,start-var))))
(when (and end (or (null at) (> end max)))
(setf max end
at ,i))))
(range (length regexs)))
(when at
(let ((image (make-array (- max ,start-var)
:element-type 'character
:displaced-to ,input-var
:displaced-index-offset ,start-var))
(filter (aref filters at)))
(values (aref classes at)
(if filter (funcall filter image) image)
max))))))
(defun lexer-form (input-var start-var defs)
(let ((regex (combine (mapcar #'first defs)))
(classes (map 'vector #'second defs))
(filters (map 'vector #'third defs)))
`(let ((parts (nth-value 3 (scan (quote ,regex) ,input-var
:start ,start-var))))
(let ((idx (position-if #'identity parts)))
(when idx
(let ((end (aref parts idx)))
(let ((image (make-array (- end ,start-var)
:element-type 'character
:displaced-to ,input-var
:displaced-index-offset ,start-var))
(filter (aref ,filters idx)))
(values (aref ,classes idx)
(if filter (funcall filter image) image)
end))))))))
;;; creating lexing functions
(defun make-lexer (defs &key priority-only)
"Returns a lexer function. The DEFS consists of token-class
definitions, each being a list of a regular expression, the name of
the class, and an optional filter. The returned function takes as
arguments an input sequence and an optional start position, and
returning the matched token-class, image, and image-length as values.
Unless PRIORITY-ONLY is true, the longest match will win, and
rule-priority will only be used to break ties. Otherwise, the first
match wins.
Example:
(let ((lexer (make-lexer '((\"[0-9]+\" number parse-integer)
(\"[a-zA-Z]\" letter)))))
(funcall lexer \"2pi\" 1))"
(eval `(lambda (input &optional (start 0))
,(if priority-only
(lexer-form 'input 'start defs)
(greedy-lexer-form 'input 'start defs)))))
(defmacro deflexer (name (&key priority-only) &body defs)
"Defines a lexer, called as a function of the given NAME, and returning
the matched token-class, image, and image-length as values. The body
consists of token-class definitions, each being a list of a regular
expression, the name of the class, and an optional filter.
Unless PRIORITY-ONLY is true, the longest match will win, and
rule-priority will only be used to break ties. Otherwise, the first
match wins.
Example:
(deflexer lexer ()
(\"[0-9]+\" number parse-integer)
(\"[a-zA-Z]\" letter))
(lexer \"2pi\" 1)"
`(defun ,name (input &optional (start 0))
,(if priority-only
(lexer-form 'input 'start defs)
(greedy-lexer-form 'input 'start defs))))
(defun lex-all (lexer input)
(labels ((scan (start tokens)
(if (> (length input) start)
(multiple-value-bind (class image remainder)
(funcall lexer input start)
(if class
(scan remainder (cons (list class image) tokens))
(nreverse (cons (list :error :error) tokens))))
(nreverse tokens))))
(scan 0 '())))
(defun lex-slow (lexer input &optional (drop nil))
"(LEX-slow LEXER INPUT) returns a function that takes 0 args; each time
the function is called, it returns two values: the next class and value.
It ignores all classes in the list DROP.
Returns 2 nils once input has been absorbed."
(let ((lexlist (remove-if #'(lambda (x) (member (first x) drop)) (lex-all lexer input))))
#'(lambda () (cond ((null lexlist) (values nil nil))
(t (let ((class (first (first lexlist)))
(value (second (first lexlist))))
(setq lexlist (cdr lexlist))
(values class value)))))))
(defun lex-inc (lexer input &optional (drop nil))
"(LEX-INC LEXER INPUT) returns a function that takes 0 args; each time
the function is called, it returns two values: the next class and value.
It ignores all classes in the list DROP.
Returns 2 nils once input has been absorbed."
(let ((index 0) (max (length input)))
#'(lambda ()
(do ((class nil) image remainder)
((or (> index max) class)
(if (> index max) (values nil nil) (values class image)))
(multiple-value-setq (class image remainder)
(funcall lexer input index))
(setq index remainder)
(cond ((member class drop)
(setq class nil))
(class)
(t
(setq index (1+ max))
(setq class :error)
(setq image (format nil "At position ~D" index))))))))
(defun lex-inc-output (lexer input &optional (drop nil))
(let ((f (lex-inc lexer input drop)))
(loop
(multiple-value-bind (v1 v2) (funcall f)
(print (cons v1 v2))
(when (and (null v1) (null v2)) (return))))))
|
38655
|
#|
Copyright (C) 2007, 2008 <NAME> <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser Public License as published by
the Free Software Foundation, either version 3 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 Lesser Public License for more details.
You should have received a copy of the GNU Lesser Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
|#
(defpackage #:dso-lex
(:documentation "Allows the definition of lexers. See DEFLEXER.")
(:use #:cl #:cl-ppcre #:dso-util)
(:export #:deflexer #:make-lexer #:lex-all #:lex-inc))
(in-package #:dso-lex)
;;; regex manipulation
(defun anchor-and-mode (regex)
`(:sequence (:flags :single-line-mode-p) :start-anchor ,regex))
(defun wrap (regex) (anchor-and-mode `(:regex ,regex)))
(defun combine (regex-list)
(let ((mapped (mapcar
(lambda (regex) `(:register (:regex ,regex)))
regex-list)))
(when (rest mapped) (setq mapped `((:alternation ,@mapped))))
(anchor-and-mode (car mapped))))
;;; creating lexing forms
(defun break-defs (defs)
(let (regexs classes filters)
(dolist (d (reverse defs) (values regexs classes filters))
(destructuring-bind (regex class &optional filter) d
(push regex regexs)
(push class classes)
(push filter filters)))))
(defun greedy-lexer-form (input-var start-var defs)
(multiple-value-bind (regexs classes filters) (break-defs defs)
(setf regexs (mapcar 'wrap regexs))
`(let ((classes ,(coerce classes 'vector))
(filters ,(coerce filters 'vector))
max
at)
,@(mapcar
(lambda (i)
`(let ((end (nth-value 1 (scan ',(nth i regexs) ,input-var :start ,start-var))))
(when (and end (or (null at) (> end max)))
(setf max end
at ,i))))
(range (length regexs)))
(when at
(let ((image (make-array (- max ,start-var)
:element-type 'character
:displaced-to ,input-var
:displaced-index-offset ,start-var))
(filter (aref filters at)))
(values (aref classes at)
(if filter (funcall filter image) image)
max))))))
(defun lexer-form (input-var start-var defs)
(let ((regex (combine (mapcar #'first defs)))
(classes (map 'vector #'second defs))
(filters (map 'vector #'third defs)))
`(let ((parts (nth-value 3 (scan (quote ,regex) ,input-var
:start ,start-var))))
(let ((idx (position-if #'identity parts)))
(when idx
(let ((end (aref parts idx)))
(let ((image (make-array (- end ,start-var)
:element-type 'character
:displaced-to ,input-var
:displaced-index-offset ,start-var))
(filter (aref ,filters idx)))
(values (aref ,classes idx)
(if filter (funcall filter image) image)
end))))))))
;;; creating lexing functions
(defun make-lexer (defs &key priority-only)
"Returns a lexer function. The DEFS consists of token-class
definitions, each being a list of a regular expression, the name of
the class, and an optional filter. The returned function takes as
arguments an input sequence and an optional start position, and
returning the matched token-class, image, and image-length as values.
Unless PRIORITY-ONLY is true, the longest match will win, and
rule-priority will only be used to break ties. Otherwise, the first
match wins.
Example:
(let ((lexer (make-lexer '((\"[0-9]+\" number parse-integer)
(\"[a-zA-Z]\" letter)))))
(funcall lexer \"2pi\" 1))"
(eval `(lambda (input &optional (start 0))
,(if priority-only
(lexer-form 'input 'start defs)
(greedy-lexer-form 'input 'start defs)))))
(defmacro deflexer (name (&key priority-only) &body defs)
"Defines a lexer, called as a function of the given NAME, and returning
the matched token-class, image, and image-length as values. The body
consists of token-class definitions, each being a list of a regular
expression, the name of the class, and an optional filter.
Unless PRIORITY-ONLY is true, the longest match will win, and
rule-priority will only be used to break ties. Otherwise, the first
match wins.
Example:
(deflexer lexer ()
(\"[0-9]+\" number parse-integer)
(\"[a-zA-Z]\" letter))
(lexer \"2pi\" 1)"
`(defun ,name (input &optional (start 0))
,(if priority-only
(lexer-form 'input 'start defs)
(greedy-lexer-form 'input 'start defs))))
(defun lex-all (lexer input)
(labels ((scan (start tokens)
(if (> (length input) start)
(multiple-value-bind (class image remainder)
(funcall lexer input start)
(if class
(scan remainder (cons (list class image) tokens))
(nreverse (cons (list :error :error) tokens))))
(nreverse tokens))))
(scan 0 '())))
(defun lex-slow (lexer input &optional (drop nil))
"(LEX-slow LEXER INPUT) returns a function that takes 0 args; each time
the function is called, it returns two values: the next class and value.
It ignores all classes in the list DROP.
Returns 2 nils once input has been absorbed."
(let ((lexlist (remove-if #'(lambda (x) (member (first x) drop)) (lex-all lexer input))))
#'(lambda () (cond ((null lexlist) (values nil nil))
(t (let ((class (first (first lexlist)))
(value (second (first lexlist))))
(setq lexlist (cdr lexlist))
(values class value)))))))
(defun lex-inc (lexer input &optional (drop nil))
"(LEX-INC LEXER INPUT) returns a function that takes 0 args; each time
the function is called, it returns two values: the next class and value.
It ignores all classes in the list DROP.
Returns 2 nils once input has been absorbed."
(let ((index 0) (max (length input)))
#'(lambda ()
(do ((class nil) image remainder)
((or (> index max) class)
(if (> index max) (values nil nil) (values class image)))
(multiple-value-setq (class image remainder)
(funcall lexer input index))
(setq index remainder)
(cond ((member class drop)
(setq class nil))
(class)
(t
(setq index (1+ max))
(setq class :error)
(setq image (format nil "At position ~D" index))))))))
(defun lex-inc-output (lexer input &optional (drop nil))
(let ((f (lex-inc lexer input drop)))
(loop
(multiple-value-bind (v1 v2) (funcall f)
(print (cons v1 v2))
(when (and (null v1) (null v2)) (return))))))
| true |
#|
Copyright (C) 2007, 2008 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser Public License as published by
the Free Software Foundation, either version 3 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 Lesser Public License for more details.
You should have received a copy of the GNU Lesser Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
|#
(defpackage #:dso-lex
(:documentation "Allows the definition of lexers. See DEFLEXER.")
(:use #:cl #:cl-ppcre #:dso-util)
(:export #:deflexer #:make-lexer #:lex-all #:lex-inc))
(in-package #:dso-lex)
;;; regex manipulation
(defun anchor-and-mode (regex)
`(:sequence (:flags :single-line-mode-p) :start-anchor ,regex))
(defun wrap (regex) (anchor-and-mode `(:regex ,regex)))
(defun combine (regex-list)
(let ((mapped (mapcar
(lambda (regex) `(:register (:regex ,regex)))
regex-list)))
(when (rest mapped) (setq mapped `((:alternation ,@mapped))))
(anchor-and-mode (car mapped))))
;;; creating lexing forms
(defun break-defs (defs)
(let (regexs classes filters)
(dolist (d (reverse defs) (values regexs classes filters))
(destructuring-bind (regex class &optional filter) d
(push regex regexs)
(push class classes)
(push filter filters)))))
(defun greedy-lexer-form (input-var start-var defs)
(multiple-value-bind (regexs classes filters) (break-defs defs)
(setf regexs (mapcar 'wrap regexs))
`(let ((classes ,(coerce classes 'vector))
(filters ,(coerce filters 'vector))
max
at)
,@(mapcar
(lambda (i)
`(let ((end (nth-value 1 (scan ',(nth i regexs) ,input-var :start ,start-var))))
(when (and end (or (null at) (> end max)))
(setf max end
at ,i))))
(range (length regexs)))
(when at
(let ((image (make-array (- max ,start-var)
:element-type 'character
:displaced-to ,input-var
:displaced-index-offset ,start-var))
(filter (aref filters at)))
(values (aref classes at)
(if filter (funcall filter image) image)
max))))))
(defun lexer-form (input-var start-var defs)
(let ((regex (combine (mapcar #'first defs)))
(classes (map 'vector #'second defs))
(filters (map 'vector #'third defs)))
`(let ((parts (nth-value 3 (scan (quote ,regex) ,input-var
:start ,start-var))))
(let ((idx (position-if #'identity parts)))
(when idx
(let ((end (aref parts idx)))
(let ((image (make-array (- end ,start-var)
:element-type 'character
:displaced-to ,input-var
:displaced-index-offset ,start-var))
(filter (aref ,filters idx)))
(values (aref ,classes idx)
(if filter (funcall filter image) image)
end))))))))
;;; creating lexing functions
(defun make-lexer (defs &key priority-only)
"Returns a lexer function. The DEFS consists of token-class
definitions, each being a list of a regular expression, the name of
the class, and an optional filter. The returned function takes as
arguments an input sequence and an optional start position, and
returning the matched token-class, image, and image-length as values.
Unless PRIORITY-ONLY is true, the longest match will win, and
rule-priority will only be used to break ties. Otherwise, the first
match wins.
Example:
(let ((lexer (make-lexer '((\"[0-9]+\" number parse-integer)
(\"[a-zA-Z]\" letter)))))
(funcall lexer \"2pi\" 1))"
(eval `(lambda (input &optional (start 0))
,(if priority-only
(lexer-form 'input 'start defs)
(greedy-lexer-form 'input 'start defs)))))
(defmacro deflexer (name (&key priority-only) &body defs)
"Defines a lexer, called as a function of the given NAME, and returning
the matched token-class, image, and image-length as values. The body
consists of token-class definitions, each being a list of a regular
expression, the name of the class, and an optional filter.
Unless PRIORITY-ONLY is true, the longest match will win, and
rule-priority will only be used to break ties. Otherwise, the first
match wins.
Example:
(deflexer lexer ()
(\"[0-9]+\" number parse-integer)
(\"[a-zA-Z]\" letter))
(lexer \"2pi\" 1)"
`(defun ,name (input &optional (start 0))
,(if priority-only
(lexer-form 'input 'start defs)
(greedy-lexer-form 'input 'start defs))))
(defun lex-all (lexer input)
(labels ((scan (start tokens)
(if (> (length input) start)
(multiple-value-bind (class image remainder)
(funcall lexer input start)
(if class
(scan remainder (cons (list class image) tokens))
(nreverse (cons (list :error :error) tokens))))
(nreverse tokens))))
(scan 0 '())))
(defun lex-slow (lexer input &optional (drop nil))
"(LEX-slow LEXER INPUT) returns a function that takes 0 args; each time
the function is called, it returns two values: the next class and value.
It ignores all classes in the list DROP.
Returns 2 nils once input has been absorbed."
(let ((lexlist (remove-if #'(lambda (x) (member (first x) drop)) (lex-all lexer input))))
#'(lambda () (cond ((null lexlist) (values nil nil))
(t (let ((class (first (first lexlist)))
(value (second (first lexlist))))
(setq lexlist (cdr lexlist))
(values class value)))))))
(defun lex-inc (lexer input &optional (drop nil))
"(LEX-INC LEXER INPUT) returns a function that takes 0 args; each time
the function is called, it returns two values: the next class and value.
It ignores all classes in the list DROP.
Returns 2 nils once input has been absorbed."
(let ((index 0) (max (length input)))
#'(lambda ()
(do ((class nil) image remainder)
((or (> index max) class)
(if (> index max) (values nil nil) (values class image)))
(multiple-value-setq (class image remainder)
(funcall lexer input index))
(setq index remainder)
(cond ((member class drop)
(setq class nil))
(class)
(t
(setq index (1+ max))
(setq class :error)
(setq image (format nil "At position ~D" index))))))))
(defun lex-inc-output (lexer input &optional (drop nil))
(let ((f (lex-inc lexer input drop)))
(loop
(multiple-value-bind (v1 v2) (funcall f)
(print (cons v1 v2))
(when (and (null v1) (null v2)) (return))))))
|
[
{
"context": "er for lists of conses\n;\n; Copyright (C) 2008-2011 Eric Smith and Stanford University\n; Copyright (C) 2013-2020",
"end": 73,
"score": 0.9997440576553345,
"start": 63,
"tag": "NAME",
"value": "Eric Smith"
},
{
"context": "ense. See the file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;",
"end": 234,
"score": 0.9997224807739258,
"start": 224,
"tag": "NAME",
"value": "Eric Smith"
},
{
"context": " file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 258,
"score": 0.9999334216117859,
"start": 236,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/kestrel/typed-lists-light/all-consp.lisp
|
mayankmanj/acl2
| 305 |
; A recognizer for lists of conses
;
; 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 "kestrel/sequences/defforall" :dir :system)
(defforall-simple consp)
(verify-guards all-consp)
|
92381
|
; A recognizer for lists of conses
;
; 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 "kestrel/sequences/defforall" :dir :system)
(defforall-simple consp)
(verify-guards all-consp)
| true |
; A recognizer for lists of conses
;
; 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 "kestrel/sequences/defforall" :dir :system)
(defforall-simple consp)
(verify-guards all-consp)
|
[
{
"context": "cription \"View server for CouchDB\"\n :maintainer \"Josh Marchán <[email protected]>\"\n :author \"Josh March",
"end": 104,
"score": 0.9998759031295776,
"start": 92,
"tag": "NAME",
"value": "Josh Marchán"
},
{
"context": " server for CouchDB\"\n :maintainer \"Josh Marchán <[email protected]>\"\n :author \"Josh Marchán <[email protected]",
"end": 130,
"score": 0.9999316930770874,
"start": 106,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "sh Marchán <[email protected]>\"\n :author \"Josh Marchán <[email protected]>\"\n :licence \"MIT\"\n :d",
"end": 156,
"score": 0.9998725652694702,
"start": 144,
"tag": "NAME",
"value": "Josh Marchán"
},
{
"context": "[email protected]>\"\n :author \"Josh Marchán <[email protected]>\"\n :licence \"MIT\"\n :depends-on (yason alexandri",
"end": 182,
"score": 0.9999311566352844,
"start": 158,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
chillax.view-server.asd
|
dmitrys99/chillax
| 0 |
(asdf:defsystem chillax.view-server
:description "View server for CouchDB"
:maintainer "Josh Marchán <[email protected]>"
:author "Josh Marchán <[email protected]>"
:licence "MIT"
:depends-on (yason alexandria)
:serial t
:components
((:module src
:serial t
:components
((:file "utils")
(:module view-server
:components
((:file "view-server")))))))
|
97779
|
(asdf:defsystem chillax.view-server
:description "View server for CouchDB"
:maintainer "<NAME> <<EMAIL>>"
:author "<NAME> <<EMAIL>>"
:licence "MIT"
:depends-on (yason alexandria)
:serial t
:components
((:module src
:serial t
:components
((:file "utils")
(:module view-server
:components
((:file "view-server")))))))
| true |
(asdf:defsystem chillax.view-server
:description "View server for CouchDB"
:maintainer "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:licence "MIT"
:depends-on (yason alexandria)
:serial t
:components
((:module src
:serial t
:components
((:file "utils")
(:module view-server
:components
((:file "view-server")))))))
|
[
{
"context": "le is a part of lack project.\n Copyright (c) 2015 Eitaro Fukamachi ([email protected])\n|#\n\n(in-package :cl-user)\n(d",
"end": 79,
"score": 0.9998850226402283,
"start": 63,
"tag": "NAME",
"value": "Eitaro Fukamachi"
},
{
"context": "k project.\n Copyright (c) 2015 Eitaro Fukamachi ([email protected])\n|#\n\n(in-package :cl-user)\n(defpackage t-lack-asd",
"end": 99,
"score": 0.9999228715896606,
"start": 81,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "ackage :t-lack-asd)\n\n(defsystem t-lack\n :author \"Eitaro Fukamachi\"\n :license \"LLGPL\"\n :depends-on (:lack\n ",
"end": 241,
"score": 0.9998875856399536,
"start": 225,
"tag": "NAME",
"value": "Eitaro Fukamachi"
}
] |
bundle-libs/software/lack-20190521-git/t-lack.asd
|
dbym4820/photon
| 4 |
#|
This file is a part of lack project.
Copyright (c) 2015 Eitaro Fukamachi ([email protected])
|#
(in-package :cl-user)
(defpackage t-lack-asd
(:use :cl :asdf))
(in-package :t-lack-asd)
(defsystem t-lack
:author "Eitaro Fukamachi"
:license "LLGPL"
:depends-on (:lack
:clack
:clack-v1-compat
:prove)
:components ((:module "t"
:components
((:test-file "builder"))))
:defsystem-depends-on (:prove-asdf)
:perform (test-op :after (op c)
(funcall (intern #.(string :run-test-system) :prove-asdf) c)
(asdf:clear-system c)))
|
77773
|
#|
This file is a part of lack project.
Copyright (c) 2015 <NAME> (<EMAIL>)
|#
(in-package :cl-user)
(defpackage t-lack-asd
(:use :cl :asdf))
(in-package :t-lack-asd)
(defsystem t-lack
:author "<NAME>"
:license "LLGPL"
:depends-on (:lack
:clack
:clack-v1-compat
:prove)
:components ((:module "t"
:components
((:test-file "builder"))))
:defsystem-depends-on (:prove-asdf)
:perform (test-op :after (op c)
(funcall (intern #.(string :run-test-system) :prove-asdf) c)
(asdf:clear-system c)))
| true |
#|
This file is a part of lack project.
Copyright (c) 2015 PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
|#
(in-package :cl-user)
(defpackage t-lack-asd
(:use :cl :asdf))
(in-package :t-lack-asd)
(defsystem t-lack
:author "PI:NAME:<NAME>END_PI"
:license "LLGPL"
:depends-on (:lack
:clack
:clack-v1-compat
:prove)
:components ((:module "t"
:components
((:test-file "builder"))))
:defsystem-depends-on (:prove-asdf)
:perform (test-op :after (op c)
(funcall (intern #.(string :run-test-system) :prove-asdf) c)
(asdf:clear-system c)))
|
[
{
"context": "he LICENSE file distributed with ACL2.\n;\n; Author: Alessandro Coglio ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 263,
"score": 0.9998722672462463,
"start": 246,
"tag": "NAME",
"value": "Alessandro Coglio"
},
{
"context": "ributed with ACL2.\n;\n; Author: Alessandro Coglio ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 283,
"score": 0.9999297857284546,
"start": 265,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/kestrel/c/atc/integer-formats.lisp
|
KestrelInstitute/acl2
| 305 |
; C Library
;
; Copyright (C) 2021 Kestrel Institute (http://www.kestrel.edu)
; Copyright (C) 2021 Kestrel Technology LLC (http://kestreltechnology.com)
;
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;
; Author: Alessandro Coglio ([email protected])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "C")
(include-book "pack")
(include-book "std/strings/case-conversion" :dir :system)
(include-book "std/util/define" :dir :system)
(include-book "std/util/defrule" :dir :system)
(include-book "xdoc/defxdoc-plus" :dir :system)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc+ atc-integer-formats
:parents (atc-shallow-embedding)
:short "A model of C integer formats for ATC."
:long
(xdoc::topstring
(xdoc::p
"[C] provides constraints on the formats of the integer types [C:6.2.5],
but not a complete definition of the formats (unlike Java).
A general formalization of C should be parameterized over these formats.
Here, for the current purposes of ATC,
we define the formats, but we do so in a way that
should make it easy to change and swap some aspects of the definitions.")
(xdoc::p
"[C:6.2.6.2/2] allows padding bits, which we disallow here.
[C:6.2.6.2/2] allows signed integers to be
two's complement, one's complement, or sign and magnitude;
we just assume two's complement here.")
(xdoc::p
"The exact number of bits in a byte is also implementation-dependent
[C:5.2.4.2.1/1] [C:6.2.6.1/3],
so we introduce a nullary function for the number of bits in a byte,
i.e. in a @('char') (unsigned, signed, or plain).
We define it to be 8, because that ought to be the most frequent case.")
(xdoc::p
"We also introduce nullary functions for the number of bits that form
(signed and unsigned)
@('short')s, @('int')s, @('long'), and @('long long')s.
Given the above choice of no padding bits,
these numbers of bits have to be multiples of the number of bits in a byte,
because those integers have to take a whole number of bytes.
Recall that each unsigned/signed integer type
takes the same storage as the corresponding signed/unsigned type
[C:6.2.5/6].")
(xdoc::p
"We prove some theorems about the nullary functions.
We disable the definitions of the nullary functions,
including executable counterparts.
This way, we minimize the dependencies from the exact definitions,
and we define the integer values, conversions, and operations
as independently from the exact sizes as possible.
Thus, it may not be difficult to replace this file
with another one with different definitions.")
(xdoc::p
"The definitions that we pick here are consistent with @('gcc')
on (at least some versions of) macOS and Linux, namely:
@('char') is 8 bits,
@('short') is 16 bits (2 bytes),
@('int') is 32 bits (4 bytes),
@('long') is 64 bits (8 bytes), and
@('long long') is also 64 bits (8 bytes).
These are all consistent with the ranges in [C:5.2.4.2.1]:
@('char') is at least 8 bits,
@('short') is at least 16 bits,
@('int') is at least 16 bits,
@('long') is at least 32 bits, and
@('long long') is at least 64 bits.
Furthermore, the ranges are increasing [C:6.2.5/8].")
(xdoc::p
"For now we only define formats for
the standard signed and unsigned integer types except @('_Bool').
Note that the plain @('char') type is not covered yet;
it is an integer type,
but not a standard integer type in C's terminology."))
:order-subtopics t
:default-parent t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro+ atc-def-integer-bits (type bits minbits)
(declare (xargs :guard (and (member-eq type '(char short int long llong))
(posp bits)
(posp minbits)
(>= bits minbits))))
:short "Macro to generate the nullary functions, and some theorems about them,
for the size in bits of the C integer types."
(b* ((type-bits (pack type '-bits))
(type-bits-bound (pack type-bits '-bound))
(type-bits-multiple-of-char-bits (pack type
'-bits-multiple-of-char-bits))
(short-substring (if (eq type 'char)
"signed, unsigned, and plain"
"signed and unsigned")))
`(define ,type-bits ()
:returns (,type-bits posp :rule-classes :type-prescription)
:short ,(str::cat "Size of "
short-substring
" @('"
(str::downcase-string (symbol-name type))
"') values, in bits.")
,bits
///
,@(and
(not (eq type 'char))
`((defrule ,type-bits-multiple-of-char-bits
(integerp (/ (,type-bits) (char-bits)))
:rule-classes :type-prescription
:enable char-bits)))
(in-theory (disable (:e ,type-bits)))
(defret ,type-bits-bound
(>= ,type-bits ,minbits)
:rule-classes :linear))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Other than the definitions of the nullary functions,
; the theorems generated by the following code
; hold for all choices of values consistent with [C].
(atc-def-integer-bits char 8 8)
(atc-def-integer-bits short 16 16)
(atc-def-integer-bits int 32 16)
(atc-def-integer-bits long 64 32)
(atc-def-integer-bits llong 64 64)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro+ atc-def-integer-bits-linear-rule (type1 rel type2 &key name disable)
(declare (xargs :guard (and (member-eq type1 '(char short int long llong))
(member-eq type2 '(char short int long llong))
(member-eq rel '(= < > <= >=))
(symbolp name)
(booleanp disable))))
:short "Macro to generate linear rules about
the sizes in bits of C integer types."
:long
(xdoc::topstring
(xdoc::p
"Each theorem says that the size in bits of the first type
has the specified relation with the size in bits of the second type.")
(xdoc::p
"Note that we also allow equalities, not just inequalities.
Linear rules may use equalities in ACL2."))
(b* ((type1-bits (pack type1 '-bits))
(type2-bits (pack type2 '-bits))
(name (or name (pack type1-bits '- rel '- type2-bits)))
(type1-string (str::cat
"@('" (str::downcase-string (symbol-name type1)) "')"))
(type2-string (str::cat
"@('" (str::downcase-string (symbol-name type2)) "')")))
`(,(if disable 'defruled 'defrule) ,name
:parents (,type1-bits ,type2-bits)
:short ,(str::cat "Relation between "
type1-string
" and "
type2-string
" bit sizes.")
(,rel (,type1-bits) (,type2-bits))
:rule-classes ((:linear :trigger-terms ((,type1-bits) (,type2-bits))))
:enable (,type1-bits ,type2-bits))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; The theorems generated by the following code calls
; hold for all choices of values consistent with [C].
; The generated rules are enabled.
(atc-def-integer-bits-linear-rule char <= short)
(atc-def-integer-bits-linear-rule short <= int)
(atc-def-integer-bits-linear-rule int <= long)
(atc-def-integer-bits-linear-rule long <= llong)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; The theorems generated by the following code
; hold for some choices of values consistent with [C].
; The code to generate the rules is the same for all choices,
; but the exact resulting rules depend on some choices.
; The rules are disabled, so it is clear when they are used,
; i.e. when there are dependencies on the choice of values.
(make-event
(b* ((rel (if (= (char-bits) (short-bits)) '= '<)))
`(atc-def-integer-bits-linear-rule char ,rel short
:name char-bits-vs-short-bits
:disable t)))
(make-event
(b* ((rel (if (= (short-bits) (int-bits)) '= '<)))
`(atc-def-integer-bits-linear-rule short ,rel int
:name short-bits-vs-int-bits
:disable t)))
(make-event
(b* ((rel (if (= (int-bits) (long-bits)) '= '<)))
`(atc-def-integer-bits-linear-rule int ,rel long
:name int-bits-vs-long-bits
:disable t)))
(make-event
(b* ((rel (if (= (long-bits) (llong-bits)) '= '<)))
`(atc-def-integer-bits-linear-rule long ,rel llong
:name long-bits-vs-llong-bits
:disable t)))
|
78837
|
; C Library
;
; Copyright (C) 2021 Kestrel Institute (http://www.kestrel.edu)
; Copyright (C) 2021 Kestrel Technology LLC (http://kestreltechnology.com)
;
; License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
;
; Author: <NAME> (<EMAIL>)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "C")
(include-book "pack")
(include-book "std/strings/case-conversion" :dir :system)
(include-book "std/util/define" :dir :system)
(include-book "std/util/defrule" :dir :system)
(include-book "xdoc/defxdoc-plus" :dir :system)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc+ atc-integer-formats
:parents (atc-shallow-embedding)
:short "A model of C integer formats for ATC."
:long
(xdoc::topstring
(xdoc::p
"[C] provides constraints on the formats of the integer types [C:6.2.5],
but not a complete definition of the formats (unlike Java).
A general formalization of C should be parameterized over these formats.
Here, for the current purposes of ATC,
we define the formats, but we do so in a way that
should make it easy to change and swap some aspects of the definitions.")
(xdoc::p
"[C:6.2.6.2/2] allows padding bits, which we disallow here.
[C:6.2.6.2/2] allows signed integers to be
two's complement, one's complement, or sign and magnitude;
we just assume two's complement here.")
(xdoc::p
"The exact number of bits in a byte is also implementation-dependent
[C:5.2.4.2.1/1] [C:6.2.6.1/3],
so we introduce a nullary function for the number of bits in a byte,
i.e. in a @('char') (unsigned, signed, or plain).
We define it to be 8, because that ought to be the most frequent case.")
(xdoc::p
"We also introduce nullary functions for the number of bits that form
(signed and unsigned)
@('short')s, @('int')s, @('long'), and @('long long')s.
Given the above choice of no padding bits,
these numbers of bits have to be multiples of the number of bits in a byte,
because those integers have to take a whole number of bytes.
Recall that each unsigned/signed integer type
takes the same storage as the corresponding signed/unsigned type
[C:6.2.5/6].")
(xdoc::p
"We prove some theorems about the nullary functions.
We disable the definitions of the nullary functions,
including executable counterparts.
This way, we minimize the dependencies from the exact definitions,
and we define the integer values, conversions, and operations
as independently from the exact sizes as possible.
Thus, it may not be difficult to replace this file
with another one with different definitions.")
(xdoc::p
"The definitions that we pick here are consistent with @('gcc')
on (at least some versions of) macOS and Linux, namely:
@('char') is 8 bits,
@('short') is 16 bits (2 bytes),
@('int') is 32 bits (4 bytes),
@('long') is 64 bits (8 bytes), and
@('long long') is also 64 bits (8 bytes).
These are all consistent with the ranges in [C:5.2.4.2.1]:
@('char') is at least 8 bits,
@('short') is at least 16 bits,
@('int') is at least 16 bits,
@('long') is at least 32 bits, and
@('long long') is at least 64 bits.
Furthermore, the ranges are increasing [C:6.2.5/8].")
(xdoc::p
"For now we only define formats for
the standard signed and unsigned integer types except @('_Bool').
Note that the plain @('char') type is not covered yet;
it is an integer type,
but not a standard integer type in C's terminology."))
:order-subtopics t
:default-parent t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro+ atc-def-integer-bits (type bits minbits)
(declare (xargs :guard (and (member-eq type '(char short int long llong))
(posp bits)
(posp minbits)
(>= bits minbits))))
:short "Macro to generate the nullary functions, and some theorems about them,
for the size in bits of the C integer types."
(b* ((type-bits (pack type '-bits))
(type-bits-bound (pack type-bits '-bound))
(type-bits-multiple-of-char-bits (pack type
'-bits-multiple-of-char-bits))
(short-substring (if (eq type 'char)
"signed, unsigned, and plain"
"signed and unsigned")))
`(define ,type-bits ()
:returns (,type-bits posp :rule-classes :type-prescription)
:short ,(str::cat "Size of "
short-substring
" @('"
(str::downcase-string (symbol-name type))
"') values, in bits.")
,bits
///
,@(and
(not (eq type 'char))
`((defrule ,type-bits-multiple-of-char-bits
(integerp (/ (,type-bits) (char-bits)))
:rule-classes :type-prescription
:enable char-bits)))
(in-theory (disable (:e ,type-bits)))
(defret ,type-bits-bound
(>= ,type-bits ,minbits)
:rule-classes :linear))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Other than the definitions of the nullary functions,
; the theorems generated by the following code
; hold for all choices of values consistent with [C].
(atc-def-integer-bits char 8 8)
(atc-def-integer-bits short 16 16)
(atc-def-integer-bits int 32 16)
(atc-def-integer-bits long 64 32)
(atc-def-integer-bits llong 64 64)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro+ atc-def-integer-bits-linear-rule (type1 rel type2 &key name disable)
(declare (xargs :guard (and (member-eq type1 '(char short int long llong))
(member-eq type2 '(char short int long llong))
(member-eq rel '(= < > <= >=))
(symbolp name)
(booleanp disable))))
:short "Macro to generate linear rules about
the sizes in bits of C integer types."
:long
(xdoc::topstring
(xdoc::p
"Each theorem says that the size in bits of the first type
has the specified relation with the size in bits of the second type.")
(xdoc::p
"Note that we also allow equalities, not just inequalities.
Linear rules may use equalities in ACL2."))
(b* ((type1-bits (pack type1 '-bits))
(type2-bits (pack type2 '-bits))
(name (or name (pack type1-bits '- rel '- type2-bits)))
(type1-string (str::cat
"@('" (str::downcase-string (symbol-name type1)) "')"))
(type2-string (str::cat
"@('" (str::downcase-string (symbol-name type2)) "')")))
`(,(if disable 'defruled 'defrule) ,name
:parents (,type1-bits ,type2-bits)
:short ,(str::cat "Relation between "
type1-string
" and "
type2-string
" bit sizes.")
(,rel (,type1-bits) (,type2-bits))
:rule-classes ((:linear :trigger-terms ((,type1-bits) (,type2-bits))))
:enable (,type1-bits ,type2-bits))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; The theorems generated by the following code calls
; hold for all choices of values consistent with [C].
; The generated rules are enabled.
(atc-def-integer-bits-linear-rule char <= short)
(atc-def-integer-bits-linear-rule short <= int)
(atc-def-integer-bits-linear-rule int <= long)
(atc-def-integer-bits-linear-rule long <= llong)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; The theorems generated by the following code
; hold for some choices of values consistent with [C].
; The code to generate the rules is the same for all choices,
; but the exact resulting rules depend on some choices.
; The rules are disabled, so it is clear when they are used,
; i.e. when there are dependencies on the choice of values.
(make-event
(b* ((rel (if (= (char-bits) (short-bits)) '= '<)))
`(atc-def-integer-bits-linear-rule char ,rel short
:name char-bits-vs-short-bits
:disable t)))
(make-event
(b* ((rel (if (= (short-bits) (int-bits)) '= '<)))
`(atc-def-integer-bits-linear-rule short ,rel int
:name short-bits-vs-int-bits
:disable t)))
(make-event
(b* ((rel (if (= (int-bits) (long-bits)) '= '<)))
`(atc-def-integer-bits-linear-rule int ,rel long
:name int-bits-vs-long-bits
:disable t)))
(make-event
(b* ((rel (if (= (long-bits) (llong-bits)) '= '<)))
`(atc-def-integer-bits-linear-rule long ,rel llong
:name long-bits-vs-llong-bits
:disable t)))
| true |
; C Library
;
; Copyright (C) 2021 Kestrel Institute (http://www.kestrel.edu)
; Copyright (C) 2021 Kestrel Technology LLC (http://kestreltechnology.com)
;
; 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 "C")
(include-book "pack")
(include-book "std/strings/case-conversion" :dir :system)
(include-book "std/util/define" :dir :system)
(include-book "std/util/defrule" :dir :system)
(include-book "xdoc/defxdoc-plus" :dir :system)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc+ atc-integer-formats
:parents (atc-shallow-embedding)
:short "A model of C integer formats for ATC."
:long
(xdoc::topstring
(xdoc::p
"[C] provides constraints on the formats of the integer types [C:6.2.5],
but not a complete definition of the formats (unlike Java).
A general formalization of C should be parameterized over these formats.
Here, for the current purposes of ATC,
we define the formats, but we do so in a way that
should make it easy to change and swap some aspects of the definitions.")
(xdoc::p
"[C:6.2.6.2/2] allows padding bits, which we disallow here.
[C:6.2.6.2/2] allows signed integers to be
two's complement, one's complement, or sign and magnitude;
we just assume two's complement here.")
(xdoc::p
"The exact number of bits in a byte is also implementation-dependent
[C:5.2.4.2.1/1] [C:6.2.6.1/3],
so we introduce a nullary function for the number of bits in a byte,
i.e. in a @('char') (unsigned, signed, or plain).
We define it to be 8, because that ought to be the most frequent case.")
(xdoc::p
"We also introduce nullary functions for the number of bits that form
(signed and unsigned)
@('short')s, @('int')s, @('long'), and @('long long')s.
Given the above choice of no padding bits,
these numbers of bits have to be multiples of the number of bits in a byte,
because those integers have to take a whole number of bytes.
Recall that each unsigned/signed integer type
takes the same storage as the corresponding signed/unsigned type
[C:6.2.5/6].")
(xdoc::p
"We prove some theorems about the nullary functions.
We disable the definitions of the nullary functions,
including executable counterparts.
This way, we minimize the dependencies from the exact definitions,
and we define the integer values, conversions, and operations
as independently from the exact sizes as possible.
Thus, it may not be difficult to replace this file
with another one with different definitions.")
(xdoc::p
"The definitions that we pick here are consistent with @('gcc')
on (at least some versions of) macOS and Linux, namely:
@('char') is 8 bits,
@('short') is 16 bits (2 bytes),
@('int') is 32 bits (4 bytes),
@('long') is 64 bits (8 bytes), and
@('long long') is also 64 bits (8 bytes).
These are all consistent with the ranges in [C:5.2.4.2.1]:
@('char') is at least 8 bits,
@('short') is at least 16 bits,
@('int') is at least 16 bits,
@('long') is at least 32 bits, and
@('long long') is at least 64 bits.
Furthermore, the ranges are increasing [C:6.2.5/8].")
(xdoc::p
"For now we only define formats for
the standard signed and unsigned integer types except @('_Bool').
Note that the plain @('char') type is not covered yet;
it is an integer type,
but not a standard integer type in C's terminology."))
:order-subtopics t
:default-parent t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro+ atc-def-integer-bits (type bits minbits)
(declare (xargs :guard (and (member-eq type '(char short int long llong))
(posp bits)
(posp minbits)
(>= bits minbits))))
:short "Macro to generate the nullary functions, and some theorems about them,
for the size in bits of the C integer types."
(b* ((type-bits (pack type '-bits))
(type-bits-bound (pack type-bits '-bound))
(type-bits-multiple-of-char-bits (pack type
'-bits-multiple-of-char-bits))
(short-substring (if (eq type 'char)
"signed, unsigned, and plain"
"signed and unsigned")))
`(define ,type-bits ()
:returns (,type-bits posp :rule-classes :type-prescription)
:short ,(str::cat "Size of "
short-substring
" @('"
(str::downcase-string (symbol-name type))
"') values, in bits.")
,bits
///
,@(and
(not (eq type 'char))
`((defrule ,type-bits-multiple-of-char-bits
(integerp (/ (,type-bits) (char-bits)))
:rule-classes :type-prescription
:enable char-bits)))
(in-theory (disable (:e ,type-bits)))
(defret ,type-bits-bound
(>= ,type-bits ,minbits)
:rule-classes :linear))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Other than the definitions of the nullary functions,
; the theorems generated by the following code
; hold for all choices of values consistent with [C].
(atc-def-integer-bits char 8 8)
(atc-def-integer-bits short 16 16)
(atc-def-integer-bits int 32 16)
(atc-def-integer-bits long 64 32)
(atc-def-integer-bits llong 64 64)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro+ atc-def-integer-bits-linear-rule (type1 rel type2 &key name disable)
(declare (xargs :guard (and (member-eq type1 '(char short int long llong))
(member-eq type2 '(char short int long llong))
(member-eq rel '(= < > <= >=))
(symbolp name)
(booleanp disable))))
:short "Macro to generate linear rules about
the sizes in bits of C integer types."
:long
(xdoc::topstring
(xdoc::p
"Each theorem says that the size in bits of the first type
has the specified relation with the size in bits of the second type.")
(xdoc::p
"Note that we also allow equalities, not just inequalities.
Linear rules may use equalities in ACL2."))
(b* ((type1-bits (pack type1 '-bits))
(type2-bits (pack type2 '-bits))
(name (or name (pack type1-bits '- rel '- type2-bits)))
(type1-string (str::cat
"@('" (str::downcase-string (symbol-name type1)) "')"))
(type2-string (str::cat
"@('" (str::downcase-string (symbol-name type2)) "')")))
`(,(if disable 'defruled 'defrule) ,name
:parents (,type1-bits ,type2-bits)
:short ,(str::cat "Relation between "
type1-string
" and "
type2-string
" bit sizes.")
(,rel (,type1-bits) (,type2-bits))
:rule-classes ((:linear :trigger-terms ((,type1-bits) (,type2-bits))))
:enable (,type1-bits ,type2-bits))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; The theorems generated by the following code calls
; hold for all choices of values consistent with [C].
; The generated rules are enabled.
(atc-def-integer-bits-linear-rule char <= short)
(atc-def-integer-bits-linear-rule short <= int)
(atc-def-integer-bits-linear-rule int <= long)
(atc-def-integer-bits-linear-rule long <= llong)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; The theorems generated by the following code
; hold for some choices of values consistent with [C].
; The code to generate the rules is the same for all choices,
; but the exact resulting rules depend on some choices.
; The rules are disabled, so it is clear when they are used,
; i.e. when there are dependencies on the choice of values.
(make-event
(b* ((rel (if (= (char-bits) (short-bits)) '= '<)))
`(atc-def-integer-bits-linear-rule char ,rel short
:name char-bits-vs-short-bits
:disable t)))
(make-event
(b* ((rel (if (= (short-bits) (int-bits)) '= '<)))
`(atc-def-integer-bits-linear-rule short ,rel int
:name short-bits-vs-int-bits
:disable t)))
(make-event
(b* ((rel (if (= (int-bits) (long-bits)) '= '<)))
`(atc-def-integer-bits-linear-rule int ,rel long
:name int-bits-vs-long-bits
:disable t)))
(make-event
(b* ((rel (if (= (long-bits) (llong-bits)) '= '<)))
`(atc-def-integer-bits-linear-rule long ,rel llong
:name long-bits-vs-llong-bits
:disable t)))
|
[
{
"context": "ds((name 0))*file*\n (print name))\n:outputs\n\"\n\\\"Beth\\\" \n\\\"Dan\\\" \n\\\"Kathy\\\" \n\\\"Mark\\\" \n\\\"Mary\\\" \n\\\"Suzi",
"end": 6484,
"score": 0.9994869232177734,
"start": 6480,
"tag": "NAME",
"value": "Beth"
},
{
"context": "))*file*\n (print name))\n:outputs\n\"\n\\\"Beth\\\" \n\\\"Dan\\\" \n\\\"Kathy\\\" \n\\\"Mark\\\" \n\\\"Mary\\\" \n\\\"Suzie\\\" \"\n\n; ",
"end": 6493,
"score": 0.9997168779373169,
"start": 6490,
"tag": "NAME",
"value": "Dan"
},
{
"context": " (print name))\n:outputs\n\"\n\\\"Beth\\\" \n\\\"Dan\\\" \n\\\"Kathy\\\" \n\\\"Mark\\\" \n\\\"Mary\\\" \n\\\"Suzie\\\" \"\n\n; body := imp",
"end": 6504,
"score": 0.9997370839118958,
"start": 6499,
"tag": "NAME",
"value": "Kathy"
},
{
"context": "name))\n:outputs\n\"\n\\\"Beth\\\" \n\\\"Dan\\\" \n\\\"Kathy\\\" \n\\\"Mark\\\" \n\\\"Mary\\\" \n\\\"Suzie\\\" \"\n\n; body := implicit prog",
"end": 6514,
"score": 0.9998403787612915,
"start": 6510,
"tag": "NAME",
"value": "Mark"
},
{
"context": "tputs\n\"\n\\\"Beth\\\" \n\\\"Dan\\\" \n\\\"Kathy\\\" \n\\\"Mark\\\" \n\\\"Mary\\\" \n\\\"Suzie\\\" \"\n\n; body := implicit progn\n\n; resul",
"end": 6524,
"score": 0.9997841119766235,
"start": 6520,
"tag": "NAME",
"value": "Mary"
},
{
"context": "Beth\\\" \n\\\"Dan\\\" \n\\\"Kathy\\\" \n\\\"Mark\\\" \n\\\"Mary\\\" \n\\\"Suzie\\\" \"\n\n; body := implicit progn\n\n; result := NIL\n#?",
"end": 6535,
"score": 0.9997242093086243,
"start": 6530,
"tag": "NAME",
"value": "Suzie"
},
{
"context": "(write-line *line*)))\n:outputs\n\"Beth 4.00 0\nDan 3.75 0\n\"\n\n#?(dofields((name 0)\n\t (payra",
"end": 7251,
"score": 0.9996943473815918,
"start": 7248,
"tag": "NAME",
"value": "Dan"
},
{
"context": "at(* payrate hrsworked))))\n:outputs\n\"total pay for Beth is 0.0\ntotal pay for Dan is 0.0\ntotal pay for Kat",
"end": 7496,
"score": 0.9727698564529419,
"start": 7492,
"tag": "NAME",
"value": "Beth"
},
{
"context": "\n:outputs\n\"total pay for Beth is 0.0\ntotal pay for Dan is 0.0\ntotal pay for Kathy is 40.0\ntotal pay for ",
"end": 7521,
"score": 0.9835560321807861,
"start": 7518,
"tag": "NAME",
"value": "Dan"
},
{
"context": "Beth is 0.0\ntotal pay for Dan is 0.0\ntotal pay for Kathy is 40.0\ntotal pay for Mark is 100.0\ntotal pay for",
"end": 7548,
"score": 0.9984556436538696,
"start": 7543,
"tag": "NAME",
"value": "Kathy"
},
{
"context": "n is 0.0\ntotal pay for Kathy is 40.0\ntotal pay for Mark is 100.0\ntotal pay for Mary is 121.0\ntotal pay fo",
"end": 7575,
"score": 0.9920750856399536,
"start": 7571,
"tag": "NAME",
"value": "Mark"
},
{
"context": " is 40.0\ntotal pay for Mark is 100.0\ntotal pay for Mary is 121.0\ntotal pay for Suzie is 76.5\"\n\n#?(let((co",
"end": 7603,
"score": 0.9977145195007324,
"start": 7599,
"tag": "NAME",
"value": "Mary"
},
{
"context": "is 100.0\ntotal pay for Mary is 121.0\ntotal pay for Suzie is 76.5\"\n\n#?(let((count 0)\n (pay 0))\n (d",
"end": 7632,
"score": 0.9981141090393066,
"start": 7627,
"tag": "NAME",
"value": "Suzie"
}
] |
spec/with-fields.lisp
|
hyotang666/with-fields
| 1 |
(defpackage :with-fields.spec
(:use :cl :jingoh :with-fields)
(:import-from :with-fields #:nth-fields)
)
(in-package :with-fields.spec)
(setup :with-fields)
(requirements-about WITH-FIELDS)
;;;; Description:
; binds var by character separated value string's specified index,
; then evaluate body.
#?(with-fields((s 1))"foo bar bazz"
s)
=> "bar"
,:test string=
#+syntax
(WITH-FIELDS (&rest bind*) init &body body) ; => result
;;;; Arguments and Values:
; bind* := (var index &key key)
; var := symbol, otherwise error. not evaluated.
#?(with-fields(("s" 1))"foo bar bazz"
"s")
:signals error
,:ignore-signals warning
#?(with-fields(((intern "VAR")1))"foo bar bazz"
var)
:signals error
,:ignore-signals warning
; var bound by string by default.
#?(with-fields((v 1))"1 2 3 4"
v)
:be-the string
; index := non negative integer, otherwise error. not evaluated.
#?(with-fields((v -1))"1 2 3 4"
v)
:signals error
,:ignore-signals warning
#?(with-fields((v (1+ 1)))"1 2 3 4"
v)
:signals error
,:ignore-signals warning
; key := function generate form. evaluated.
; when specified, var is bound by return value of such function.
#?(with-fields((v 1 :key #'read-from-string))"1 2 3 4"
v)
=> 2
#?(with-fields((v 1 :key read-from-string))"1 2 3 4"
v)
:signals (or error
warning ; for ccl
)
; init := string generate form. evaluated.
#?(with-fields((v 0))(format nil "~{~A~^ ~}"'(a s d f))
v)
=> "A"
,:test string=
; when init does not generate string, an error is signaled.
#?(with-fields((v 0))'("foo" "bar")
v)
:signals error
,:ignore-signals warning
; body := implicit progn.
; CL:DECLARE is valid, when it appear top of BODY.
#?(with-fields((v 0 :key #'parse-integer))"1 2 3"
(declare(type fixnum v))
v)
=> 1
; result := return value of BODY.
;;;; Affected By:
; none
;;;; Side-Effects:
; none
;;;; Notes:
; The default separator is #\space.
; When you need to specify another separator, you can use declare in top of body.
#?(with-fields((v 0))"foo:bar:bazz"
v)
=> "foo:bar:bazz"
,:test string=
#?(with-fields((v 0))"foo:bar:bazz"
(declare(separator #\:))
v)
=> "foo"
,:test string=
; When index over the length of fields, var bound by nil.
#?(with-fields((v 1))"foo"
v)
=> unspecified ; <--- NIL, but is error better? or empty string?
; INIT is string generate form, not `LINE` generate form.
; #\Newline is included as field value.
#?(with-fields((v 2))"zero one two
three"
v)
=> "two
three"
,:test string=
;;;; Exceptional-Situations:
(requirements-about DO-STREAM-FIELDS
:around
(with-input-from-string(*standard-input* (format nil "~{~A ~A~%~}"'(foo 1 bar 2)))
(call-body)))
;;;; Description:
; same like with-fields but accepts stream,
; and iterate lines.
#?(do-stream-fields((num 1))*standard-input*
(princ num))
:outputs "12"
#+syntax
(DO-STREAM-FIELDS (&rest bind*) input &body body) ; => result
;;;; Arguments and Values:
; bind* := (var index &key key)
; var := symbol, otherwise error.
#?(do-stream-fields(("VAR" 0))*standard-input*
var)
:signals error
; not evaluated.
#?(do-stream-fields(((intern "VAR")0))*standard-input*
var)
:signals error
; bound by string
#?(do-stream-fields((s 0))*standard-input*
(princ(stringp s)))
:outputs "TT"
; index := non negative integer, otherwise error.
#?(do-stream-fields((s -1))*standard-input*
s)
:signals error
#?(do-stream-fields((s zero))*standard-input*
s)
:signals error
; not evaluated.
#?(do-stream-fields((s (1+ 1)))*standard-input*
s)
:signals error
; key := function which applied string.
#?(do-stream-fields((num 1 :key #'read-from-string))*standard-input*
(prin1 num))
:outputs "12"
; evaluated.
#?(do-stream-fields((num 1 :key read-from-string))*standard-input*
(princ num))
:signals (or error
warning ; for ccl
)
; input := input stream generate form, evaluated.
; otherwise error.
#?(do-stream-fields((var 1))"not input stream"
(princ var))
:signals error
,:ignore-signals warning
; body := implicit progn
; result := NIL
#?(do-stream-fields((num 1 :key #'parse-integer))*standard-input*
(1+ num))
=> NIL
;;;; Affected By:
; none
;;;; Side-Effects:
; Bounds `*LINE*` with current line.
#?(do-stream-fields((num 1 :key #'parse-integer))*standard-input*
(when(= 2 num)
(write-string *line*)))
:outputs "BAR 2"
;;;; Notes:
; When index over the length of fields, unspecified.
#?(do-stream-fields((nothing 5))*standard-input*
nothing)
=> unspecified ; <--- currently NIL, is error better?
; return can work
#?(do-stream-fields((num 1 :key #'parse-integer))*standard-input*
(return num))
=> 1
; go can work.
#?(do-stream-fields((num 1 :key #'parse-integer))*standard-input*
(when(evenp num)
(go :end))
(princ num)
:end)
:outputs "1"
; declare can work.
#?(do-stream-fields((num 1 :key #'parse-integer))*standard-input*
(declare(type integer num))
(princ num))
:outputs "12"
; When need to specify separator, you can use declare.
#?(with-input-from-string(in "foo:bar:bazz")
(do-stream-fields((foo 0))in
(declare(separator #\:))
(princ foo)))
:outputs "foo"
;;;; Exceptional-Situations:
(requirements-about DOFIELDS)
;;;; Description:
; accept input line generator, then bound fields to var,
; then iterate body in such context.
#?(with-input-from-string(in "foo bar bazz")
(dofields((bar 1))in
(princ bar)))
:outputs "bar"
#+syntax
(DOFIELDS (&rest bind*) input &body body) ; => result
;;;; Arguments and Values:
; bind* := (var index &key key)
; var := symbol, otherwise error.
#?(dofields(("VAR" 0))"emp.data"
var)
:signals error
; not evaluated.
#?(dofields(((intern "VAR")0))"emp.data"
var)
:signals error
; index := non negative integer, otherwise error.
#?(dofields((v -1))"emp.data"
v)
:signals error
; not evaluated.
#?(dofields((v (1+ 1)))"emp.data"
v)
:signals error
; key := function applied field string of line.
#?(with-input-from-string(in "foo bar bazz")
(dofields((sym 0 :key #'read-from-string))in
(princ sym)))
:outputs "FOO"
; evaluated.
#?(dofields((v 0 :key read-from-string))"emp.data"
v)
:signals error
,:ignore-signals warning
; input := input stream or pathname designator.
#?(defvar *file*(merge-pathnames (asdf:system-source-directory
(asdf:find-system :with-fields.test))
"emp.data"))
=> *FILE*
,:lazy NIL
#?(dofields((name 0))*file*
(print name))
:outputs
"
\"Beth\"
\"Dan\"
\"Kathy\"
\"Mark\"
\"Mary\"
\"Suzie\" "
; body := implicit progn
; result := NIL
#?(dofields((name 0))*file*
(print name))
=> NIL
,:stream nil
;;;; Affected By:
; none
;;;; Side-Effects:
; consume stream contents.
;;;; Notes:
;;;; Exceptional-Situations:
;;;; Tests from clawk.
; Chapter 1, page 1, example 1
; Print all employees that have worked this week
;
; $3 > 0 { print $1 $2 $3 }
;
#?(dofields((name 0)(payrate 1)(hrsworked 2 :key #'parse-integer))*file*
(when(< 0 hrsworked)
(format t "~A~A~A~&" name payrate hrsworked)))
:outputs
"Kathy4.0010
Mark5.0020
Mary5.5022
Suzie4.2518
"
#?(dofields((hrsworked 2 :key #'parse-integer))*file*
(when(zerop hrsworked)
(write-line *line*)))
:outputs
"Beth 4.00 0
Dan 3.75 0
"
#?(dofields((name 0)
(payrate 1 :key #'read-from-string)
(hrsworked 2 :key #'read-from-string))
*file*
(format t "~&total pay for ~A is ~D"
name (float(* payrate hrsworked))))
:outputs
"total pay for Beth is 0.0
total pay for Dan is 0.0
total pay for Kathy is 40.0
total pay for Mark is 100.0
total pay for Mary is 121.0
total pay for Suzie is 76.5"
#?(let((count 0)
(pay 0))
(dofields((payrate 1 :key #'read-from-string)
(hrsworked 2 :key #'read-from-string))
*file*
(incf count)
(incf pay (* payrate hrsworked)))
(format t "~D employees~&total pay is ~D~&average pay is ~D"
count
pay
(/ pay count)))
:outputs
"6 employees
total pay is 337.5
average pay is 56.25"
(requirements-about NTH-FIELDS :test equal)
;;;; NOTE!
; This is internal, behavior may be changed.
; Especially...
; * When string is empty, NIL vs Signaling condition.
; * When there is no fields, NIL vs empty string.
;;;; Description:
; Collect nth fields of string.
#+syntax
(NTH-FIELDS string separator &rest indexies) ; => result
#?(nth-fields "foo bar bazz" #\space 0 2)
=> ("foo" "bazz")
;;;; Arguments and Values:
; string := string which separated by CHARACTER.
; When not string, an error is signaled.
#?(nth-fields () #\space 0) :signals error
,:lazy t
; When STRING is empty, NIL is returned.
#?(nth-fields "" #\space 2) => NIL
; separator := character which separates STRING.
; When separator imedeately follows separator, it is interpreted as empty field.
#?(nth-fields "foo::bar" #\: 0 1 2)
=> ("foo" "" "bar")
; #\Space is special. It is reduced.
#?(nth-fields "foo bar" #\space 0 1 2)
=> ("foo" "bar" nil)
; When separator be at first, it means first field is empty.
#?(nth-fields ":foo:bar" #\: 0 1 2)
=> ("" "foo" "bar")
; When separator is escaped, such separator is ignored as separator.
#?(nth-fields "foo\\:bar:bazz" #\: 0 1 2)
=> ("foo\\:bar" "bazz" nil)
; index := (INTEGER 0 *)
; When specified index's fields is not exist, such field's value becomes NIL.
#?(nth-fields "foo bar" #\space 5) => (NIL)
; When end without separator, it is interpretted no more fields.
#?(nth-fields "foo:bar" #\: 0 1 2) => ("foo" "bar" nil)
; When end with separator, it is interpretted one more fields.
#?(nth-fields "foo:bar:" #\: 0 1 2) => ("foo" "bar" "")
; NOTE! #\Space is treated as special. (Trimmed at first.)
#?(nth-fields " foo bar " #\space 0 1 2) => ("foo" "bar" nil)
; result := list which include specified index's sub string of STRING.
; Sub string's #\space is trimmed.
#?(nth-fields "foo : bar: bazz :" #\: 0 1 2 3)
=> ("foo" "bar" "bazz" "")
;;;; Affected By:
; none
;;;; Side-Effects:
; none
;;;; Notes:
;;;; Exceptional-Situations:
(requirements-about FOR-EACH-LINE)
;;;; Description:
; Almost same with DOFIELDS.
; DOFIELDS's syntax is based on CL:DO family, but FOR-EACH-LINE's syntax is based on CL:LOOP facility.
; In the body, you can use CL:LOOP macro keywords, but INITIALLY is invalid, and FOR, and WITH are implementation dependent (especially CLISP).
#+syntax
(FOR-EACH-LINE (&rest bind*) input &body body) ; => result
;;;; Arguments and Values:
; bind* := (var index)
; var := symbol
; index := (integer 0 *)
; input := pathname-designator
; body := implicit-progn
; result := NIL (the default).
;;;; Affected By:
; none
;;;; Side-Effects:
; Reading contents from specified input.
; Binds `*line*`.
;;;; Notes:
;;;; Exceptional-Situations:
;;;; Examples:
#?(let((path(probe-file "/proc/cpuinfo")))
(when path
(for-each-line((tag 0))path
(declare(separator #\:))
:when (uiop:string-prefix-p "processor" tag)
:count :it)))
=> implementation-dependent ; <--- In particular, environment dependent, the number of cpu cores.
#?(for-each-line((hrsworked 2 :key #'parse-integer))*file*
:when(zerop hrsworked)
:do (write-line *line*))
:outputs
"Beth 4.00 0
Dan 3.75 0
"
#?(for-each-line((payrate 1 :key #'read-from-string)
(hrsworked 2 :key #'read-from-string))
*file*
:count :it :into count
:sum (* payrate hrsworked) :into pay
:finally (format t "~D employees~&total pay is ~D~&average pay is ~D"
count pay (/ pay count)))
:outputs
"6 employees
total pay is 337.5
average pay is 56.25"
(requirements-about *LINE*)
;;;; Description:
; Bound with processing current line.
#?*line* :signals unbound-variable
#?(with-input-from-string(s "foo bar")
(dofields((v 0))s
(declare(ignore v))
(write-string *line*)))
:outputs "foo bar"
;;;; Value type is UNBOUND
;;;; Affected By:
; DO-STREAM-FIELDS DOFIELDS FOR-EACH-LINE
;;;; Notes:
|
74864
|
(defpackage :with-fields.spec
(:use :cl :jingoh :with-fields)
(:import-from :with-fields #:nth-fields)
)
(in-package :with-fields.spec)
(setup :with-fields)
(requirements-about WITH-FIELDS)
;;;; Description:
; binds var by character separated value string's specified index,
; then evaluate body.
#?(with-fields((s 1))"foo bar bazz"
s)
=> "bar"
,:test string=
#+syntax
(WITH-FIELDS (&rest bind*) init &body body) ; => result
;;;; Arguments and Values:
; bind* := (var index &key key)
; var := symbol, otherwise error. not evaluated.
#?(with-fields(("s" 1))"foo bar bazz"
"s")
:signals error
,:ignore-signals warning
#?(with-fields(((intern "VAR")1))"foo bar bazz"
var)
:signals error
,:ignore-signals warning
; var bound by string by default.
#?(with-fields((v 1))"1 2 3 4"
v)
:be-the string
; index := non negative integer, otherwise error. not evaluated.
#?(with-fields((v -1))"1 2 3 4"
v)
:signals error
,:ignore-signals warning
#?(with-fields((v (1+ 1)))"1 2 3 4"
v)
:signals error
,:ignore-signals warning
; key := function generate form. evaluated.
; when specified, var is bound by return value of such function.
#?(with-fields((v 1 :key #'read-from-string))"1 2 3 4"
v)
=> 2
#?(with-fields((v 1 :key read-from-string))"1 2 3 4"
v)
:signals (or error
warning ; for ccl
)
; init := string generate form. evaluated.
#?(with-fields((v 0))(format nil "~{~A~^ ~}"'(a s d f))
v)
=> "A"
,:test string=
; when init does not generate string, an error is signaled.
#?(with-fields((v 0))'("foo" "bar")
v)
:signals error
,:ignore-signals warning
; body := implicit progn.
; CL:DECLARE is valid, when it appear top of BODY.
#?(with-fields((v 0 :key #'parse-integer))"1 2 3"
(declare(type fixnum v))
v)
=> 1
; result := return value of BODY.
;;;; Affected By:
; none
;;;; Side-Effects:
; none
;;;; Notes:
; The default separator is #\space.
; When you need to specify another separator, you can use declare in top of body.
#?(with-fields((v 0))"foo:bar:bazz"
v)
=> "foo:bar:bazz"
,:test string=
#?(with-fields((v 0))"foo:bar:bazz"
(declare(separator #\:))
v)
=> "foo"
,:test string=
; When index over the length of fields, var bound by nil.
#?(with-fields((v 1))"foo"
v)
=> unspecified ; <--- NIL, but is error better? or empty string?
; INIT is string generate form, not `LINE` generate form.
; #\Newline is included as field value.
#?(with-fields((v 2))"zero one two
three"
v)
=> "two
three"
,:test string=
;;;; Exceptional-Situations:
(requirements-about DO-STREAM-FIELDS
:around
(with-input-from-string(*standard-input* (format nil "~{~A ~A~%~}"'(foo 1 bar 2)))
(call-body)))
;;;; Description:
; same like with-fields but accepts stream,
; and iterate lines.
#?(do-stream-fields((num 1))*standard-input*
(princ num))
:outputs "12"
#+syntax
(DO-STREAM-FIELDS (&rest bind*) input &body body) ; => result
;;;; Arguments and Values:
; bind* := (var index &key key)
; var := symbol, otherwise error.
#?(do-stream-fields(("VAR" 0))*standard-input*
var)
:signals error
; not evaluated.
#?(do-stream-fields(((intern "VAR")0))*standard-input*
var)
:signals error
; bound by string
#?(do-stream-fields((s 0))*standard-input*
(princ(stringp s)))
:outputs "TT"
; index := non negative integer, otherwise error.
#?(do-stream-fields((s -1))*standard-input*
s)
:signals error
#?(do-stream-fields((s zero))*standard-input*
s)
:signals error
; not evaluated.
#?(do-stream-fields((s (1+ 1)))*standard-input*
s)
:signals error
; key := function which applied string.
#?(do-stream-fields((num 1 :key #'read-from-string))*standard-input*
(prin1 num))
:outputs "12"
; evaluated.
#?(do-stream-fields((num 1 :key read-from-string))*standard-input*
(princ num))
:signals (or error
warning ; for ccl
)
; input := input stream generate form, evaluated.
; otherwise error.
#?(do-stream-fields((var 1))"not input stream"
(princ var))
:signals error
,:ignore-signals warning
; body := implicit progn
; result := NIL
#?(do-stream-fields((num 1 :key #'parse-integer))*standard-input*
(1+ num))
=> NIL
;;;; Affected By:
; none
;;;; Side-Effects:
; Bounds `*LINE*` with current line.
#?(do-stream-fields((num 1 :key #'parse-integer))*standard-input*
(when(= 2 num)
(write-string *line*)))
:outputs "BAR 2"
;;;; Notes:
; When index over the length of fields, unspecified.
#?(do-stream-fields((nothing 5))*standard-input*
nothing)
=> unspecified ; <--- currently NIL, is error better?
; return can work
#?(do-stream-fields((num 1 :key #'parse-integer))*standard-input*
(return num))
=> 1
; go can work.
#?(do-stream-fields((num 1 :key #'parse-integer))*standard-input*
(when(evenp num)
(go :end))
(princ num)
:end)
:outputs "1"
; declare can work.
#?(do-stream-fields((num 1 :key #'parse-integer))*standard-input*
(declare(type integer num))
(princ num))
:outputs "12"
; When need to specify separator, you can use declare.
#?(with-input-from-string(in "foo:bar:bazz")
(do-stream-fields((foo 0))in
(declare(separator #\:))
(princ foo)))
:outputs "foo"
;;;; Exceptional-Situations:
(requirements-about DOFIELDS)
;;;; Description:
; accept input line generator, then bound fields to var,
; then iterate body in such context.
#?(with-input-from-string(in "foo bar bazz")
(dofields((bar 1))in
(princ bar)))
:outputs "bar"
#+syntax
(DOFIELDS (&rest bind*) input &body body) ; => result
;;;; Arguments and Values:
; bind* := (var index &key key)
; var := symbol, otherwise error.
#?(dofields(("VAR" 0))"emp.data"
var)
:signals error
; not evaluated.
#?(dofields(((intern "VAR")0))"emp.data"
var)
:signals error
; index := non negative integer, otherwise error.
#?(dofields((v -1))"emp.data"
v)
:signals error
; not evaluated.
#?(dofields((v (1+ 1)))"emp.data"
v)
:signals error
; key := function applied field string of line.
#?(with-input-from-string(in "foo bar bazz")
(dofields((sym 0 :key #'read-from-string))in
(princ sym)))
:outputs "FOO"
; evaluated.
#?(dofields((v 0 :key read-from-string))"emp.data"
v)
:signals error
,:ignore-signals warning
; input := input stream or pathname designator.
#?(defvar *file*(merge-pathnames (asdf:system-source-directory
(asdf:find-system :with-fields.test))
"emp.data"))
=> *FILE*
,:lazy NIL
#?(dofields((name 0))*file*
(print name))
:outputs
"
\"<NAME>\"
\"<NAME>\"
\"<NAME>\"
\"<NAME>\"
\"<NAME>\"
\"<NAME>\" "
; body := implicit progn
; result := NIL
#?(dofields((name 0))*file*
(print name))
=> NIL
,:stream nil
;;;; Affected By:
; none
;;;; Side-Effects:
; consume stream contents.
;;;; Notes:
;;;; Exceptional-Situations:
;;;; Tests from clawk.
; Chapter 1, page 1, example 1
; Print all employees that have worked this week
;
; $3 > 0 { print $1 $2 $3 }
;
#?(dofields((name 0)(payrate 1)(hrsworked 2 :key #'parse-integer))*file*
(when(< 0 hrsworked)
(format t "~A~A~A~&" name payrate hrsworked)))
:outputs
"Kathy4.0010
Mark5.0020
Mary5.5022
Suzie4.2518
"
#?(dofields((hrsworked 2 :key #'parse-integer))*file*
(when(zerop hrsworked)
(write-line *line*)))
:outputs
"Beth 4.00 0
<NAME> 3.75 0
"
#?(dofields((name 0)
(payrate 1 :key #'read-from-string)
(hrsworked 2 :key #'read-from-string))
*file*
(format t "~&total pay for ~A is ~D"
name (float(* payrate hrsworked))))
:outputs
"total pay for <NAME> is 0.0
total pay for <NAME> is 0.0
total pay for <NAME> is 40.0
total pay for <NAME> is 100.0
total pay for <NAME> is 121.0
total pay for <NAME> is 76.5"
#?(let((count 0)
(pay 0))
(dofields((payrate 1 :key #'read-from-string)
(hrsworked 2 :key #'read-from-string))
*file*
(incf count)
(incf pay (* payrate hrsworked)))
(format t "~D employees~&total pay is ~D~&average pay is ~D"
count
pay
(/ pay count)))
:outputs
"6 employees
total pay is 337.5
average pay is 56.25"
(requirements-about NTH-FIELDS :test equal)
;;;; NOTE!
; This is internal, behavior may be changed.
; Especially...
; * When string is empty, NIL vs Signaling condition.
; * When there is no fields, NIL vs empty string.
;;;; Description:
; Collect nth fields of string.
#+syntax
(NTH-FIELDS string separator &rest indexies) ; => result
#?(nth-fields "foo bar bazz" #\space 0 2)
=> ("foo" "bazz")
;;;; Arguments and Values:
; string := string which separated by CHARACTER.
; When not string, an error is signaled.
#?(nth-fields () #\space 0) :signals error
,:lazy t
; When STRING is empty, NIL is returned.
#?(nth-fields "" #\space 2) => NIL
; separator := character which separates STRING.
; When separator imedeately follows separator, it is interpreted as empty field.
#?(nth-fields "foo::bar" #\: 0 1 2)
=> ("foo" "" "bar")
; #\Space is special. It is reduced.
#?(nth-fields "foo bar" #\space 0 1 2)
=> ("foo" "bar" nil)
; When separator be at first, it means first field is empty.
#?(nth-fields ":foo:bar" #\: 0 1 2)
=> ("" "foo" "bar")
; When separator is escaped, such separator is ignored as separator.
#?(nth-fields "foo\\:bar:bazz" #\: 0 1 2)
=> ("foo\\:bar" "bazz" nil)
; index := (INTEGER 0 *)
; When specified index's fields is not exist, such field's value becomes NIL.
#?(nth-fields "foo bar" #\space 5) => (NIL)
; When end without separator, it is interpretted no more fields.
#?(nth-fields "foo:bar" #\: 0 1 2) => ("foo" "bar" nil)
; When end with separator, it is interpretted one more fields.
#?(nth-fields "foo:bar:" #\: 0 1 2) => ("foo" "bar" "")
; NOTE! #\Space is treated as special. (Trimmed at first.)
#?(nth-fields " foo bar " #\space 0 1 2) => ("foo" "bar" nil)
; result := list which include specified index's sub string of STRING.
; Sub string's #\space is trimmed.
#?(nth-fields "foo : bar: bazz :" #\: 0 1 2 3)
=> ("foo" "bar" "bazz" "")
;;;; Affected By:
; none
;;;; Side-Effects:
; none
;;;; Notes:
;;;; Exceptional-Situations:
(requirements-about FOR-EACH-LINE)
;;;; Description:
; Almost same with DOFIELDS.
; DOFIELDS's syntax is based on CL:DO family, but FOR-EACH-LINE's syntax is based on CL:LOOP facility.
; In the body, you can use CL:LOOP macro keywords, but INITIALLY is invalid, and FOR, and WITH are implementation dependent (especially CLISP).
#+syntax
(FOR-EACH-LINE (&rest bind*) input &body body) ; => result
;;;; Arguments and Values:
; bind* := (var index)
; var := symbol
; index := (integer 0 *)
; input := pathname-designator
; body := implicit-progn
; result := NIL (the default).
;;;; Affected By:
; none
;;;; Side-Effects:
; Reading contents from specified input.
; Binds `*line*`.
;;;; Notes:
;;;; Exceptional-Situations:
;;;; Examples:
#?(let((path(probe-file "/proc/cpuinfo")))
(when path
(for-each-line((tag 0))path
(declare(separator #\:))
:when (uiop:string-prefix-p "processor" tag)
:count :it)))
=> implementation-dependent ; <--- In particular, environment dependent, the number of cpu cores.
#?(for-each-line((hrsworked 2 :key #'parse-integer))*file*
:when(zerop hrsworked)
:do (write-line *line*))
:outputs
"Beth 4.00 0
Dan 3.75 0
"
#?(for-each-line((payrate 1 :key #'read-from-string)
(hrsworked 2 :key #'read-from-string))
*file*
:count :it :into count
:sum (* payrate hrsworked) :into pay
:finally (format t "~D employees~&total pay is ~D~&average pay is ~D"
count pay (/ pay count)))
:outputs
"6 employees
total pay is 337.5
average pay is 56.25"
(requirements-about *LINE*)
;;;; Description:
; Bound with processing current line.
#?*line* :signals unbound-variable
#?(with-input-from-string(s "foo bar")
(dofields((v 0))s
(declare(ignore v))
(write-string *line*)))
:outputs "foo bar"
;;;; Value type is UNBOUND
;;;; Affected By:
; DO-STREAM-FIELDS DOFIELDS FOR-EACH-LINE
;;;; Notes:
| true |
(defpackage :with-fields.spec
(:use :cl :jingoh :with-fields)
(:import-from :with-fields #:nth-fields)
)
(in-package :with-fields.spec)
(setup :with-fields)
(requirements-about WITH-FIELDS)
;;;; Description:
; binds var by character separated value string's specified index,
; then evaluate body.
#?(with-fields((s 1))"foo bar bazz"
s)
=> "bar"
,:test string=
#+syntax
(WITH-FIELDS (&rest bind*) init &body body) ; => result
;;;; Arguments and Values:
; bind* := (var index &key key)
; var := symbol, otherwise error. not evaluated.
#?(with-fields(("s" 1))"foo bar bazz"
"s")
:signals error
,:ignore-signals warning
#?(with-fields(((intern "VAR")1))"foo bar bazz"
var)
:signals error
,:ignore-signals warning
; var bound by string by default.
#?(with-fields((v 1))"1 2 3 4"
v)
:be-the string
; index := non negative integer, otherwise error. not evaluated.
#?(with-fields((v -1))"1 2 3 4"
v)
:signals error
,:ignore-signals warning
#?(with-fields((v (1+ 1)))"1 2 3 4"
v)
:signals error
,:ignore-signals warning
; key := function generate form. evaluated.
; when specified, var is bound by return value of such function.
#?(with-fields((v 1 :key #'read-from-string))"1 2 3 4"
v)
=> 2
#?(with-fields((v 1 :key read-from-string))"1 2 3 4"
v)
:signals (or error
warning ; for ccl
)
; init := string generate form. evaluated.
#?(with-fields((v 0))(format nil "~{~A~^ ~}"'(a s d f))
v)
=> "A"
,:test string=
; when init does not generate string, an error is signaled.
#?(with-fields((v 0))'("foo" "bar")
v)
:signals error
,:ignore-signals warning
; body := implicit progn.
; CL:DECLARE is valid, when it appear top of BODY.
#?(with-fields((v 0 :key #'parse-integer))"1 2 3"
(declare(type fixnum v))
v)
=> 1
; result := return value of BODY.
;;;; Affected By:
; none
;;;; Side-Effects:
; none
;;;; Notes:
; The default separator is #\space.
; When you need to specify another separator, you can use declare in top of body.
#?(with-fields((v 0))"foo:bar:bazz"
v)
=> "foo:bar:bazz"
,:test string=
#?(with-fields((v 0))"foo:bar:bazz"
(declare(separator #\:))
v)
=> "foo"
,:test string=
; When index over the length of fields, var bound by nil.
#?(with-fields((v 1))"foo"
v)
=> unspecified ; <--- NIL, but is error better? or empty string?
; INIT is string generate form, not `LINE` generate form.
; #\Newline is included as field value.
#?(with-fields((v 2))"zero one two
three"
v)
=> "two
three"
,:test string=
;;;; Exceptional-Situations:
(requirements-about DO-STREAM-FIELDS
:around
(with-input-from-string(*standard-input* (format nil "~{~A ~A~%~}"'(foo 1 bar 2)))
(call-body)))
;;;; Description:
; same like with-fields but accepts stream,
; and iterate lines.
#?(do-stream-fields((num 1))*standard-input*
(princ num))
:outputs "12"
#+syntax
(DO-STREAM-FIELDS (&rest bind*) input &body body) ; => result
;;;; Arguments and Values:
; bind* := (var index &key key)
; var := symbol, otherwise error.
#?(do-stream-fields(("VAR" 0))*standard-input*
var)
:signals error
; not evaluated.
#?(do-stream-fields(((intern "VAR")0))*standard-input*
var)
:signals error
; bound by string
#?(do-stream-fields((s 0))*standard-input*
(princ(stringp s)))
:outputs "TT"
; index := non negative integer, otherwise error.
#?(do-stream-fields((s -1))*standard-input*
s)
:signals error
#?(do-stream-fields((s zero))*standard-input*
s)
:signals error
; not evaluated.
#?(do-stream-fields((s (1+ 1)))*standard-input*
s)
:signals error
; key := function which applied string.
#?(do-stream-fields((num 1 :key #'read-from-string))*standard-input*
(prin1 num))
:outputs "12"
; evaluated.
#?(do-stream-fields((num 1 :key read-from-string))*standard-input*
(princ num))
:signals (or error
warning ; for ccl
)
; input := input stream generate form, evaluated.
; otherwise error.
#?(do-stream-fields((var 1))"not input stream"
(princ var))
:signals error
,:ignore-signals warning
; body := implicit progn
; result := NIL
#?(do-stream-fields((num 1 :key #'parse-integer))*standard-input*
(1+ num))
=> NIL
;;;; Affected By:
; none
;;;; Side-Effects:
; Bounds `*LINE*` with current line.
#?(do-stream-fields((num 1 :key #'parse-integer))*standard-input*
(when(= 2 num)
(write-string *line*)))
:outputs "BAR 2"
;;;; Notes:
; When index over the length of fields, unspecified.
#?(do-stream-fields((nothing 5))*standard-input*
nothing)
=> unspecified ; <--- currently NIL, is error better?
; return can work
#?(do-stream-fields((num 1 :key #'parse-integer))*standard-input*
(return num))
=> 1
; go can work.
#?(do-stream-fields((num 1 :key #'parse-integer))*standard-input*
(when(evenp num)
(go :end))
(princ num)
:end)
:outputs "1"
; declare can work.
#?(do-stream-fields((num 1 :key #'parse-integer))*standard-input*
(declare(type integer num))
(princ num))
:outputs "12"
; When need to specify separator, you can use declare.
#?(with-input-from-string(in "foo:bar:bazz")
(do-stream-fields((foo 0))in
(declare(separator #\:))
(princ foo)))
:outputs "foo"
;;;; Exceptional-Situations:
(requirements-about DOFIELDS)
;;;; Description:
; accept input line generator, then bound fields to var,
; then iterate body in such context.
#?(with-input-from-string(in "foo bar bazz")
(dofields((bar 1))in
(princ bar)))
:outputs "bar"
#+syntax
(DOFIELDS (&rest bind*) input &body body) ; => result
;;;; Arguments and Values:
; bind* := (var index &key key)
; var := symbol, otherwise error.
#?(dofields(("VAR" 0))"emp.data"
var)
:signals error
; not evaluated.
#?(dofields(((intern "VAR")0))"emp.data"
var)
:signals error
; index := non negative integer, otherwise error.
#?(dofields((v -1))"emp.data"
v)
:signals error
; not evaluated.
#?(dofields((v (1+ 1)))"emp.data"
v)
:signals error
; key := function applied field string of line.
#?(with-input-from-string(in "foo bar bazz")
(dofields((sym 0 :key #'read-from-string))in
(princ sym)))
:outputs "FOO"
; evaluated.
#?(dofields((v 0 :key read-from-string))"emp.data"
v)
:signals error
,:ignore-signals warning
; input := input stream or pathname designator.
#?(defvar *file*(merge-pathnames (asdf:system-source-directory
(asdf:find-system :with-fields.test))
"emp.data"))
=> *FILE*
,:lazy NIL
#?(dofields((name 0))*file*
(print name))
:outputs
"
\"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\" "
; body := implicit progn
; result := NIL
#?(dofields((name 0))*file*
(print name))
=> NIL
,:stream nil
;;;; Affected By:
; none
;;;; Side-Effects:
; consume stream contents.
;;;; Notes:
;;;; Exceptional-Situations:
;;;; Tests from clawk.
; Chapter 1, page 1, example 1
; Print all employees that have worked this week
;
; $3 > 0 { print $1 $2 $3 }
;
#?(dofields((name 0)(payrate 1)(hrsworked 2 :key #'parse-integer))*file*
(when(< 0 hrsworked)
(format t "~A~A~A~&" name payrate hrsworked)))
:outputs
"Kathy4.0010
Mark5.0020
Mary5.5022
Suzie4.2518
"
#?(dofields((hrsworked 2 :key #'parse-integer))*file*
(when(zerop hrsworked)
(write-line *line*)))
:outputs
"Beth 4.00 0
PI:NAME:<NAME>END_PI 3.75 0
"
#?(dofields((name 0)
(payrate 1 :key #'read-from-string)
(hrsworked 2 :key #'read-from-string))
*file*
(format t "~&total pay for ~A is ~D"
name (float(* payrate hrsworked))))
:outputs
"total pay for PI:NAME:<NAME>END_PI is 0.0
total pay for PI:NAME:<NAME>END_PI is 0.0
total pay for PI:NAME:<NAME>END_PI is 40.0
total pay for PI:NAME:<NAME>END_PI is 100.0
total pay for PI:NAME:<NAME>END_PI is 121.0
total pay for PI:NAME:<NAME>END_PI is 76.5"
#?(let((count 0)
(pay 0))
(dofields((payrate 1 :key #'read-from-string)
(hrsworked 2 :key #'read-from-string))
*file*
(incf count)
(incf pay (* payrate hrsworked)))
(format t "~D employees~&total pay is ~D~&average pay is ~D"
count
pay
(/ pay count)))
:outputs
"6 employees
total pay is 337.5
average pay is 56.25"
(requirements-about NTH-FIELDS :test equal)
;;;; NOTE!
; This is internal, behavior may be changed.
; Especially...
; * When string is empty, NIL vs Signaling condition.
; * When there is no fields, NIL vs empty string.
;;;; Description:
; Collect nth fields of string.
#+syntax
(NTH-FIELDS string separator &rest indexies) ; => result
#?(nth-fields "foo bar bazz" #\space 0 2)
=> ("foo" "bazz")
;;;; Arguments and Values:
; string := string which separated by CHARACTER.
; When not string, an error is signaled.
#?(nth-fields () #\space 0) :signals error
,:lazy t
; When STRING is empty, NIL is returned.
#?(nth-fields "" #\space 2) => NIL
; separator := character which separates STRING.
; When separator imedeately follows separator, it is interpreted as empty field.
#?(nth-fields "foo::bar" #\: 0 1 2)
=> ("foo" "" "bar")
; #\Space is special. It is reduced.
#?(nth-fields "foo bar" #\space 0 1 2)
=> ("foo" "bar" nil)
; When separator be at first, it means first field is empty.
#?(nth-fields ":foo:bar" #\: 0 1 2)
=> ("" "foo" "bar")
; When separator is escaped, such separator is ignored as separator.
#?(nth-fields "foo\\:bar:bazz" #\: 0 1 2)
=> ("foo\\:bar" "bazz" nil)
; index := (INTEGER 0 *)
; When specified index's fields is not exist, such field's value becomes NIL.
#?(nth-fields "foo bar" #\space 5) => (NIL)
; When end without separator, it is interpretted no more fields.
#?(nth-fields "foo:bar" #\: 0 1 2) => ("foo" "bar" nil)
; When end with separator, it is interpretted one more fields.
#?(nth-fields "foo:bar:" #\: 0 1 2) => ("foo" "bar" "")
; NOTE! #\Space is treated as special. (Trimmed at first.)
#?(nth-fields " foo bar " #\space 0 1 2) => ("foo" "bar" nil)
; result := list which include specified index's sub string of STRING.
; Sub string's #\space is trimmed.
#?(nth-fields "foo : bar: bazz :" #\: 0 1 2 3)
=> ("foo" "bar" "bazz" "")
;;;; Affected By:
; none
;;;; Side-Effects:
; none
;;;; Notes:
;;;; Exceptional-Situations:
(requirements-about FOR-EACH-LINE)
;;;; Description:
; Almost same with DOFIELDS.
; DOFIELDS's syntax is based on CL:DO family, but FOR-EACH-LINE's syntax is based on CL:LOOP facility.
; In the body, you can use CL:LOOP macro keywords, but INITIALLY is invalid, and FOR, and WITH are implementation dependent (especially CLISP).
#+syntax
(FOR-EACH-LINE (&rest bind*) input &body body) ; => result
;;;; Arguments and Values:
; bind* := (var index)
; var := symbol
; index := (integer 0 *)
; input := pathname-designator
; body := implicit-progn
; result := NIL (the default).
;;;; Affected By:
; none
;;;; Side-Effects:
; Reading contents from specified input.
; Binds `*line*`.
;;;; Notes:
;;;; Exceptional-Situations:
;;;; Examples:
#?(let((path(probe-file "/proc/cpuinfo")))
(when path
(for-each-line((tag 0))path
(declare(separator #\:))
:when (uiop:string-prefix-p "processor" tag)
:count :it)))
=> implementation-dependent ; <--- In particular, environment dependent, the number of cpu cores.
#?(for-each-line((hrsworked 2 :key #'parse-integer))*file*
:when(zerop hrsworked)
:do (write-line *line*))
:outputs
"Beth 4.00 0
Dan 3.75 0
"
#?(for-each-line((payrate 1 :key #'read-from-string)
(hrsworked 2 :key #'read-from-string))
*file*
:count :it :into count
:sum (* payrate hrsworked) :into pay
:finally (format t "~D employees~&total pay is ~D~&average pay is ~D"
count pay (/ pay count)))
:outputs
"6 employees
total pay is 337.5
average pay is 56.25"
(requirements-about *LINE*)
;;;; Description:
; Bound with processing current line.
#?*line* :signals unbound-variable
#?(with-input-from-string(s "foo bar")
(dofields((v 0))s
(declare(ignore v))
(write-string *line*)))
:outputs "foo bar"
;;;; Value type is UNBOUND
;;;; Affected By:
; DO-STREAM-FIELDS DOFIELDS FOR-EACH-LINE
;;;; Notes:
|
[
{
"context": ";-*- Mode: Lisp -*-\n;;;; Author: Paul Dietz\n;;;; Created: Sun Apr 6 17:00:30 2003\n;;;; Cont",
"end": 49,
"score": 0.9998772740364075,
"start": 39,
"tag": "NAME",
"value": "Paul Dietz"
},
{
"context": "EVAL-WHEN\n\n;;; The following test was suggested by Sam Steingold,\n;;; so I've created this file to hold it.\n\n(in-p",
"end": 179,
"score": 0.9998208284378052,
"start": 166,
"tag": "NAME",
"value": "Sam Steingold"
}
] |
ansi-tests/eval-when.lsp
|
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD
| 10 |
;-*- Mode: Lisp -*-
;;;; Author: Paul Dietz
;;;; Created: Sun Apr 6 17:00:30 2003
;;;; Contains: Tests for EVAL-WHEN
;;; The following test was suggested by Sam Steingold,
;;; so I've created this file to hold it.
(in-package :cl-test)
(defvar *eval-when.1-collector*)
(deftest eval-when.1
(let ((forms nil) all (ff "generated-eval-when-test-file.lisp"))
(dolist (c '(nil (:compile-toplevel)))
(dolist (l '(nil (:load-toplevel)))
(dolist (x '(nil (:execute)))
(push `(eval-when (,@c ,@l ,@x)
(push '(,@c ,@l ,@x) *eval-when.1-collector*))
forms))))
(dolist (c '(nil (:compile-toplevel)))
(dolist (l '(nil (:load-toplevel)))
(dolist (x '(nil (:execute)))
(push `(let () (eval-when (,@c ,@l ,@x)
(push '(let ,@c ,@l ,@x) *eval-when.1-collector*)))
forms))))
(with-open-file (o ff :direction :output :if-exists :supersede)
(dolist (f forms)
(prin1 f o)
(terpri o)))
(let ((*eval-when.1-collector* nil))
(load ff)
(push (cons "load source" *eval-when.1-collector*) all))
(let ((*eval-when.1-collector* nil))
(compile-file ff)
(push (cons "compile source" *eval-when.1-collector*) all))
(let ((*eval-when.1-collector* nil))
(load (compile-file-pathname ff))
(push (cons "load compiled" *eval-when.1-collector*) all))
(delete-file ff)
(delete-file (compile-file-pathname ff))
#+clisp (delete-file (make-pathname :type "lib" :defaults ff))
(nreverse all))
(("load source"
(:execute) (:load-toplevel :execute) (:compile-toplevel :execute)
(:compile-toplevel :load-toplevel :execute)
(let :execute) (let :load-toplevel :execute)
(let :compile-toplevel :execute)
(let :compile-toplevel :load-toplevel :execute))
("compile source"
(:compile-toplevel) (:compile-toplevel :execute)
(:compile-toplevel :load-toplevel)
(:compile-toplevel :load-toplevel :execute))
("load compiled"
(:load-toplevel) (:load-toplevel :execute)
(:compile-toplevel :load-toplevel)
(:compile-toplevel :load-toplevel :execute)
(let :execute) (let :load-toplevel :execute)
(let :compile-toplevel :execute)
(let :compile-toplevel :load-toplevel :execute))))
;;; More EVAL-WHEN tests to go here
(deftest eval-when.2
(eval-when () :bad)
nil)
(deftest eval-when.3
(eval-when (:execute))
nil)
(deftest eval-when.4
(eval-when (:execute) :good)
:good)
(deftest eval-when.5
(eval-when (:compile-toplevel) :bad)
nil)
(deftest eval-when.6
(eval-when (:load-toplevel) :bad)
nil)
(deftest eval-when.7
(eval-when (:compile-toplevel :execute) :good)
:good)
(deftest eval-when.8
(eval-when (:load-toplevel :execute) :good)
:good)
(deftest eval-when.9
(eval-when (:load-toplevel :compile-toplevel) :bad)
nil)
(deftest eval-when.10
(eval-when (:load-toplevel :compile-toplevel :execute) :good)
:good)
(deftest eval-when.11
(eval-when (:execute) (values 'a 'b 'c 'd))
a b c d)
(deftest eval-when.12
(let ((x :good))
(values (eval-when (:load-toplevel) (setq x :bad)) x))
nil :good)
(deftest eval-when.13
(let ((x :good))
(values (eval-when (:compile-toplevel) (setq x :bad)) x))
nil :good)
(deftest eval-when.14
(let ((x :bad))
(values (eval-when (:execute) (setq x :good)) x))
:good :good)
(deftest eval-when.15
(let ((x :good))
(values (eval-when (load) (setq x :bad)) x))
nil :good)
(deftest eval-when.16
(let ((x :good))
(values (eval-when (compile) (setq x :bad)) x))
nil :good)
(deftest eval-when.17
(let ((x :bad))
(values (eval-when (eval) (setq x :good)) x))
:good :good)
;;; Macros are expanded in the appropriate environment
(deftest eval-when.18
(macrolet ((%m (z) z))
(eval-when (:execute) (expand-in-current-env (%m :good))))
:good)
|
68669
|
;-*- Mode: Lisp -*-
;;;; Author: <NAME>
;;;; Created: Sun Apr 6 17:00:30 2003
;;;; Contains: Tests for EVAL-WHEN
;;; The following test was suggested by <NAME>,
;;; so I've created this file to hold it.
(in-package :cl-test)
(defvar *eval-when.1-collector*)
(deftest eval-when.1
(let ((forms nil) all (ff "generated-eval-when-test-file.lisp"))
(dolist (c '(nil (:compile-toplevel)))
(dolist (l '(nil (:load-toplevel)))
(dolist (x '(nil (:execute)))
(push `(eval-when (,@c ,@l ,@x)
(push '(,@c ,@l ,@x) *eval-when.1-collector*))
forms))))
(dolist (c '(nil (:compile-toplevel)))
(dolist (l '(nil (:load-toplevel)))
(dolist (x '(nil (:execute)))
(push `(let () (eval-when (,@c ,@l ,@x)
(push '(let ,@c ,@l ,@x) *eval-when.1-collector*)))
forms))))
(with-open-file (o ff :direction :output :if-exists :supersede)
(dolist (f forms)
(prin1 f o)
(terpri o)))
(let ((*eval-when.1-collector* nil))
(load ff)
(push (cons "load source" *eval-when.1-collector*) all))
(let ((*eval-when.1-collector* nil))
(compile-file ff)
(push (cons "compile source" *eval-when.1-collector*) all))
(let ((*eval-when.1-collector* nil))
(load (compile-file-pathname ff))
(push (cons "load compiled" *eval-when.1-collector*) all))
(delete-file ff)
(delete-file (compile-file-pathname ff))
#+clisp (delete-file (make-pathname :type "lib" :defaults ff))
(nreverse all))
(("load source"
(:execute) (:load-toplevel :execute) (:compile-toplevel :execute)
(:compile-toplevel :load-toplevel :execute)
(let :execute) (let :load-toplevel :execute)
(let :compile-toplevel :execute)
(let :compile-toplevel :load-toplevel :execute))
("compile source"
(:compile-toplevel) (:compile-toplevel :execute)
(:compile-toplevel :load-toplevel)
(:compile-toplevel :load-toplevel :execute))
("load compiled"
(:load-toplevel) (:load-toplevel :execute)
(:compile-toplevel :load-toplevel)
(:compile-toplevel :load-toplevel :execute)
(let :execute) (let :load-toplevel :execute)
(let :compile-toplevel :execute)
(let :compile-toplevel :load-toplevel :execute))))
;;; More EVAL-WHEN tests to go here
(deftest eval-when.2
(eval-when () :bad)
nil)
(deftest eval-when.3
(eval-when (:execute))
nil)
(deftest eval-when.4
(eval-when (:execute) :good)
:good)
(deftest eval-when.5
(eval-when (:compile-toplevel) :bad)
nil)
(deftest eval-when.6
(eval-when (:load-toplevel) :bad)
nil)
(deftest eval-when.7
(eval-when (:compile-toplevel :execute) :good)
:good)
(deftest eval-when.8
(eval-when (:load-toplevel :execute) :good)
:good)
(deftest eval-when.9
(eval-when (:load-toplevel :compile-toplevel) :bad)
nil)
(deftest eval-when.10
(eval-when (:load-toplevel :compile-toplevel :execute) :good)
:good)
(deftest eval-when.11
(eval-when (:execute) (values 'a 'b 'c 'd))
a b c d)
(deftest eval-when.12
(let ((x :good))
(values (eval-when (:load-toplevel) (setq x :bad)) x))
nil :good)
(deftest eval-when.13
(let ((x :good))
(values (eval-when (:compile-toplevel) (setq x :bad)) x))
nil :good)
(deftest eval-when.14
(let ((x :bad))
(values (eval-when (:execute) (setq x :good)) x))
:good :good)
(deftest eval-when.15
(let ((x :good))
(values (eval-when (load) (setq x :bad)) x))
nil :good)
(deftest eval-when.16
(let ((x :good))
(values (eval-when (compile) (setq x :bad)) x))
nil :good)
(deftest eval-when.17
(let ((x :bad))
(values (eval-when (eval) (setq x :good)) x))
:good :good)
;;; Macros are expanded in the appropriate environment
(deftest eval-when.18
(macrolet ((%m (z) z))
(eval-when (:execute) (expand-in-current-env (%m :good))))
:good)
| true |
;-*- Mode: Lisp -*-
;;;; Author: PI:NAME:<NAME>END_PI
;;;; Created: Sun Apr 6 17:00:30 2003
;;;; Contains: Tests for EVAL-WHEN
;;; The following test was suggested by PI:NAME:<NAME>END_PI,
;;; so I've created this file to hold it.
(in-package :cl-test)
(defvar *eval-when.1-collector*)
(deftest eval-when.1
(let ((forms nil) all (ff "generated-eval-when-test-file.lisp"))
(dolist (c '(nil (:compile-toplevel)))
(dolist (l '(nil (:load-toplevel)))
(dolist (x '(nil (:execute)))
(push `(eval-when (,@c ,@l ,@x)
(push '(,@c ,@l ,@x) *eval-when.1-collector*))
forms))))
(dolist (c '(nil (:compile-toplevel)))
(dolist (l '(nil (:load-toplevel)))
(dolist (x '(nil (:execute)))
(push `(let () (eval-when (,@c ,@l ,@x)
(push '(let ,@c ,@l ,@x) *eval-when.1-collector*)))
forms))))
(with-open-file (o ff :direction :output :if-exists :supersede)
(dolist (f forms)
(prin1 f o)
(terpri o)))
(let ((*eval-when.1-collector* nil))
(load ff)
(push (cons "load source" *eval-when.1-collector*) all))
(let ((*eval-when.1-collector* nil))
(compile-file ff)
(push (cons "compile source" *eval-when.1-collector*) all))
(let ((*eval-when.1-collector* nil))
(load (compile-file-pathname ff))
(push (cons "load compiled" *eval-when.1-collector*) all))
(delete-file ff)
(delete-file (compile-file-pathname ff))
#+clisp (delete-file (make-pathname :type "lib" :defaults ff))
(nreverse all))
(("load source"
(:execute) (:load-toplevel :execute) (:compile-toplevel :execute)
(:compile-toplevel :load-toplevel :execute)
(let :execute) (let :load-toplevel :execute)
(let :compile-toplevel :execute)
(let :compile-toplevel :load-toplevel :execute))
("compile source"
(:compile-toplevel) (:compile-toplevel :execute)
(:compile-toplevel :load-toplevel)
(:compile-toplevel :load-toplevel :execute))
("load compiled"
(:load-toplevel) (:load-toplevel :execute)
(:compile-toplevel :load-toplevel)
(:compile-toplevel :load-toplevel :execute)
(let :execute) (let :load-toplevel :execute)
(let :compile-toplevel :execute)
(let :compile-toplevel :load-toplevel :execute))))
;;; More EVAL-WHEN tests to go here
(deftest eval-when.2
(eval-when () :bad)
nil)
(deftest eval-when.3
(eval-when (:execute))
nil)
(deftest eval-when.4
(eval-when (:execute) :good)
:good)
(deftest eval-when.5
(eval-when (:compile-toplevel) :bad)
nil)
(deftest eval-when.6
(eval-when (:load-toplevel) :bad)
nil)
(deftest eval-when.7
(eval-when (:compile-toplevel :execute) :good)
:good)
(deftest eval-when.8
(eval-when (:load-toplevel :execute) :good)
:good)
(deftest eval-when.9
(eval-when (:load-toplevel :compile-toplevel) :bad)
nil)
(deftest eval-when.10
(eval-when (:load-toplevel :compile-toplevel :execute) :good)
:good)
(deftest eval-when.11
(eval-when (:execute) (values 'a 'b 'c 'd))
a b c d)
(deftest eval-when.12
(let ((x :good))
(values (eval-when (:load-toplevel) (setq x :bad)) x))
nil :good)
(deftest eval-when.13
(let ((x :good))
(values (eval-when (:compile-toplevel) (setq x :bad)) x))
nil :good)
(deftest eval-when.14
(let ((x :bad))
(values (eval-when (:execute) (setq x :good)) x))
:good :good)
(deftest eval-when.15
(let ((x :good))
(values (eval-when (load) (setq x :bad)) x))
nil :good)
(deftest eval-when.16
(let ((x :good))
(values (eval-when (compile) (setq x :bad)) x))
nil :good)
(deftest eval-when.17
(let ((x :bad))
(values (eval-when (eval) (setq x :good)) x))
:good :good)
;;; Macros are expanded in the appropriate environment
(deftest eval-when.18
(macrolet ((%m (z) z))
(eval-when (:execute) (expand-in-current-env (%m :good))))
:good)
|
[
{
"context": ";;\n;; Copyright (c) 2005, Gigamonkeys Consulting All rights reserved.\n;;\n\n(in-package :monkeylib-u",
"end": 48,
"score": 0.999750554561615,
"start": 26,
"tag": "NAME",
"value": "Gigamonkeys Consulting"
}
] |
with-time.lisp
|
ymmmt/monkeylib-utilities
| 0 |
;;
;; Copyright (c) 2005, Gigamonkeys Consulting All rights reserved.
;;
(in-package :monkeylib-utilities)
;; Note these are the offsets as the rest of the world (e.g. ISO-8601)
;; thinks of them. The time-zone argument to DECODE-UNIVERSAL-TIME is
;; the negation of these numeric values. The information that went
;; into this list was originally found at
;; <http://www.timeanddate.com/library/abbreviations/timezones/>
;; though any transcription errors are likely my own.
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter *time-zones*
'(;; North America
(:nst -7/2 "Newfoundland Standard Time")
(:hnt -7/2 "Heure Normale de Terre-Neuve")
(:ndt -5/2 "Newfoundland Daylight Time")
(:hat -5/2 "Heure Avancée de Terre-Neuve")
(:haa -3 "Heure Avancée de l'Atlantique")
(:adt -3 "Atlantic Daylight Time")
(:hna -4 "Heure Normale de l'Atlantique")
(:hae -4 "Heure Avancée de l'Est")
(:edt -4 "Eastern Daylight Time")
(:ast -4 "Atlantic Standard Time")
(:hne -5 "Heure Normale de l'Est")
(:hac -5 "Heure Avancée du Centre")
(:est -5 "Eastern Standard Time")
(:cdt -5 "Central Daylight Time")
(:mdt -6 "Mountain Daylight Time")
(:hnc -6 "Heure Normale du Centre")
(:har -6 "Heure Avancée des Rocheuses")
(:cst -6 "Central Standard Time")
(:pdt -7 "Pacific Daylight Time")
(:mst -7 "Mountain Standard Time")
(:hnr -7 "Heure Normale des Rocheuses")
(:hap -7 "Heure Avancée du Pacifique")
(:pst -8 "Pacific Standard Time")
(:hnp -8 "Heure Normale du Pacifique")
(:hay -8 "Heure Avancée du Yukon")
(:akdt -8 "Alaska Daylight Time")
(:hny -9 "Heure Normale du Yukon")
(:hadt -9 "Hawaii-Aleutian Daylight Time")
(:akst -9 "Alaska Standard Time")
(:hast -10 "Hawaii-Aleutian Standard Time")
;; Military
(:m 12 "Mike Time Zone")
(:l 11 "Lima Time Zone")
(:k 10 "Kilo Time Zone")
(:i 9 "India Time Zone")
(:h 8 "Hotel Time Zone")
(:g 7 "Golf Time Zone")
(:f 6 "Foxtrot Time Zone")
(:e 5 "Echo Time Zone")
(:d 4 "Delta Time Zone")
(:c 3 "Charlie Time Zone")
(:b 2 "Bravo Time Zone")
(:a 1 "Alpha Time Zone")
(:z 0 "Zulu Time Zone")
(:n -1 "November Time Zone")
(:o -2 "Oscar Time Zone")
(:p -3 "Papa Time Zone")
(:q -4 "Quebec Time Zone")
(:r -5 "Romeo Time Zone")
(:s -6 "Sierra Time Zone")
(:t -7 "Tango Time Zone")
(:u -8 "Uniform Time Zone")
(:v -9 "Victor Time Zone")
(:w -10 "Whiskey Time Zone")
(:x -11 "X-ray Time Zone")
(:y -12 "Yankee Time Zone")
;; Europe
(:eest 3 "Eastern European Summer Time")
(:mesz 2 "Mitteleuropäische Sommerzeit")
(:eet 2 "Eastern European Time")
(:cest 2 "Central European Summer Time")
(:west 1 "Western European Summer Time")
(:mez 1 "Mitteleuropäische Zeit")
(:ist 1 "Irish Summer Time")
(:cet 1 "Central European Time")
(:bst 1 "British Summer Time")
(:wet 0 "Western European Time")
(:utc 0 "Coordinated Universal Time")
(:gmt 0 "Greenwich Mean Time")
;; Australia
(:nft 23/2 "Norfolk (Island) Time")
(:edt 11 "Eastern Daylight Time")
(:aedt 11 "Australian Eastern Daylight Time")
(:cdt 21/2 "Central Daylight Time")
(:acdt 21/2 "Australian Central Daylight Time")
(:est 10 "Eastern Standard Time")
(:aest 10 "Australian Eastern Standard Time")
(:cst 19/2 "Central Standard Time")
(:acst 19/2 "Australian Central Standard Time")
(:wst 8 "Western Standard Time")
(:awst 8 "Australian Western Standard Time")
(:cxt 7 "Christmas Island Time"))))
(defparameter *long-month-names*
#("January"
"February"
"March"
"April"
"May"
"June"
"July"
"August"
"September"
"October"
"November"
"December"))
(defparameter *day-names*
#("Monday"
"Tuesday"
"Wednesday"
"Thursday"
"Friday"
"Saturday"
"Sunday"))
(defun month-name (number)
(aref *long-month-names* (1- number)))
(defun day-name (number)
(aref *day-names* number))
(defun make-time (&rest args &key second minute hour day month year zone (defaults (get-universal-time)))
(declare (ignore second minute hour day month year zone))
(remf args :defaults)
(apply #'merge-time defaults args))
;;(defun midnight (&key day month year zone)
;; (make-time :second 0 :minute 0 :hour 0 :day day :month month :year year :zone zone))
(defun merge-time (utc &key second minute hour day month year zone)
(multiple-value-bind (utc-second
utc-minute
utc-hour
utc-day
utc-month
utc-year
utc-day-of-week
utc-daylight-savings-p
utc-zone)
(decode-universal-time utc)
(declare (ignore utc-day-of-week))
(encode-universal-time
(or second utc-second)
(or minute utc-minute)
(or hour utc-hour)
(or day utc-day)
(or month utc-month)
(or year utc-year)
(or (translate-zone zone) (if utc-daylight-savings-p (1- utc-zone) utc-zone)))))
(defun translate-zone (zone)
(typecase zone
(number zone)
(keyword (- (second (find zone *time-zones* :key #'first))))))
(defun reverse-translate-zone (zone)
(first (find zone *time-zones* :key #'second)))
(defmacro with-time ((&rest args) utc &body body)
(let* ((zone-cons (member '&zone args))
(zone (if zone-cons (cadr zone-cons)))
(args (nconc (ldiff args zone-cons) (cddr zone-cons)))
(gensymed-vars ()))
(when (find zone *time-zones* :key #'first)
(setf zone (- (second (find zone *time-zones* :key #'first)))))
(labels ((part-name (spec)
(if (symbolp spec) spec (first spec)))
(var-name (spec)
(if (symbolp spec) spec (second spec)))
(new-gensym () (first (push (gensym) gensymed-vars)))
(find-var (name)
(let ((name (find name args :key #'part-name :test #'string=)))
(if name (var-name name) (new-gensym)))))
(let ((vars (mapcar #'find-var '(second minute hour date month year day daylight-p zone))))
`(multiple-value-bind ,vars ,(if zone
`(decode-universal-time ,utc ,zone)
`(decode-universal-time ,utc))
(declare (ignore ,@gensymed-vars))
,@body)))))
(defmacro with-current-time ((&rest args) &body body)
`(with-time (,@args) (get-universal-time) ,@body))
;; Loosely based on code from <http://www.pvv.ntnu.no/~nsaa/ISO8601.html>
(defun format-iso-8601-time (time-value &key time-zone omit-time-zone omit-date omit-time)
"Formats a universal time TIME-VALUE in ISO 8601 format. If no
time zone is provided the default timezone returned by
DECODE-UNIVERSAL-TIME, adjusted by daylights savings time as
appropriate, is used. The time zone information is included in
the generated string unless OMIT-TIME-ZONE is true. (In general,
if you want a shorter string, rather than omit the timezone
altogether it is better to pass an explicit time-zone argument of
0 (GMT) which will add only a single 'Z' to the string yet still
produce an unambiguous date/time string.)"
(multiple-value-bind (second minute hour day month year day-of-week daylight-savings-p zone)
(etypecase time-zone
(number (decode-universal-time time-value (- time-zone)))
(keyword (decode-universal-time time-value (lisp-time-zone time-zone)))
(null (decode-universal-time time-value)))
(declare (ignore day-of-week))
(when daylight-savings-p (decf zone))
(setf zone (- zone))
(with-output-to-string (s)
(unless omit-date
(format s "~4,'0d-~2,'0d-~2,'0d" year month day))
(unless (or omit-date omit-time)
(write-char #\T s))
(unless omit-time
(format s "~2,'0d:~2,'0d:~2,'0d" hour minute second)
(unless omit-time-zone
(if (zerop zone)
(princ #\Z s)
(multiple-value-bind (h m) (truncate (* 60 zone) 60)
(format s "~2,'0@d:~2,'0d" h (abs m)))))))))
(defpackage :iso (:use) (:export :|8601|))
(defun iso:8601 (out arg colon-p at-sign-p &rest params)
(write-string (format-iso-8601-time
arg
:time-zone (first params)
:omit-time (and at-sign-p (not colon-p))
:omit-date colon-p
:omit-time-zone (and colon-p (not at-sign-p))) out))
(defun parse-iso-8601-time (text)
;; For now parse a full time like "2009-08-05T04:28:30Z" or
;; "2009-08-05T05:17:40-7:00"
(flet ((int (start &optional end)
(parse-integer (subseq text start end))))
(let ((year (int 0 4))
(month (int 5 7))
(day (int 8 10))
(hour (int 11 13))
(minute (int 14 16))
(second (int 17 19))
(timezone (subseq text 19)))
(cond
((string= timezone "Z")
(setf timezone 0))
(t
(let ((colon (position #\: timezone)))
(let ((tz-sign (if (string= (subseq timezone 0 1) "-") 1 -1))
(tz-hours (parse-integer (subseq timezone 1 colon)))
(tz-minutes (parse-integer (subseq timezone (1+ colon)))))
(setf timezone (* tz-sign (+ tz-hours (/ tz-minutes 60))))))))
(encode-universal-time second minute hour day month year timezone))))
(defun iso-8601-time-zone (name)
(find name *time-zones* :key #'first))
(defun lisp-time-zone (name)
(- (second (find name *time-zones* :key #'first))))
(defun now () (get-universal-time))
(defun date/time->utc (year month date &optional (hour 0) (minute 0) (second 0))
(encode-universal-time second minute hour date month year))
(defun time->utc (hour minute)
(with-time (year month date) (get-universal-time)
(encode-universal-time 0 minute hour date month year)))
(defun hh-mm-ss (seconds)
(multiple-value-bind (minutes seconds) (floor (round seconds) 60)
(multiple-value-bind (hours minutes) (floor minutes 60)
(format nil "~2,'0d:~2,'0d:~2,'0d" hours minutes seconds))))
(defun hh-mm (seconds)
(multiple-value-bind (minutes seconds) (floor seconds 60)
(declare (ignore seconds))
(multiple-value-bind (hours minutes) (floor minutes 60)
(format nil "~2,'0d:~2,'0d" hours minutes))))
(defun human-time (seconds)
(multiple-value-bind (minutes seconds) (floor seconds 60)
(multiple-value-bind (hours minutes) (floor minutes 60)
(multiple-value-bind (days hours) (floor hours 24)
(multiple-value-bind (weeks days) (floor days 7)
(multiple-value-bind (years weeks) (floor weeks 52)
(multiple-value-bind (centuries years) (floor years 100)
(format nil "~[~:;~:*~d centur~:@p ~]~[~:;~:*~d year~:p ~]~[~:;~:*~d week~:p ~]~[~:;~:*~d day~:p ~]~[~:;~:*~d hour~:p ~]~[~:;~:*~d minute~:p ~]~[~:;~:*~d second~:p ~]"
centuries years weeks days hours minutes seconds))))))))
(defun parse-date-string (string)
(apply #'date/time->utc
(loop for start = 0 then (1+ dash)
for dash = (position #\- string :start start)
collect (parse-integer (subseq string start dash))
while dash)))
(defun weekday-p (time)
(with-time (day) time (< day 5)))
(defparameter *unix-epoch* (make-time :second 0 :minute 0 :hour 0 :day 1 :month 1 :year 1970 :zone :utc))
(defparameter *cocoa-epoch* (make-time :second 0 :minute 0 :hour 0 :day 1 :month 1 :year 2001 :zone :gmt))
(defun seconds-since-epoch (lisp-time epoch)
(- lisp-time epoch))
(defun milliseconds-since-epoch (lisp-time epoch)
(* (- lisp-time epoch) 1000))
(defun epochal-seconds->lisp (seconds epoch)
(+ seconds epoch))
(defun epochal-milliseconds->lisp (milliseconds epoch)
(+ (round milliseconds 1000) epoch))
(defun unix-time (&optional (utc (get-universal-time)))
(seconds-since-epoch utc *unix-epoch*))
(defun from-unix-time (unix-seconds)
(epochal-seconds->lisp unix-seconds *unix-epoch*))
(defun javascript-time (&optional (utc (get-universal-time)))
"Javascript time is Unix time but in millisecond units."
(milliseconds-since-epoch utc *unix-epoch*))
(defun from-javascript-time (javascript-time)
"Javascript time is Unix time but in millisecond units."
(epochal-milliseconds->lisp javascript-time *unix-epoch*))
|
4438
|
;;
;; Copyright (c) 2005, <NAME> All rights reserved.
;;
(in-package :monkeylib-utilities)
;; Note these are the offsets as the rest of the world (e.g. ISO-8601)
;; thinks of them. The time-zone argument to DECODE-UNIVERSAL-TIME is
;; the negation of these numeric values. The information that went
;; into this list was originally found at
;; <http://www.timeanddate.com/library/abbreviations/timezones/>
;; though any transcription errors are likely my own.
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter *time-zones*
'(;; North America
(:nst -7/2 "Newfoundland Standard Time")
(:hnt -7/2 "Heure Normale de Terre-Neuve")
(:ndt -5/2 "Newfoundland Daylight Time")
(:hat -5/2 "Heure Avancée de Terre-Neuve")
(:haa -3 "Heure Avancée de l'Atlantique")
(:adt -3 "Atlantic Daylight Time")
(:hna -4 "Heure Normale de l'Atlantique")
(:hae -4 "Heure Avancée de l'Est")
(:edt -4 "Eastern Daylight Time")
(:ast -4 "Atlantic Standard Time")
(:hne -5 "Heure Normale de l'Est")
(:hac -5 "Heure Avancée du Centre")
(:est -5 "Eastern Standard Time")
(:cdt -5 "Central Daylight Time")
(:mdt -6 "Mountain Daylight Time")
(:hnc -6 "Heure Normale du Centre")
(:har -6 "Heure Avancée des Rocheuses")
(:cst -6 "Central Standard Time")
(:pdt -7 "Pacific Daylight Time")
(:mst -7 "Mountain Standard Time")
(:hnr -7 "Heure Normale des Rocheuses")
(:hap -7 "Heure Avancée du Pacifique")
(:pst -8 "Pacific Standard Time")
(:hnp -8 "Heure Normale du Pacifique")
(:hay -8 "Heure Avancée du Yukon")
(:akdt -8 "Alaska Daylight Time")
(:hny -9 "Heure Normale du Yukon")
(:hadt -9 "Hawaii-Aleutian Daylight Time")
(:akst -9 "Alaska Standard Time")
(:hast -10 "Hawaii-Aleutian Standard Time")
;; Military
(:m 12 "Mike Time Zone")
(:l 11 "Lima Time Zone")
(:k 10 "Kilo Time Zone")
(:i 9 "India Time Zone")
(:h 8 "Hotel Time Zone")
(:g 7 "Golf Time Zone")
(:f 6 "Foxtrot Time Zone")
(:e 5 "Echo Time Zone")
(:d 4 "Delta Time Zone")
(:c 3 "Charlie Time Zone")
(:b 2 "Bravo Time Zone")
(:a 1 "Alpha Time Zone")
(:z 0 "Zulu Time Zone")
(:n -1 "November Time Zone")
(:o -2 "Oscar Time Zone")
(:p -3 "Papa Time Zone")
(:q -4 "Quebec Time Zone")
(:r -5 "Romeo Time Zone")
(:s -6 "Sierra Time Zone")
(:t -7 "Tango Time Zone")
(:u -8 "Uniform Time Zone")
(:v -9 "Victor Time Zone")
(:w -10 "Whiskey Time Zone")
(:x -11 "X-ray Time Zone")
(:y -12 "Yankee Time Zone")
;; Europe
(:eest 3 "Eastern European Summer Time")
(:mesz 2 "Mitteleuropäische Sommerzeit")
(:eet 2 "Eastern European Time")
(:cest 2 "Central European Summer Time")
(:west 1 "Western European Summer Time")
(:mez 1 "Mitteleuropäische Zeit")
(:ist 1 "Irish Summer Time")
(:cet 1 "Central European Time")
(:bst 1 "British Summer Time")
(:wet 0 "Western European Time")
(:utc 0 "Coordinated Universal Time")
(:gmt 0 "Greenwich Mean Time")
;; Australia
(:nft 23/2 "Norfolk (Island) Time")
(:edt 11 "Eastern Daylight Time")
(:aedt 11 "Australian Eastern Daylight Time")
(:cdt 21/2 "Central Daylight Time")
(:acdt 21/2 "Australian Central Daylight Time")
(:est 10 "Eastern Standard Time")
(:aest 10 "Australian Eastern Standard Time")
(:cst 19/2 "Central Standard Time")
(:acst 19/2 "Australian Central Standard Time")
(:wst 8 "Western Standard Time")
(:awst 8 "Australian Western Standard Time")
(:cxt 7 "Christmas Island Time"))))
(defparameter *long-month-names*
#("January"
"February"
"March"
"April"
"May"
"June"
"July"
"August"
"September"
"October"
"November"
"December"))
(defparameter *day-names*
#("Monday"
"Tuesday"
"Wednesday"
"Thursday"
"Friday"
"Saturday"
"Sunday"))
(defun month-name (number)
(aref *long-month-names* (1- number)))
(defun day-name (number)
(aref *day-names* number))
(defun make-time (&rest args &key second minute hour day month year zone (defaults (get-universal-time)))
(declare (ignore second minute hour day month year zone))
(remf args :defaults)
(apply #'merge-time defaults args))
;;(defun midnight (&key day month year zone)
;; (make-time :second 0 :minute 0 :hour 0 :day day :month month :year year :zone zone))
(defun merge-time (utc &key second minute hour day month year zone)
(multiple-value-bind (utc-second
utc-minute
utc-hour
utc-day
utc-month
utc-year
utc-day-of-week
utc-daylight-savings-p
utc-zone)
(decode-universal-time utc)
(declare (ignore utc-day-of-week))
(encode-universal-time
(or second utc-second)
(or minute utc-minute)
(or hour utc-hour)
(or day utc-day)
(or month utc-month)
(or year utc-year)
(or (translate-zone zone) (if utc-daylight-savings-p (1- utc-zone) utc-zone)))))
(defun translate-zone (zone)
(typecase zone
(number zone)
(keyword (- (second (find zone *time-zones* :key #'first))))))
(defun reverse-translate-zone (zone)
(first (find zone *time-zones* :key #'second)))
(defmacro with-time ((&rest args) utc &body body)
(let* ((zone-cons (member '&zone args))
(zone (if zone-cons (cadr zone-cons)))
(args (nconc (ldiff args zone-cons) (cddr zone-cons)))
(gensymed-vars ()))
(when (find zone *time-zones* :key #'first)
(setf zone (- (second (find zone *time-zones* :key #'first)))))
(labels ((part-name (spec)
(if (symbolp spec) spec (first spec)))
(var-name (spec)
(if (symbolp spec) spec (second spec)))
(new-gensym () (first (push (gensym) gensymed-vars)))
(find-var (name)
(let ((name (find name args :key #'part-name :test #'string=)))
(if name (var-name name) (new-gensym)))))
(let ((vars (mapcar #'find-var '(second minute hour date month year day daylight-p zone))))
`(multiple-value-bind ,vars ,(if zone
`(decode-universal-time ,utc ,zone)
`(decode-universal-time ,utc))
(declare (ignore ,@gensymed-vars))
,@body)))))
(defmacro with-current-time ((&rest args) &body body)
`(with-time (,@args) (get-universal-time) ,@body))
;; Loosely based on code from <http://www.pvv.ntnu.no/~nsaa/ISO8601.html>
(defun format-iso-8601-time (time-value &key time-zone omit-time-zone omit-date omit-time)
"Formats a universal time TIME-VALUE in ISO 8601 format. If no
time zone is provided the default timezone returned by
DECODE-UNIVERSAL-TIME, adjusted by daylights savings time as
appropriate, is used. The time zone information is included in
the generated string unless OMIT-TIME-ZONE is true. (In general,
if you want a shorter string, rather than omit the timezone
altogether it is better to pass an explicit time-zone argument of
0 (GMT) which will add only a single 'Z' to the string yet still
produce an unambiguous date/time string.)"
(multiple-value-bind (second minute hour day month year day-of-week daylight-savings-p zone)
(etypecase time-zone
(number (decode-universal-time time-value (- time-zone)))
(keyword (decode-universal-time time-value (lisp-time-zone time-zone)))
(null (decode-universal-time time-value)))
(declare (ignore day-of-week))
(when daylight-savings-p (decf zone))
(setf zone (- zone))
(with-output-to-string (s)
(unless omit-date
(format s "~4,'0d-~2,'0d-~2,'0d" year month day))
(unless (or omit-date omit-time)
(write-char #\T s))
(unless omit-time
(format s "~2,'0d:~2,'0d:~2,'0d" hour minute second)
(unless omit-time-zone
(if (zerop zone)
(princ #\Z s)
(multiple-value-bind (h m) (truncate (* 60 zone) 60)
(format s "~2,'0@d:~2,'0d" h (abs m)))))))))
(defpackage :iso (:use) (:export :|8601|))
(defun iso:8601 (out arg colon-p at-sign-p &rest params)
(write-string (format-iso-8601-time
arg
:time-zone (first params)
:omit-time (and at-sign-p (not colon-p))
:omit-date colon-p
:omit-time-zone (and colon-p (not at-sign-p))) out))
(defun parse-iso-8601-time (text)
;; For now parse a full time like "2009-08-05T04:28:30Z" or
;; "2009-08-05T05:17:40-7:00"
(flet ((int (start &optional end)
(parse-integer (subseq text start end))))
(let ((year (int 0 4))
(month (int 5 7))
(day (int 8 10))
(hour (int 11 13))
(minute (int 14 16))
(second (int 17 19))
(timezone (subseq text 19)))
(cond
((string= timezone "Z")
(setf timezone 0))
(t
(let ((colon (position #\: timezone)))
(let ((tz-sign (if (string= (subseq timezone 0 1) "-") 1 -1))
(tz-hours (parse-integer (subseq timezone 1 colon)))
(tz-minutes (parse-integer (subseq timezone (1+ colon)))))
(setf timezone (* tz-sign (+ tz-hours (/ tz-minutes 60))))))))
(encode-universal-time second minute hour day month year timezone))))
(defun iso-8601-time-zone (name)
(find name *time-zones* :key #'first))
(defun lisp-time-zone (name)
(- (second (find name *time-zones* :key #'first))))
(defun now () (get-universal-time))
(defun date/time->utc (year month date &optional (hour 0) (minute 0) (second 0))
(encode-universal-time second minute hour date month year))
(defun time->utc (hour minute)
(with-time (year month date) (get-universal-time)
(encode-universal-time 0 minute hour date month year)))
(defun hh-mm-ss (seconds)
(multiple-value-bind (minutes seconds) (floor (round seconds) 60)
(multiple-value-bind (hours minutes) (floor minutes 60)
(format nil "~2,'0d:~2,'0d:~2,'0d" hours minutes seconds))))
(defun hh-mm (seconds)
(multiple-value-bind (minutes seconds) (floor seconds 60)
(declare (ignore seconds))
(multiple-value-bind (hours minutes) (floor minutes 60)
(format nil "~2,'0d:~2,'0d" hours minutes))))
(defun human-time (seconds)
(multiple-value-bind (minutes seconds) (floor seconds 60)
(multiple-value-bind (hours minutes) (floor minutes 60)
(multiple-value-bind (days hours) (floor hours 24)
(multiple-value-bind (weeks days) (floor days 7)
(multiple-value-bind (years weeks) (floor weeks 52)
(multiple-value-bind (centuries years) (floor years 100)
(format nil "~[~:;~:*~d centur~:@p ~]~[~:;~:*~d year~:p ~]~[~:;~:*~d week~:p ~]~[~:;~:*~d day~:p ~]~[~:;~:*~d hour~:p ~]~[~:;~:*~d minute~:p ~]~[~:;~:*~d second~:p ~]"
centuries years weeks days hours minutes seconds))))))))
(defun parse-date-string (string)
(apply #'date/time->utc
(loop for start = 0 then (1+ dash)
for dash = (position #\- string :start start)
collect (parse-integer (subseq string start dash))
while dash)))
(defun weekday-p (time)
(with-time (day) time (< day 5)))
(defparameter *unix-epoch* (make-time :second 0 :minute 0 :hour 0 :day 1 :month 1 :year 1970 :zone :utc))
(defparameter *cocoa-epoch* (make-time :second 0 :minute 0 :hour 0 :day 1 :month 1 :year 2001 :zone :gmt))
(defun seconds-since-epoch (lisp-time epoch)
(- lisp-time epoch))
(defun milliseconds-since-epoch (lisp-time epoch)
(* (- lisp-time epoch) 1000))
(defun epochal-seconds->lisp (seconds epoch)
(+ seconds epoch))
(defun epochal-milliseconds->lisp (milliseconds epoch)
(+ (round milliseconds 1000) epoch))
(defun unix-time (&optional (utc (get-universal-time)))
(seconds-since-epoch utc *unix-epoch*))
(defun from-unix-time (unix-seconds)
(epochal-seconds->lisp unix-seconds *unix-epoch*))
(defun javascript-time (&optional (utc (get-universal-time)))
"Javascript time is Unix time but in millisecond units."
(milliseconds-since-epoch utc *unix-epoch*))
(defun from-javascript-time (javascript-time)
"Javascript time is Unix time but in millisecond units."
(epochal-milliseconds->lisp javascript-time *unix-epoch*))
| true |
;;
;; Copyright (c) 2005, PI:NAME:<NAME>END_PI All rights reserved.
;;
(in-package :monkeylib-utilities)
;; Note these are the offsets as the rest of the world (e.g. ISO-8601)
;; thinks of them. The time-zone argument to DECODE-UNIVERSAL-TIME is
;; the negation of these numeric values. The information that went
;; into this list was originally found at
;; <http://www.timeanddate.com/library/abbreviations/timezones/>
;; though any transcription errors are likely my own.
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter *time-zones*
'(;; North America
(:nst -7/2 "Newfoundland Standard Time")
(:hnt -7/2 "Heure Normale de Terre-Neuve")
(:ndt -5/2 "Newfoundland Daylight Time")
(:hat -5/2 "Heure Avancée de Terre-Neuve")
(:haa -3 "Heure Avancée de l'Atlantique")
(:adt -3 "Atlantic Daylight Time")
(:hna -4 "Heure Normale de l'Atlantique")
(:hae -4 "Heure Avancée de l'Est")
(:edt -4 "Eastern Daylight Time")
(:ast -4 "Atlantic Standard Time")
(:hne -5 "Heure Normale de l'Est")
(:hac -5 "Heure Avancée du Centre")
(:est -5 "Eastern Standard Time")
(:cdt -5 "Central Daylight Time")
(:mdt -6 "Mountain Daylight Time")
(:hnc -6 "Heure Normale du Centre")
(:har -6 "Heure Avancée des Rocheuses")
(:cst -6 "Central Standard Time")
(:pdt -7 "Pacific Daylight Time")
(:mst -7 "Mountain Standard Time")
(:hnr -7 "Heure Normale des Rocheuses")
(:hap -7 "Heure Avancée du Pacifique")
(:pst -8 "Pacific Standard Time")
(:hnp -8 "Heure Normale du Pacifique")
(:hay -8 "Heure Avancée du Yukon")
(:akdt -8 "Alaska Daylight Time")
(:hny -9 "Heure Normale du Yukon")
(:hadt -9 "Hawaii-Aleutian Daylight Time")
(:akst -9 "Alaska Standard Time")
(:hast -10 "Hawaii-Aleutian Standard Time")
;; Military
(:m 12 "Mike Time Zone")
(:l 11 "Lima Time Zone")
(:k 10 "Kilo Time Zone")
(:i 9 "India Time Zone")
(:h 8 "Hotel Time Zone")
(:g 7 "Golf Time Zone")
(:f 6 "Foxtrot Time Zone")
(:e 5 "Echo Time Zone")
(:d 4 "Delta Time Zone")
(:c 3 "Charlie Time Zone")
(:b 2 "Bravo Time Zone")
(:a 1 "Alpha Time Zone")
(:z 0 "Zulu Time Zone")
(:n -1 "November Time Zone")
(:o -2 "Oscar Time Zone")
(:p -3 "Papa Time Zone")
(:q -4 "Quebec Time Zone")
(:r -5 "Romeo Time Zone")
(:s -6 "Sierra Time Zone")
(:t -7 "Tango Time Zone")
(:u -8 "Uniform Time Zone")
(:v -9 "Victor Time Zone")
(:w -10 "Whiskey Time Zone")
(:x -11 "X-ray Time Zone")
(:y -12 "Yankee Time Zone")
;; Europe
(:eest 3 "Eastern European Summer Time")
(:mesz 2 "Mitteleuropäische Sommerzeit")
(:eet 2 "Eastern European Time")
(:cest 2 "Central European Summer Time")
(:west 1 "Western European Summer Time")
(:mez 1 "Mitteleuropäische Zeit")
(:ist 1 "Irish Summer Time")
(:cet 1 "Central European Time")
(:bst 1 "British Summer Time")
(:wet 0 "Western European Time")
(:utc 0 "Coordinated Universal Time")
(:gmt 0 "Greenwich Mean Time")
;; Australia
(:nft 23/2 "Norfolk (Island) Time")
(:edt 11 "Eastern Daylight Time")
(:aedt 11 "Australian Eastern Daylight Time")
(:cdt 21/2 "Central Daylight Time")
(:acdt 21/2 "Australian Central Daylight Time")
(:est 10 "Eastern Standard Time")
(:aest 10 "Australian Eastern Standard Time")
(:cst 19/2 "Central Standard Time")
(:acst 19/2 "Australian Central Standard Time")
(:wst 8 "Western Standard Time")
(:awst 8 "Australian Western Standard Time")
(:cxt 7 "Christmas Island Time"))))
(defparameter *long-month-names*
#("January"
"February"
"March"
"April"
"May"
"June"
"July"
"August"
"September"
"October"
"November"
"December"))
(defparameter *day-names*
#("Monday"
"Tuesday"
"Wednesday"
"Thursday"
"Friday"
"Saturday"
"Sunday"))
(defun month-name (number)
(aref *long-month-names* (1- number)))
(defun day-name (number)
(aref *day-names* number))
(defun make-time (&rest args &key second minute hour day month year zone (defaults (get-universal-time)))
(declare (ignore second minute hour day month year zone))
(remf args :defaults)
(apply #'merge-time defaults args))
;;(defun midnight (&key day month year zone)
;; (make-time :second 0 :minute 0 :hour 0 :day day :month month :year year :zone zone))
(defun merge-time (utc &key second minute hour day month year zone)
(multiple-value-bind (utc-second
utc-minute
utc-hour
utc-day
utc-month
utc-year
utc-day-of-week
utc-daylight-savings-p
utc-zone)
(decode-universal-time utc)
(declare (ignore utc-day-of-week))
(encode-universal-time
(or second utc-second)
(or minute utc-minute)
(or hour utc-hour)
(or day utc-day)
(or month utc-month)
(or year utc-year)
(or (translate-zone zone) (if utc-daylight-savings-p (1- utc-zone) utc-zone)))))
(defun translate-zone (zone)
(typecase zone
(number zone)
(keyword (- (second (find zone *time-zones* :key #'first))))))
(defun reverse-translate-zone (zone)
(first (find zone *time-zones* :key #'second)))
(defmacro with-time ((&rest args) utc &body body)
(let* ((zone-cons (member '&zone args))
(zone (if zone-cons (cadr zone-cons)))
(args (nconc (ldiff args zone-cons) (cddr zone-cons)))
(gensymed-vars ()))
(when (find zone *time-zones* :key #'first)
(setf zone (- (second (find zone *time-zones* :key #'first)))))
(labels ((part-name (spec)
(if (symbolp spec) spec (first spec)))
(var-name (spec)
(if (symbolp spec) spec (second spec)))
(new-gensym () (first (push (gensym) gensymed-vars)))
(find-var (name)
(let ((name (find name args :key #'part-name :test #'string=)))
(if name (var-name name) (new-gensym)))))
(let ((vars (mapcar #'find-var '(second minute hour date month year day daylight-p zone))))
`(multiple-value-bind ,vars ,(if zone
`(decode-universal-time ,utc ,zone)
`(decode-universal-time ,utc))
(declare (ignore ,@gensymed-vars))
,@body)))))
(defmacro with-current-time ((&rest args) &body body)
`(with-time (,@args) (get-universal-time) ,@body))
;; Loosely based on code from <http://www.pvv.ntnu.no/~nsaa/ISO8601.html>
(defun format-iso-8601-time (time-value &key time-zone omit-time-zone omit-date omit-time)
"Formats a universal time TIME-VALUE in ISO 8601 format. If no
time zone is provided the default timezone returned by
DECODE-UNIVERSAL-TIME, adjusted by daylights savings time as
appropriate, is used. The time zone information is included in
the generated string unless OMIT-TIME-ZONE is true. (In general,
if you want a shorter string, rather than omit the timezone
altogether it is better to pass an explicit time-zone argument of
0 (GMT) which will add only a single 'Z' to the string yet still
produce an unambiguous date/time string.)"
(multiple-value-bind (second minute hour day month year day-of-week daylight-savings-p zone)
(etypecase time-zone
(number (decode-universal-time time-value (- time-zone)))
(keyword (decode-universal-time time-value (lisp-time-zone time-zone)))
(null (decode-universal-time time-value)))
(declare (ignore day-of-week))
(when daylight-savings-p (decf zone))
(setf zone (- zone))
(with-output-to-string (s)
(unless omit-date
(format s "~4,'0d-~2,'0d-~2,'0d" year month day))
(unless (or omit-date omit-time)
(write-char #\T s))
(unless omit-time
(format s "~2,'0d:~2,'0d:~2,'0d" hour minute second)
(unless omit-time-zone
(if (zerop zone)
(princ #\Z s)
(multiple-value-bind (h m) (truncate (* 60 zone) 60)
(format s "~2,'0@d:~2,'0d" h (abs m)))))))))
(defpackage :iso (:use) (:export :|8601|))
(defun iso:8601 (out arg colon-p at-sign-p &rest params)
(write-string (format-iso-8601-time
arg
:time-zone (first params)
:omit-time (and at-sign-p (not colon-p))
:omit-date colon-p
:omit-time-zone (and colon-p (not at-sign-p))) out))
(defun parse-iso-8601-time (text)
;; For now parse a full time like "2009-08-05T04:28:30Z" or
;; "2009-08-05T05:17:40-7:00"
(flet ((int (start &optional end)
(parse-integer (subseq text start end))))
(let ((year (int 0 4))
(month (int 5 7))
(day (int 8 10))
(hour (int 11 13))
(minute (int 14 16))
(second (int 17 19))
(timezone (subseq text 19)))
(cond
((string= timezone "Z")
(setf timezone 0))
(t
(let ((colon (position #\: timezone)))
(let ((tz-sign (if (string= (subseq timezone 0 1) "-") 1 -1))
(tz-hours (parse-integer (subseq timezone 1 colon)))
(tz-minutes (parse-integer (subseq timezone (1+ colon)))))
(setf timezone (* tz-sign (+ tz-hours (/ tz-minutes 60))))))))
(encode-universal-time second minute hour day month year timezone))))
(defun iso-8601-time-zone (name)
(find name *time-zones* :key #'first))
(defun lisp-time-zone (name)
(- (second (find name *time-zones* :key #'first))))
(defun now () (get-universal-time))
(defun date/time->utc (year month date &optional (hour 0) (minute 0) (second 0))
(encode-universal-time second minute hour date month year))
(defun time->utc (hour minute)
(with-time (year month date) (get-universal-time)
(encode-universal-time 0 minute hour date month year)))
(defun hh-mm-ss (seconds)
(multiple-value-bind (minutes seconds) (floor (round seconds) 60)
(multiple-value-bind (hours minutes) (floor minutes 60)
(format nil "~2,'0d:~2,'0d:~2,'0d" hours minutes seconds))))
(defun hh-mm (seconds)
(multiple-value-bind (minutes seconds) (floor seconds 60)
(declare (ignore seconds))
(multiple-value-bind (hours minutes) (floor minutes 60)
(format nil "~2,'0d:~2,'0d" hours minutes))))
(defun human-time (seconds)
(multiple-value-bind (minutes seconds) (floor seconds 60)
(multiple-value-bind (hours minutes) (floor minutes 60)
(multiple-value-bind (days hours) (floor hours 24)
(multiple-value-bind (weeks days) (floor days 7)
(multiple-value-bind (years weeks) (floor weeks 52)
(multiple-value-bind (centuries years) (floor years 100)
(format nil "~[~:;~:*~d centur~:@p ~]~[~:;~:*~d year~:p ~]~[~:;~:*~d week~:p ~]~[~:;~:*~d day~:p ~]~[~:;~:*~d hour~:p ~]~[~:;~:*~d minute~:p ~]~[~:;~:*~d second~:p ~]"
centuries years weeks days hours minutes seconds))))))))
(defun parse-date-string (string)
(apply #'date/time->utc
(loop for start = 0 then (1+ dash)
for dash = (position #\- string :start start)
collect (parse-integer (subseq string start dash))
while dash)))
(defun weekday-p (time)
(with-time (day) time (< day 5)))
(defparameter *unix-epoch* (make-time :second 0 :minute 0 :hour 0 :day 1 :month 1 :year 1970 :zone :utc))
(defparameter *cocoa-epoch* (make-time :second 0 :minute 0 :hour 0 :day 1 :month 1 :year 2001 :zone :gmt))
(defun seconds-since-epoch (lisp-time epoch)
(- lisp-time epoch))
(defun milliseconds-since-epoch (lisp-time epoch)
(* (- lisp-time epoch) 1000))
(defun epochal-seconds->lisp (seconds epoch)
(+ seconds epoch))
(defun epochal-milliseconds->lisp (milliseconds epoch)
(+ (round milliseconds 1000) epoch))
(defun unix-time (&optional (utc (get-universal-time)))
(seconds-since-epoch utc *unix-epoch*))
(defun from-unix-time (unix-seconds)
(epochal-seconds->lisp unix-seconds *unix-epoch*))
(defun javascript-time (&optional (utc (get-universal-time)))
"Javascript time is Unix time but in millisecond units."
(milliseconds-since-epoch utc *unix-epoch*))
(defun from-javascript-time (javascript-time)
"Javascript time is Unix time but in millisecond units."
(epochal-milliseconds->lisp javascript-time *unix-epoch*))
|
[
{
"context": "он этой ф-ии - ТРАНСЛЯТОР-ЯРА-В-ЛИСП:Выполни-скрипт-Яра\"\n (let* ((pathname (pathname filename))\n ",
"end": 1916,
"score": 0.7378681302070618,
"start": 1911,
"tag": "NAME",
"value": "т-Яра"
}
] |
swank-compilation-errors.lisp
|
lisp-mirror/clcon
| 0 |
;; -*- coding: utf-8 ; Encoding: utf-8 ; system :clcon-server ; -*-
;; Backend of compilation error browser, see also error-browser.erbr.tcl
(in-package :clco)
(defun calc-details-code (note serial)
(let* ((title (getf note :message))
(severity (getf note :severity))
(location (getf note :location))
(source-context (getf note :source-context))
(references (getf note :references))
(details-code
(with-output-to-string (ou)
(cond
((not (or location references source-context))
nil) ; string will be empty
(t
(print-just-line ou title :index "end")
(when location
(write-one-dspec-and-location "Go to Source" location ou :index "end")
(print-just-line ou (format nil "~%") :index "end")
)
(when source-context
(print-just-line ou source-context :index "end"))
(when references
(print-just-line ou
(format nil "~%References: ~S" references)
:index "end")
)))))
(code-to-jump-to-location
(cond
(location
(with-output-to-string (ou2)
(write-code-to-pass-to-loc ou2 location :mode :eval)))
(t
"{}")))
)
(format nil "::erbr::AppendData ~A ~A ~A ~A ~A"
serial
(cl-tk:tcl-escape (string-downcase (string severity)))
(cl-tk:tcl-escape title)
(cl-tk:tcl-escape details-code)
(cl-tk:tcl-escape code-to-jump-to-location))))
(defun compile-lisp-file-for-tcl (filename load-p &rest options)
"Value of oduvanchik::compile-and-load-buffer-file-function for Lisp mode. Клон этой ф-ии - ТРАНСЛЯТОР-ЯРА-В-ЛИСП:Выполни-скрипт-Яра"
(let* ((pathname (pathname filename))
(compilation-result (apply #'swank:compile-file-for-emacs pathname load-p options))
(success (swank::compilation-result-successp compilation-result))
(notes (swank::compilation-result-notes compilation-result))
(serial 0)
)
(when (and success load-p)
(load (swank::compilation-result-faslfile compilation-result) :verbose t))
(when (or notes (not success))
(eval-in-tcl (format nil "::erbr::SwankBrowseErrors1 ~A" (CLCO::CONVERT-OBJECT-TO-TCL compilation-result)))
(dolist (note notes)
(eval-in-tcl (calc-details-code note (incf serial)))
))
))
(setf (oduvanchik-interface:variable-value 'oduvanchik::compile-and-load-buffer-file-function :mode "Lisp")
'compile-lisp-file-for-tcl)
(defun compile-tcl-file-for-tcl (filename load-p &rest options)
"Value of oduvanchik::compile-and-load-buffer-file-function for Tcl mode"
(declare (ignore load-p options))
(let* ((q-pathname (clco::tcl-escape-filename filename)))
(format t "~%Loading ~A into tcl...~%" q-pathname)
(eval-in-tcl (format nil "namespace eval :: source ~A" q-pathname)
)))
(setf (oduvanchik-interface:variable-value 'oduvanchik::compile-and-load-buffer-file-function :mode "Tcl")
'compile-tcl-file-for-tcl)
(defun compile-file-for-tcl (clcon_text filename)
"Backend for ::edt::CompileAndLoadTheFile . Rather untraditional c-s dialog. We normally do such things in tcl. It can be sometimes more convenient to edit though as we're in Lisp"
(let ((l (length filename)))
(when (and (> (length filename) 3) (string= (subseq filename (- l 3) l) "asd"))
(let* ((system-name
(subseq filename
(+ 1 (position #\/ filename :from-end t))
(- l 4)))
(system (ignore-errors (asdf:find-system system-name))))
(cond
((not system) (format t "Вы пытаетесь загрузить систему ~A (из файла ~S), но asdf не нашёл такой системы. Если эта система - новая, попробуйте Консоль/Меню/Файл/Очистить кеш asd-систем в quicklisp. См. также Консоль/Меню/Справка/Руководство clcon. ~%" system-name filename))
((not (string-equal (namestring (asdf:system-definition-pathname system)) filename))
(format t "Что-то не так с настройкой ASDF/Quicklisp: вы пытаетесь загрузить систему ~A (из файла ~S), но asdf нашёл её в файле ~S" system-name filename (namestring (asdf:system-definition-pathname system))))
(t
(format t "Вы пытаетесь загрузить систему ~A (из файла ~S)" system-name filename)
(clco:operate-on-system-for-tcl system))))
(return-from compile-file-for-tcl nil)))
(let* ((buffer (oi::clcon_text-to-buffer clcon_text))
(mode (first (oi::buffer-modes buffer)))
(fn (oduvanchik-interface:variable-value 'oduvanchik::compile-and-load-buffer-file-function :mode mode)))
(funcall fn filename t)))
(defun operate-on-system-for-tcl (system-name &optional (operation 'asdf:load-op) &rest options)
"Выполняет действие над системой ASDF"
(let* ((compilation-result (apply #'swank:operate-on-system-for-emacs system-name operation options))
(success (swank::compilation-result-successp compilation-result))
(notes (swank::compilation-result-notes compilation-result))
(serial 0)
)
(when (or notes (not success))
(eval-in-tcl (format nil "::erbr::SwankBrowseErrors1 ~A" (CLCO::CONVERT-OBJECT-TO-TCL compilation-result)))
(dolist (note notes)
(eval-in-tcl (calc-details-code note (incf serial)))
))
))
|
68403
|
;; -*- coding: utf-8 ; Encoding: utf-8 ; system :clcon-server ; -*-
;; Backend of compilation error browser, see also error-browser.erbr.tcl
(in-package :clco)
(defun calc-details-code (note serial)
(let* ((title (getf note :message))
(severity (getf note :severity))
(location (getf note :location))
(source-context (getf note :source-context))
(references (getf note :references))
(details-code
(with-output-to-string (ou)
(cond
((not (or location references source-context))
nil) ; string will be empty
(t
(print-just-line ou title :index "end")
(when location
(write-one-dspec-and-location "Go to Source" location ou :index "end")
(print-just-line ou (format nil "~%") :index "end")
)
(when source-context
(print-just-line ou source-context :index "end"))
(when references
(print-just-line ou
(format nil "~%References: ~S" references)
:index "end")
)))))
(code-to-jump-to-location
(cond
(location
(with-output-to-string (ou2)
(write-code-to-pass-to-loc ou2 location :mode :eval)))
(t
"{}")))
)
(format nil "::erbr::AppendData ~A ~A ~A ~A ~A"
serial
(cl-tk:tcl-escape (string-downcase (string severity)))
(cl-tk:tcl-escape title)
(cl-tk:tcl-escape details-code)
(cl-tk:tcl-escape code-to-jump-to-location))))
(defun compile-lisp-file-for-tcl (filename load-p &rest options)
"Value of oduvanchik::compile-and-load-buffer-file-function for Lisp mode. Клон этой ф-ии - ТРАНСЛЯТОР-ЯРА-В-ЛИСП:Выполни-скрип<NAME>"
(let* ((pathname (pathname filename))
(compilation-result (apply #'swank:compile-file-for-emacs pathname load-p options))
(success (swank::compilation-result-successp compilation-result))
(notes (swank::compilation-result-notes compilation-result))
(serial 0)
)
(when (and success load-p)
(load (swank::compilation-result-faslfile compilation-result) :verbose t))
(when (or notes (not success))
(eval-in-tcl (format nil "::erbr::SwankBrowseErrors1 ~A" (CLCO::CONVERT-OBJECT-TO-TCL compilation-result)))
(dolist (note notes)
(eval-in-tcl (calc-details-code note (incf serial)))
))
))
(setf (oduvanchik-interface:variable-value 'oduvanchik::compile-and-load-buffer-file-function :mode "Lisp")
'compile-lisp-file-for-tcl)
(defun compile-tcl-file-for-tcl (filename load-p &rest options)
"Value of oduvanchik::compile-and-load-buffer-file-function for Tcl mode"
(declare (ignore load-p options))
(let* ((q-pathname (clco::tcl-escape-filename filename)))
(format t "~%Loading ~A into tcl...~%" q-pathname)
(eval-in-tcl (format nil "namespace eval :: source ~A" q-pathname)
)))
(setf (oduvanchik-interface:variable-value 'oduvanchik::compile-and-load-buffer-file-function :mode "Tcl")
'compile-tcl-file-for-tcl)
(defun compile-file-for-tcl (clcon_text filename)
"Backend for ::edt::CompileAndLoadTheFile . Rather untraditional c-s dialog. We normally do such things in tcl. It can be sometimes more convenient to edit though as we're in Lisp"
(let ((l (length filename)))
(when (and (> (length filename) 3) (string= (subseq filename (- l 3) l) "asd"))
(let* ((system-name
(subseq filename
(+ 1 (position #\/ filename :from-end t))
(- l 4)))
(system (ignore-errors (asdf:find-system system-name))))
(cond
((not system) (format t "Вы пытаетесь загрузить систему ~A (из файла ~S), но asdf не нашёл такой системы. Если эта система - новая, попробуйте Консоль/Меню/Файл/Очистить кеш asd-систем в quicklisp. См. также Консоль/Меню/Справка/Руководство clcon. ~%" system-name filename))
((not (string-equal (namestring (asdf:system-definition-pathname system)) filename))
(format t "Что-то не так с настройкой ASDF/Quicklisp: вы пытаетесь загрузить систему ~A (из файла ~S), но asdf нашёл её в файле ~S" system-name filename (namestring (asdf:system-definition-pathname system))))
(t
(format t "Вы пытаетесь загрузить систему ~A (из файла ~S)" system-name filename)
(clco:operate-on-system-for-tcl system))))
(return-from compile-file-for-tcl nil)))
(let* ((buffer (oi::clcon_text-to-buffer clcon_text))
(mode (first (oi::buffer-modes buffer)))
(fn (oduvanchik-interface:variable-value 'oduvanchik::compile-and-load-buffer-file-function :mode mode)))
(funcall fn filename t)))
(defun operate-on-system-for-tcl (system-name &optional (operation 'asdf:load-op) &rest options)
"Выполняет действие над системой ASDF"
(let* ((compilation-result (apply #'swank:operate-on-system-for-emacs system-name operation options))
(success (swank::compilation-result-successp compilation-result))
(notes (swank::compilation-result-notes compilation-result))
(serial 0)
)
(when (or notes (not success))
(eval-in-tcl (format nil "::erbr::SwankBrowseErrors1 ~A" (CLCO::CONVERT-OBJECT-TO-TCL compilation-result)))
(dolist (note notes)
(eval-in-tcl (calc-details-code note (incf serial)))
))
))
| true |
;; -*- coding: utf-8 ; Encoding: utf-8 ; system :clcon-server ; -*-
;; Backend of compilation error browser, see also error-browser.erbr.tcl
(in-package :clco)
(defun calc-details-code (note serial)
(let* ((title (getf note :message))
(severity (getf note :severity))
(location (getf note :location))
(source-context (getf note :source-context))
(references (getf note :references))
(details-code
(with-output-to-string (ou)
(cond
((not (or location references source-context))
nil) ; string will be empty
(t
(print-just-line ou title :index "end")
(when location
(write-one-dspec-and-location "Go to Source" location ou :index "end")
(print-just-line ou (format nil "~%") :index "end")
)
(when source-context
(print-just-line ou source-context :index "end"))
(when references
(print-just-line ou
(format nil "~%References: ~S" references)
:index "end")
)))))
(code-to-jump-to-location
(cond
(location
(with-output-to-string (ou2)
(write-code-to-pass-to-loc ou2 location :mode :eval)))
(t
"{}")))
)
(format nil "::erbr::AppendData ~A ~A ~A ~A ~A"
serial
(cl-tk:tcl-escape (string-downcase (string severity)))
(cl-tk:tcl-escape title)
(cl-tk:tcl-escape details-code)
(cl-tk:tcl-escape code-to-jump-to-location))))
(defun compile-lisp-file-for-tcl (filename load-p &rest options)
"Value of oduvanchik::compile-and-load-buffer-file-function for Lisp mode. Клон этой ф-ии - ТРАНСЛЯТОР-ЯРА-В-ЛИСП:Выполни-скрипPI:NAME:<NAME>END_PI"
(let* ((pathname (pathname filename))
(compilation-result (apply #'swank:compile-file-for-emacs pathname load-p options))
(success (swank::compilation-result-successp compilation-result))
(notes (swank::compilation-result-notes compilation-result))
(serial 0)
)
(when (and success load-p)
(load (swank::compilation-result-faslfile compilation-result) :verbose t))
(when (or notes (not success))
(eval-in-tcl (format nil "::erbr::SwankBrowseErrors1 ~A" (CLCO::CONVERT-OBJECT-TO-TCL compilation-result)))
(dolist (note notes)
(eval-in-tcl (calc-details-code note (incf serial)))
))
))
(setf (oduvanchik-interface:variable-value 'oduvanchik::compile-and-load-buffer-file-function :mode "Lisp")
'compile-lisp-file-for-tcl)
(defun compile-tcl-file-for-tcl (filename load-p &rest options)
"Value of oduvanchik::compile-and-load-buffer-file-function for Tcl mode"
(declare (ignore load-p options))
(let* ((q-pathname (clco::tcl-escape-filename filename)))
(format t "~%Loading ~A into tcl...~%" q-pathname)
(eval-in-tcl (format nil "namespace eval :: source ~A" q-pathname)
)))
(setf (oduvanchik-interface:variable-value 'oduvanchik::compile-and-load-buffer-file-function :mode "Tcl")
'compile-tcl-file-for-tcl)
(defun compile-file-for-tcl (clcon_text filename)
"Backend for ::edt::CompileAndLoadTheFile . Rather untraditional c-s dialog. We normally do such things in tcl. It can be sometimes more convenient to edit though as we're in Lisp"
(let ((l (length filename)))
(when (and (> (length filename) 3) (string= (subseq filename (- l 3) l) "asd"))
(let* ((system-name
(subseq filename
(+ 1 (position #\/ filename :from-end t))
(- l 4)))
(system (ignore-errors (asdf:find-system system-name))))
(cond
((not system) (format t "Вы пытаетесь загрузить систему ~A (из файла ~S), но asdf не нашёл такой системы. Если эта система - новая, попробуйте Консоль/Меню/Файл/Очистить кеш asd-систем в quicklisp. См. также Консоль/Меню/Справка/Руководство clcon. ~%" system-name filename))
((not (string-equal (namestring (asdf:system-definition-pathname system)) filename))
(format t "Что-то не так с настройкой ASDF/Quicklisp: вы пытаетесь загрузить систему ~A (из файла ~S), но asdf нашёл её в файле ~S" system-name filename (namestring (asdf:system-definition-pathname system))))
(t
(format t "Вы пытаетесь загрузить систему ~A (из файла ~S)" system-name filename)
(clco:operate-on-system-for-tcl system))))
(return-from compile-file-for-tcl nil)))
(let* ((buffer (oi::clcon_text-to-buffer clcon_text))
(mode (first (oi::buffer-modes buffer)))
(fn (oduvanchik-interface:variable-value 'oduvanchik::compile-and-load-buffer-file-function :mode mode)))
(funcall fn filename t)))
(defun operate-on-system-for-tcl (system-name &optional (operation 'asdf:load-op) &rest options)
"Выполняет действие над системой ASDF"
(let* ((compilation-result (apply #'swank:operate-on-system-for-emacs system-name operation options))
(success (swank::compilation-result-successp compilation-result))
(notes (swank::compilation-result-notes compilation-result))
(serial 0)
)
(when (or notes (not success))
(eval-in-tcl (format nil "::erbr::SwankBrowseErrors1 ~A" (CLCO::CONVERT-OBJECT-TO-TCL compilation-result)))
(dolist (note notes)
(eval-in-tcl (calc-details-code note (incf serial)))
))
))
|
[
{
"context": "sed on Closette\r\n;;;;\tHistory:\tRGC 12/16/98 Added Vassili Bykov's WITH-SLOTS implementation.\r\n;;;;\t\t\t\tRGC 9/8/99 ",
"end": 142,
"score": 0.8223565220832825,
"start": 129,
"tag": "NAME",
"value": "Vassili Bykov"
},
{
"context": " 3/3/18 Shared slot fixes.\r\n;;;;\r\n;;;; Note from Roger Corman, 7/29/2001:\r\n;;;; This file has been hacked and m",
"end": 1805,
"score": 0.9998793601989746,
"start": 1793,
"tag": "NAME",
"value": "Roger Corman"
}
] |
Sys/clos.lisp
|
foss-santanu/cormanlisp
| 608 |
;;;;
;;;; File: clos.lisp
;;;; Contents: Corman Lisp CLOS implementation based on Closette
;;;; History: RGC 12/16/98 Added Vassili Bykov's WITH-SLOTS implementation.
;;;; RGC 9/8/99 Added STANDARD-CLASS-P.
;;;; Decreased generic function call overhead by 40%
;;;; by building, compiling and caching the generic function
;;;; on the fly.
;;;; RGC 10/14/99 DEFCLASS adds a type descriminator function to
;;;; support TYPEP.
;;;; RGC 12/06/99 Added RATIO builtin class.
;;;; RGC 2/15/01 Modified structures to be integrated better with CLOS.
;;;; i.e. CLASS-OF returns a class unique to that structure type.
;;;; RGC 2/24/01 Added code to patch common lisp structures which are created
;;;; prior to CLOS loading to support method dispatching.
;;;; RGC 7/29/01 Integrated EQL specializer code, optimized per generic function.
;;;; RGC 10/21/01 Integrated generic functions so they are now first-class
;;;; functions, satisfying FUNCTIONP, and callable by FUNCALL and APPLY.
;;;;
;;;; RGC 9/19/03 Incorporated Frank Adrian's modification to DEFGENERIC to support :documentation option.
;;;; RGC 8/17/06 Modified method generation to handle &AUX in argument lists
;;;; LC 9/6/17 Lower EQL specializer overhead and name EQL specializers to their "intern form" for display purposes.
;;;; LC 2/19/18 Class redefinition with propagation to subclasses and instances, :documentation and :default-initargs
;;;; DEFCLASS options, Forward-referenced-class, Built-in-class and other AMOP Metaobjects and guidelines.
;;;; LC 3/3/18 Shared slot fixes.
;;;;
;;;; Note from Roger Corman, 7/29/2001:
;;;; This file has been hacked and modified for over 5 years by
;;;; me and others. It no longer bears much resemblance to the original,
;;;; but I will leave the following messages from Xerox in anyway.
;;;;
;;;; Optimizations for use with Corman Lisp 1.0 (May 15, 1998)
;;;; Minor modifications for use with PowerLisp 2.0 (May 15, 1996)
;;;;
;;;; Closette Version 1.0 (February 10, 1991)
;;;; Copyright (c) 1990, 1991 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.
;;;;
;;;; Closette is an implementation of a subset of CLOS with a metaobject
;;;; protocol as described in "The Art of The Metaobject Protocol",
;;;; MIT Press, 1991.
;;;;
(provide :clos)
(in-package :common-lisp)
;; need to override warning here -RGC
(setq *COMPILER-WARN-ON-UNDEFINED-FUNCTION* nil)
(defvar exports
'(defclass defgeneric defmethod
find-class class-of
call-next-method next-method-p
slot-value slot-boundp slot-exists-p slot-makunbound
make-instance change-class
initialize-instance reinitialize-instance shared-initialize
update-instance-for-different-class
print-object
standard-object metaobject forward-referenced-class specializer
standard-class standard-generic-function standard-method eql-specializer
class-name
class-direct-superclasses class-direct-slots
class-precedence-list class-slots class-direct-subclasses
class-direct-methods class-direct-default-initargs class-default-initargs
generic-function-name generic-function-lambda-list
generic-function-methods generic-function-discriminating-function
generic-function-method-class
method-lambda-list method-qualifiers method-specializers method-body
method-environment method-generic-function method-function
slot-definition-name slot-definition-initfunction
slot-definition-initform slot-definition-initargs
slot-definition-readers slot-definition-writers
slot-definition-allocation
;;
;; Class-related metaobject protocol
;;
compute-class-precedence-list compute-slots
compute-effective-slot-definition
finalize-inheritance allocate-instance
slot-value-using-class slot-boundp-using-class
slot-exists-p-using-class slot-makunbound-using-class
;;
;; Generic function related metaobject protocol
;;
compute-discriminating-function
compute-applicable-methods-using-classes method-more-specific-p
compute-effective-method-function compute-method-function
apply-methods apply-method
describe-object
find-generic-function ; Necessary artifact of this implementation
))
(export exports)
;;; This hash-table supports CLOS EQL specializers.
(defconstant *clos-singleton-specializers* (make-hash-table :synchronized t))
;; fixed position of required-args in generic-function
(defconstant slot-location-generic-function-name 0)
(defconstant slot-location-generic-function-documentation 1)
(defconstant slot-location-generic-function-lambda-list 2)
(defconstant slot-location-generic-function-required-args 3)
(defconstant slot-location-generic-function-methods 4)
(defconstant slot-location-generic-function-method-class 5)
(defconstant slot-location-generic-function-discriminating-function 6)
(defconstant slot-location-generic-function-classes-to-emf-table 7)
(defconstant slot-location-generic-function-method-combination 8)
(defconstant slot-location-generic-function-method-combination-order 9)
;;;
;;; Utilities
;;;
;;; push-on-end is like push except it uses the other end:
(defmacro push-on-end (value location)
`(setf ,location (nconc ,location (list ,value))))
;;; (setf getf*) is like (setf getf) except that it always changes the list,
;;; which must be non-nil.
(defun (setf getf*) (new-value plist key)
(block body
(do ((x plist (cddr x)))
((null x))
(when (eq (car x) key)
(setf (car (cdr x)) new-value)
(return-from body new-value)))
(push-on-end key plist)
(push-on-end new-value plist)
new-value))
;;; mapappend is like mapcar except that the results are appended together:
(defun mapappend (fun &rest args)
(if (some #'null args)
()
(append (apply fun (mapcar #'car args))
(apply #'mapappend fun (mapcar #'cdr args)))))
;;; mapplist is mapcar for property lists:
(defun mapplist (fun x)
(if (null x)
()
(cons (funcall fun (car x) (cadr x))
(mapplist fun (cddr x)))))
;;; the method table is only used internally--optimize to the max
(proclaim '(optimize (speed 3)(safety 0)))
(defstruct method-table
(method-list nil)
(cached-method nil)
(cached-method-types nil)
(sync (cl::allocate-critical-section))
(eql-specializers nil))
(proclaim '(optimize (speed 0)(safety 3)))
(defun clear-method-table (table)
(with-synchronization (method-table-sync table)
(setf (method-table-method-list table) nil)
(setf (method-table-cached-method table) nil)
(setf (method-table-cached-method-types table) nil))
table)
(defun add-method-table-method (table types method)
(with-synchronization (method-table-sync table)
(setf (method-table-method-list table)
(cons types (cons method (method-table-method-list table))))
(setf (method-table-cached-method table) method)
(setf (method-table-cached-method-types table) types))
table)
(proclaim '(optimize (speed 3)(safety 0)))
(defun lists-match (list1 list2)
(do ((x list1 (cdr x)) (y list2 (cdr y))) ((null x) t)
(unless (eq (car x) (car y)) (return nil))))
(defun find-method-table-method (table eqls-classes)
(with-synchronization (method-table-sync table)
(do ((p (method-table-method-list table) (cddr p))) ((null p) (return nil))
(when (lists-match (car p) eqls-classes) (return (cadr p))))))
(proclaim '(optimize (speed 0)(safety 3)))
;;;
;;; Standard instances
;;;
(defun std-instance-class (x)
(if (clos-instance-p x)
(clos-instance-class x)
(error "Not a CLOS instance: ~S" x)))
(defun (setf std-instance-class) (val x)
(if (clos-instance-p x)
(setf (uref x clos-instance-class-offset) val)
(error "Not a CLOS instance: ~S" x)))
(defun std-instance-slots (x)
(if (clos-instance-p x)
(clos-instance-slots x)
(error "Not a CLOS instance: ~S" x)))
(defun (setf std-instance-slots) (val x)
(if (clos-instance-p x)
(setf (uref x clos-instance-slots-offset) val)
(error "Not a CLOS instance: ~S" x)))
;;; Fortunately there was an empty cell to store class signatures
(defun std-instance-signature (x)
(if (clos-instance-p x) (uref x 3) (error "Not a CLOS instance: ~S" x)))
(defun (setf std-instance-signature) (val x)
(if (clos-instance-p x) (setf (uref x 3) val) (error "Not a CLOS instance: ~S" x)))
(defun allocate-std-instance (class slots)
(let ((x (alloc-clos-instance)))
(setf (uref x clos-instance-class-offset) class)
(setf (uref x clos-instance-slots-offset) slots)
x))
(defun check-update (object)
(when (clos-instance-p object)
(let ((class (class-of object)) (signature (std-instance-signature object)))
(unless (or (eq 0 signature) (eq (car signature) (class-effective-slots class))) (update-instance object class signature)))))
;;; Standard instance allocation
(defparameter secret-unbound-value (list "slot unbound"))
(defun instance-slot-p (slot)
(eq (slot-definition-allocation slot) ':instance))
(defun std-allocate-instance (class)
(allocate-std-instance
class
(allocate-slot-storage
(length (class-effective-slots class)) ; class-effective-slots are the instance-slots-p slots
secret-unbound-value)))
;;; Simple vectors are used for slot storage.
(defun allocate-slot-storage (size initial-value)
(make-array size :initial-element initial-value))
;;; Standard instance slot access
;;; N.B. The location of the effective-slots slots in the class metaobject for
;;; standard-class must be determined without making any further slot
;;; references.
(defvar the-slots-of-standard-class) ;standard-class's class-slots
(defvar the-class-standard-class) ;standard-class's class metaobject
;;;
;;; This now returns null, rather than signal an error, if the slot is not found.
;;; This is to enable further searches for class slots by the functions which
;;; use this. -RGC 8/28/01
;;;
(defun slot-location (class slot-name)
(if (and (eq slot-name 'effective-slots)
(eq class the-class-standard-class))
;; (position 'effective-slots the-slots-of-standard-class :key #'slot-definition-name)
7 ;; for optimization, hard-code this
(let* ((slots (class-effective-slots class)))
(do* ((s slots (cdr s))
(x (car s)(car s))
(pos 0))
((null s))
(when (eq (slot-definition-name x) slot-name)
(return pos))
(if (eq (slot-definition-allocation x) ':instance)
(incf pos))))))
(defun shared-slot-location (class slot-name)
(let* ((slots (class-shared-slot-definitions class)))
(do* ((s slots (cdr s))
(x (car s)(car s))
(pos 0 (+ pos 1)))
((null s))
(when (eq (slot-definition-name x) slot-name)
(return pos)))))
;; optimize these by direct calls to inlined uref
(declaim (inline slot-contents (setf slot-contents)))
(defun slot-contents (slots location) (uref slots (+ location 2)) #|(svref slots location)|#)
(defun (setf slot-contents) (new-value slots location)
(setf (uref slots (+ location 2)) new-value)#|(setf (svref slots location) new-value)|#)
(defun std-slot-value (instance slot-name)
(let* ((class (class-of instance))
(location (slot-location class slot-name))
val)
(if location
(setf val (slot-contents (std-instance-slots instance) location))
(progn
(setf location (shared-slot-location class slot-name))
(if location
(setf val (car (slot-contents (class-shared-slots class) location)))
(error "The slot ~S is missing from the class ~S." slot-name class))))
(if (eq secret-unbound-value val)
(error "The slot ~S is unbound in the object ~S." slot-name instance))
val))
;;; Fast method to determine if a lisp object is a standard object.
;;; By our definition, any object which is not a CLOS instance (lisp
;;; primitive types, for example) are of type standard-class.
;;; CLOS instances are of type standard-class if the classes of their
;;; classes are standard-class.
;;; The number of arguments is not checked.
;;; We assume that the class of any object is a clos instance
;;; (for optimization purposes).
;;;
(ccl:defasm standard-class-p (object)
{
push ebp
mov ebp, esp
mov eax, [ebp + ARGS_OFFSET]
mov edx, eax
and edx, 7
cmp edx, uvector-tag
jne short :t-exit
mov edx, [eax - uvector-tag]
shr edx, 3
and edx, #x1f
cmp edx, cl::uvector-clos-instance-tag
jne short :t-exit
mov eax, [eax + (uvector-offset cl::clos-instance-class-offset)]
mov eax, [eax + (uvector-offset cl::clos-instance-class-offset)]
mov edx, 'cl::the-class-standard-class
mov edx, [edx + (uvector-offset cl::symbol-value-offset)]
mov edx, [edx - cons-tag]
cmp edx, eax
jne short :nil-exit
:t-exit
mov eax, [esi + t-offset]
jmp short :exit
:nil-exit
mov eax, [esi]
:exit
pop ebp
ret
})
;;; Fast method to determine if a lisp object is a standard generic function.
(ccl:defasm standard-generic-function-p (object)
{
push ebp
mov ebp, esp
mov eax, [ebp + ARGS_OFFSET]
mov edx, eax
and edx, 7
cmp edx, uvector-tag
jne short :nil-exit
mov edx, [eax - uvector-tag]
shr edx, 3
and edx, #x1f
cmp edx, cl::uvector-clos-instance-tag
jne short :nil-exit
mov eax, [eax + (uvector-offset cl::clos-instance-class-offset)]
mov edx, 'cl::the-class-standard-gf
mov edx, [edx + (uvector-offset cl::symbol-value-offset)]
mov edx, [edx - cons-tag]
cmp edx, eax
jne short :nil-exit
:t-exit
mov eax, [esi + t-offset]
jmp short :exit
:nil-exit
mov eax, [esi]
:exit
pop ebp
ret
})
;;; now patch (SETF SYMBOL-FUNCTION) to store the generic function
;;; in the symbol's function slot. We call the kernel function
;;; first to ensure that the jump table gets setup with the
;;; address of the discrimination function closure.
;;;
(defparameter +save-set-symbol-function+ (fdefinition '(setf symbol-function)))
(defun (setf symbol-function) (value symbol)
(if (standard-generic-function-p value)
(let ((discrimination-function
(uref
(uref value cl::clos-instance-slots-offset)
(+ 2 cl::slot-location-generic-function-discriminating-function))))
(funcall +save-set-symbol-function+ discrimination-function symbol)
;; now replace the function slot of the symbol
(setf (car (uref symbol cl::symbol-function-offset)) value))
(funcall +save-set-symbol-function+ value symbol)))
(defun slot-value (object slot-name) (check-update object)
(if (standard-class-p object)
(std-slot-value object slot-name)
(slot-value-using-class (class-of object) object slot-name)))
;; For fixed known slot positions (optimization) for std-slots
;;
(defun slot-value-with-index (object slot-name index)
(if (standard-class-p object)
(let* ((slots (std-instance-slots object))
(val (svref slots index)))
(if (eq secret-unbound-value val)
(error "The slot ~S is unbound in the object ~S." slot-name object)
val))
(slot-value-using-class (class-of object) object slot-name)))
(defun (setf slot-value-with-index) (new-value object slot-name index)
(if (standard-class-p object)
(let* ((slots (std-instance-slots object)))
(setf (svref slots index) new-value))
(setf-slot-value-using-class
new-value (class-of object) object slot-name)))
(defun (setf std-slot-value) (new-value instance slot-name)
(let* ((class (class-of instance))
(location (slot-location class slot-name)))
(if location
(setf (slot-contents (std-instance-slots instance) location) new-value)
(progn
(setf location (shared-slot-location class slot-name))
(if location
(setf (car (slot-contents (class-shared-slots class) location)) new-value)
(error "The slot ~S is missing from the class ~S." slot-name class))))))
(defun (setf slot-value) (new-value object slot-name) (check-update object)
(if (standard-class-p object)
(setf (std-slot-value object slot-name) new-value)
(setf-slot-value-using-class
new-value (class-of object) object slot-name)))
(defun std-slot-boundp (instance slot-name)
(let* ((class (class-of instance))
(location (slot-location class slot-name)))
(if location
(not (eq secret-unbound-value (slot-contents (std-instance-slots instance) location)))
(progn
(setf location (shared-slot-location class slot-name))
(if location
(not (eq secret-unbound-value (car (slot-contents (class-shared-slots class) location))))
(error "The slot ~S is missing from the class ~S." slot-name class))))))
(defun slot-boundp (object slot-name) (check-update object)
(if (standard-class-p object)
(std-slot-boundp object slot-name)
(slot-boundp-using-class (class-of object) object slot-name)))
(defun std-slot-makunbound (instance slot-name)
(let* ((class (class-of instance))
(location (slot-location class slot-name)))
(if location
(setf (slot-contents (std-instance-slots instance) location) secret-unbound-value)
(progn
(setf location (shared-slot-location class slot-name))
(if location
(setf (car (slot-contents (class-shared-slots class) location)) secret-unbound-value)
(error "The slot ~S is missing from the class ~S." slot-name class)))))
instance)
(defun slot-makunbound (object slot-name) (check-update object)
(if (standard-class-p object)
(std-slot-makunbound object slot-name)
(slot-makunbound-using-class (class-of object) object slot-name)))
(defun std-slot-exists-p (instance slot-name)
(not (null (find slot-name (class-slots (class-of instance))
:key #'slot-definition-name))))
(defun slot-exists-p (object slot-name)
(if (standard-class-p object)
(std-slot-exists-p object slot-name)
(slot-exists-p-using-class (class-of object) object slot-name)))
;;; class-of
(defun class-of (x)
(if (clos-instance-p x)
(std-instance-class x)
(built-in-class-of x)))
;;; N.B. This version of built-in-class-of is straightforward but very slow.
;;; This is only for booting, a faster method is used later -RGC
;;;
(defun built-in-class-of (x)
(typecase x
(null (find-class 'null))
((and symbol (not null)) (find-class 'symbol))
((complex *) (find-class 'complex))
(integer (find-class 'integer))
((float * *) (find-class 'float))
(cons (find-class 'cons))
(character (find-class 'character))
(hash-table (find-class 'hash-table))
(package (find-class 'package))
(pathname (find-class 'pathname))
(readtable (find-class 'readtable))
(stream (find-class 'stream))
(number (find-class 'number))
((string *) (find-class 'string))
((bit-vector *) (find-class 'bit-vector))
((vector * *) (find-class 'vector))
((array * *) (find-class 'array))
(sequence (find-class 'sequence))
(function (find-class 'function))
(t (find-class 't))))
;;; subclassp and sub-specializer-p
(defun subclassp (c1 c2)
(not (null (find c2 (class-precedence-list c1)))))
(defun sub-specializer-p (c1 c2 c-arg)
(let ((cpl (class-precedence-list c-arg)))
(not (null (find c2 (cdr (member c1 cpl)))))))
;;;
;;; Class metaobjects and standard-class
;;;
(defparameter the-defclass-standard-class ;standard-class's defclass form
'(defclass standard-class (class)
((name :initarg :name) ; :accessor class-name
(documentation :initform () :initarg :documentation) ; :accessor class-documentation
(direct-subclasses :initform ()) ; :accessor class-direct-subclasses
(direct-superclasses ; :accessor class-direct-superclasses
:initarg :direct-superclasses)
(class-precedence-list) ; :accessor class-precedence-list
(direct-methods :initform ()) ; :accessor class-direct-methods
(direct-slots) ; :accessor class-direct-slots
(effective-slots) ; :accessor class-effective-slots
(shared-slot-definitions :initform ()) ; :accessor class-shared-slot-definitions
(shared-slots :initform ()) ; :accessor class-shared-slots
(direct-default-initargs :initform () :initarg :direct-default-initargs) ; :accessor class-direct-default-initargs
(effective-default-initargs :initform ())))) ; :accessor class-default-initargs
;;; Defining the metaobject slot accessor function as regular functions
;;; greatly simplifies the implementation without removing functionality.
(defun class-name (class) (std-slot-value class 'name))
(defun (setf class-name) (new-value class) (setf (slot-value class 'name) new-value))
(defun class-documentation (class) (slot-value class 'documentation))
(defun (setf class-documentation) (new-value class)
(setf (slot-value class 'documentation) new-value))
(defun class-direct-superclasses (class) (slot-value class 'direct-superclasses))
(defun (setf class-direct-superclasses) (new-value class)
(setf (slot-value class 'direct-superclasses) new-value))
(defun class-direct-slots (class) (slot-value class 'direct-slots))
(defun (setf class-direct-slots) (new-value class)
(setf (slot-value class 'direct-slots) new-value))
(defun class-precedence-list (class) (slot-value class 'class-precedence-list))
(defun (setf class-precedence-list) (new-value class)
(setf (slot-value class 'class-precedence-list) new-value))
; class-slots generic defined below
(defun class-effective-slots (class) (slot-value class 'effective-slots))
(defun (setf class-effective-slots) (new-value class)
(setf (slot-value class 'effective-slots) new-value))
(defun class-direct-subclasses (class) (slot-value class 'direct-subclasses))
(defun (setf class-direct-subclasses) (new-value class)
(setf (slot-value class 'direct-subclasses) new-value))
(defun class-direct-methods (class) (slot-value class 'direct-methods))
(defun (setf class-direct-methods) (new-value class)
(setf (slot-value class 'direct-methods) new-value))
(defun class-shared-slots (class) (slot-value class 'shared-slots))
(defun (setf class-shared-slots) (new-value class)
(setf (slot-value class 'shared-slots) new-value))
(defun class-shared-slot-definitions (class) (slot-value class 'shared-slot-definitions))
(defun (setf class-shared-slot-definitions) (new-value class)
(setf (slot-value class 'shared-slot-definitions) new-value))
;;; defclass
(defmacro defclass (name direct-superclasses slot-definitions
&rest options)
`(ensure-class ',name
:direct-superclasses
,(canonicalize-direct-superclasses direct-superclasses)
:direct-slots
,(canonicalize-direct-slots slot-definitions)
,@(canonicalize-defclass-options options)))
(defun canonicalize-direct-slots (slot-definitions)
`(list ,@(mapcar #'canonicalize-direct-slot slot-definitions)))
(defun canonicalize-direct-slot (spec)
(if (symbolp spec) `(list :name ',spec)
(let ((name (car spec))
(initfunction nil)
(initform nil)
(initargs ())
(readers ())
(writers ())
(other-options ()))
(do ((olist (cdr spec) (cddr olist)))
((null olist))
(case (car olist)
(:initform
(setq initfunction
`(function (lambda () ,(cadr olist))))
(setq initform `',(cadr olist)))
(:initarg (push-on-end (cadr olist) initargs))
(:reader (push-on-end (cadr olist) readers))
(:writer (push-on-end (cadr olist) writers))
(:accessor
(push-on-end (cadr olist) readers)
(push-on-end `(setf ,(cadr olist)) writers))
(otherwise
(push-on-end `',(car olist) other-options)
(push-on-end `',(cadr olist) other-options))))
`(list
:name ',name
,@(when initfunction
`(:initform ,initform :initfunction ,initfunction))
,@(when initargs `(:initargs ',initargs))
,@(when readers `(:readers ',readers))
,@(when writers `(:writers ',writers))
,@other-options))))
(defun canonicalize-direct-superclasses (direct-superclasses)
`(list ,@(mapcar #'canonicalize-direct-superclass direct-superclasses)))
(defun canonicalize-direct-superclass (class-name)
`(find-class ',class-name))
(defun canonicalize-defclass-options (options)
(mapappend #'canonicalize-defclass-option options))
(defun canonicalize-defclass-option (option)
(case (car option)
(:metaclass
(list ':metaclass
`(find-class ',(cadr option))))
(:documentation (list ':documentation `',(cadr option)))
(:default-initargs
(list
':direct-default-initargs
`(list ,@(mapplist
#'(lambda (key value)
`(list ',key ',value #'(lambda () ,value)))
(cdr option)))))
(t (list `',(car option) `',(cdr option)))))
;;; find-class
(let ((class-table (make-hash-table :test #'eq :synchronized t)))
(defun find-class (symbol &optional (errorp t)(environment nil))
(declare (ignore environment))
(let ((class (gethash symbol class-table nil)))
(if (and (null class) errorp)
(error "No class named ~S." symbol)
class)))
(defun (setf find-class) (new-value symbol)
(setf (gethash symbol class-table) new-value))
(defun forget-all-classes ()
(clrhash class-table)
(values))
) ;end let class-table
;;; Ensure class
(defun ensure-class (name &rest all-keys
&key (metaclass the-class-standard-class)
&allow-other-keys)
(let ((class (apply (if (eq metaclass the-class-standard-class)
#'make-instance-standard-class
#'make-instance)
metaclass :name name all-keys)))
(setf (find-class name) class)
class))
;;; make-instance-standard-class creates and initializes an instance of
;;; standard-class without falling into method lookup. However, it cannot be
;;; called until standard-class itself exists.
(defun make-instance-standard-class (metaclass
&key name direct-superclasses direct-slots &allow-other-keys)
(declare (ignore metaclass))
(let ((class (std-allocate-instance the-class-standard-class)))
(setf (class-name class) name)
(setf (class-documentation class) ())
(setf (class-direct-subclasses class) ())
(setf (class-direct-methods class) ())
(setf (slot-value class 'direct-default-initargs) ()) ; default initargs accessor methods defined later
(setf (slot-value class 'effective-default-initargs) ())
(std-after-initialization-for-classes class
:direct-slots direct-slots
:direct-superclasses direct-superclasses)
(std-finalize-inheritance class)
class))
(defun std-after-initialization-for-classes (class
&key direct-superclasses direct-slots (documentation nil supp) &allow-other-keys)
;; update class hierarchy
(let ((supers
(or direct-superclasses
(list (find-class 'standard-object)))))
(setf (class-direct-superclasses class) supers)
(dolist (superclass supers)
(pushnew class (class-direct-subclasses superclass)))) ; pushnew to add
(let ((slots
(mapcar #'(lambda (slot-properties)
(apply #'make-direct-slot-definition
slot-properties))
direct-slots)))
(setf (class-direct-slots class) slots)
(dolist (direct-slot slots)
(dolist (reader (slot-definition-readers direct-slot))
(add-reader-method
class reader (slot-definition-name direct-slot)))
(dolist (writer (slot-definition-writers direct-slot))
(add-writer-method
class writer (slot-definition-name direct-slot)))))
(when (and supp (or (stringp documentation) (not documentation))) (setf (documentation (class-name class) 'type) documentation))
(values))
;;; Slot definition metaobjects
;;; N.B. Quietly retain all unknown slot options (rather than signaling an
;;; error), so that it's easy to add new ones.
;;; This is used for shared slots as well. -RGC
(defun make-direct-slot-definition
(&rest properties
&key name (initargs ()) (initform nil) (initfunction nil)
(readers ()) (writers ()) (allocation :instance)
&allow-other-keys)
(let ((slot (copy-list properties))) ; Don't want to side effect &rest list
(setf (getf* slot ':name) name)
(setf (getf* slot ':initargs) initargs)
(setf (getf* slot ':initform) initform)
(setf (getf* slot ':initfunction) initfunction)
(setf (getf* slot ':readers) readers)
(setf (getf* slot ':writers) writers)
(setf (getf* slot ':allocation) allocation)
(when (eq allocation :class) (setf (getf* slot ':shared-slot) (list secret-unbound-value)))
slot))
(defun make-effective-slot-definition
(&rest properties
&key name (initargs ()) (initform nil) (initfunction nil)
(allocation :instance)
&allow-other-keys)
(let ((slot (copy-list properties))) ; Don't want to side effect &rest list
(setf (getf* slot ':name) name)
(setf (getf* slot ':initargs) initargs)
(setf (getf* slot ':initform) initform)
(setf (getf* slot ':initfunction) initfunction)
(setf (getf* slot ':allocation) allocation)
slot))
(defun slot-definition-name (slot) (getf slot ':name))
(defun (setf slot-definition-name) (new-value slot)
(setf (getf* slot ':name) new-value))
(defun slot-definition-initfunction (slot) (getf slot ':initfunction))
(defun (setf slot-definition-initfunction) (new-value slot)
(setf (getf* slot ':initfunction) new-value))
(defun slot-definition-initform (slot) (getf slot ':initform))
(defun (setf slot-definition-initform) (new-value slot)
(setf (getf* slot ':initform) new-value))
(defun slot-definition-initargs (slot) (getf slot ':initargs))
(defun (setf slot-definition-initargs) (new-value slot)
(setf (getf* slot ':initargs) new-value))
(defun slot-definition-readers (slot) (getf slot ':readers))
(defun (setf slot-definition-readers) (new-value slot)
(setf (getf* slot ':readers) new-value))
(defun slot-definition-writers (slot) (getf slot ':writers))
(defun (setf slot-definition-writers) (new-value slot)
(setf (getf* slot ':writers) new-value))
(defun slot-definition-allocation (slot)
(getf slot ':allocation))
(defun (setf slot-definition-allocation) (new-value slot)
(setf (getf* slot ':allocation) new-value))
(defun slot-definition-documentation (slot) (getf slot ':documentation))
(defun (setf slot-definition-documentation) (new-value slot)
(setf (getf* slot ':documentation) new-value))
(defun slot-definition-shared-slot (slot) (getf slot ':shared-slot))
;;; finalize-inheritance
(defun finalize-inheritance (class) (std-finalize-inheritance class))
; Delete either the slot class-shared-slot-definitions or class-shared-slots as shared slots are in both
; but leave for compatibility and speed? for now.
(defun std-finalize-inheritance (class)
(setf (class-precedence-list class) (compute-class-precedence-list class))
(let* ((class-slots (compute-slots class)) (shared-defs (remove-if #'instance-slot-p class-slots))
(shared-slots (when shared-defs (allocate-slot-storage (length shared-defs) ()))))
(setf (class-effective-slots class) (remove-if-not #'instance-slot-p class-slots)
(class-shared-slot-definitions class) shared-defs
(class-shared-slots class) shared-slots)
(dotimes (i (length shared-defs)) (setf (slot-contents shared-slots i) (slot-definition-shared-slot (nth i shared-defs)))))
(values))
(defun class-finalized-p (class) (typecase class (standard-class (and (slot-boundp class 'effective-slots) class)) (specializer class))) ; nil for forward referenced classes
(defun update-instance (instance class signature)
(let* ((local (mapcar #'slot-definition-name (car signature))) (shared (mapcar #'slot-definition-name (cadr signature)))
(p-slot-value (mapappend #'list (append local shared)
(append (coerce (std-instance-slots instance) 'list)
(mapcar #'(lambda (x) (car (slot-definition-shared-slot x))) (cadr signature)))))
(class-effective-slots (class-effective-slots class)) (class-shared-slot-definitions (class-shared-slot-definitions class))
(class-local (mapcar #'slot-definition-name class-effective-slots))
(class-shared (mapcar #'slot-definition-name class-shared-slot-definitions)))
(setf (std-instance-slots instance) (allocate-slot-storage (length class-local) secret-unbound-value))
(setf (std-instance-signature instance)
(list class-effective-slots class-shared-slot-definitions)) ; we'll next use setf on slot-value
(dolist (slot class-local)
(multiple-value-bind (ignore val foundp) (get-properties p-slot-value (list slot)) (declare (ignore ignore))
(and foundp (setf (slot-value instance slot) val))))
(let ((discarded (set-difference local class-local)))
(update-instance-for-redefined-class instance
(set-difference (set-difference class-local local) shared)
(set-difference discarded class-shared)
(apply #'append (mapplist #'(lambda (x y) (when (and (not (eq y secret-unbound-value)) (member x discarded)) (list x y))) p-slot-value))))))
(defun remove-from-deleted-classes (class new-superclasses)
(mapc #'(lambda (x) (setf (class-direct-subclasses x) (remove class (class-direct-subclasses x))))
(set-difference (class-direct-superclasses class) new-superclasses)))
(defun collect-subclasses (class)
(do* ((subs (reverse (class-direct-subclasses class))
(mapappend #'(lambda (x) (reverse (class-direct-subclasses x))) subs))
(all subs (append all subs)))
((not subs) (delete-duplicates all))))
;;; Class precedence lists
(defun compute-class-precedence-list (class) (std-compute-class-precedence-list class))
(defun std-compute-class-precedence-list (class)
(let ((classes-to-order (collect-superclasses* class)))
(topological-sort classes-to-order
(remove-duplicates
(mapappend #'local-precedence-ordering
classes-to-order))
#'std-tie-breaker-rule)))
;;; topological-sort implements the standard algorithm for topologically
;;; sorting an arbitrary set of elements while honoring the precedence
;;; constraints given by a set of (X,Y) pairs that indicate that element
;;; X must precede element Y. The tie-breaker procedure is called when it
;;; is necessary to choose from multiple minimal elements; both a list of
;;; candidates and the ordering so far are provided as arguments.
(defun topological-sort (elements constraints tie-breaker)
(let ((remaining-constraints constraints)
(remaining-elements elements)
(result ()))
(loop
(let ((minimal-elements
(remove-if
#'(lambda (class)
(member class remaining-constraints
:key #'cadr))
remaining-elements)))
(when (null minimal-elements)
(if (null remaining-elements)
(return-from topological-sort result)
(error "Inconsistent precedence graph.")))
(let ((choice (if (null (cdr minimal-elements))
(car minimal-elements)
(funcall tie-breaker
minimal-elements
result))))
(setq result (append result (list choice)))
(setq remaining-elements
(remove choice remaining-elements))
(setq remaining-constraints
(remove choice
remaining-constraints
:test #'member)))))))
;;; In the event of a tie while topologically sorting class precedence lists,
;;; the CLOS Specification says to "select the one that has a direct subclass
;;; rightmost in the class precedence list computed so far." The same result
;;; is obtained by inspecting the partially constructed class precedence list
;;; from right to left, looking for the first minimal element to show up among
;;; the direct superclasses of the class precedence list constituent.
;;; (There's a lemma that shows that this rule yields a unique result.)
(defun std-tie-breaker-rule (minimal-elements cpl-so-far)
(dolist (cpl-constituent (reverse cpl-so-far))
(let* ((supers (class-direct-superclasses cpl-constituent))
(common (intersection minimal-elements supers)))
(when (not (null common))
(return-from std-tie-breaker-rule (car common))))))
;;; This version of collect-superclasses* isn't bothered by cycles in the class
;;; hierarchy, which sometimes happen by accident.
(defun collect-superclasses* (class)
(labels ((all-superclasses-loop (seen superclasses)
(let ((to-be-processed
(set-difference superclasses seen)))
(if (null to-be-processed)
superclasses
(let ((class-to-process
(car to-be-processed)))
(all-superclasses-loop
(cons class-to-process seen)
(union (class-direct-superclasses
class-to-process)
superclasses)))))))
(all-superclasses-loop () (list class))))
;;; The local precedence ordering of a class C with direct superclasses C_1,
;;; C_2, ..., C_n is the set ((C C_1) (C_1 C_2) ...(C_n-1 C_n)).
(defun local-precedence-ordering (class)
(mapcar #'list
(cons class
(butlast (class-direct-superclasses class)))
(class-direct-superclasses class)))
;;; Slot inheritance
(defun compute-slots (class) (std-compute-slots class))
(defun std-compute-slots (class)
(let* ((all-slots (nreverse (mapappend #'class-direct-slots
(reverse (class-precedence-list class)))))
(all-names (remove-duplicates
(mapcar #'slot-definition-name all-slots))))
(nreverse (mapcar #'(lambda (name)
(compute-effective-slot-definition
class
(remove name all-slots
:key #'slot-definition-name
:test-not #'eq)))
all-names))))
(defun compute-effective-slot-definition (class direct-slots) (std-compute-effective-slot-definition class direct-slots))
(defun std-compute-effective-slot-definition (class direct-slots)
(let* ((initer (find-if-not #'null direct-slots
:key #'slot-definition-initfunction))
(doc (find-if-not #'null direct-slots
:key #'slot-definition-documentation))
(first-slot (car direct-slots))
(alloc (slot-definition-allocation first-slot))
(slot (make-effective-slot-definition
:name (slot-definition-name first-slot)
:initform (when initer (slot-definition-initform initer))
:initfunction (when initer (slot-definition-initfunction initer))
:initargs (remove-duplicates (mapappend #'slot-definition-initargs direct-slots))
:allocation alloc)))
(when (eq alloc :class)
(let ((shared-slot (slot-definition-shared-slot first-slot)))
(setf (getf* slot :shared-slot) shared-slot)
(when (member shared-slot (class-direct-slots class) :key #'slot-definition-shared-slot)
(let ((old-shared-slot (and (class-finalized-p class)
(slot-definition-shared-slot (find (slot-definition-name slot) (class-shared-slot-definitions class)
:key #'slot-definition-name)))))
(setf (car shared-slot) (if old-shared-slot (car old-shared-slot) (if initer (funcall (slot-definition-initfunction initer)) secret-unbound-value)))))))
(when doc (setf (getf* slot :documentation) (slot-definition-documentation doc)))
slot))
;;;
;;; Generic function metaobjects and standard-generic-function
;;;
(defparameter the-defclass-generic-function
'(defclass generic-function (metaobject)))
(defparameter the-defclass-standard-generic-function
'(defclass standard-generic-function (generic-function)
( ; (name :initarg :name) ; name from metaobject :accessor generic-function-name
(lambda-list ; :accessor generic-function-lambda-list
:initarg :lambda-list)
(required-args ; :accessor generic-function-required-args
:initarg :required-args)
(methods :initform ()) ; :accessor generic-function-methods
(method-class ; :accessor generic-function-method-class
:initarg :method-class)
(discriminating-function) ; :accessor generic-function-
; -discriminating-function
(classes-to-emf-table ; :accessor classes-to-emf-table
:initform (make-method-table))
(method-combination :initarg :method-combination :initform 'standard) ; :accessor generic-function-method-combination
(method-combination-order :initform ':most-specific-first)))) ; :accessor generic-function-method-combination-order
(defvar the-class-gf) ;generic-function's class metaobject
(defvar the-class-standard-gf) ;standard-generic-function's class metaobject
(defun generic-function-name (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'name slot-location-generic-function-name)
(slot-value gf 'name)))
(defun (setf generic-function-name) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'name slot-location-generic-function-name)
new-value)
(setf (slot-value gf 'name) new-value)))
(defun generic-function-required-args (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'required-args
slot-location-generic-function-required-args)
(slot-value gf 'required-args)))
(defun (setf generic-function-required-args) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf
'required-args slot-location-generic-function-required-args)
new-value)
(setf (slot-value gf 'required-args) new-value)))
(defun generic-function-lambda-list (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'lambda-list
slot-location-generic-function-lambda-list)
(slot-value gf 'lambda-list)))
(defun (setf generic-function-lambda-list) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(progn
(setf (generic-function-required-args gf)
(getf (analyze-lambda-list new-value) ':required-args))
(setf (slot-value-with-index gf 'lambda-list
slot-location-generic-function-lambda-list)
new-value))
(setf (slot-value gf 'lambda-list) new-value)))
(defun generic-function-methods (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'methods slot-location-generic-function-methods)
(slot-value gf 'methods)))
(defun (setf generic-function-methods) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'methods slot-location-generic-function-methods)
new-value)
(setf (slot-value gf 'methods) new-value)))
(defun generic-function-discriminating-function (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'discriminating-function
slot-location-generic-function-discriminating-function)
(slot-value gf 'discriminating-function)))
(defun (setf generic-function-discriminating-function) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'discriminating-function
slot-location-generic-function-discriminating-function)
new-value)
(setf (slot-value gf 'discriminating-function) new-value)))
(defun generic-function-method-class (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'method-class
slot-location-generic-function-method-class)
(slot-value gf 'method-class)))
(defun (setf generic-function-method-class) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'method-class
slot-location-generic-function-method-class)
new-value)
(setf (slot-value gf 'method-class) new-value)))
;;; Internal accessor for effective method function table
(defun classes-to-emf-table (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'classes-to-emf-table
slot-location-generic-function-classes-to-emf-table)
(slot-value gf 'classes-to-emf-table)))
(defun (setf classes-to-emf-table) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'classes-to-emf-table
slot-location-generic-function-classes-to-emf-table)
new-value)
(setf (slot-value gf 'classes-to-emf-table) new-value)))
(defun (setf generic-function-method-combination) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'method-combination
slot-location-generic-function-method-combination)
new-value)
(setf (slot-value gf 'method-combination) new-value)))
(defun (setf generic-function-method-combination-order) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'method-combination-order
slot-location-generic-function-method-combination-order)
new-value)
(setf (slot-value gf 'method-combination-order) new-value)))
;;;
;;; Method metaobjects and standard-method
;;;
(defparameter the-defclass-standard-method
'(defclass standard-method (method)
((qualifiers :initarg :qualifiers) ; :accessor method-qualifiers
(lambda-list :initarg :lambda-list) ; :accessor method-lambda-list
(specializers :initarg :specializers) ; :accessor method-specializers
(body :initarg :body) ; :accessor method-body
(generic-function :initform nil) ; :accessor method-generic-function
(function) ; :accessor method-function
(environment :initarg :environment)))) ; :accessor method-environment
(defvar the-class-standard-method) ;standard-method's class metaobject
(defun method-lambda-list (method) (slot-value method 'lambda-list))
(defun (setf method-lambda-list) (new-value method)
(setf (slot-value method 'lambda-list) new-value))
(defun method-qualifiers (method) (slot-value method 'qualifiers))
(defun (setf method-qualifiers) (new-value method)
(setf (slot-value method 'qualifiers) new-value))
(defun method-specializers (method) (slot-value method 'specializers))
(defun (setf method-specializers) (new-value method)
(setf (slot-value method 'specializers) new-value))
(defun method-body (method) (slot-value method 'body))
(defun (setf method-body) (new-value method)
(setf (slot-value method 'body) new-value))
(defun method-environment (method) (slot-value method 'environment))
(defun (setf method-environment) (new-value method)
(setf (slot-value method 'environment) new-value))
(defun method-generic-function (method)
(slot-value method 'generic-function))
(defun (setf method-generic-function) (new-value method)
(setf (slot-value method 'generic-function) new-value))
(defun method-function (method) (slot-value method 'function))
(defun (setf method-function) (new-value method)
(setf (slot-value method 'function) new-value))
;;;
;;; Common Lisp DEFGENERIC macro
;;;
(defmacro defgeneric (function-name lambda-list &rest options)
(flet ((is-method-option (opt) (eq (car opt) :method))
(method-definition-form (opt) `(defmethod ,function-name ,@(cdr opt))))
(let* ((method-definitions (mapcar #'method-definition-form (remove-if (complement #'is-method-option) options)))
(non-method-options (remove-if #'is-method-option options))
(documentation-form
(let ((doc-string (cadr (find-if #'(lambda (opt) (eq (car opt) :documentation)) non-method-options))))
(when doc-string `(setf (documentation ',function-name 'function) ,doc-string)))))
`(prog1
(ensure-generic-function
',function-name
:lambda-list ',lambda-list
,@(canonicalize-defgeneric-options non-method-options))
,(when documentation-form documentation-form)
,@method-definitions
))))
(defun canonicalize-defgeneric-options (options)
(mapappend #'canonicalize-defgeneric-option options))
(defun canonicalize-defgeneric-option (option)
(case (car option)
(:generic-function-class
(list ':generic-function-class
`(find-class ',(cadr option))))
(:method-class
(list ':method-class
`(find-class ',(cadr option))))
(:method-combination
`(:method-combination ',(cadr option)))
(t (list `',(car option) `',(cadr option)))))
;;; find-generic-function looks up a generic function by name. It's an
;;; artifact of the fact that our generic function metaobjects can't legally
;;; be stored a symbol's function value.
(let ((generic-function-table (make-hash-table :test #'equal :synchronized t)))
(defun find-generic-function (symbol &optional (errorp t))
(if (consp symbol)
(if (and (eq (car symbol) 'SETF)(symbolp (cadr symbol)))
(let ((setf-func (get-setf-function (cadr symbol))))
(if (and (symbolp setf-func) (fboundp setf-func))
(setf setf-func (symbol-function setf-func)))
(if (and setf-func (standard-generic-function-p setf-func))
(return-from find-generic-function setf-func)))
(error "Invalid generic function name: ~S" symbol))
(if (fboundp symbol)
(let ((func (symbol-function symbol)))
(if (standard-generic-function-p func)
(return-from find-generic-function func)))))
(let ((gf (gethash symbol generic-function-table nil)))
(if (and (null gf) errorp)
(error "No generic function named ~S." symbol)
gf)))
(defun (setf find-generic-function) (func symbol)
(if (standard-generic-function-p func)
(if (consp symbol)
(if (and (eq (car symbol) 'SETF)(symbolp (cadr symbol)))
(let ((setter-name (cl::setf-function-symbol symbol)))
(setf (symbol-function setter-name) func)
(register-setf-function (cadr symbol) setter-name))
(error "Invalid generic function name: ~S" symbol))
(setf (symbol-function symbol) func))
(setf (gethash symbol generic-function-table) func)))
(defun forget-all-generic-functions ()
(clrhash generic-function-table)
(values))
) ;end let generic-function-table
;;; ensure-generic-function
(defun ensure-generic-function
(function-name
&rest all-keys
&key (generic-function-class the-class-standard-gf)
(method-class the-class-standard-method)
lambda-list
&allow-other-keys)
(if (find-generic-function function-name nil)
(find-generic-function function-name)
(let ((gf (apply (if (eq generic-function-class the-class-standard-gf)
#'make-instance-standard-generic-function
#'make-instance)
generic-function-class
:name function-name
:method-class method-class
:required-args (getf (analyze-lambda-list lambda-list) ':required-args)
all-keys)))
(setf (find-generic-function function-name) gf)
gf)))
;;; finalize-generic-function
;;; Same basic idea as finalize-inheritance.
;;; Takes care of recomputing and storing the discriminating
;;; function, and clearing the effective method function table.
(defun finalize-generic-function (gf)
(setf (generic-function-discriminating-function gf)
(funcall (if (eq (class-of gf) the-class-standard-gf)
#'std-compute-discriminating-function
#'compute-discriminating-function)
gf))
(unless (standard-generic-function-p gf)
(setf (fdefinition (generic-function-name gf))
(generic-function-discriminating-function gf)))
(clear-method-table (classes-to-emf-table gf))
(values))
;;; make-instance-standard-generic-function creates and initializes an
;;; instance of standard-generic-function without falling into method lookup.
;;; However, it cannot be called until standard-generic-function exists.
(defun make-instance-standard-generic-function
(generic-function-class
&key
name
documentation
lambda-list
method-class
(method-combination 'standard)
(method-combination-order ':most-specific-first)
&allow-other-keys)
(declare (ignore generic-function-class))
(let ((gf (std-allocate-instance the-class-standard-gf)))
(setf (generic-function-name gf) name)
(setf (class-documentation gf) documentation)
(setf (generic-function-lambda-list gf) lambda-list)
(setf (generic-function-methods gf) ())
(setf (generic-function-method-class gf) method-class)
(setf (classes-to-emf-table gf) (make-method-table))
(setf (generic-function-method-combination gf) method-combination)
(setf (generic-function-method-combination-order gf) method-combination-order)
(finalize-generic-function gf)
gf))
;;; defmethod
(defmacro defmethod (&rest args)
(multiple-value-bind (function-name qualifiers
lambda-list specializers body)
(parse-defmethod args)
`(ensure-method (find-generic-function ',function-name nil)
:generic-function-name ',function-name
:lambda-list ',lambda-list
:qualifiers ',qualifiers
:specializers ,(canonicalize-specializers specializers)
:body ',body
:environment (funcall (lambda () (cl::capture-compiler-environment)))#| nil |#
#| :eql-specializers (some #'(lambda (x) (and (listp x)(eq (car x) 'EQL))) ',specializers) |#)))
(defun canonicalize-specializers (specializers)
`(list ,@(mapcar #'canonicalize-specializer specializers)))
(defun canonicalize-specializer (specializer)
(if (and (listp specializer) (eq (car specializer) 'eql)) `(intern-eql-specializer ,(cadr specializer) ',(cadr specializer))
`(find-class ',specializer)))
(defun specalization-vars (specialized-lambda-list)
(let ((vars '()))
(dolist (x specialized-lambda-list (nreverse vars))
(if (member x lambda-list-keywords)
(return (nreverse vars))
(if (consp x)
(push (car x) vars))))))
(defun create-ignorable-decls (vars)
`(declare (ignorable ,@vars)))
(defun parse-defmethod (args)
(let ((fn-spec (car args))
(qualifiers ())
(specialized-lambda-list nil)
(body '())
(decls '())
(doc-string nil)
(parse-state :qualifiers))
(do* ((a (cdr args))
(arg (car a)(car a)))
((null a))
(cond
((eq parse-state :qualifiers)
(if (and (atom arg) (not (null arg)))
(progn
(push-on-end arg qualifiers)
(setf a (cdr a)))
(setq parse-state :lambda-list)))
((eq parse-state :lambda-list)
(setq specialized-lambda-list arg)
(setq parse-state :decls-and-doc-string)
(setf a (cdr a)))
((eq parse-state :decls-and-doc-string)
(if (and (null doc-string) (stringp arg))
(setq doc-string arg a (cdr a))
(if (and (consp arg)(eq (car arg) 'declare))
(progn
(push-on-end arg decls)
(setf a (cdr a)))
(setq parse-state :body))))
((eq parse-state :body)
(push-on-end arg body)
(setf a (cdr a)))))
;; watch for case where a literal string is the only item in body--
;; we don't want to mistake it for a doc-string
(if (and (null body) doc-string)
(setf body (list doc-string) doc-string nil))
(values fn-spec
qualifiers
(extract-lambda-list specialized-lambda-list)
(extract-specializers specialized-lambda-list)
;; add IGNORABLE declarations to specializers so they don't cause
;; warnings if they are not referenced in generated lambdas
`(,@(cons (create-ignorable-decls (specalization-vars specialized-lambda-list))
decls)
,@(if doc-string (list doc-string))
(block
,(if (consp fn-spec) (cadr fn-spec) fn-spec)
,@body)))))
;;; Several tedious functions for analyzing lambda lists
(defun gf-required-arglist (gf)
(generic-function-required-args gf))
(defun required-portion (gf args)
(let ((required-args (generic-function-required-args gf))
(new-args nil))
(dolist (x required-args (nreverse new-args))
(declare (ignore x))
(unless (consp args)
(error "Too few arguments to generic function ~S." gf))
(push (car args) new-args)
(setf args (cdr args)))))
(defun num-required-args (gf) (length (generic-function-required-args gf)))
(defun extract-lambda-list (specialized-lambda-list)
(let* ((plist (analyze-lambda-list specialized-lambda-list))
(requireds (getf plist ':required-names))
(rv (getf plist ':rest-var))
(ks (getf plist ':key-args))
(aok (getf plist ':allow-other-keys))
(opts (getf plist ':optional-args))
(auxs (getf plist ':auxiliary-args)))
`(,@requireds
,@(if opts `(&optional ,@opts) ())
,@(if rv `(&rest ,rv) ())
,@(if (or ks aok) `(&key ,@ks) ())
,@(if aok '(&allow-other-keys) ())
,@(if auxs `(&aux ,@auxs) ()))))
(defun extract-specializers (specialized-lambda-list)
(let ((plist (analyze-lambda-list specialized-lambda-list)))
(getf plist ':specializers)))
(defun analyze-lambda-list (lambda-list)
(labels ((make-keyword (symbol)
(intern (symbol-name symbol)
(find-package 'keyword)))
(get-keyword-from-arg (arg)
(if (listp arg)
(if (listp (car arg))
(caar arg)
(make-keyword (car arg)))
(make-keyword arg))))
(let ((keys ()) ; Just the keywords
(key-args ()) ; Keywords argument specs
(required-names ()) ; Just the variable names
(required-args ()) ; Variable names & specializers
(specializers ()) ; Just the specializers
(rest-var nil)
(optionals ())
(auxs ())
(allow-other-keys nil)
(state :parsing-required))
(dolist (arg lambda-list)
(if (member arg lambda-list-keywords)
(ecase arg
(&optional
(setq state :parsing-optional))
(&rest
(setq state :parsing-rest))
(&key
(setq state :parsing-key))
(&allow-other-keys
(setq allow-other-keys 't))
(&aux
(setq state :parsing-aux)))
(case state
(:parsing-required
(push-on-end arg required-args)
(if (listp arg)
(progn (push-on-end (car arg) required-names)
(push-on-end (cadr arg) specializers))
(progn (push-on-end arg required-names)
(push-on-end 't specializers))))
(:parsing-optional (push-on-end arg optionals))
(:parsing-rest (setq rest-var arg))
(:parsing-key
(push-on-end (get-keyword-from-arg arg) keys)
(push-on-end arg key-args))
(:parsing-aux (push-on-end arg auxs)))))
(list :required-names required-names
:required-args required-args
:specializers specializers
:rest-var rest-var
:keywords keys
:key-args key-args
:auxiliary-args auxs
:optional-args optionals
:allow-other-keys allow-other-keys))))
;;; ensure method
(defun ensure-method (gf &rest all-keys #| &key eql-specializers &allow-other-keys |#)
(if (null gf)
;; define a generic function on the fly
(setf gf
(ensure-generic-function
(getf all-keys :generic-function-name)
':lambda-list (getf all-keys :lambda-list))))
;; as soon as we define one method with an EQL specifier, we assume
;; methods of that generic function may specify this way
;(if eql-specializers ** redundantly too soon as add-method has to, for it can be called by the user
; (setf (method-table-eql-specializers (classes-to-emf-table gf)) t))
(let ((new-method
(apply
(if (eq (generic-function-method-class gf)
the-class-standard-method)
#'make-instance-standard-method
#'make-instance)
(generic-function-method-class gf)
all-keys)))
(setf (class-name new-method) (getf all-keys :generic-function-name))
(add-method gf new-method)
new-method))
;;; make-instance-standard-method creates and initializes an instance of
;;; standard-method without falling into method lookup. However, it cannot
;;; be called until standard-method exists.
(defun make-instance-standard-method (method-class
&key lambda-list qualifiers
specializers body environment
&allow-other-keys)
(declare (ignore method-class))
(let ((method (std-allocate-instance the-class-standard-method)))
(setf (method-lambda-list method) lambda-list)
(setf (class-documentation method) (when (stringp (cadr body)) (cadr body)))
(setf (method-qualifiers method) qualifiers)
(setf (method-specializers method) specializers)
(setf (method-body method) body)
(setf (method-environment method) environment)
(setf (method-generic-function method) nil)
(setf (method-function method)
(std-compute-method-function method))
method))
;;; add-method
;;; This version first removes any existing method on the generic function
;;; with the same qualifiers and specializers.
(defun eql-specializer-p (x) (declare (ignore x))) ; redefined below
(defun add-method (gf method)
(let ((old-method
(find-method gf (method-qualifiers method)
(method-specializers method) nil)))
(when old-method (remove-method gf old-method)))
(setf (method-generic-function method) gf)
(push method (generic-function-methods gf))
(dolist (specializer (method-specializers method))
(when (eql-specializer-p specializer)
(setf (method-table-eql-specializers (classes-to-emf-table gf)) t)) ; set to t to recalculate eqls
(pushnew method (class-direct-methods specializer)))
(finalize-generic-function gf)
gf) ; add-method should return gf.
(defun remove-method (gf method)
(setf (generic-function-methods gf)
(remove method (generic-function-methods gf)))
(setf (method-generic-function method) nil)
(dolist (class (method-specializers method))
(when (eql-specializer-p class)
(setf (method-table-eql-specializers (classes-to-emf-table gf)) t)) ; set to t to recalculate eqls
(setf (class-direct-methods class)
(remove method (class-direct-methods class))))
(finalize-generic-function gf)
gf) ; remove-method should return gf. Bug when trying to print a deleted method.
(defun find-method (gf qualifiers specializers
&optional (errorp t))
(let ((method
(find-if #'(lambda (method)
(and (equal qualifiers
(method-qualifiers method))
(equal specializers
(method-specializers method))))
(generic-function-methods gf))))
(if (and (null method) errorp)
(error "No such method for ~S." (generic-function-name gf))
method)))
;;; Reader and write methods
(defun add-reader-method (class fn-name slot-name)
(ensure-method
(ensure-generic-function fn-name :lambda-list '(object))
:lambda-list '(object)
:qualifiers ()
:specializers (list class)
:body `((slot-value object ',slot-name))
:environment (top-level-environment))
(values))
(defun add-class-slot-reader-method (class fn-name slot-name index)
(declare (ignore slot-name))
(ensure-method
(ensure-generic-function fn-name :lambda-list '(object))
:lambda-list '(object)
:qualifiers ()
:specializers (list class)
:body `((let* ((class (class-of object))
(val (car (aref (slot-value class 'shared-slots) ,index))))
(if (eq secret-unbound-value val)
(error "The class slot ~S is unbound in the class ~S." ',slot-name (class-name class))
val)))
:environment (top-level-environment))
(values))
(defun add-writer-method (class fn-name slot-name)
(ensure-method
(ensure-generic-function
fn-name :lambda-list '(new-value object))
:lambda-list '(new-value object)
:qualifiers ()
:specializers (list (find-class 't) class)
:body `((setf (slot-value object ',slot-name)
new-value))
:environment (top-level-environment))
(values))
(defun add-class-slot-writer-method (class fn-name slot-name index)
(declare (ignore slot-name))
(ensure-method
(ensure-generic-function
fn-name :lambda-list '(new-value object))
:lambda-list '(new-value object)
:qualifiers ()
:specializers (list (find-class 't) class)
:body `((setf (car (aref (slot-value (class-of object) 'shared-slots) ,index))
new-value))
:environment (top-level-environment))
(values))
(defun remove-read-write-methods (class)
(mapc #'(lambda (x)
(mapc #'(lambda (x)
(let* ((gf (find-generic-function x))
(meth (find-method gf () (if (= 2 (length (generic-function-required-args gf))) (list (find-class t) class) (list class)) nil)))
(when meth (remove-method gf meth))))
(append (slot-definition-readers x) (slot-definition-writers x))))
(class-direct-slots class)))
(defun convert-function-to-method (function-name method-lambda-list)
(eval (let* ((function-symbol (if (and (consp function-name) (eq 'setf (car function-name)))
(get-setf-function (cadr function-name))
function-name))
(meth (gensym))
(args (analyze-lambda-list method-lambda-list))
(args (append (getf args :required-names)
(mapcar #'(lambda (x) (if (consp x) (car x) x)) (getf args :optional-args))
(mapappend #'list (getf args :keywords) (getf args :key-args)) (list (getf args :rest-var)))))
`(prog1 (defmethod ,meth ,method-lambda-list (apply #',meth ,.(butlast args) ,(car (last args))))
(setf (generic-function-name #',meth) ',function-name
(class-name (car (generic-function-methods #',meth))) ',function-name
(getf (function-info-list (fdefinition ',function-name)) 'function-name) ',meth)
(rotatef (symbol-function ',meth) (symbol-function ',function-symbol))))))
;;;
;;; Generic function invocation
;;;
;;; apply-generic-function
(defun apply-generic-function (gf args)
(apply (generic-function-discriminating-function gf) args))
(defun std-compute-discriminating-function (gf &aux (table (classes-to-emf-table gf)) (num (num-required-args gf)))
#'(lambda (&rest args)
(let* ((tail (let ((tail (- (length args) num))) (if (minusp tail) (error "Too few arguments to generic function ~S." gf) tail)))
(eqls (if (listp (method-table-eql-specializers table)) (method-table-eql-specializers table)
(let ((eqls (make-list num)))
(dolist (meth (generic-function-methods gf) (setf (method-table-eql-specializers table)
(when (member-if #'consp eqls) eqls)))
(do ((specs (method-specializers meth) (cdr specs)) (eqls eqls (cdr eqls)))
((not specs))
(when (eql-specializer-p (car specs))
(pushnew (list (slot-value (car specs) 'object)) (car eqls)
:test #'(lambda (x y) (eql (car x) (car y))))))))))
(eqls-classes (if eqls (mapcar #'(lambda (arg eqls) (or (car (member arg eqls :key #'car)) (class-of arg))) args eqls)
(mapcar #'class-of (butlast args tail)))))
(funcall (or (find-method-table-method table eqls-classes)
(slow-method-lookup gf table args
(if eqls (mapcar #'(lambda (arg eql-class)
(if (consp eql-class)
(gethash arg *clos-singleton-specializers*)
eql-class)) args eqls-classes)
eqls-classes) eqls-classes)) args))))
(defun slow-method-lookup (gf table args classes eqls-classes)
(let* ((applicable-methods (compute-applicable-methods-using-classes gf classes))
(emfun (if (member-if #'primary-method-p applicable-methods)
(if (eq (class-of gf) the-class-standard-gf)
(std-compute-effective-method-function gf applicable-methods)
(compute-effective-method-function gf applicable-methods))
(error "No primary methods for ~S in the ~S." args gf))))
(add-method-table-method table eqls-classes emfun) emfun))
;;; compute-applicable-methods-using-classes
(defun compute-applicable-methods-using-classes
(gf required-classes)
(sort
(copy-list
(remove-if-not #'(lambda (method)
(every #'subclassp
required-classes
(method-specializers method)))
(generic-function-methods gf)))
#'(lambda (m1 m2)
(funcall
(if (eq (class-of gf) the-class-standard-gf)
#'std-method-more-specific-p
#'method-more-specific-p)
gf m1 m2 required-classes))))
;;; method-more-specific-p
;(setq cl::*compiler-warn-on-dynamic-return* nil)
(defun std-method-more-specific-p (gf method1 method2 required-classes)
(declare (ignore gf))
(do* ((specs1 (method-specializers method1)(cdr specs1))
(specs2 (method-specializers method2)(cdr specs2))
(classes required-classes (cdr classes))
(spec1 (car specs1)(car specs1))
(spec2 (car specs2)(car specs2))
(arg-class (car classes)(car classes)))
((or (endp specs1)(endp specs2)(endp classes)) nil)
(unless (eq spec1 spec2)
(return-from std-method-more-specific-p
(sub-specializer-p spec1 spec2 arg-class)))))
;(setq cl::*compiler-warn-on-dynamic-return* t)
;;; apply-methods and compute-effective-method-function
(defun apply-methods (gf args methods)
(funcall (compute-effective-method-function gf methods)
args))
(defun primary-method-p (method)
(null (method-qualifiers method)))
(defun before-method-p (method)
(equal '(:before) (method-qualifiers method)))
(defun after-method-p (method)
(equal '(:after) (method-qualifiers method)))
(defun around-method-p (method)
(equal '(:around) (method-qualifiers method)))
;;; If the name is a list i.e. (SETF FOO) then this creates a symbolic
;;; representation of the name, suitable as a block label.
(defun generic-func-name (gf)
(let ((gfn (generic-function-name gf)))
(if (symbolp gfn)
gfn
(make-symbol (format nil "~A" gfn)))))
;; new way in Corman Lisp 1.5 release
(defun std-compute-effective-method-function (gf methods)
(let ((primaries (remove-if-not #'primary-method-p methods))
(around (find-if #'around-method-p methods)))
(when (null primaries)
(error "No primary methods for the generic function ~S." gf))
(if around
(let ((next-emfun
(if (eq (class-of gf) the-class-standard-gf)
(std-compute-effective-method-function gf (remove around methods))
(compute-effective-method-function gf (remove around methods)))))
#'(lambda (args)
(funcall (method-function around) args next-emfun)))
(let* ((next-emfun (compute-primary-emfun (cdr primaries)))
(befores (remove-if-not #'before-method-p methods))
(reverse-afters
(reverse (remove-if-not #'after-method-p methods)))
(before-calls
(mapcar #'(lambda (before)
`(funcall ,(method-function before) args nil))
befores))
(after-calls
(mapcar #'(lambda (after)
`(funcall ,(method-function after) args nil))
reverse-afters)))
(if after-calls
(compile nil
`(lambda (args)
(block ,(generic-func-name gf) ;; a named block enables the compiler to
,@before-calls ;; tag the compiled code with the name
(multiple-value-prog1 ;; (for debugging, etc.)
(funcall ,(method-function (car primaries)) args ,next-emfun)
,@after-calls))))
(compile nil
`(lambda (args)
(block ,(generic-func-name gf)
,@before-calls
(funcall ,(method-function (car primaries)) args ,next-emfun)))))))))
;;; compute an effective method function from a list of primary methods:
(defun compute-primary-emfun (methods)
(if (null methods)
nil
(let ((next-emfun (compute-primary-emfun (cdr methods))))
#'(lambda (args)
(funcall (method-function (car methods)) args next-emfun)))))
;;; apply-method and compute-method-function
(defun apply-method (method args next-methods)
(funcall (method-function method)
args
(if (null next-methods)
nil
(compute-effective-method-function
(method-generic-function method) next-methods))))
;;; search a tree for a passed symbol or form
(defun search-tree (tree form)
(if tree
(if (eq tree form)
t
(if (consp tree)
(or (search-tree (car tree) form)
(search-tree (cdr tree) form))))))
(defun std-compute-method-function (method)
(let ((form (macroexpand-all (cons 'progn (method-body method))))
(lambda-list (method-lambda-list method)))
(if (or (search-tree form 'call-next-method)
(search-tree form 'next-method-p))
(compile-in-lexical-environment (method-environment method)
`(lambda (args next-emfun)
(flet ((call-next-method (&rest cnm-args)
(if (null next-emfun)
(error "No next method for the~@
generic function ~S."
(method-generic-function ',method))
(funcall next-emfun (or cnm-args args))))
(next-method-p () (not (null next-emfun))))
(apply #'(lambda ,(kludge-arglist lambda-list) ,@(cdr form)) args))))
(compile-in-lexical-environment (method-environment method)
`(lambda (args next-emfun)
(declare (ignore next-emfun))
(apply #'(lambda ,(kludge-arglist lambda-list) ,@(cdr form)) args))))))
;;; N.B. The function kludge-arglist is used to pave over the differences
;;; between argument keyword compatibility for regular functions versus
;;; generic functions.
;;; RGC--17 Aug 2006--modified to handle &aux lambda list variables.
;;;
(defun kludge-arglist (lambda-list)
(let ((aux-vars (member '&aux lambda-list)))
(if aux-vars
(setq lambda-list (subseq lambda-list 0 (position '&aux lambda-list))))
(if (and (member '&key lambda-list)
(not (member '&allow-other-keys lambda-list)))
(append lambda-list '(&allow-other-keys))
(if (and (not (member '&rest lambda-list))
(not (member '&key lambda-list)))
(append lambda-list '(&key &allow-other-keys) aux-vars)
(append lambda-list aux-vars)))))
;;; Run-time environment hacking (Common Lisp ain't got 'em).
(defun top-level-environment ()
nil) ; Bogus top level lexical environment
(defvar compile-methods nil) ; by default, run everything interpreted
(defun compile-in-lexical-environment (env lambda-expr)
(declare (ignore env))
(if compile-methods
(compile nil lambda-expr)
(eval `(function ,lambda-expr ,env))))
;;;;
;;;; Common Lisp FUNCALL function.
;;;; Modified here to allow Standard-Generic-Functions as the
;;;; first argument.
;;;;
(in-package :x86)
(defasm funcall (func &rest args)
{
push ebp
mov ebp, esp
push edi
push ecx
push ebx
push 0 ;; one cell local storage at [ebp - 16]
cmp ecx, 1
jge short :t1
callp _wrong-number-of-args-error
:t1
mov eax, [ebp + ecx*4 + 4] ;; eax = function
mov edx, eax
and edx, 7
cmp edx, uvector-tag ;; see if func arg is a uvector
je short :t2
push eax
callp _not-a-function-error
:t2
mov edx, [eax - uvector-tag] ;; edx = uvector header
shl edx, 24
shr edx, 27
cmp edx, uvector-symbol-tag ;; see if it is a symbol
jne short :t3
;; get the function that is bound to the symbol
mov eax, [eax + (- (* 4 symbol-function-offset) uvector-tag)]
mov eax, [eax - 4]
mov edx, eax
and edx, 7
cmp edx, uvector-tag
je short :t9
push [ebp + ecx*4 + 4]
callp _not-a-function-error
:t9
mov edx, [eax - uvector-tag] ;; edx = uvector header
shl edx, 24
shr edx, 27
:t3 ;; we now know we have a function in eax, and dl is the type
;; push all the arguments
mov [ebp - 16], esp
mov ebx, ecx
dec ecx
:t4
dec ebx
jle short :t5
push [ebp + ebx*4 + 4]
jmp short :t4
:t5
cmp edx, uvector-function-tag
jne short :t6
:t11
mov edi, [eax + (- (* 4 function-environment-offset) uvector-tag)]
callfunc eax
jmp short :t8
:t6
cmp edx, uvector-kfunction-tag
jne short :t10
mov edi, [esi] ;; environment for kfunctions is always NIL
call [eax + (- (* function-code-buffer-offset 4) uvector-tag)]
jmp short :t8
:t10
cmp edx, uvector-clos-instance-tag
jne short :t7
mov edx, [eax + (uvector-offset cl::clos-instance-class-offset)] ;; edx = clos class
mov ebx, 'cl::the-class-standard-gf
mov ebx, [ebx + (uvector-offset cl::symbol-value-offset)]
mov ebx, [ebx - cons-tag]
cmp ebx, edx ;; class = the-class-standard-gf?
jne short :t7
mov eax, [eax + (uvector-offset cl::clos-instance-slots-offset)] ;; eax = clos class slots
mov eax, [eax + (uvector-offset (+ 2 cl::slot-location-generic-function-discriminating-function))]
jmp short :t11
:t7
push eax
callp _not-a-function-error
:t8
mov esp, [ebp - 16]
pop edi
pop ebx
pop edi
pop edi
mov esp, ebp
pop ebp
ret
})
;;;;
;;;; Common Lisp APPLY function.
;;;; Modified here to allow Standard-Generic-Functions as the
;;;; first argument.
;;;;
(defasm apply (func &rest args)
{
push ebp
mov ebp, esp
push edi
push ecx
push ebx
push 0 ;; one cell local storage at [ebp - 16]
cmp ecx, 2
jge short :t1
callp _wrong-number-of-args-error
:t1
mov eax, [ebp + ecx*4 + 4] ;; eax = function
mov edx, eax
and edx, 7
cmp edx, uvector-tag ;; see if func arg is a uvector
je short :t2
push eax
callp _not-a-function-error
:t2
mov edx, [eax - uvector-tag] ;; edx = uvector header
shl edx, 24
shr edx, 27
cmp edx, uvector-symbol-tag ;; see if it is a symbol
jne short :t4
;; get the function that is bound to the symbol
mov eax, [eax + (- (* 4 symbol-function-offset) uvector-tag)]
mov eax, [eax - 4]
mov edx, eax
and edx, 7
cmp edx, uvector-tag
je short :t3
push [ebp + ecx*4 + 4]
callp _not-a-function-error
:t3
mov edx, [eax - uvector-tag] ;; edx = uvector header
shl edx, 24
shr edx, 27
:t4 ;; we now know we have a function in eax, and dl is the type
;; push all the arguments except the last
mov [ebp - 16], esp
dec ecx
mov ebx, ecx
dec ecx
:t5
dec ebx
jle short :t6
push [ebp + ebx*4 + 8]
jmp short :t5
:t6
;; the last argument is a list of remaining arguments
mov edi, [ebp + ARGS_OFFSET]
:t7
mov ebx, edi
and ebx, 7
cmp ebx, cons-tag ;; is a cons cell?
jne short :t8 ;; if not, exit
push [edi - 4]
inc ecx
mov edi, [edi]
jmp short :t7
:t8
cmp edx, uvector-function-tag
jne short :t9
:t13
mov edi, [eax + (- (* 4 function-environment-offset) uvector-tag)]
callfunc eax
jmp short :t11
:t9
cmp edx, uvector-kfunction-tag
jne short :t12
mov edi, [esi] ;; environment for kfunctions is always NIL
call [eax + (- (* function-code-buffer-offset 4) uvector-tag)]
jmp short :t11
:t12
cmp edx, uvector-clos-instance-tag
jne short :t10
mov edx, [eax + (uvector-offset cl::clos-instance-class-offset)] ;; edx = clos class
mov ebx, 'cl::the-class-standard-gf
mov ebx, [ebx + (uvector-offset cl::symbol-value-offset)]
mov ebx, [ebx - cons-tag]
cmp ebx, edx ;; class = the-class-standard-gf?
jne short :t10
mov eax, [eax + (uvector-offset cl::clos-instance-slots-offset)] ;; eax = clos class slots
mov eax, [eax + (uvector-offset (+ 2 cl::slot-location-generic-function-discriminating-function))]
jmp short :t13
:t10
push eax
callp _not-a-function-error
:t11
mov esp, [ebp - 16]
pop edi ;; remove local storage
pop ebx
pop edi
pop edi
mov esp, ebp
pop ebp
ret
})
;;;;
;;;; Common Lisp FUNCTIONP function.
;;;; Redefined here to add support for generic functions.
;;;;
(defasm functionp (x)
{
push ebp
mov ebp, esp
cmp ecx, 1
jz short :next1
callp _wrong-number-of-args-error
:next1
mov edx, [ebp + ARGS_OFFSET] ;; edx = argument
mov eax, edx
and eax, 7
cmp eax, uvector-tag
jne short :nil-exit
mov eax, [edx - uvector-tag]
cmp al, (tag-byte uvector-kfunction-tag)
jbe short :t-exit
cmp al, (tag-byte uvector-clos-instance-tag)
jne short :nil-exit
mov eax, [edx + (uvector-offset cl::clos-instance-class-offset)] ;; eax = clos class
mov edx, 'cl::the-class-standard-gf
mov edx, [edx + (uvector-offset cl::symbol-value-offset)]
mov edx, [edx - cons-tag]
cmp eax, edx ;; class = the-class-standard-gf?
jne short :nil-exit
:t-exit
mov eax, [esi + t-offset]
jmp short :exit
:nil-exit
mov eax, [esi]
:exit
pop ebp
ret
})
(defasm cl::execution-address (func &rest args)
{
push ebp
mov ebp, esp
push edi
push ebx
cmp ecx, 1
je short :t1
callp _wrong-number-of-args-error
:t1
mov eax, [ebp + ARGS_OFFSET] ;; eax = argument
mov edx, eax
and edx, 7
cmp edx, uvector-tag ;; see if func arg is a uvector
je short :t2
push eax
callp _not-a-function-error
:t2
mov edx, [eax - uvector-tag] ;; edx = uvector header
shl edx, 24
shr edx, 27
cmp edx, uvector-symbol-tag ;; see if it is a symbol
jne short :t3
;; get the function that is bound to the symbol
mov eax, [eax + (uvector-offset symbol-function-offset)]
mov eax, [eax - 4]
mov edx, eax
and edx, 7
cmp edx, uvector-tag
je short :t9
push [ebp + ARGS_OFFSET]
callp _not-a-function-error
:t9
mov edx, [eax - uvector-tag] ;; edx = uvector header
shl edx, 24
shr edx, 27
:t3 ;; we should have a function in eax, and dl is the type
cmp edx, uvector-function-tag
jne short :t6
:t11
mov eax, [eax + (uvector-offset function-code-buffer-offset)]
lea eax, [eax + (uvector-offset compiled-code-execution-offset)] ;; eax = exec address
jmp short :got-addr
:t6
cmp edx, uvector-kfunction-tag
jne short :t10
mov eax, [eax + (uvector-offset function-code-buffer-offset)]
jmp short :got-addr
:t10
cmp edx, uvector-clos-instance-tag
jne short :t7
mov edx, [eax + (uvector-offset cl::clos-instance-class-offset)] ;; edx = clos class
mov ebx, 'cl::the-class-standard-gf
mov ebx, [ebx + (uvector-offset cl::symbol-value-offset)]
mov ebx, [ebx - cons-tag]
cmp ebx, edx ;; class = the-class-standard-gf?
jne short :t7
mov eax, [eax + (uvector-offset cl::clos-instance-slots-offset)] ;; eax = clos class slots
mov eax, [eax + (uvector-offset (+ 2 cl::slot-location-generic-function-discriminating-function))]
jmp short :t11
:t7
push eax
callp _not-a-function-error
:got-addr ;; eax = execution address
mov edx, 0
mov dl, [eax]
cmp dl, #xe9 ;; watch for jump table entry: if so, resolve to real address
jne short :t8
add eax, [eax + 1]
add eax, 5
:t8
test eax, #xf0000000
jne :bignum
shl eax, 3
jmp short :exit
:bignum
push eax
push 8
mov ecx, 1
callf cl::alloc-bignum ;; allocate 1 cell
add esp, 4
pop [eax + (uvector-offset cl::bignum-first-cell-offset)]
:exit
pop ebx
pop edi
mov ecx, 1
mov esp, ebp
pop ebp
ret
})
(in-package :cl)
;;;
;;; Bootstrap
;;;
;(progn ; Extends to end-of-file (to avoid printing intermediate results).
;;(format t "Beginning to bootstrap Closette...")
(forget-all-classes)
(forget-all-generic-functions)
;; How to create the class hierarchy in 10 easy steps:
;; 1. Figure out standard-class's slots.
(setq the-slots-of-standard-class
(mapcar #'(lambda (slotd)
(make-effective-slot-definition
:name (car slotd)
:initargs
(let ((a (getf (cdr slotd) ':initarg)))
(if a (list a) ()))
:initform (getf (cdr slotd) ':initform)
:initfunction
(let ((a (getf (cdr slotd) ':initform)))
(if a #'(lambda () (eval a)) nil))
:allocation ':instance))
(nth 3 the-defclass-standard-class)))
;; 2. Create the standard-class metaobject by hand.
(setq the-class-standard-class
(allocate-std-instance
'tba
(make-array (length the-slots-of-standard-class)
:initial-element secret-unbound-value)))
;; 3. Install standard-class's (circular) class-of link.
(setf (std-instance-class the-class-standard-class)
the-class-standard-class)
;; (It's now okay to use class-... accessor).
;; 4. Fill in standard-class's class-slots.
(setf (class-effective-slots the-class-standard-class) the-slots-of-standard-class)
;; (Skeleton built; it's now okay to call make-instance-standard-class.)
;; 5. Hand build the class t so that it has no direct superclasses.
(setf (find-class 't)
(let ((class (std-allocate-instance the-class-standard-class)))
(setf (class-name class) 't)
(setf (class-documentation class) ())
(setf (class-direct-subclasses class) ())
(setf (class-direct-superclasses class) ())
(setf (class-direct-methods class) ())
(setf (class-direct-slots class) ())
(setf (class-precedence-list class) (list class))
(setf (class-effective-slots class) ())
(setf (class-shared-slot-definitions class) ()) ; Shared Slots Bug
(setf (class-shared-slots class) ())
class))
;; (It's now okay to define subclasses of t.)
;; 6. Create the other superclass of standard-class (i.e., standard-object).
(defclass standard-object (t) ())
(defclass metaobject () ((name :initarg :name) (documentation :initform () :initarg :documentation)))
(defclass forward-referenced-class (metaobject) ((direct-subclasses :initform ())))
(defclass specializer (forward-referenced-class)
((direct-superclasses :initarg :direct-superclasses) class-precedence-list (direct-methods :initform ())))
(defclass class (specializer))
;; 7. Define the full-blown version of standard-class.
(setq the-class-standard-class
(defclass standard-class (class)
(direct-slots effective-slots (shared-slot-definitions :initform ()) (shared-slots :initform ())
(direct-default-initargs :initform () :initarg :direct-default-initargs) (effective-default-initargs :initform ()))))
;; 8. Replace all existing pointers to the skeleton with real one.
;; and Declare types (not for t)
(mapc #'(lambda (x) (setf (std-instance-class (find-class x)) the-class-standard-class)
(unless (eq t x)
(install-type-specifier x #'(lambda (s1 s2)
(and (cl::clos-instance-p s1)
(cl::subclassp (class-of s1) (find-class s2)))))))
'(t standard-object metaobject forward-referenced-class specializer class standard-class))
;; (Clear sailing from here on in).
;; 9. Define the other built-in classes.
(defclass symbol (t) ())
(defclass sequence (t) ())
(defclass array (t) ())
(defclass number (t) ())
(defclass character (t) ())
(defclass function (t) ())
; (defclass hash-table (t) ()) defined below
(defclass package (t) ())
(defclass pathname (t) ())
(defclass readtable (t) ())
(defclass stream (t) ())
(defclass list (sequence) ())
(defclass null (symbol list) ())
(defclass cons (list) ())
(defclass vector (array sequence) ())
(defclass bit-vector (vector) ())
(defclass string (vector) ())
(defclass complex (number) ())
(defclass integer (number) ())
(defclass float (number) ())
(defclass ratio (number) ())
;; 10. Define the other standard metaobject classes.
;;; redefine to add type support for TYPEP
(defmacro defclass (name direct-superclasses slot-definitions
&rest options)
(let ((s1 (gensym))(s2 (gensym)))
`(prog1
(ensure-class ',name
:direct-superclasses
,(canonicalize-direct-superclasses direct-superclasses)
:direct-slots
,(canonicalize-direct-slots slot-definitions)
,@(canonicalize-defclass-options options))
(declare-type-specifier ,name (,s1 ,s2)
(and (or (cl::clos-instance-p ,s1) (structurep ,s1))
(cl::subclassp (class-of ,s1) (find-class ,s2)))))))
(defclass eql-specializer (specializer) (object))
(defclass built-in-class (class))
(defclass structure-class (class) ())
(setq the-class-gf (eval the-defclass-generic-function))
(setq the-class-standard-gf (eval the-defclass-standard-generic-function))
(defclass method (metaobject))
(setq the-class-standard-method (eval the-defclass-standard-method))
;; Voila! The class hierarchy is in place.
;;(format t "Class hierarchy created.")
;; (It's now okay to define generic functions and methods.)
(defgeneric print-object (instance stream))
(defmethod print-object ((instance standard-object) stream)
(print-unreadable-object (instance stream :identity t)
(format stream "~:(~S~)"
(class-name (class-of instance))))
instance)
;;; Slot access
(defgeneric slot-value-using-class (class instance slot-name))
(defmethod slot-value-using-class ((class standard-class) instance slot-name)
(declare (ignore class))
(std-slot-value instance slot-name))
(defgeneric (setf slot-value-using-class) (new-value class instance slot-name))
(defmethod (setf slot-value-using-class)
(new-value (class standard-class) instance slot-name)
(declare (ignore class))
(setf (std-slot-value instance slot-name) new-value))
; (values)) ;end progn
;;; N.B. To avoid making a forward reference to a (setf xxx) generic function:
(defun setf-slot-value-using-class (new-value class object slot-name)
(setf (slot-value-using-class class object slot-name) new-value))
(defun forward-referenced-class-p (x) (eq (class-of x) #.(find-class 'forward-referenced-class)))
(defun eql-specializer-p (x) (eq (class-of x) #.(find-class 'eql-specializer)))
(mapc #'(lambda (x) (convert-function-to-method (car x) (cadr x)))
'((class-name ((class metaobject))) ((setf class-name) (new-value (class metaobject))) ; setf gf ansi fun amop
(class-direct-subclasses ((class forward-referenced-class))) ((setf class-direct-subclasses) (new-value (class forward-referenced-class)))
(class-direct-superclasses ((class specializer))) ((setf class-direct-superclasses) (new-value (class specializer)))
(class-direct-methods ((class specializer))) ((setf class-direct-methods) (new-value (class specializer)))
(class-direct-slots ((class standard-class))) ((setf class-direct-slots) (new-value (class standard-class)))
(class-shared-slot-definitions ((class standard-class))) ((setf class-shared-slot-definitions) (new-value (class standard-class)))
(class-shared-slots ((class standard-class))) ((setf class-shared-slots) (new-value (class standard-class)))
(add-method ((generic-function standard-generic-function) (method standard-method)))
(remove-method ((generic-function standard-generic-function) (method standard-method)))
(find-method ((generic-function standard-generic-function) method-qualifiers specializers &optional errorp))))
(defmethod class-direct-superclasses ((x forward-referenced-class))) ; amop
(defmethod class-direct-slots ((class forward-referenced-class))) ; amop
(defmethod (setf class-direct-slots) (new-value (class forward-referenced-class)) (declare (ignore new-value)))
(defmethod class-shared-slot-definitions ((class forward-referenced-class)))
(defmethod (setf class-shared-slot-definitions) (new-value (class forward-referenced-class)) (declare (ignore new-value)))
(defmethod class-shared-slots ((class forward-referenced-class)))
(defmethod (setf class-shared-slots) (new-value (class forward-referenced-class)) (declare (ignore new-value)))
(defmethod class-slots ((class forward-referenced-class)) (declare (ignore class)))
(defmethod class-slots ((class standard-class)) (append (class-effective-slots class) (class-shared-slot-definitions class)))
(defmethod class-direct-default-initargs ((class forward-referenced-class)))
(defmethod class-direct-default-initargs ((class standard-class)) (slot-value class 'direct-default-initargs))
(defmethod class-default-initargs ((class standard-class)) (slot-value class 'effective-default-initargs))
(defun (setf class-default-initargs) (new-value class)
(setf (slot-value class 'effective-default-initargs) new-value))
;(progn
(defgeneric slot-exists-p-using-class (class instance slot-name))
(defmethod slot-exists-p-using-class
((class standard-class) instance slot-name)
(declare (ignore class))
(std-slot-exists-p instance slot-name))
(defgeneric slot-boundp-using-class (class instance slot-name))
(defmethod slot-boundp-using-class
((class standard-class) instance slot-name)
(declare (ignore class))
(std-slot-boundp instance slot-name))
(defgeneric slot-makunbound-using-class (class instance slot-name))
(defmethod slot-makunbound-using-class
((class standard-class) instance slot-name)
(declare (ignore class))
(std-slot-makunbound instance slot-name))
;;; Instance creation and initialization
(defgeneric allocate-instance (class))
(defmethod allocate-instance ((class standard-class))
(let ((instance (std-allocate-instance class)))
(unless ; all subclasses of metaobject except strict subclasses of standard-class,
; standard-generic-function and standard-method. Standard-class only for now.
(and (subclassp class #.(find-class 'metaobject))
(or (eq class the-class-standard-class) (not (subclassp class the-class-standard-class))))
(setf (std-instance-signature instance)
(list (class-effective-slots class) (class-shared-slot-definitions class))))
instance))
(defgeneric make-instance (class &key))
(defmethod make-instance ((class standard-class) &rest initargs)
(let ((instance (allocate-instance class)))
(apply #'initialize-instance instance initargs)
instance))
(defmethod make-instance ((class symbol) &rest initargs)
(apply #'make-instance (find-class class) initargs))
(defgeneric initialize-instance (instance &key))
(defmethod initialize-instance ((instance standard-object) &rest initargs)
(apply #'shared-initialize instance t initargs))
(defgeneric reinitialize-instance (instance &key))
(defmethod reinitialize-instance
((instance standard-object) &rest initargs)
(apply #'shared-initialize instance () initargs))
(defgeneric shared-initialize (instance slot-names &key))
(defmethod shared-initialize ((instance standard-object)
slot-names &rest all-keys)
(dolist (slot (class-slots (class-of instance)))
(let ((slot-name (slot-definition-name slot)))
(multiple-value-bind (init-key init-value foundp)
(get-properties
all-keys (slot-definition-initargs slot))
(declare (ignore init-key))
(if foundp
(setf (slot-value instance slot-name) init-value)
(when (and (not (slot-boundp instance slot-name))
(not (null (slot-definition-initfunction slot)))
(or (eq slot-names t)
(member slot-name slot-names)))
(setf (slot-value instance slot-name)
(funcall (slot-definition-initfunction slot))))))))
instance)
(defmethod update-instance-for-redefined-class ((instance standard-object) added-slots discarded-slots property-list &rest initargs)
(declare (ignore discarded-slots property-list))
(apply #'shared-initialize instance added-slots initargs))
;;; change-class
(defgeneric change-class (instance new-class &key))
(defmethod change-class
((old-instance standard-object)
(new-class standard-class)
&rest initargs)
(let ((new-instance (allocate-instance new-class)))
(dolist (slot-name (mapcar #'slot-definition-name
(class-effective-slots new-class)))
(when (and (slot-exists-p old-instance slot-name)
(slot-boundp old-instance slot-name))
(setf (slot-value new-instance slot-name)
(slot-value old-instance slot-name))))
(rotatef (std-instance-slots new-instance)
(std-instance-slots old-instance))
(rotatef (std-instance-class new-instance)
(std-instance-class old-instance))
(rotatef (std-instance-signature new-instance)
(std-instance-signature old-instance))
(apply #'update-instance-for-different-class
new-instance old-instance initargs)
old-instance))
(defmethod change-class
((instance standard-object) (new-class symbol) &rest initargs)
(apply #'change-class instance (find-class new-class) initargs))
(defgeneric update-instance-for-different-class (old new &key))
(defmethod update-instance-for-different-class
((old standard-object) (new standard-object) &rest initargs)
(let ((added-slots
(remove-if #'(lambda (slot-name)
(slot-exists-p old slot-name))
(mapcar #'slot-definition-name
(class-effective-slots (class-of new))))))
(apply #'shared-initialize new added-slots initargs)))
;;; change-class the built-in classes
(mapc #'(lambda (x) (change-class (find-class x) 'built-in-class))
'(t symbol sequence array number character function package pathname readtable stream
list null cons vector bit-vector string complex integer float ratio))
;;;
;;; Methods having to do with class metaobjects.
;;;
(defmethod print-object ((class metaobject) stream)
(print-unreadable-object (class stream :identity t)
(format stream "~:(~S~) ~S"
(class-name (class-of class))
(class-name class)))
class)
(defmethod initialize-instance :after ((class specializer) &rest args)
(apply #'std-after-initialization-for-classes class args))
;;; Finalize inheritance
(defgeneric finalize-inheritance (class))
(defmethod finalize-inheritance ((class specializer))
(setf (class-precedence-list class)
(compute-class-precedence-list class))
(values))
(defmethod finalize-inheritance ((class standard-class))
(std-finalize-inheritance class)
(values))
;;; Class precedence lists
(defgeneric compute-class-precedence-list (class))
(defmethod compute-class-precedence-list ((class specializer))
(std-compute-class-precedence-list class))
;;; Slot inheritance
(defgeneric compute-slots (class))
(defmethod compute-slots ((class standard-class))
(std-compute-slots class))
(defgeneric compute-effective-slot-definition (class direct-slots))
(defmethod compute-effective-slot-definition
((class standard-class) direct-slots)
(std-compute-effective-slot-definition class direct-slots))
;;;
;;; Methods having to do with generic function metaobjects.
;;;
(defmethod initialize-instance :after ((gf standard-generic-function) &key)
(finalize-generic-function gf))
;;;
;;; Methods having to do with method metaobjects.
;;;
(defmethod print-object ((method standard-method) stream)
(print-unreadable-object (method stream :identity t)
(format stream "~:(~S~) ~S~{ ~S~} ~S"
(class-name (class-of method))
(generic-function-name (method-generic-function method))
(method-qualifiers method)
(mapcar #'(lambda (x) (if (eql-specializer-p x) `(eql ,(class-name x)) (class-name x))) (method-specializers method))))
method)
(defmethod initialize-instance :after ((method standard-method) &key)
(setf (method-function method) (compute-method-function method)))
;;;
;;; Methods having to do with generic function invocation.
;;;
(defgeneric compute-discriminating-function (gf))
(defmethod compute-discriminating-function ((gf standard-generic-function))
(std-compute-discriminating-function gf))
(defgeneric method-more-specific-p (gf method1 method2 required-classes))
(defmethod method-more-specific-p
((gf standard-generic-function) method1 method2 required-classes)
(std-method-more-specific-p gf method1 method2 required-classes))
(defgeneric compute-effective-method-function (gf methods))
(defmethod compute-effective-method-function
((gf standard-generic-function) methods)
(std-compute-effective-method-function gf methods))
(defgeneric compute-method-function (method))
(defmethod compute-method-function ((method standard-method))
(std-compute-method-function method))
;;; describe-object is a handy tool for enquiring minds:
(defgeneric describe-object (object stream))
(defmethod describe-object ((object standard-object) stream)
(format stream "CLOS OBJECT:~%~?~?~?"
"~4T~A:~20T~A~%" (list "printed representation" object)
"~4T~A:~20T~A~%" (list "class" (class-of object))
"~4T~A:~20T#x~X~%" (list "heap address" (%uvector-address object)))
(dolist (sn (mapcar #'slot-definition-name
(class-slots (class-of object))))
(format stream "~4T~A: ~:[not bound~;~S~]~%"
(string-downcase (symbol-name sn))
(slot-boundp object sn)
(and (slot-boundp object sn)
(slot-value object sn))))
(values))
(defmethod describe-object ((object t) stream)
(cl:describe object stream)
(values))
;;(format t "~%Closette is a Knights of the Lambda Calculus production.")
;(values)) ;end progn
;;; add default-initargs functionality
(defmethod compute-default-initargs ((class standard-class))
(remove-duplicates (mapappend #'class-direct-default-initargs (class-precedence-list class)) :from-end t :key #'car))
(defmethod finalize-inheritance :after ((class standard-class))
(setf (class-default-initargs class) (compute-default-initargs class)))
(defmethod make-instance :around ((class standard-class) &rest initargs)
(apply #'call-next-method class
(append initargs (mapappend #'(lambda (def-init)
(let ((key (car def-init)))
(unless (caddr (multiple-value-list (get-properties initargs (list key))))
(list key (funcall (caddr def-init))))))
(class-default-initargs class)))))
;;; add class redefinition functionality
;;; t for the amop. nil can be useful for development.
;;; By carefully violating the amop rules we can get a glance at finalized classes.
(defparameter *lazy-finalize*)
(defmethod initialize-instance :after ((class eql-specializer) &key) (finalize-inheritance class)) ; always finalized
(defmethod reinitialize-instance :after ((class class) &rest args) ; leave open; funcallable-standard-class?
(apply #'std-after-initialization-for-classes class args))
;;;
;;; setup parent class for all structures
;;;
(defmethod initialize-instance :after ((class structure-class) &key) (finalize-inheritance class)) ; always finalized
(defmethod reinitialize-instance :after ((class structure-class) &key) (finalize-inheritance class)) ; not actually needed
(defclass structure-object (t) () (:metaclass structure-class))
(defmethod initialize-instance :after ((class standard-class) &key) (unless *lazy-finalize* (finalize-inheritance class)))
(defmethod reinitialize-instance :after ((class standard-class) &key) (unless *lazy-finalize* (finalize-inheritance class)))
(defmethod ensure-class-using-class ((class class) name &rest all-keys
&key (metaclass the-class-standard-class) direct-superclasses &allow-other-keys)
(declare (ignore name))
(unless (eq (class-of class) (or (and (symbolp metaclass) (find-class metaclass)) metaclass))
(error "~a is not a ~a" class metaclass))
(let ((subs (if *lazy-finalize*
(remove-if-not #'class-finalized-p (cons class (collect-subclasses class)))
(cons class (collect-subclasses class)))))
(when *lazy-finalize*
(let ((forward (find-if #'forward-referenced-class-p direct-superclasses)))
(when (and forward (eq class (car subs)))
(error "Cannot redefine finalized ~a~%;;; with an undefined ~a" class forward))))
(remove-read-write-methods class)
(unless (lists-match (class-direct-superclasses class) direct-superclasses)
(remove-from-deleted-classes class direct-superclasses)
(mapc #'(lambda (x) (clear-method-table (classes-to-emf-table x)))
(remove-duplicates (mapcar #'method-generic-function (mapappend #'class-direct-methods subs)))))
(apply #'reinitialize-instance class all-keys)
(mapc #'finalize-inheritance (if *lazy-finalize* subs (cdr subs))))
class)
(defmethod ensure-class-using-class ((class null) name &rest all-keys &key (metaclass the-class-standard-class) &allow-other-keys)
(setf (find-class name) (apply #'make-instance metaclass :name name all-keys)))
;;; add forward-referenced-class functionality
(defun not-instantiable-p (class)
(let ((supers (class-direct-superclasses class)))
(or (find-if #'forward-referenced-class-p supers)
(dolist (class supers) (let ((class (not-instantiable-p class))) (when class (return class)))))))
;;; For forward-referenced classes to behave like "identity" elements in a null *lazy-finalize* mode "environment"
;;; we should consider the more general case by defining a generic function say, default-direct-superclass.
(defmethod compute-class-precedence-list ((class standard-class))
(let ((list (call-next-method)))
(if (forward-referenced-class-p (car (last list)))
(nconc (remove-if #'(lambda (x) (member x '#.(list (find-class 'standard-object) (find-class t)))) list)
(list #.(find-class 'standard-object) #.(find-class t)))
list)))
(defmethod finalize-inheritance ((class forward-referenced-class)) (error "Cannot finalize ~a." class))
(defmethod finalize-inheritance :before ((class standard-class)) ; we should actually only finalize classes with shared slots
(when *lazy-finalize* (mapc #'(lambda (x) (unless (class-finalized-p x) (finalize-inheritance x))) (class-direct-superclasses class))))
(defmethod allocate-instance :before ((class standard-class))
(if *lazy-finalize*
(unless (class-finalized-p class) (finalize-inheritance class))
(let ((forward (not-instantiable-p class)))
(when forward (cerror "Continue anyway." "Continuable attempt to instantiate ~a~%;;; with an undefined ~a superclass." class forward)))))
; redefine
(defun canonicalize-direct-superclasses (direct-superclasses) `',direct-superclasses)
(defmethod ensure-class-using-class ((class forward-referenced-class) name &rest all-keys
&key (metaclass the-class-standard-class) &allow-other-keys) (declare (ignore name))
(change-class class metaclass) (apply #'reinitialize-instance class all-keys)
(mapc #'(lambda (x) (when (class-finalized-p x) (finalize-inheritance x))) (collect-subclasses class))
class)
; redefine
(defun ensure-class (name &rest all-keys &key direct-superclasses &allow-other-keys)
(apply #'ensure-class-using-class (find-class name nil) name
:direct-superclasses (mapcar #'(lambda (x) (or (and (symbolp x) (find-class x nil))
(and (clos-instance-p x) x)
(ensure-class-using-class nil x :metaclass (find-class 'forward-referenced-class))))
direct-superclasses)
all-keys))
(defmacro with-slots (slot-entries instance-form &body forms)
(let ((sym (gensym))
(vars '())
(slots '()))
(unless (listp slot-entries)
(error "Invalid WITH-SLOTS slot entry list: ~S" slot-entries))
(dolist (varslot slot-entries)
(typecase varslot
(symbol
(push varslot vars)
(push varslot slots))
(list
(unless (= 2 (length varslot))
(error "Invalid WITH-SLOTS slot entry: ~S" varslot))
(push (first varslot) vars)
(push (second varslot) slots))
(t (error "Invalid WITH-SLOTS slot entry: ~S" varslot))))
`(LET ((,sym ,instance-form))
(SYMBOL-MACROLET
,(mapcar #'(lambda (v s) `(,v (slot-value ,sym ',s)))
(nreverse vars)
(nreverse slots))
,@forms))))
(defun intern-structure-class (name superclass doc)
(ensure-class name
:direct-superclasses (list (or (and superclass (find-class superclass)) #.(find-class 'structure-object)))
:metaclass 'structure-class
:documentation doc))
(defun struct-template (struct-name)
(get struct-name :struct-template))
(defun patch-clos (struct-name)
(setf (elt (struct-template struct-name) 1)
(intern-structure-class struct-name nil (documentation struct-name 'structure))))
;; make sure the following common lisp structures (which are defined before
;; this module is loaded) have CLOS definitions
(patch-clos 'hash-table)
(patch-clos 'random-state)
(patch-clos 'byte)
;; this is internal only, but we will patch it just in case...
(patch-clos 'method-table)
;;; EQL specializer support
;;; Returns a CLOS class representing a type that is specific
;;; for the object. Used in defmethod to implement EQL
;;; specialisers.
(defun intern-eql-specializer (object &optional (intern-form object))
(let* ((singleton (gethash object *clos-singleton-specializers*))
(real (and singleton
(car (member intern-form (class-precedence-list singleton)
:test #'(lambda (x y) (and (eql-specializer-p y) (equal x (class-name y)))))))))
(or real (let ((newsingle (make-instance #.(find-class 'eql-specializer)
:name intern-form :direct-superclasses (list (or singleton (class-of object))))))
(setf (slot-value newsingle 'object) object (gethash object *clos-singleton-specializers*) newsingle)))))
;; need to restore warning here
(setq *COMPILER-WARN-ON-UNDEFINED-FUNCTION* t) ;; restore warnings
;;;
;;; Common Lisp WITH-ACCESSORS macro.
;;;
(defmacro with-accessors (slot-entries instance-form &body forms)
(let ((sym (gensym))
(vars '())
(slots '()))
(unless (listp slot-entries)
(error "Invalid WITH-ACCESSORS slot entry list: ~S" slot-entries))
(dolist (varslot slot-entries)
(typecase varslot
(symbol
(push varslot vars)
(push varslot slots))
(list
(unless (= 2 (length varslot))
(error "Invalid WITH-ACCESSORS slot entry: ~S" varslot))
(push (first varslot) vars)
(push (second varslot) slots))
(t (error "Invalid WITH-ACCESSORS slot entry: ~S" varslot))))
`(LET ((,sym ,instance-form))
(SYMBOL-MACROLET
,(mapcar #'(lambda (v s) `(,v (,s ,sym)))
(nreverse vars)
(nreverse slots))
,@forms))))
;;;
;;; Handle STRUCTURE-derived classes
;;;
(defmethod print-object ((instance structure-object) stream)
(let ((*standard-output* stream))
(cl::write-builtin-object instance)))
;;;
;;; Handle all other Lisp data types
;;;
(defmethod print-object ((instance t) stream)
(let ((*standard-output* stream))
(cl::write-builtin-object instance)))
(defun has-print-object-method (obj)
(let ((gf (find-generic-function 'print-object)))
(> (length (cl::compute-applicable-methods-using-classes gf (list (class-of obj)))) 1)))
;;;
;;; Hook into WRITE so that PRINT-OBJECT may be overridden for builtin objects.
;;;
(defun write-lisp-object (object)
(print-object object *standard-output*))
|
58341
|
;;;;
;;;; File: clos.lisp
;;;; Contents: Corman Lisp CLOS implementation based on Closette
;;;; History: RGC 12/16/98 Added <NAME>'s WITH-SLOTS implementation.
;;;; RGC 9/8/99 Added STANDARD-CLASS-P.
;;;; Decreased generic function call overhead by 40%
;;;; by building, compiling and caching the generic function
;;;; on the fly.
;;;; RGC 10/14/99 DEFCLASS adds a type descriminator function to
;;;; support TYPEP.
;;;; RGC 12/06/99 Added RATIO builtin class.
;;;; RGC 2/15/01 Modified structures to be integrated better with CLOS.
;;;; i.e. CLASS-OF returns a class unique to that structure type.
;;;; RGC 2/24/01 Added code to patch common lisp structures which are created
;;;; prior to CLOS loading to support method dispatching.
;;;; RGC 7/29/01 Integrated EQL specializer code, optimized per generic function.
;;;; RGC 10/21/01 Integrated generic functions so they are now first-class
;;;; functions, satisfying FUNCTIONP, and callable by FUNCALL and APPLY.
;;;;
;;;; RGC 9/19/03 Incorporated Frank Adrian's modification to DEFGENERIC to support :documentation option.
;;;; RGC 8/17/06 Modified method generation to handle &AUX in argument lists
;;;; LC 9/6/17 Lower EQL specializer overhead and name EQL specializers to their "intern form" for display purposes.
;;;; LC 2/19/18 Class redefinition with propagation to subclasses and instances, :documentation and :default-initargs
;;;; DEFCLASS options, Forward-referenced-class, Built-in-class and other AMOP Metaobjects and guidelines.
;;;; LC 3/3/18 Shared slot fixes.
;;;;
;;;; Note from <NAME>, 7/29/2001:
;;;; This file has been hacked and modified for over 5 years by
;;;; me and others. It no longer bears much resemblance to the original,
;;;; but I will leave the following messages from Xerox in anyway.
;;;;
;;;; Optimizations for use with Corman Lisp 1.0 (May 15, 1998)
;;;; Minor modifications for use with PowerLisp 2.0 (May 15, 1996)
;;;;
;;;; Closette Version 1.0 (February 10, 1991)
;;;; Copyright (c) 1990, 1991 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.
;;;;
;;;; Closette is an implementation of a subset of CLOS with a metaobject
;;;; protocol as described in "The Art of The Metaobject Protocol",
;;;; MIT Press, 1991.
;;;;
(provide :clos)
(in-package :common-lisp)
;; need to override warning here -RGC
(setq *COMPILER-WARN-ON-UNDEFINED-FUNCTION* nil)
(defvar exports
'(defclass defgeneric defmethod
find-class class-of
call-next-method next-method-p
slot-value slot-boundp slot-exists-p slot-makunbound
make-instance change-class
initialize-instance reinitialize-instance shared-initialize
update-instance-for-different-class
print-object
standard-object metaobject forward-referenced-class specializer
standard-class standard-generic-function standard-method eql-specializer
class-name
class-direct-superclasses class-direct-slots
class-precedence-list class-slots class-direct-subclasses
class-direct-methods class-direct-default-initargs class-default-initargs
generic-function-name generic-function-lambda-list
generic-function-methods generic-function-discriminating-function
generic-function-method-class
method-lambda-list method-qualifiers method-specializers method-body
method-environment method-generic-function method-function
slot-definition-name slot-definition-initfunction
slot-definition-initform slot-definition-initargs
slot-definition-readers slot-definition-writers
slot-definition-allocation
;;
;; Class-related metaobject protocol
;;
compute-class-precedence-list compute-slots
compute-effective-slot-definition
finalize-inheritance allocate-instance
slot-value-using-class slot-boundp-using-class
slot-exists-p-using-class slot-makunbound-using-class
;;
;; Generic function related metaobject protocol
;;
compute-discriminating-function
compute-applicable-methods-using-classes method-more-specific-p
compute-effective-method-function compute-method-function
apply-methods apply-method
describe-object
find-generic-function ; Necessary artifact of this implementation
))
(export exports)
;;; This hash-table supports CLOS EQL specializers.
(defconstant *clos-singleton-specializers* (make-hash-table :synchronized t))
;; fixed position of required-args in generic-function
(defconstant slot-location-generic-function-name 0)
(defconstant slot-location-generic-function-documentation 1)
(defconstant slot-location-generic-function-lambda-list 2)
(defconstant slot-location-generic-function-required-args 3)
(defconstant slot-location-generic-function-methods 4)
(defconstant slot-location-generic-function-method-class 5)
(defconstant slot-location-generic-function-discriminating-function 6)
(defconstant slot-location-generic-function-classes-to-emf-table 7)
(defconstant slot-location-generic-function-method-combination 8)
(defconstant slot-location-generic-function-method-combination-order 9)
;;;
;;; Utilities
;;;
;;; push-on-end is like push except it uses the other end:
(defmacro push-on-end (value location)
`(setf ,location (nconc ,location (list ,value))))
;;; (setf getf*) is like (setf getf) except that it always changes the list,
;;; which must be non-nil.
(defun (setf getf*) (new-value plist key)
(block body
(do ((x plist (cddr x)))
((null x))
(when (eq (car x) key)
(setf (car (cdr x)) new-value)
(return-from body new-value)))
(push-on-end key plist)
(push-on-end new-value plist)
new-value))
;;; mapappend is like mapcar except that the results are appended together:
(defun mapappend (fun &rest args)
(if (some #'null args)
()
(append (apply fun (mapcar #'car args))
(apply #'mapappend fun (mapcar #'cdr args)))))
;;; mapplist is mapcar for property lists:
(defun mapplist (fun x)
(if (null x)
()
(cons (funcall fun (car x) (cadr x))
(mapplist fun (cddr x)))))
;;; the method table is only used internally--optimize to the max
(proclaim '(optimize (speed 3)(safety 0)))
(defstruct method-table
(method-list nil)
(cached-method nil)
(cached-method-types nil)
(sync (cl::allocate-critical-section))
(eql-specializers nil))
(proclaim '(optimize (speed 0)(safety 3)))
(defun clear-method-table (table)
(with-synchronization (method-table-sync table)
(setf (method-table-method-list table) nil)
(setf (method-table-cached-method table) nil)
(setf (method-table-cached-method-types table) nil))
table)
(defun add-method-table-method (table types method)
(with-synchronization (method-table-sync table)
(setf (method-table-method-list table)
(cons types (cons method (method-table-method-list table))))
(setf (method-table-cached-method table) method)
(setf (method-table-cached-method-types table) types))
table)
(proclaim '(optimize (speed 3)(safety 0)))
(defun lists-match (list1 list2)
(do ((x list1 (cdr x)) (y list2 (cdr y))) ((null x) t)
(unless (eq (car x) (car y)) (return nil))))
(defun find-method-table-method (table eqls-classes)
(with-synchronization (method-table-sync table)
(do ((p (method-table-method-list table) (cddr p))) ((null p) (return nil))
(when (lists-match (car p) eqls-classes) (return (cadr p))))))
(proclaim '(optimize (speed 0)(safety 3)))
;;;
;;; Standard instances
;;;
(defun std-instance-class (x)
(if (clos-instance-p x)
(clos-instance-class x)
(error "Not a CLOS instance: ~S" x)))
(defun (setf std-instance-class) (val x)
(if (clos-instance-p x)
(setf (uref x clos-instance-class-offset) val)
(error "Not a CLOS instance: ~S" x)))
(defun std-instance-slots (x)
(if (clos-instance-p x)
(clos-instance-slots x)
(error "Not a CLOS instance: ~S" x)))
(defun (setf std-instance-slots) (val x)
(if (clos-instance-p x)
(setf (uref x clos-instance-slots-offset) val)
(error "Not a CLOS instance: ~S" x)))
;;; Fortunately there was an empty cell to store class signatures
(defun std-instance-signature (x)
(if (clos-instance-p x) (uref x 3) (error "Not a CLOS instance: ~S" x)))
(defun (setf std-instance-signature) (val x)
(if (clos-instance-p x) (setf (uref x 3) val) (error "Not a CLOS instance: ~S" x)))
(defun allocate-std-instance (class slots)
(let ((x (alloc-clos-instance)))
(setf (uref x clos-instance-class-offset) class)
(setf (uref x clos-instance-slots-offset) slots)
x))
(defun check-update (object)
(when (clos-instance-p object)
(let ((class (class-of object)) (signature (std-instance-signature object)))
(unless (or (eq 0 signature) (eq (car signature) (class-effective-slots class))) (update-instance object class signature)))))
;;; Standard instance allocation
(defparameter secret-unbound-value (list "slot unbound"))
(defun instance-slot-p (slot)
(eq (slot-definition-allocation slot) ':instance))
(defun std-allocate-instance (class)
(allocate-std-instance
class
(allocate-slot-storage
(length (class-effective-slots class)) ; class-effective-slots are the instance-slots-p slots
secret-unbound-value)))
;;; Simple vectors are used for slot storage.
(defun allocate-slot-storage (size initial-value)
(make-array size :initial-element initial-value))
;;; Standard instance slot access
;;; N.B. The location of the effective-slots slots in the class metaobject for
;;; standard-class must be determined without making any further slot
;;; references.
(defvar the-slots-of-standard-class) ;standard-class's class-slots
(defvar the-class-standard-class) ;standard-class's class metaobject
;;;
;;; This now returns null, rather than signal an error, if the slot is not found.
;;; This is to enable further searches for class slots by the functions which
;;; use this. -RGC 8/28/01
;;;
(defun slot-location (class slot-name)
(if (and (eq slot-name 'effective-slots)
(eq class the-class-standard-class))
;; (position 'effective-slots the-slots-of-standard-class :key #'slot-definition-name)
7 ;; for optimization, hard-code this
(let* ((slots (class-effective-slots class)))
(do* ((s slots (cdr s))
(x (car s)(car s))
(pos 0))
((null s))
(when (eq (slot-definition-name x) slot-name)
(return pos))
(if (eq (slot-definition-allocation x) ':instance)
(incf pos))))))
(defun shared-slot-location (class slot-name)
(let* ((slots (class-shared-slot-definitions class)))
(do* ((s slots (cdr s))
(x (car s)(car s))
(pos 0 (+ pos 1)))
((null s))
(when (eq (slot-definition-name x) slot-name)
(return pos)))))
;; optimize these by direct calls to inlined uref
(declaim (inline slot-contents (setf slot-contents)))
(defun slot-contents (slots location) (uref slots (+ location 2)) #|(svref slots location)|#)
(defun (setf slot-contents) (new-value slots location)
(setf (uref slots (+ location 2)) new-value)#|(setf (svref slots location) new-value)|#)
(defun std-slot-value (instance slot-name)
(let* ((class (class-of instance))
(location (slot-location class slot-name))
val)
(if location
(setf val (slot-contents (std-instance-slots instance) location))
(progn
(setf location (shared-slot-location class slot-name))
(if location
(setf val (car (slot-contents (class-shared-slots class) location)))
(error "The slot ~S is missing from the class ~S." slot-name class))))
(if (eq secret-unbound-value val)
(error "The slot ~S is unbound in the object ~S." slot-name instance))
val))
;;; Fast method to determine if a lisp object is a standard object.
;;; By our definition, any object which is not a CLOS instance (lisp
;;; primitive types, for example) are of type standard-class.
;;; CLOS instances are of type standard-class if the classes of their
;;; classes are standard-class.
;;; The number of arguments is not checked.
;;; We assume that the class of any object is a clos instance
;;; (for optimization purposes).
;;;
(ccl:defasm standard-class-p (object)
{
push ebp
mov ebp, esp
mov eax, [ebp + ARGS_OFFSET]
mov edx, eax
and edx, 7
cmp edx, uvector-tag
jne short :t-exit
mov edx, [eax - uvector-tag]
shr edx, 3
and edx, #x1f
cmp edx, cl::uvector-clos-instance-tag
jne short :t-exit
mov eax, [eax + (uvector-offset cl::clos-instance-class-offset)]
mov eax, [eax + (uvector-offset cl::clos-instance-class-offset)]
mov edx, 'cl::the-class-standard-class
mov edx, [edx + (uvector-offset cl::symbol-value-offset)]
mov edx, [edx - cons-tag]
cmp edx, eax
jne short :nil-exit
:t-exit
mov eax, [esi + t-offset]
jmp short :exit
:nil-exit
mov eax, [esi]
:exit
pop ebp
ret
})
;;; Fast method to determine if a lisp object is a standard generic function.
(ccl:defasm standard-generic-function-p (object)
{
push ebp
mov ebp, esp
mov eax, [ebp + ARGS_OFFSET]
mov edx, eax
and edx, 7
cmp edx, uvector-tag
jne short :nil-exit
mov edx, [eax - uvector-tag]
shr edx, 3
and edx, #x1f
cmp edx, cl::uvector-clos-instance-tag
jne short :nil-exit
mov eax, [eax + (uvector-offset cl::clos-instance-class-offset)]
mov edx, 'cl::the-class-standard-gf
mov edx, [edx + (uvector-offset cl::symbol-value-offset)]
mov edx, [edx - cons-tag]
cmp edx, eax
jne short :nil-exit
:t-exit
mov eax, [esi + t-offset]
jmp short :exit
:nil-exit
mov eax, [esi]
:exit
pop ebp
ret
})
;;; now patch (SETF SYMBOL-FUNCTION) to store the generic function
;;; in the symbol's function slot. We call the kernel function
;;; first to ensure that the jump table gets setup with the
;;; address of the discrimination function closure.
;;;
(defparameter +save-set-symbol-function+ (fdefinition '(setf symbol-function)))
(defun (setf symbol-function) (value symbol)
(if (standard-generic-function-p value)
(let ((discrimination-function
(uref
(uref value cl::clos-instance-slots-offset)
(+ 2 cl::slot-location-generic-function-discriminating-function))))
(funcall +save-set-symbol-function+ discrimination-function symbol)
;; now replace the function slot of the symbol
(setf (car (uref symbol cl::symbol-function-offset)) value))
(funcall +save-set-symbol-function+ value symbol)))
(defun slot-value (object slot-name) (check-update object)
(if (standard-class-p object)
(std-slot-value object slot-name)
(slot-value-using-class (class-of object) object slot-name)))
;; For fixed known slot positions (optimization) for std-slots
;;
(defun slot-value-with-index (object slot-name index)
(if (standard-class-p object)
(let* ((slots (std-instance-slots object))
(val (svref slots index)))
(if (eq secret-unbound-value val)
(error "The slot ~S is unbound in the object ~S." slot-name object)
val))
(slot-value-using-class (class-of object) object slot-name)))
(defun (setf slot-value-with-index) (new-value object slot-name index)
(if (standard-class-p object)
(let* ((slots (std-instance-slots object)))
(setf (svref slots index) new-value))
(setf-slot-value-using-class
new-value (class-of object) object slot-name)))
(defun (setf std-slot-value) (new-value instance slot-name)
(let* ((class (class-of instance))
(location (slot-location class slot-name)))
(if location
(setf (slot-contents (std-instance-slots instance) location) new-value)
(progn
(setf location (shared-slot-location class slot-name))
(if location
(setf (car (slot-contents (class-shared-slots class) location)) new-value)
(error "The slot ~S is missing from the class ~S." slot-name class))))))
(defun (setf slot-value) (new-value object slot-name) (check-update object)
(if (standard-class-p object)
(setf (std-slot-value object slot-name) new-value)
(setf-slot-value-using-class
new-value (class-of object) object slot-name)))
(defun std-slot-boundp (instance slot-name)
(let* ((class (class-of instance))
(location (slot-location class slot-name)))
(if location
(not (eq secret-unbound-value (slot-contents (std-instance-slots instance) location)))
(progn
(setf location (shared-slot-location class slot-name))
(if location
(not (eq secret-unbound-value (car (slot-contents (class-shared-slots class) location))))
(error "The slot ~S is missing from the class ~S." slot-name class))))))
(defun slot-boundp (object slot-name) (check-update object)
(if (standard-class-p object)
(std-slot-boundp object slot-name)
(slot-boundp-using-class (class-of object) object slot-name)))
(defun std-slot-makunbound (instance slot-name)
(let* ((class (class-of instance))
(location (slot-location class slot-name)))
(if location
(setf (slot-contents (std-instance-slots instance) location) secret-unbound-value)
(progn
(setf location (shared-slot-location class slot-name))
(if location
(setf (car (slot-contents (class-shared-slots class) location)) secret-unbound-value)
(error "The slot ~S is missing from the class ~S." slot-name class)))))
instance)
(defun slot-makunbound (object slot-name) (check-update object)
(if (standard-class-p object)
(std-slot-makunbound object slot-name)
(slot-makunbound-using-class (class-of object) object slot-name)))
(defun std-slot-exists-p (instance slot-name)
(not (null (find slot-name (class-slots (class-of instance))
:key #'slot-definition-name))))
(defun slot-exists-p (object slot-name)
(if (standard-class-p object)
(std-slot-exists-p object slot-name)
(slot-exists-p-using-class (class-of object) object slot-name)))
;;; class-of
(defun class-of (x)
(if (clos-instance-p x)
(std-instance-class x)
(built-in-class-of x)))
;;; N.B. This version of built-in-class-of is straightforward but very slow.
;;; This is only for booting, a faster method is used later -RGC
;;;
(defun built-in-class-of (x)
(typecase x
(null (find-class 'null))
((and symbol (not null)) (find-class 'symbol))
((complex *) (find-class 'complex))
(integer (find-class 'integer))
((float * *) (find-class 'float))
(cons (find-class 'cons))
(character (find-class 'character))
(hash-table (find-class 'hash-table))
(package (find-class 'package))
(pathname (find-class 'pathname))
(readtable (find-class 'readtable))
(stream (find-class 'stream))
(number (find-class 'number))
((string *) (find-class 'string))
((bit-vector *) (find-class 'bit-vector))
((vector * *) (find-class 'vector))
((array * *) (find-class 'array))
(sequence (find-class 'sequence))
(function (find-class 'function))
(t (find-class 't))))
;;; subclassp and sub-specializer-p
(defun subclassp (c1 c2)
(not (null (find c2 (class-precedence-list c1)))))
(defun sub-specializer-p (c1 c2 c-arg)
(let ((cpl (class-precedence-list c-arg)))
(not (null (find c2 (cdr (member c1 cpl)))))))
;;;
;;; Class metaobjects and standard-class
;;;
(defparameter the-defclass-standard-class ;standard-class's defclass form
'(defclass standard-class (class)
((name :initarg :name) ; :accessor class-name
(documentation :initform () :initarg :documentation) ; :accessor class-documentation
(direct-subclasses :initform ()) ; :accessor class-direct-subclasses
(direct-superclasses ; :accessor class-direct-superclasses
:initarg :direct-superclasses)
(class-precedence-list) ; :accessor class-precedence-list
(direct-methods :initform ()) ; :accessor class-direct-methods
(direct-slots) ; :accessor class-direct-slots
(effective-slots) ; :accessor class-effective-slots
(shared-slot-definitions :initform ()) ; :accessor class-shared-slot-definitions
(shared-slots :initform ()) ; :accessor class-shared-slots
(direct-default-initargs :initform () :initarg :direct-default-initargs) ; :accessor class-direct-default-initargs
(effective-default-initargs :initform ())))) ; :accessor class-default-initargs
;;; Defining the metaobject slot accessor function as regular functions
;;; greatly simplifies the implementation without removing functionality.
(defun class-name (class) (std-slot-value class 'name))
(defun (setf class-name) (new-value class) (setf (slot-value class 'name) new-value))
(defun class-documentation (class) (slot-value class 'documentation))
(defun (setf class-documentation) (new-value class)
(setf (slot-value class 'documentation) new-value))
(defun class-direct-superclasses (class) (slot-value class 'direct-superclasses))
(defun (setf class-direct-superclasses) (new-value class)
(setf (slot-value class 'direct-superclasses) new-value))
(defun class-direct-slots (class) (slot-value class 'direct-slots))
(defun (setf class-direct-slots) (new-value class)
(setf (slot-value class 'direct-slots) new-value))
(defun class-precedence-list (class) (slot-value class 'class-precedence-list))
(defun (setf class-precedence-list) (new-value class)
(setf (slot-value class 'class-precedence-list) new-value))
; class-slots generic defined below
(defun class-effective-slots (class) (slot-value class 'effective-slots))
(defun (setf class-effective-slots) (new-value class)
(setf (slot-value class 'effective-slots) new-value))
(defun class-direct-subclasses (class) (slot-value class 'direct-subclasses))
(defun (setf class-direct-subclasses) (new-value class)
(setf (slot-value class 'direct-subclasses) new-value))
(defun class-direct-methods (class) (slot-value class 'direct-methods))
(defun (setf class-direct-methods) (new-value class)
(setf (slot-value class 'direct-methods) new-value))
(defun class-shared-slots (class) (slot-value class 'shared-slots))
(defun (setf class-shared-slots) (new-value class)
(setf (slot-value class 'shared-slots) new-value))
(defun class-shared-slot-definitions (class) (slot-value class 'shared-slot-definitions))
(defun (setf class-shared-slot-definitions) (new-value class)
(setf (slot-value class 'shared-slot-definitions) new-value))
;;; defclass
(defmacro defclass (name direct-superclasses slot-definitions
&rest options)
`(ensure-class ',name
:direct-superclasses
,(canonicalize-direct-superclasses direct-superclasses)
:direct-slots
,(canonicalize-direct-slots slot-definitions)
,@(canonicalize-defclass-options options)))
(defun canonicalize-direct-slots (slot-definitions)
`(list ,@(mapcar #'canonicalize-direct-slot slot-definitions)))
(defun canonicalize-direct-slot (spec)
(if (symbolp spec) `(list :name ',spec)
(let ((name (car spec))
(initfunction nil)
(initform nil)
(initargs ())
(readers ())
(writers ())
(other-options ()))
(do ((olist (cdr spec) (cddr olist)))
((null olist))
(case (car olist)
(:initform
(setq initfunction
`(function (lambda () ,(cadr olist))))
(setq initform `',(cadr olist)))
(:initarg (push-on-end (cadr olist) initargs))
(:reader (push-on-end (cadr olist) readers))
(:writer (push-on-end (cadr olist) writers))
(:accessor
(push-on-end (cadr olist) readers)
(push-on-end `(setf ,(cadr olist)) writers))
(otherwise
(push-on-end `',(car olist) other-options)
(push-on-end `',(cadr olist) other-options))))
`(list
:name ',name
,@(when initfunction
`(:initform ,initform :initfunction ,initfunction))
,@(when initargs `(:initargs ',initargs))
,@(when readers `(:readers ',readers))
,@(when writers `(:writers ',writers))
,@other-options))))
(defun canonicalize-direct-superclasses (direct-superclasses)
`(list ,@(mapcar #'canonicalize-direct-superclass direct-superclasses)))
(defun canonicalize-direct-superclass (class-name)
`(find-class ',class-name))
(defun canonicalize-defclass-options (options)
(mapappend #'canonicalize-defclass-option options))
(defun canonicalize-defclass-option (option)
(case (car option)
(:metaclass
(list ':metaclass
`(find-class ',(cadr option))))
(:documentation (list ':documentation `',(cadr option)))
(:default-initargs
(list
':direct-default-initargs
`(list ,@(mapplist
#'(lambda (key value)
`(list ',key ',value #'(lambda () ,value)))
(cdr option)))))
(t (list `',(car option) `',(cdr option)))))
;;; find-class
(let ((class-table (make-hash-table :test #'eq :synchronized t)))
(defun find-class (symbol &optional (errorp t)(environment nil))
(declare (ignore environment))
(let ((class (gethash symbol class-table nil)))
(if (and (null class) errorp)
(error "No class named ~S." symbol)
class)))
(defun (setf find-class) (new-value symbol)
(setf (gethash symbol class-table) new-value))
(defun forget-all-classes ()
(clrhash class-table)
(values))
) ;end let class-table
;;; Ensure class
(defun ensure-class (name &rest all-keys
&key (metaclass the-class-standard-class)
&allow-other-keys)
(let ((class (apply (if (eq metaclass the-class-standard-class)
#'make-instance-standard-class
#'make-instance)
metaclass :name name all-keys)))
(setf (find-class name) class)
class))
;;; make-instance-standard-class creates and initializes an instance of
;;; standard-class without falling into method lookup. However, it cannot be
;;; called until standard-class itself exists.
(defun make-instance-standard-class (metaclass
&key name direct-superclasses direct-slots &allow-other-keys)
(declare (ignore metaclass))
(let ((class (std-allocate-instance the-class-standard-class)))
(setf (class-name class) name)
(setf (class-documentation class) ())
(setf (class-direct-subclasses class) ())
(setf (class-direct-methods class) ())
(setf (slot-value class 'direct-default-initargs) ()) ; default initargs accessor methods defined later
(setf (slot-value class 'effective-default-initargs) ())
(std-after-initialization-for-classes class
:direct-slots direct-slots
:direct-superclasses direct-superclasses)
(std-finalize-inheritance class)
class))
(defun std-after-initialization-for-classes (class
&key direct-superclasses direct-slots (documentation nil supp) &allow-other-keys)
;; update class hierarchy
(let ((supers
(or direct-superclasses
(list (find-class 'standard-object)))))
(setf (class-direct-superclasses class) supers)
(dolist (superclass supers)
(pushnew class (class-direct-subclasses superclass)))) ; pushnew to add
(let ((slots
(mapcar #'(lambda (slot-properties)
(apply #'make-direct-slot-definition
slot-properties))
direct-slots)))
(setf (class-direct-slots class) slots)
(dolist (direct-slot slots)
(dolist (reader (slot-definition-readers direct-slot))
(add-reader-method
class reader (slot-definition-name direct-slot)))
(dolist (writer (slot-definition-writers direct-slot))
(add-writer-method
class writer (slot-definition-name direct-slot)))))
(when (and supp (or (stringp documentation) (not documentation))) (setf (documentation (class-name class) 'type) documentation))
(values))
;;; Slot definition metaobjects
;;; N.B. Quietly retain all unknown slot options (rather than signaling an
;;; error), so that it's easy to add new ones.
;;; This is used for shared slots as well. -RGC
(defun make-direct-slot-definition
(&rest properties
&key name (initargs ()) (initform nil) (initfunction nil)
(readers ()) (writers ()) (allocation :instance)
&allow-other-keys)
(let ((slot (copy-list properties))) ; Don't want to side effect &rest list
(setf (getf* slot ':name) name)
(setf (getf* slot ':initargs) initargs)
(setf (getf* slot ':initform) initform)
(setf (getf* slot ':initfunction) initfunction)
(setf (getf* slot ':readers) readers)
(setf (getf* slot ':writers) writers)
(setf (getf* slot ':allocation) allocation)
(when (eq allocation :class) (setf (getf* slot ':shared-slot) (list secret-unbound-value)))
slot))
(defun make-effective-slot-definition
(&rest properties
&key name (initargs ()) (initform nil) (initfunction nil)
(allocation :instance)
&allow-other-keys)
(let ((slot (copy-list properties))) ; Don't want to side effect &rest list
(setf (getf* slot ':name) name)
(setf (getf* slot ':initargs) initargs)
(setf (getf* slot ':initform) initform)
(setf (getf* slot ':initfunction) initfunction)
(setf (getf* slot ':allocation) allocation)
slot))
(defun slot-definition-name (slot) (getf slot ':name))
(defun (setf slot-definition-name) (new-value slot)
(setf (getf* slot ':name) new-value))
(defun slot-definition-initfunction (slot) (getf slot ':initfunction))
(defun (setf slot-definition-initfunction) (new-value slot)
(setf (getf* slot ':initfunction) new-value))
(defun slot-definition-initform (slot) (getf slot ':initform))
(defun (setf slot-definition-initform) (new-value slot)
(setf (getf* slot ':initform) new-value))
(defun slot-definition-initargs (slot) (getf slot ':initargs))
(defun (setf slot-definition-initargs) (new-value slot)
(setf (getf* slot ':initargs) new-value))
(defun slot-definition-readers (slot) (getf slot ':readers))
(defun (setf slot-definition-readers) (new-value slot)
(setf (getf* slot ':readers) new-value))
(defun slot-definition-writers (slot) (getf slot ':writers))
(defun (setf slot-definition-writers) (new-value slot)
(setf (getf* slot ':writers) new-value))
(defun slot-definition-allocation (slot)
(getf slot ':allocation))
(defun (setf slot-definition-allocation) (new-value slot)
(setf (getf* slot ':allocation) new-value))
(defun slot-definition-documentation (slot) (getf slot ':documentation))
(defun (setf slot-definition-documentation) (new-value slot)
(setf (getf* slot ':documentation) new-value))
(defun slot-definition-shared-slot (slot) (getf slot ':shared-slot))
;;; finalize-inheritance
(defun finalize-inheritance (class) (std-finalize-inheritance class))
; Delete either the slot class-shared-slot-definitions or class-shared-slots as shared slots are in both
; but leave for compatibility and speed? for now.
(defun std-finalize-inheritance (class)
(setf (class-precedence-list class) (compute-class-precedence-list class))
(let* ((class-slots (compute-slots class)) (shared-defs (remove-if #'instance-slot-p class-slots))
(shared-slots (when shared-defs (allocate-slot-storage (length shared-defs) ()))))
(setf (class-effective-slots class) (remove-if-not #'instance-slot-p class-slots)
(class-shared-slot-definitions class) shared-defs
(class-shared-slots class) shared-slots)
(dotimes (i (length shared-defs)) (setf (slot-contents shared-slots i) (slot-definition-shared-slot (nth i shared-defs)))))
(values))
(defun class-finalized-p (class) (typecase class (standard-class (and (slot-boundp class 'effective-slots) class)) (specializer class))) ; nil for forward referenced classes
(defun update-instance (instance class signature)
(let* ((local (mapcar #'slot-definition-name (car signature))) (shared (mapcar #'slot-definition-name (cadr signature)))
(p-slot-value (mapappend #'list (append local shared)
(append (coerce (std-instance-slots instance) 'list)
(mapcar #'(lambda (x) (car (slot-definition-shared-slot x))) (cadr signature)))))
(class-effective-slots (class-effective-slots class)) (class-shared-slot-definitions (class-shared-slot-definitions class))
(class-local (mapcar #'slot-definition-name class-effective-slots))
(class-shared (mapcar #'slot-definition-name class-shared-slot-definitions)))
(setf (std-instance-slots instance) (allocate-slot-storage (length class-local) secret-unbound-value))
(setf (std-instance-signature instance)
(list class-effective-slots class-shared-slot-definitions)) ; we'll next use setf on slot-value
(dolist (slot class-local)
(multiple-value-bind (ignore val foundp) (get-properties p-slot-value (list slot)) (declare (ignore ignore))
(and foundp (setf (slot-value instance slot) val))))
(let ((discarded (set-difference local class-local)))
(update-instance-for-redefined-class instance
(set-difference (set-difference class-local local) shared)
(set-difference discarded class-shared)
(apply #'append (mapplist #'(lambda (x y) (when (and (not (eq y secret-unbound-value)) (member x discarded)) (list x y))) p-slot-value))))))
(defun remove-from-deleted-classes (class new-superclasses)
(mapc #'(lambda (x) (setf (class-direct-subclasses x) (remove class (class-direct-subclasses x))))
(set-difference (class-direct-superclasses class) new-superclasses)))
(defun collect-subclasses (class)
(do* ((subs (reverse (class-direct-subclasses class))
(mapappend #'(lambda (x) (reverse (class-direct-subclasses x))) subs))
(all subs (append all subs)))
((not subs) (delete-duplicates all))))
;;; Class precedence lists
(defun compute-class-precedence-list (class) (std-compute-class-precedence-list class))
(defun std-compute-class-precedence-list (class)
(let ((classes-to-order (collect-superclasses* class)))
(topological-sort classes-to-order
(remove-duplicates
(mapappend #'local-precedence-ordering
classes-to-order))
#'std-tie-breaker-rule)))
;;; topological-sort implements the standard algorithm for topologically
;;; sorting an arbitrary set of elements while honoring the precedence
;;; constraints given by a set of (X,Y) pairs that indicate that element
;;; X must precede element Y. The tie-breaker procedure is called when it
;;; is necessary to choose from multiple minimal elements; both a list of
;;; candidates and the ordering so far are provided as arguments.
(defun topological-sort (elements constraints tie-breaker)
(let ((remaining-constraints constraints)
(remaining-elements elements)
(result ()))
(loop
(let ((minimal-elements
(remove-if
#'(lambda (class)
(member class remaining-constraints
:key #'cadr))
remaining-elements)))
(when (null minimal-elements)
(if (null remaining-elements)
(return-from topological-sort result)
(error "Inconsistent precedence graph.")))
(let ((choice (if (null (cdr minimal-elements))
(car minimal-elements)
(funcall tie-breaker
minimal-elements
result))))
(setq result (append result (list choice)))
(setq remaining-elements
(remove choice remaining-elements))
(setq remaining-constraints
(remove choice
remaining-constraints
:test #'member)))))))
;;; In the event of a tie while topologically sorting class precedence lists,
;;; the CLOS Specification says to "select the one that has a direct subclass
;;; rightmost in the class precedence list computed so far." The same result
;;; is obtained by inspecting the partially constructed class precedence list
;;; from right to left, looking for the first minimal element to show up among
;;; the direct superclasses of the class precedence list constituent.
;;; (There's a lemma that shows that this rule yields a unique result.)
(defun std-tie-breaker-rule (minimal-elements cpl-so-far)
(dolist (cpl-constituent (reverse cpl-so-far))
(let* ((supers (class-direct-superclasses cpl-constituent))
(common (intersection minimal-elements supers)))
(when (not (null common))
(return-from std-tie-breaker-rule (car common))))))
;;; This version of collect-superclasses* isn't bothered by cycles in the class
;;; hierarchy, which sometimes happen by accident.
(defun collect-superclasses* (class)
(labels ((all-superclasses-loop (seen superclasses)
(let ((to-be-processed
(set-difference superclasses seen)))
(if (null to-be-processed)
superclasses
(let ((class-to-process
(car to-be-processed)))
(all-superclasses-loop
(cons class-to-process seen)
(union (class-direct-superclasses
class-to-process)
superclasses)))))))
(all-superclasses-loop () (list class))))
;;; The local precedence ordering of a class C with direct superclasses C_1,
;;; C_2, ..., C_n is the set ((C C_1) (C_1 C_2) ...(C_n-1 C_n)).
(defun local-precedence-ordering (class)
(mapcar #'list
(cons class
(butlast (class-direct-superclasses class)))
(class-direct-superclasses class)))
;;; Slot inheritance
(defun compute-slots (class) (std-compute-slots class))
(defun std-compute-slots (class)
(let* ((all-slots (nreverse (mapappend #'class-direct-slots
(reverse (class-precedence-list class)))))
(all-names (remove-duplicates
(mapcar #'slot-definition-name all-slots))))
(nreverse (mapcar #'(lambda (name)
(compute-effective-slot-definition
class
(remove name all-slots
:key #'slot-definition-name
:test-not #'eq)))
all-names))))
(defun compute-effective-slot-definition (class direct-slots) (std-compute-effective-slot-definition class direct-slots))
(defun std-compute-effective-slot-definition (class direct-slots)
(let* ((initer (find-if-not #'null direct-slots
:key #'slot-definition-initfunction))
(doc (find-if-not #'null direct-slots
:key #'slot-definition-documentation))
(first-slot (car direct-slots))
(alloc (slot-definition-allocation first-slot))
(slot (make-effective-slot-definition
:name (slot-definition-name first-slot)
:initform (when initer (slot-definition-initform initer))
:initfunction (when initer (slot-definition-initfunction initer))
:initargs (remove-duplicates (mapappend #'slot-definition-initargs direct-slots))
:allocation alloc)))
(when (eq alloc :class)
(let ((shared-slot (slot-definition-shared-slot first-slot)))
(setf (getf* slot :shared-slot) shared-slot)
(when (member shared-slot (class-direct-slots class) :key #'slot-definition-shared-slot)
(let ((old-shared-slot (and (class-finalized-p class)
(slot-definition-shared-slot (find (slot-definition-name slot) (class-shared-slot-definitions class)
:key #'slot-definition-name)))))
(setf (car shared-slot) (if old-shared-slot (car old-shared-slot) (if initer (funcall (slot-definition-initfunction initer)) secret-unbound-value)))))))
(when doc (setf (getf* slot :documentation) (slot-definition-documentation doc)))
slot))
;;;
;;; Generic function metaobjects and standard-generic-function
;;;
(defparameter the-defclass-generic-function
'(defclass generic-function (metaobject)))
(defparameter the-defclass-standard-generic-function
'(defclass standard-generic-function (generic-function)
( ; (name :initarg :name) ; name from metaobject :accessor generic-function-name
(lambda-list ; :accessor generic-function-lambda-list
:initarg :lambda-list)
(required-args ; :accessor generic-function-required-args
:initarg :required-args)
(methods :initform ()) ; :accessor generic-function-methods
(method-class ; :accessor generic-function-method-class
:initarg :method-class)
(discriminating-function) ; :accessor generic-function-
; -discriminating-function
(classes-to-emf-table ; :accessor classes-to-emf-table
:initform (make-method-table))
(method-combination :initarg :method-combination :initform 'standard) ; :accessor generic-function-method-combination
(method-combination-order :initform ':most-specific-first)))) ; :accessor generic-function-method-combination-order
(defvar the-class-gf) ;generic-function's class metaobject
(defvar the-class-standard-gf) ;standard-generic-function's class metaobject
(defun generic-function-name (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'name slot-location-generic-function-name)
(slot-value gf 'name)))
(defun (setf generic-function-name) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'name slot-location-generic-function-name)
new-value)
(setf (slot-value gf 'name) new-value)))
(defun generic-function-required-args (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'required-args
slot-location-generic-function-required-args)
(slot-value gf 'required-args)))
(defun (setf generic-function-required-args) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf
'required-args slot-location-generic-function-required-args)
new-value)
(setf (slot-value gf 'required-args) new-value)))
(defun generic-function-lambda-list (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'lambda-list
slot-location-generic-function-lambda-list)
(slot-value gf 'lambda-list)))
(defun (setf generic-function-lambda-list) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(progn
(setf (generic-function-required-args gf)
(getf (analyze-lambda-list new-value) ':required-args))
(setf (slot-value-with-index gf 'lambda-list
slot-location-generic-function-lambda-list)
new-value))
(setf (slot-value gf 'lambda-list) new-value)))
(defun generic-function-methods (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'methods slot-location-generic-function-methods)
(slot-value gf 'methods)))
(defun (setf generic-function-methods) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'methods slot-location-generic-function-methods)
new-value)
(setf (slot-value gf 'methods) new-value)))
(defun generic-function-discriminating-function (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'discriminating-function
slot-location-generic-function-discriminating-function)
(slot-value gf 'discriminating-function)))
(defun (setf generic-function-discriminating-function) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'discriminating-function
slot-location-generic-function-discriminating-function)
new-value)
(setf (slot-value gf 'discriminating-function) new-value)))
(defun generic-function-method-class (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'method-class
slot-location-generic-function-method-class)
(slot-value gf 'method-class)))
(defun (setf generic-function-method-class) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'method-class
slot-location-generic-function-method-class)
new-value)
(setf (slot-value gf 'method-class) new-value)))
;;; Internal accessor for effective method function table
(defun classes-to-emf-table (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'classes-to-emf-table
slot-location-generic-function-classes-to-emf-table)
(slot-value gf 'classes-to-emf-table)))
(defun (setf classes-to-emf-table) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'classes-to-emf-table
slot-location-generic-function-classes-to-emf-table)
new-value)
(setf (slot-value gf 'classes-to-emf-table) new-value)))
(defun (setf generic-function-method-combination) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'method-combination
slot-location-generic-function-method-combination)
new-value)
(setf (slot-value gf 'method-combination) new-value)))
(defun (setf generic-function-method-combination-order) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'method-combination-order
slot-location-generic-function-method-combination-order)
new-value)
(setf (slot-value gf 'method-combination-order) new-value)))
;;;
;;; Method metaobjects and standard-method
;;;
(defparameter the-defclass-standard-method
'(defclass standard-method (method)
((qualifiers :initarg :qualifiers) ; :accessor method-qualifiers
(lambda-list :initarg :lambda-list) ; :accessor method-lambda-list
(specializers :initarg :specializers) ; :accessor method-specializers
(body :initarg :body) ; :accessor method-body
(generic-function :initform nil) ; :accessor method-generic-function
(function) ; :accessor method-function
(environment :initarg :environment)))) ; :accessor method-environment
(defvar the-class-standard-method) ;standard-method's class metaobject
(defun method-lambda-list (method) (slot-value method 'lambda-list))
(defun (setf method-lambda-list) (new-value method)
(setf (slot-value method 'lambda-list) new-value))
(defun method-qualifiers (method) (slot-value method 'qualifiers))
(defun (setf method-qualifiers) (new-value method)
(setf (slot-value method 'qualifiers) new-value))
(defun method-specializers (method) (slot-value method 'specializers))
(defun (setf method-specializers) (new-value method)
(setf (slot-value method 'specializers) new-value))
(defun method-body (method) (slot-value method 'body))
(defun (setf method-body) (new-value method)
(setf (slot-value method 'body) new-value))
(defun method-environment (method) (slot-value method 'environment))
(defun (setf method-environment) (new-value method)
(setf (slot-value method 'environment) new-value))
(defun method-generic-function (method)
(slot-value method 'generic-function))
(defun (setf method-generic-function) (new-value method)
(setf (slot-value method 'generic-function) new-value))
(defun method-function (method) (slot-value method 'function))
(defun (setf method-function) (new-value method)
(setf (slot-value method 'function) new-value))
;;;
;;; Common Lisp DEFGENERIC macro
;;;
(defmacro defgeneric (function-name lambda-list &rest options)
(flet ((is-method-option (opt) (eq (car opt) :method))
(method-definition-form (opt) `(defmethod ,function-name ,@(cdr opt))))
(let* ((method-definitions (mapcar #'method-definition-form (remove-if (complement #'is-method-option) options)))
(non-method-options (remove-if #'is-method-option options))
(documentation-form
(let ((doc-string (cadr (find-if #'(lambda (opt) (eq (car opt) :documentation)) non-method-options))))
(when doc-string `(setf (documentation ',function-name 'function) ,doc-string)))))
`(prog1
(ensure-generic-function
',function-name
:lambda-list ',lambda-list
,@(canonicalize-defgeneric-options non-method-options))
,(when documentation-form documentation-form)
,@method-definitions
))))
(defun canonicalize-defgeneric-options (options)
(mapappend #'canonicalize-defgeneric-option options))
(defun canonicalize-defgeneric-option (option)
(case (car option)
(:generic-function-class
(list ':generic-function-class
`(find-class ',(cadr option))))
(:method-class
(list ':method-class
`(find-class ',(cadr option))))
(:method-combination
`(:method-combination ',(cadr option)))
(t (list `',(car option) `',(cadr option)))))
;;; find-generic-function looks up a generic function by name. It's an
;;; artifact of the fact that our generic function metaobjects can't legally
;;; be stored a symbol's function value.
(let ((generic-function-table (make-hash-table :test #'equal :synchronized t)))
(defun find-generic-function (symbol &optional (errorp t))
(if (consp symbol)
(if (and (eq (car symbol) 'SETF)(symbolp (cadr symbol)))
(let ((setf-func (get-setf-function (cadr symbol))))
(if (and (symbolp setf-func) (fboundp setf-func))
(setf setf-func (symbol-function setf-func)))
(if (and setf-func (standard-generic-function-p setf-func))
(return-from find-generic-function setf-func)))
(error "Invalid generic function name: ~S" symbol))
(if (fboundp symbol)
(let ((func (symbol-function symbol)))
(if (standard-generic-function-p func)
(return-from find-generic-function func)))))
(let ((gf (gethash symbol generic-function-table nil)))
(if (and (null gf) errorp)
(error "No generic function named ~S." symbol)
gf)))
(defun (setf find-generic-function) (func symbol)
(if (standard-generic-function-p func)
(if (consp symbol)
(if (and (eq (car symbol) 'SETF)(symbolp (cadr symbol)))
(let ((setter-name (cl::setf-function-symbol symbol)))
(setf (symbol-function setter-name) func)
(register-setf-function (cadr symbol) setter-name))
(error "Invalid generic function name: ~S" symbol))
(setf (symbol-function symbol) func))
(setf (gethash symbol generic-function-table) func)))
(defun forget-all-generic-functions ()
(clrhash generic-function-table)
(values))
) ;end let generic-function-table
;;; ensure-generic-function
(defun ensure-generic-function
(function-name
&rest all-keys
&key (generic-function-class the-class-standard-gf)
(method-class the-class-standard-method)
lambda-list
&allow-other-keys)
(if (find-generic-function function-name nil)
(find-generic-function function-name)
(let ((gf (apply (if (eq generic-function-class the-class-standard-gf)
#'make-instance-standard-generic-function
#'make-instance)
generic-function-class
:name function-name
:method-class method-class
:required-args (getf (analyze-lambda-list lambda-list) ':required-args)
all-keys)))
(setf (find-generic-function function-name) gf)
gf)))
;;; finalize-generic-function
;;; Same basic idea as finalize-inheritance.
;;; Takes care of recomputing and storing the discriminating
;;; function, and clearing the effective method function table.
(defun finalize-generic-function (gf)
(setf (generic-function-discriminating-function gf)
(funcall (if (eq (class-of gf) the-class-standard-gf)
#'std-compute-discriminating-function
#'compute-discriminating-function)
gf))
(unless (standard-generic-function-p gf)
(setf (fdefinition (generic-function-name gf))
(generic-function-discriminating-function gf)))
(clear-method-table (classes-to-emf-table gf))
(values))
;;; make-instance-standard-generic-function creates and initializes an
;;; instance of standard-generic-function without falling into method lookup.
;;; However, it cannot be called until standard-generic-function exists.
(defun make-instance-standard-generic-function
(generic-function-class
&key
name
documentation
lambda-list
method-class
(method-combination 'standard)
(method-combination-order ':most-specific-first)
&allow-other-keys)
(declare (ignore generic-function-class))
(let ((gf (std-allocate-instance the-class-standard-gf)))
(setf (generic-function-name gf) name)
(setf (class-documentation gf) documentation)
(setf (generic-function-lambda-list gf) lambda-list)
(setf (generic-function-methods gf) ())
(setf (generic-function-method-class gf) method-class)
(setf (classes-to-emf-table gf) (make-method-table))
(setf (generic-function-method-combination gf) method-combination)
(setf (generic-function-method-combination-order gf) method-combination-order)
(finalize-generic-function gf)
gf))
;;; defmethod
(defmacro defmethod (&rest args)
(multiple-value-bind (function-name qualifiers
lambda-list specializers body)
(parse-defmethod args)
`(ensure-method (find-generic-function ',function-name nil)
:generic-function-name ',function-name
:lambda-list ',lambda-list
:qualifiers ',qualifiers
:specializers ,(canonicalize-specializers specializers)
:body ',body
:environment (funcall (lambda () (cl::capture-compiler-environment)))#| nil |#
#| :eql-specializers (some #'(lambda (x) (and (listp x)(eq (car x) 'EQL))) ',specializers) |#)))
(defun canonicalize-specializers (specializers)
`(list ,@(mapcar #'canonicalize-specializer specializers)))
(defun canonicalize-specializer (specializer)
(if (and (listp specializer) (eq (car specializer) 'eql)) `(intern-eql-specializer ,(cadr specializer) ',(cadr specializer))
`(find-class ',specializer)))
(defun specalization-vars (specialized-lambda-list)
(let ((vars '()))
(dolist (x specialized-lambda-list (nreverse vars))
(if (member x lambda-list-keywords)
(return (nreverse vars))
(if (consp x)
(push (car x) vars))))))
(defun create-ignorable-decls (vars)
`(declare (ignorable ,@vars)))
(defun parse-defmethod (args)
(let ((fn-spec (car args))
(qualifiers ())
(specialized-lambda-list nil)
(body '())
(decls '())
(doc-string nil)
(parse-state :qualifiers))
(do* ((a (cdr args))
(arg (car a)(car a)))
((null a))
(cond
((eq parse-state :qualifiers)
(if (and (atom arg) (not (null arg)))
(progn
(push-on-end arg qualifiers)
(setf a (cdr a)))
(setq parse-state :lambda-list)))
((eq parse-state :lambda-list)
(setq specialized-lambda-list arg)
(setq parse-state :decls-and-doc-string)
(setf a (cdr a)))
((eq parse-state :decls-and-doc-string)
(if (and (null doc-string) (stringp arg))
(setq doc-string arg a (cdr a))
(if (and (consp arg)(eq (car arg) 'declare))
(progn
(push-on-end arg decls)
(setf a (cdr a)))
(setq parse-state :body))))
((eq parse-state :body)
(push-on-end arg body)
(setf a (cdr a)))))
;; watch for case where a literal string is the only item in body--
;; we don't want to mistake it for a doc-string
(if (and (null body) doc-string)
(setf body (list doc-string) doc-string nil))
(values fn-spec
qualifiers
(extract-lambda-list specialized-lambda-list)
(extract-specializers specialized-lambda-list)
;; add IGNORABLE declarations to specializers so they don't cause
;; warnings if they are not referenced in generated lambdas
`(,@(cons (create-ignorable-decls (specalization-vars specialized-lambda-list))
decls)
,@(if doc-string (list doc-string))
(block
,(if (consp fn-spec) (cadr fn-spec) fn-spec)
,@body)))))
;;; Several tedious functions for analyzing lambda lists
(defun gf-required-arglist (gf)
(generic-function-required-args gf))
(defun required-portion (gf args)
(let ((required-args (generic-function-required-args gf))
(new-args nil))
(dolist (x required-args (nreverse new-args))
(declare (ignore x))
(unless (consp args)
(error "Too few arguments to generic function ~S." gf))
(push (car args) new-args)
(setf args (cdr args)))))
(defun num-required-args (gf) (length (generic-function-required-args gf)))
(defun extract-lambda-list (specialized-lambda-list)
(let* ((plist (analyze-lambda-list specialized-lambda-list))
(requireds (getf plist ':required-names))
(rv (getf plist ':rest-var))
(ks (getf plist ':key-args))
(aok (getf plist ':allow-other-keys))
(opts (getf plist ':optional-args))
(auxs (getf plist ':auxiliary-args)))
`(,@requireds
,@(if opts `(&optional ,@opts) ())
,@(if rv `(&rest ,rv) ())
,@(if (or ks aok) `(&key ,@ks) ())
,@(if aok '(&allow-other-keys) ())
,@(if auxs `(&aux ,@auxs) ()))))
(defun extract-specializers (specialized-lambda-list)
(let ((plist (analyze-lambda-list specialized-lambda-list)))
(getf plist ':specializers)))
(defun analyze-lambda-list (lambda-list)
(labels ((make-keyword (symbol)
(intern (symbol-name symbol)
(find-package 'keyword)))
(get-keyword-from-arg (arg)
(if (listp arg)
(if (listp (car arg))
(caar arg)
(make-keyword (car arg)))
(make-keyword arg))))
(let ((keys ()) ; Just the keywords
(key-args ()) ; Keywords argument specs
(required-names ()) ; Just the variable names
(required-args ()) ; Variable names & specializers
(specializers ()) ; Just the specializers
(rest-var nil)
(optionals ())
(auxs ())
(allow-other-keys nil)
(state :parsing-required))
(dolist (arg lambda-list)
(if (member arg lambda-list-keywords)
(ecase arg
(&optional
(setq state :parsing-optional))
(&rest
(setq state :parsing-rest))
(&key
(setq state :parsing-key))
(&allow-other-keys
(setq allow-other-keys 't))
(&aux
(setq state :parsing-aux)))
(case state
(:parsing-required
(push-on-end arg required-args)
(if (listp arg)
(progn (push-on-end (car arg) required-names)
(push-on-end (cadr arg) specializers))
(progn (push-on-end arg required-names)
(push-on-end 't specializers))))
(:parsing-optional (push-on-end arg optionals))
(:parsing-rest (setq rest-var arg))
(:parsing-key
(push-on-end (get-keyword-from-arg arg) keys)
(push-on-end arg key-args))
(:parsing-aux (push-on-end arg auxs)))))
(list :required-names required-names
:required-args required-args
:specializers specializers
:rest-var rest-var
:keywords keys
:key-args key-args
:auxiliary-args auxs
:optional-args optionals
:allow-other-keys allow-other-keys))))
;;; ensure method
(defun ensure-method (gf &rest all-keys #| &key eql-specializers &allow-other-keys |#)
(if (null gf)
;; define a generic function on the fly
(setf gf
(ensure-generic-function
(getf all-keys :generic-function-name)
':lambda-list (getf all-keys :lambda-list))))
;; as soon as we define one method with an EQL specifier, we assume
;; methods of that generic function may specify this way
;(if eql-specializers ** redundantly too soon as add-method has to, for it can be called by the user
; (setf (method-table-eql-specializers (classes-to-emf-table gf)) t))
(let ((new-method
(apply
(if (eq (generic-function-method-class gf)
the-class-standard-method)
#'make-instance-standard-method
#'make-instance)
(generic-function-method-class gf)
all-keys)))
(setf (class-name new-method) (getf all-keys :generic-function-name))
(add-method gf new-method)
new-method))
;;; make-instance-standard-method creates and initializes an instance of
;;; standard-method without falling into method lookup. However, it cannot
;;; be called until standard-method exists.
(defun make-instance-standard-method (method-class
&key lambda-list qualifiers
specializers body environment
&allow-other-keys)
(declare (ignore method-class))
(let ((method (std-allocate-instance the-class-standard-method)))
(setf (method-lambda-list method) lambda-list)
(setf (class-documentation method) (when (stringp (cadr body)) (cadr body)))
(setf (method-qualifiers method) qualifiers)
(setf (method-specializers method) specializers)
(setf (method-body method) body)
(setf (method-environment method) environment)
(setf (method-generic-function method) nil)
(setf (method-function method)
(std-compute-method-function method))
method))
;;; add-method
;;; This version first removes any existing method on the generic function
;;; with the same qualifiers and specializers.
(defun eql-specializer-p (x) (declare (ignore x))) ; redefined below
(defun add-method (gf method)
(let ((old-method
(find-method gf (method-qualifiers method)
(method-specializers method) nil)))
(when old-method (remove-method gf old-method)))
(setf (method-generic-function method) gf)
(push method (generic-function-methods gf))
(dolist (specializer (method-specializers method))
(when (eql-specializer-p specializer)
(setf (method-table-eql-specializers (classes-to-emf-table gf)) t)) ; set to t to recalculate eqls
(pushnew method (class-direct-methods specializer)))
(finalize-generic-function gf)
gf) ; add-method should return gf.
(defun remove-method (gf method)
(setf (generic-function-methods gf)
(remove method (generic-function-methods gf)))
(setf (method-generic-function method) nil)
(dolist (class (method-specializers method))
(when (eql-specializer-p class)
(setf (method-table-eql-specializers (classes-to-emf-table gf)) t)) ; set to t to recalculate eqls
(setf (class-direct-methods class)
(remove method (class-direct-methods class))))
(finalize-generic-function gf)
gf) ; remove-method should return gf. Bug when trying to print a deleted method.
(defun find-method (gf qualifiers specializers
&optional (errorp t))
(let ((method
(find-if #'(lambda (method)
(and (equal qualifiers
(method-qualifiers method))
(equal specializers
(method-specializers method))))
(generic-function-methods gf))))
(if (and (null method) errorp)
(error "No such method for ~S." (generic-function-name gf))
method)))
;;; Reader and write methods
(defun add-reader-method (class fn-name slot-name)
(ensure-method
(ensure-generic-function fn-name :lambda-list '(object))
:lambda-list '(object)
:qualifiers ()
:specializers (list class)
:body `((slot-value object ',slot-name))
:environment (top-level-environment))
(values))
(defun add-class-slot-reader-method (class fn-name slot-name index)
(declare (ignore slot-name))
(ensure-method
(ensure-generic-function fn-name :lambda-list '(object))
:lambda-list '(object)
:qualifiers ()
:specializers (list class)
:body `((let* ((class (class-of object))
(val (car (aref (slot-value class 'shared-slots) ,index))))
(if (eq secret-unbound-value val)
(error "The class slot ~S is unbound in the class ~S." ',slot-name (class-name class))
val)))
:environment (top-level-environment))
(values))
(defun add-writer-method (class fn-name slot-name)
(ensure-method
(ensure-generic-function
fn-name :lambda-list '(new-value object))
:lambda-list '(new-value object)
:qualifiers ()
:specializers (list (find-class 't) class)
:body `((setf (slot-value object ',slot-name)
new-value))
:environment (top-level-environment))
(values))
(defun add-class-slot-writer-method (class fn-name slot-name index)
(declare (ignore slot-name))
(ensure-method
(ensure-generic-function
fn-name :lambda-list '(new-value object))
:lambda-list '(new-value object)
:qualifiers ()
:specializers (list (find-class 't) class)
:body `((setf (car (aref (slot-value (class-of object) 'shared-slots) ,index))
new-value))
:environment (top-level-environment))
(values))
(defun remove-read-write-methods (class)
(mapc #'(lambda (x)
(mapc #'(lambda (x)
(let* ((gf (find-generic-function x))
(meth (find-method gf () (if (= 2 (length (generic-function-required-args gf))) (list (find-class t) class) (list class)) nil)))
(when meth (remove-method gf meth))))
(append (slot-definition-readers x) (slot-definition-writers x))))
(class-direct-slots class)))
(defun convert-function-to-method (function-name method-lambda-list)
(eval (let* ((function-symbol (if (and (consp function-name) (eq 'setf (car function-name)))
(get-setf-function (cadr function-name))
function-name))
(meth (gensym))
(args (analyze-lambda-list method-lambda-list))
(args (append (getf args :required-names)
(mapcar #'(lambda (x) (if (consp x) (car x) x)) (getf args :optional-args))
(mapappend #'list (getf args :keywords) (getf args :key-args)) (list (getf args :rest-var)))))
`(prog1 (defmethod ,meth ,method-lambda-list (apply #',meth ,.(butlast args) ,(car (last args))))
(setf (generic-function-name #',meth) ',function-name
(class-name (car (generic-function-methods #',meth))) ',function-name
(getf (function-info-list (fdefinition ',function-name)) 'function-name) ',meth)
(rotatef (symbol-function ',meth) (symbol-function ',function-symbol))))))
;;;
;;; Generic function invocation
;;;
;;; apply-generic-function
(defun apply-generic-function (gf args)
(apply (generic-function-discriminating-function gf) args))
(defun std-compute-discriminating-function (gf &aux (table (classes-to-emf-table gf)) (num (num-required-args gf)))
#'(lambda (&rest args)
(let* ((tail (let ((tail (- (length args) num))) (if (minusp tail) (error "Too few arguments to generic function ~S." gf) tail)))
(eqls (if (listp (method-table-eql-specializers table)) (method-table-eql-specializers table)
(let ((eqls (make-list num)))
(dolist (meth (generic-function-methods gf) (setf (method-table-eql-specializers table)
(when (member-if #'consp eqls) eqls)))
(do ((specs (method-specializers meth) (cdr specs)) (eqls eqls (cdr eqls)))
((not specs))
(when (eql-specializer-p (car specs))
(pushnew (list (slot-value (car specs) 'object)) (car eqls)
:test #'(lambda (x y) (eql (car x) (car y))))))))))
(eqls-classes (if eqls (mapcar #'(lambda (arg eqls) (or (car (member arg eqls :key #'car)) (class-of arg))) args eqls)
(mapcar #'class-of (butlast args tail)))))
(funcall (or (find-method-table-method table eqls-classes)
(slow-method-lookup gf table args
(if eqls (mapcar #'(lambda (arg eql-class)
(if (consp eql-class)
(gethash arg *clos-singleton-specializers*)
eql-class)) args eqls-classes)
eqls-classes) eqls-classes)) args))))
(defun slow-method-lookup (gf table args classes eqls-classes)
(let* ((applicable-methods (compute-applicable-methods-using-classes gf classes))
(emfun (if (member-if #'primary-method-p applicable-methods)
(if (eq (class-of gf) the-class-standard-gf)
(std-compute-effective-method-function gf applicable-methods)
(compute-effective-method-function gf applicable-methods))
(error "No primary methods for ~S in the ~S." args gf))))
(add-method-table-method table eqls-classes emfun) emfun))
;;; compute-applicable-methods-using-classes
(defun compute-applicable-methods-using-classes
(gf required-classes)
(sort
(copy-list
(remove-if-not #'(lambda (method)
(every #'subclassp
required-classes
(method-specializers method)))
(generic-function-methods gf)))
#'(lambda (m1 m2)
(funcall
(if (eq (class-of gf) the-class-standard-gf)
#'std-method-more-specific-p
#'method-more-specific-p)
gf m1 m2 required-classes))))
;;; method-more-specific-p
;(setq cl::*compiler-warn-on-dynamic-return* nil)
(defun std-method-more-specific-p (gf method1 method2 required-classes)
(declare (ignore gf))
(do* ((specs1 (method-specializers method1)(cdr specs1))
(specs2 (method-specializers method2)(cdr specs2))
(classes required-classes (cdr classes))
(spec1 (car specs1)(car specs1))
(spec2 (car specs2)(car specs2))
(arg-class (car classes)(car classes)))
((or (endp specs1)(endp specs2)(endp classes)) nil)
(unless (eq spec1 spec2)
(return-from std-method-more-specific-p
(sub-specializer-p spec1 spec2 arg-class)))))
;(setq cl::*compiler-warn-on-dynamic-return* t)
;;; apply-methods and compute-effective-method-function
(defun apply-methods (gf args methods)
(funcall (compute-effective-method-function gf methods)
args))
(defun primary-method-p (method)
(null (method-qualifiers method)))
(defun before-method-p (method)
(equal '(:before) (method-qualifiers method)))
(defun after-method-p (method)
(equal '(:after) (method-qualifiers method)))
(defun around-method-p (method)
(equal '(:around) (method-qualifiers method)))
;;; If the name is a list i.e. (SETF FOO) then this creates a symbolic
;;; representation of the name, suitable as a block label.
(defun generic-func-name (gf)
(let ((gfn (generic-function-name gf)))
(if (symbolp gfn)
gfn
(make-symbol (format nil "~A" gfn)))))
;; new way in Corman Lisp 1.5 release
(defun std-compute-effective-method-function (gf methods)
(let ((primaries (remove-if-not #'primary-method-p methods))
(around (find-if #'around-method-p methods)))
(when (null primaries)
(error "No primary methods for the generic function ~S." gf))
(if around
(let ((next-emfun
(if (eq (class-of gf) the-class-standard-gf)
(std-compute-effective-method-function gf (remove around methods))
(compute-effective-method-function gf (remove around methods)))))
#'(lambda (args)
(funcall (method-function around) args next-emfun)))
(let* ((next-emfun (compute-primary-emfun (cdr primaries)))
(befores (remove-if-not #'before-method-p methods))
(reverse-afters
(reverse (remove-if-not #'after-method-p methods)))
(before-calls
(mapcar #'(lambda (before)
`(funcall ,(method-function before) args nil))
befores))
(after-calls
(mapcar #'(lambda (after)
`(funcall ,(method-function after) args nil))
reverse-afters)))
(if after-calls
(compile nil
`(lambda (args)
(block ,(generic-func-name gf) ;; a named block enables the compiler to
,@before-calls ;; tag the compiled code with the name
(multiple-value-prog1 ;; (for debugging, etc.)
(funcall ,(method-function (car primaries)) args ,next-emfun)
,@after-calls))))
(compile nil
`(lambda (args)
(block ,(generic-func-name gf)
,@before-calls
(funcall ,(method-function (car primaries)) args ,next-emfun)))))))))
;;; compute an effective method function from a list of primary methods:
(defun compute-primary-emfun (methods)
(if (null methods)
nil
(let ((next-emfun (compute-primary-emfun (cdr methods))))
#'(lambda (args)
(funcall (method-function (car methods)) args next-emfun)))))
;;; apply-method and compute-method-function
(defun apply-method (method args next-methods)
(funcall (method-function method)
args
(if (null next-methods)
nil
(compute-effective-method-function
(method-generic-function method) next-methods))))
;;; search a tree for a passed symbol or form
(defun search-tree (tree form)
(if tree
(if (eq tree form)
t
(if (consp tree)
(or (search-tree (car tree) form)
(search-tree (cdr tree) form))))))
(defun std-compute-method-function (method)
(let ((form (macroexpand-all (cons 'progn (method-body method))))
(lambda-list (method-lambda-list method)))
(if (or (search-tree form 'call-next-method)
(search-tree form 'next-method-p))
(compile-in-lexical-environment (method-environment method)
`(lambda (args next-emfun)
(flet ((call-next-method (&rest cnm-args)
(if (null next-emfun)
(error "No next method for the~@
generic function ~S."
(method-generic-function ',method))
(funcall next-emfun (or cnm-args args))))
(next-method-p () (not (null next-emfun))))
(apply #'(lambda ,(kludge-arglist lambda-list) ,@(cdr form)) args))))
(compile-in-lexical-environment (method-environment method)
`(lambda (args next-emfun)
(declare (ignore next-emfun))
(apply #'(lambda ,(kludge-arglist lambda-list) ,@(cdr form)) args))))))
;;; N.B. The function kludge-arglist is used to pave over the differences
;;; between argument keyword compatibility for regular functions versus
;;; generic functions.
;;; RGC--17 Aug 2006--modified to handle &aux lambda list variables.
;;;
(defun kludge-arglist (lambda-list)
(let ((aux-vars (member '&aux lambda-list)))
(if aux-vars
(setq lambda-list (subseq lambda-list 0 (position '&aux lambda-list))))
(if (and (member '&key lambda-list)
(not (member '&allow-other-keys lambda-list)))
(append lambda-list '(&allow-other-keys))
(if (and (not (member '&rest lambda-list))
(not (member '&key lambda-list)))
(append lambda-list '(&key &allow-other-keys) aux-vars)
(append lambda-list aux-vars)))))
;;; Run-time environment hacking (Common Lisp ain't got 'em).
(defun top-level-environment ()
nil) ; Bogus top level lexical environment
(defvar compile-methods nil) ; by default, run everything interpreted
(defun compile-in-lexical-environment (env lambda-expr)
(declare (ignore env))
(if compile-methods
(compile nil lambda-expr)
(eval `(function ,lambda-expr ,env))))
;;;;
;;;; Common Lisp FUNCALL function.
;;;; Modified here to allow Standard-Generic-Functions as the
;;;; first argument.
;;;;
(in-package :x86)
(defasm funcall (func &rest args)
{
push ebp
mov ebp, esp
push edi
push ecx
push ebx
push 0 ;; one cell local storage at [ebp - 16]
cmp ecx, 1
jge short :t1
callp _wrong-number-of-args-error
:t1
mov eax, [ebp + ecx*4 + 4] ;; eax = function
mov edx, eax
and edx, 7
cmp edx, uvector-tag ;; see if func arg is a uvector
je short :t2
push eax
callp _not-a-function-error
:t2
mov edx, [eax - uvector-tag] ;; edx = uvector header
shl edx, 24
shr edx, 27
cmp edx, uvector-symbol-tag ;; see if it is a symbol
jne short :t3
;; get the function that is bound to the symbol
mov eax, [eax + (- (* 4 symbol-function-offset) uvector-tag)]
mov eax, [eax - 4]
mov edx, eax
and edx, 7
cmp edx, uvector-tag
je short :t9
push [ebp + ecx*4 + 4]
callp _not-a-function-error
:t9
mov edx, [eax - uvector-tag] ;; edx = uvector header
shl edx, 24
shr edx, 27
:t3 ;; we now know we have a function in eax, and dl is the type
;; push all the arguments
mov [ebp - 16], esp
mov ebx, ecx
dec ecx
:t4
dec ebx
jle short :t5
push [ebp + ebx*4 + 4]
jmp short :t4
:t5
cmp edx, uvector-function-tag
jne short :t6
:t11
mov edi, [eax + (- (* 4 function-environment-offset) uvector-tag)]
callfunc eax
jmp short :t8
:t6
cmp edx, uvector-kfunction-tag
jne short :t10
mov edi, [esi] ;; environment for kfunctions is always NIL
call [eax + (- (* function-code-buffer-offset 4) uvector-tag)]
jmp short :t8
:t10
cmp edx, uvector-clos-instance-tag
jne short :t7
mov edx, [eax + (uvector-offset cl::clos-instance-class-offset)] ;; edx = clos class
mov ebx, 'cl::the-class-standard-gf
mov ebx, [ebx + (uvector-offset cl::symbol-value-offset)]
mov ebx, [ebx - cons-tag]
cmp ebx, edx ;; class = the-class-standard-gf?
jne short :t7
mov eax, [eax + (uvector-offset cl::clos-instance-slots-offset)] ;; eax = clos class slots
mov eax, [eax + (uvector-offset (+ 2 cl::slot-location-generic-function-discriminating-function))]
jmp short :t11
:t7
push eax
callp _not-a-function-error
:t8
mov esp, [ebp - 16]
pop edi
pop ebx
pop edi
pop edi
mov esp, ebp
pop ebp
ret
})
;;;;
;;;; Common Lisp APPLY function.
;;;; Modified here to allow Standard-Generic-Functions as the
;;;; first argument.
;;;;
(defasm apply (func &rest args)
{
push ebp
mov ebp, esp
push edi
push ecx
push ebx
push 0 ;; one cell local storage at [ebp - 16]
cmp ecx, 2
jge short :t1
callp _wrong-number-of-args-error
:t1
mov eax, [ebp + ecx*4 + 4] ;; eax = function
mov edx, eax
and edx, 7
cmp edx, uvector-tag ;; see if func arg is a uvector
je short :t2
push eax
callp _not-a-function-error
:t2
mov edx, [eax - uvector-tag] ;; edx = uvector header
shl edx, 24
shr edx, 27
cmp edx, uvector-symbol-tag ;; see if it is a symbol
jne short :t4
;; get the function that is bound to the symbol
mov eax, [eax + (- (* 4 symbol-function-offset) uvector-tag)]
mov eax, [eax - 4]
mov edx, eax
and edx, 7
cmp edx, uvector-tag
je short :t3
push [ebp + ecx*4 + 4]
callp _not-a-function-error
:t3
mov edx, [eax - uvector-tag] ;; edx = uvector header
shl edx, 24
shr edx, 27
:t4 ;; we now know we have a function in eax, and dl is the type
;; push all the arguments except the last
mov [ebp - 16], esp
dec ecx
mov ebx, ecx
dec ecx
:t5
dec ebx
jle short :t6
push [ebp + ebx*4 + 8]
jmp short :t5
:t6
;; the last argument is a list of remaining arguments
mov edi, [ebp + ARGS_OFFSET]
:t7
mov ebx, edi
and ebx, 7
cmp ebx, cons-tag ;; is a cons cell?
jne short :t8 ;; if not, exit
push [edi - 4]
inc ecx
mov edi, [edi]
jmp short :t7
:t8
cmp edx, uvector-function-tag
jne short :t9
:t13
mov edi, [eax + (- (* 4 function-environment-offset) uvector-tag)]
callfunc eax
jmp short :t11
:t9
cmp edx, uvector-kfunction-tag
jne short :t12
mov edi, [esi] ;; environment for kfunctions is always NIL
call [eax + (- (* function-code-buffer-offset 4) uvector-tag)]
jmp short :t11
:t12
cmp edx, uvector-clos-instance-tag
jne short :t10
mov edx, [eax + (uvector-offset cl::clos-instance-class-offset)] ;; edx = clos class
mov ebx, 'cl::the-class-standard-gf
mov ebx, [ebx + (uvector-offset cl::symbol-value-offset)]
mov ebx, [ebx - cons-tag]
cmp ebx, edx ;; class = the-class-standard-gf?
jne short :t10
mov eax, [eax + (uvector-offset cl::clos-instance-slots-offset)] ;; eax = clos class slots
mov eax, [eax + (uvector-offset (+ 2 cl::slot-location-generic-function-discriminating-function))]
jmp short :t13
:t10
push eax
callp _not-a-function-error
:t11
mov esp, [ebp - 16]
pop edi ;; remove local storage
pop ebx
pop edi
pop edi
mov esp, ebp
pop ebp
ret
})
;;;;
;;;; Common Lisp FUNCTIONP function.
;;;; Redefined here to add support for generic functions.
;;;;
(defasm functionp (x)
{
push ebp
mov ebp, esp
cmp ecx, 1
jz short :next1
callp _wrong-number-of-args-error
:next1
mov edx, [ebp + ARGS_OFFSET] ;; edx = argument
mov eax, edx
and eax, 7
cmp eax, uvector-tag
jne short :nil-exit
mov eax, [edx - uvector-tag]
cmp al, (tag-byte uvector-kfunction-tag)
jbe short :t-exit
cmp al, (tag-byte uvector-clos-instance-tag)
jne short :nil-exit
mov eax, [edx + (uvector-offset cl::clos-instance-class-offset)] ;; eax = clos class
mov edx, 'cl::the-class-standard-gf
mov edx, [edx + (uvector-offset cl::symbol-value-offset)]
mov edx, [edx - cons-tag]
cmp eax, edx ;; class = the-class-standard-gf?
jne short :nil-exit
:t-exit
mov eax, [esi + t-offset]
jmp short :exit
:nil-exit
mov eax, [esi]
:exit
pop ebp
ret
})
(defasm cl::execution-address (func &rest args)
{
push ebp
mov ebp, esp
push edi
push ebx
cmp ecx, 1
je short :t1
callp _wrong-number-of-args-error
:t1
mov eax, [ebp + ARGS_OFFSET] ;; eax = argument
mov edx, eax
and edx, 7
cmp edx, uvector-tag ;; see if func arg is a uvector
je short :t2
push eax
callp _not-a-function-error
:t2
mov edx, [eax - uvector-tag] ;; edx = uvector header
shl edx, 24
shr edx, 27
cmp edx, uvector-symbol-tag ;; see if it is a symbol
jne short :t3
;; get the function that is bound to the symbol
mov eax, [eax + (uvector-offset symbol-function-offset)]
mov eax, [eax - 4]
mov edx, eax
and edx, 7
cmp edx, uvector-tag
je short :t9
push [ebp + ARGS_OFFSET]
callp _not-a-function-error
:t9
mov edx, [eax - uvector-tag] ;; edx = uvector header
shl edx, 24
shr edx, 27
:t3 ;; we should have a function in eax, and dl is the type
cmp edx, uvector-function-tag
jne short :t6
:t11
mov eax, [eax + (uvector-offset function-code-buffer-offset)]
lea eax, [eax + (uvector-offset compiled-code-execution-offset)] ;; eax = exec address
jmp short :got-addr
:t6
cmp edx, uvector-kfunction-tag
jne short :t10
mov eax, [eax + (uvector-offset function-code-buffer-offset)]
jmp short :got-addr
:t10
cmp edx, uvector-clos-instance-tag
jne short :t7
mov edx, [eax + (uvector-offset cl::clos-instance-class-offset)] ;; edx = clos class
mov ebx, 'cl::the-class-standard-gf
mov ebx, [ebx + (uvector-offset cl::symbol-value-offset)]
mov ebx, [ebx - cons-tag]
cmp ebx, edx ;; class = the-class-standard-gf?
jne short :t7
mov eax, [eax + (uvector-offset cl::clos-instance-slots-offset)] ;; eax = clos class slots
mov eax, [eax + (uvector-offset (+ 2 cl::slot-location-generic-function-discriminating-function))]
jmp short :t11
:t7
push eax
callp _not-a-function-error
:got-addr ;; eax = execution address
mov edx, 0
mov dl, [eax]
cmp dl, #xe9 ;; watch for jump table entry: if so, resolve to real address
jne short :t8
add eax, [eax + 1]
add eax, 5
:t8
test eax, #xf0000000
jne :bignum
shl eax, 3
jmp short :exit
:bignum
push eax
push 8
mov ecx, 1
callf cl::alloc-bignum ;; allocate 1 cell
add esp, 4
pop [eax + (uvector-offset cl::bignum-first-cell-offset)]
:exit
pop ebx
pop edi
mov ecx, 1
mov esp, ebp
pop ebp
ret
})
(in-package :cl)
;;;
;;; Bootstrap
;;;
;(progn ; Extends to end-of-file (to avoid printing intermediate results).
;;(format t "Beginning to bootstrap Closette...")
(forget-all-classes)
(forget-all-generic-functions)
;; How to create the class hierarchy in 10 easy steps:
;; 1. Figure out standard-class's slots.
(setq the-slots-of-standard-class
(mapcar #'(lambda (slotd)
(make-effective-slot-definition
:name (car slotd)
:initargs
(let ((a (getf (cdr slotd) ':initarg)))
(if a (list a) ()))
:initform (getf (cdr slotd) ':initform)
:initfunction
(let ((a (getf (cdr slotd) ':initform)))
(if a #'(lambda () (eval a)) nil))
:allocation ':instance))
(nth 3 the-defclass-standard-class)))
;; 2. Create the standard-class metaobject by hand.
(setq the-class-standard-class
(allocate-std-instance
'tba
(make-array (length the-slots-of-standard-class)
:initial-element secret-unbound-value)))
;; 3. Install standard-class's (circular) class-of link.
(setf (std-instance-class the-class-standard-class)
the-class-standard-class)
;; (It's now okay to use class-... accessor).
;; 4. Fill in standard-class's class-slots.
(setf (class-effective-slots the-class-standard-class) the-slots-of-standard-class)
;; (Skeleton built; it's now okay to call make-instance-standard-class.)
;; 5. Hand build the class t so that it has no direct superclasses.
(setf (find-class 't)
(let ((class (std-allocate-instance the-class-standard-class)))
(setf (class-name class) 't)
(setf (class-documentation class) ())
(setf (class-direct-subclasses class) ())
(setf (class-direct-superclasses class) ())
(setf (class-direct-methods class) ())
(setf (class-direct-slots class) ())
(setf (class-precedence-list class) (list class))
(setf (class-effective-slots class) ())
(setf (class-shared-slot-definitions class) ()) ; Shared Slots Bug
(setf (class-shared-slots class) ())
class))
;; (It's now okay to define subclasses of t.)
;; 6. Create the other superclass of standard-class (i.e., standard-object).
(defclass standard-object (t) ())
(defclass metaobject () ((name :initarg :name) (documentation :initform () :initarg :documentation)))
(defclass forward-referenced-class (metaobject) ((direct-subclasses :initform ())))
(defclass specializer (forward-referenced-class)
((direct-superclasses :initarg :direct-superclasses) class-precedence-list (direct-methods :initform ())))
(defclass class (specializer))
;; 7. Define the full-blown version of standard-class.
(setq the-class-standard-class
(defclass standard-class (class)
(direct-slots effective-slots (shared-slot-definitions :initform ()) (shared-slots :initform ())
(direct-default-initargs :initform () :initarg :direct-default-initargs) (effective-default-initargs :initform ()))))
;; 8. Replace all existing pointers to the skeleton with real one.
;; and Declare types (not for t)
(mapc #'(lambda (x) (setf (std-instance-class (find-class x)) the-class-standard-class)
(unless (eq t x)
(install-type-specifier x #'(lambda (s1 s2)
(and (cl::clos-instance-p s1)
(cl::subclassp (class-of s1) (find-class s2)))))))
'(t standard-object metaobject forward-referenced-class specializer class standard-class))
;; (Clear sailing from here on in).
;; 9. Define the other built-in classes.
(defclass symbol (t) ())
(defclass sequence (t) ())
(defclass array (t) ())
(defclass number (t) ())
(defclass character (t) ())
(defclass function (t) ())
; (defclass hash-table (t) ()) defined below
(defclass package (t) ())
(defclass pathname (t) ())
(defclass readtable (t) ())
(defclass stream (t) ())
(defclass list (sequence) ())
(defclass null (symbol list) ())
(defclass cons (list) ())
(defclass vector (array sequence) ())
(defclass bit-vector (vector) ())
(defclass string (vector) ())
(defclass complex (number) ())
(defclass integer (number) ())
(defclass float (number) ())
(defclass ratio (number) ())
;; 10. Define the other standard metaobject classes.
;;; redefine to add type support for TYPEP
(defmacro defclass (name direct-superclasses slot-definitions
&rest options)
(let ((s1 (gensym))(s2 (gensym)))
`(prog1
(ensure-class ',name
:direct-superclasses
,(canonicalize-direct-superclasses direct-superclasses)
:direct-slots
,(canonicalize-direct-slots slot-definitions)
,@(canonicalize-defclass-options options))
(declare-type-specifier ,name (,s1 ,s2)
(and (or (cl::clos-instance-p ,s1) (structurep ,s1))
(cl::subclassp (class-of ,s1) (find-class ,s2)))))))
(defclass eql-specializer (specializer) (object))
(defclass built-in-class (class))
(defclass structure-class (class) ())
(setq the-class-gf (eval the-defclass-generic-function))
(setq the-class-standard-gf (eval the-defclass-standard-generic-function))
(defclass method (metaobject))
(setq the-class-standard-method (eval the-defclass-standard-method))
;; Voila! The class hierarchy is in place.
;;(format t "Class hierarchy created.")
;; (It's now okay to define generic functions and methods.)
(defgeneric print-object (instance stream))
(defmethod print-object ((instance standard-object) stream)
(print-unreadable-object (instance stream :identity t)
(format stream "~:(~S~)"
(class-name (class-of instance))))
instance)
;;; Slot access
(defgeneric slot-value-using-class (class instance slot-name))
(defmethod slot-value-using-class ((class standard-class) instance slot-name)
(declare (ignore class))
(std-slot-value instance slot-name))
(defgeneric (setf slot-value-using-class) (new-value class instance slot-name))
(defmethod (setf slot-value-using-class)
(new-value (class standard-class) instance slot-name)
(declare (ignore class))
(setf (std-slot-value instance slot-name) new-value))
; (values)) ;end progn
;;; N.B. To avoid making a forward reference to a (setf xxx) generic function:
(defun setf-slot-value-using-class (new-value class object slot-name)
(setf (slot-value-using-class class object slot-name) new-value))
(defun forward-referenced-class-p (x) (eq (class-of x) #.(find-class 'forward-referenced-class)))
(defun eql-specializer-p (x) (eq (class-of x) #.(find-class 'eql-specializer)))
(mapc #'(lambda (x) (convert-function-to-method (car x) (cadr x)))
'((class-name ((class metaobject))) ((setf class-name) (new-value (class metaobject))) ; setf gf ansi fun amop
(class-direct-subclasses ((class forward-referenced-class))) ((setf class-direct-subclasses) (new-value (class forward-referenced-class)))
(class-direct-superclasses ((class specializer))) ((setf class-direct-superclasses) (new-value (class specializer)))
(class-direct-methods ((class specializer))) ((setf class-direct-methods) (new-value (class specializer)))
(class-direct-slots ((class standard-class))) ((setf class-direct-slots) (new-value (class standard-class)))
(class-shared-slot-definitions ((class standard-class))) ((setf class-shared-slot-definitions) (new-value (class standard-class)))
(class-shared-slots ((class standard-class))) ((setf class-shared-slots) (new-value (class standard-class)))
(add-method ((generic-function standard-generic-function) (method standard-method)))
(remove-method ((generic-function standard-generic-function) (method standard-method)))
(find-method ((generic-function standard-generic-function) method-qualifiers specializers &optional errorp))))
(defmethod class-direct-superclasses ((x forward-referenced-class))) ; amop
(defmethod class-direct-slots ((class forward-referenced-class))) ; amop
(defmethod (setf class-direct-slots) (new-value (class forward-referenced-class)) (declare (ignore new-value)))
(defmethod class-shared-slot-definitions ((class forward-referenced-class)))
(defmethod (setf class-shared-slot-definitions) (new-value (class forward-referenced-class)) (declare (ignore new-value)))
(defmethod class-shared-slots ((class forward-referenced-class)))
(defmethod (setf class-shared-slots) (new-value (class forward-referenced-class)) (declare (ignore new-value)))
(defmethod class-slots ((class forward-referenced-class)) (declare (ignore class)))
(defmethod class-slots ((class standard-class)) (append (class-effective-slots class) (class-shared-slot-definitions class)))
(defmethod class-direct-default-initargs ((class forward-referenced-class)))
(defmethod class-direct-default-initargs ((class standard-class)) (slot-value class 'direct-default-initargs))
(defmethod class-default-initargs ((class standard-class)) (slot-value class 'effective-default-initargs))
(defun (setf class-default-initargs) (new-value class)
(setf (slot-value class 'effective-default-initargs) new-value))
;(progn
(defgeneric slot-exists-p-using-class (class instance slot-name))
(defmethod slot-exists-p-using-class
((class standard-class) instance slot-name)
(declare (ignore class))
(std-slot-exists-p instance slot-name))
(defgeneric slot-boundp-using-class (class instance slot-name))
(defmethod slot-boundp-using-class
((class standard-class) instance slot-name)
(declare (ignore class))
(std-slot-boundp instance slot-name))
(defgeneric slot-makunbound-using-class (class instance slot-name))
(defmethod slot-makunbound-using-class
((class standard-class) instance slot-name)
(declare (ignore class))
(std-slot-makunbound instance slot-name))
;;; Instance creation and initialization
(defgeneric allocate-instance (class))
(defmethod allocate-instance ((class standard-class))
(let ((instance (std-allocate-instance class)))
(unless ; all subclasses of metaobject except strict subclasses of standard-class,
; standard-generic-function and standard-method. Standard-class only for now.
(and (subclassp class #.(find-class 'metaobject))
(or (eq class the-class-standard-class) (not (subclassp class the-class-standard-class))))
(setf (std-instance-signature instance)
(list (class-effective-slots class) (class-shared-slot-definitions class))))
instance))
(defgeneric make-instance (class &key))
(defmethod make-instance ((class standard-class) &rest initargs)
(let ((instance (allocate-instance class)))
(apply #'initialize-instance instance initargs)
instance))
(defmethod make-instance ((class symbol) &rest initargs)
(apply #'make-instance (find-class class) initargs))
(defgeneric initialize-instance (instance &key))
(defmethod initialize-instance ((instance standard-object) &rest initargs)
(apply #'shared-initialize instance t initargs))
(defgeneric reinitialize-instance (instance &key))
(defmethod reinitialize-instance
((instance standard-object) &rest initargs)
(apply #'shared-initialize instance () initargs))
(defgeneric shared-initialize (instance slot-names &key))
(defmethod shared-initialize ((instance standard-object)
slot-names &rest all-keys)
(dolist (slot (class-slots (class-of instance)))
(let ((slot-name (slot-definition-name slot)))
(multiple-value-bind (init-key init-value foundp)
(get-properties
all-keys (slot-definition-initargs slot))
(declare (ignore init-key))
(if foundp
(setf (slot-value instance slot-name) init-value)
(when (and (not (slot-boundp instance slot-name))
(not (null (slot-definition-initfunction slot)))
(or (eq slot-names t)
(member slot-name slot-names)))
(setf (slot-value instance slot-name)
(funcall (slot-definition-initfunction slot))))))))
instance)
(defmethod update-instance-for-redefined-class ((instance standard-object) added-slots discarded-slots property-list &rest initargs)
(declare (ignore discarded-slots property-list))
(apply #'shared-initialize instance added-slots initargs))
;;; change-class
(defgeneric change-class (instance new-class &key))
(defmethod change-class
((old-instance standard-object)
(new-class standard-class)
&rest initargs)
(let ((new-instance (allocate-instance new-class)))
(dolist (slot-name (mapcar #'slot-definition-name
(class-effective-slots new-class)))
(when (and (slot-exists-p old-instance slot-name)
(slot-boundp old-instance slot-name))
(setf (slot-value new-instance slot-name)
(slot-value old-instance slot-name))))
(rotatef (std-instance-slots new-instance)
(std-instance-slots old-instance))
(rotatef (std-instance-class new-instance)
(std-instance-class old-instance))
(rotatef (std-instance-signature new-instance)
(std-instance-signature old-instance))
(apply #'update-instance-for-different-class
new-instance old-instance initargs)
old-instance))
(defmethod change-class
((instance standard-object) (new-class symbol) &rest initargs)
(apply #'change-class instance (find-class new-class) initargs))
(defgeneric update-instance-for-different-class (old new &key))
(defmethod update-instance-for-different-class
((old standard-object) (new standard-object) &rest initargs)
(let ((added-slots
(remove-if #'(lambda (slot-name)
(slot-exists-p old slot-name))
(mapcar #'slot-definition-name
(class-effective-slots (class-of new))))))
(apply #'shared-initialize new added-slots initargs)))
;;; change-class the built-in classes
(mapc #'(lambda (x) (change-class (find-class x) 'built-in-class))
'(t symbol sequence array number character function package pathname readtable stream
list null cons vector bit-vector string complex integer float ratio))
;;;
;;; Methods having to do with class metaobjects.
;;;
(defmethod print-object ((class metaobject) stream)
(print-unreadable-object (class stream :identity t)
(format stream "~:(~S~) ~S"
(class-name (class-of class))
(class-name class)))
class)
(defmethod initialize-instance :after ((class specializer) &rest args)
(apply #'std-after-initialization-for-classes class args))
;;; Finalize inheritance
(defgeneric finalize-inheritance (class))
(defmethod finalize-inheritance ((class specializer))
(setf (class-precedence-list class)
(compute-class-precedence-list class))
(values))
(defmethod finalize-inheritance ((class standard-class))
(std-finalize-inheritance class)
(values))
;;; Class precedence lists
(defgeneric compute-class-precedence-list (class))
(defmethod compute-class-precedence-list ((class specializer))
(std-compute-class-precedence-list class))
;;; Slot inheritance
(defgeneric compute-slots (class))
(defmethod compute-slots ((class standard-class))
(std-compute-slots class))
(defgeneric compute-effective-slot-definition (class direct-slots))
(defmethod compute-effective-slot-definition
((class standard-class) direct-slots)
(std-compute-effective-slot-definition class direct-slots))
;;;
;;; Methods having to do with generic function metaobjects.
;;;
(defmethod initialize-instance :after ((gf standard-generic-function) &key)
(finalize-generic-function gf))
;;;
;;; Methods having to do with method metaobjects.
;;;
(defmethod print-object ((method standard-method) stream)
(print-unreadable-object (method stream :identity t)
(format stream "~:(~S~) ~S~{ ~S~} ~S"
(class-name (class-of method))
(generic-function-name (method-generic-function method))
(method-qualifiers method)
(mapcar #'(lambda (x) (if (eql-specializer-p x) `(eql ,(class-name x)) (class-name x))) (method-specializers method))))
method)
(defmethod initialize-instance :after ((method standard-method) &key)
(setf (method-function method) (compute-method-function method)))
;;;
;;; Methods having to do with generic function invocation.
;;;
(defgeneric compute-discriminating-function (gf))
(defmethod compute-discriminating-function ((gf standard-generic-function))
(std-compute-discriminating-function gf))
(defgeneric method-more-specific-p (gf method1 method2 required-classes))
(defmethod method-more-specific-p
((gf standard-generic-function) method1 method2 required-classes)
(std-method-more-specific-p gf method1 method2 required-classes))
(defgeneric compute-effective-method-function (gf methods))
(defmethod compute-effective-method-function
((gf standard-generic-function) methods)
(std-compute-effective-method-function gf methods))
(defgeneric compute-method-function (method))
(defmethod compute-method-function ((method standard-method))
(std-compute-method-function method))
;;; describe-object is a handy tool for enquiring minds:
(defgeneric describe-object (object stream))
(defmethod describe-object ((object standard-object) stream)
(format stream "CLOS OBJECT:~%~?~?~?"
"~4T~A:~20T~A~%" (list "printed representation" object)
"~4T~A:~20T~A~%" (list "class" (class-of object))
"~4T~A:~20T#x~X~%" (list "heap address" (%uvector-address object)))
(dolist (sn (mapcar #'slot-definition-name
(class-slots (class-of object))))
(format stream "~4T~A: ~:[not bound~;~S~]~%"
(string-downcase (symbol-name sn))
(slot-boundp object sn)
(and (slot-boundp object sn)
(slot-value object sn))))
(values))
(defmethod describe-object ((object t) stream)
(cl:describe object stream)
(values))
;;(format t "~%Closette is a Knights of the Lambda Calculus production.")
;(values)) ;end progn
;;; add default-initargs functionality
(defmethod compute-default-initargs ((class standard-class))
(remove-duplicates (mapappend #'class-direct-default-initargs (class-precedence-list class)) :from-end t :key #'car))
(defmethod finalize-inheritance :after ((class standard-class))
(setf (class-default-initargs class) (compute-default-initargs class)))
(defmethod make-instance :around ((class standard-class) &rest initargs)
(apply #'call-next-method class
(append initargs (mapappend #'(lambda (def-init)
(let ((key (car def-init)))
(unless (caddr (multiple-value-list (get-properties initargs (list key))))
(list key (funcall (caddr def-init))))))
(class-default-initargs class)))))
;;; add class redefinition functionality
;;; t for the amop. nil can be useful for development.
;;; By carefully violating the amop rules we can get a glance at finalized classes.
(defparameter *lazy-finalize*)
(defmethod initialize-instance :after ((class eql-specializer) &key) (finalize-inheritance class)) ; always finalized
(defmethod reinitialize-instance :after ((class class) &rest args) ; leave open; funcallable-standard-class?
(apply #'std-after-initialization-for-classes class args))
;;;
;;; setup parent class for all structures
;;;
(defmethod initialize-instance :after ((class structure-class) &key) (finalize-inheritance class)) ; always finalized
(defmethod reinitialize-instance :after ((class structure-class) &key) (finalize-inheritance class)) ; not actually needed
(defclass structure-object (t) () (:metaclass structure-class))
(defmethod initialize-instance :after ((class standard-class) &key) (unless *lazy-finalize* (finalize-inheritance class)))
(defmethod reinitialize-instance :after ((class standard-class) &key) (unless *lazy-finalize* (finalize-inheritance class)))
(defmethod ensure-class-using-class ((class class) name &rest all-keys
&key (metaclass the-class-standard-class) direct-superclasses &allow-other-keys)
(declare (ignore name))
(unless (eq (class-of class) (or (and (symbolp metaclass) (find-class metaclass)) metaclass))
(error "~a is not a ~a" class metaclass))
(let ((subs (if *lazy-finalize*
(remove-if-not #'class-finalized-p (cons class (collect-subclasses class)))
(cons class (collect-subclasses class)))))
(when *lazy-finalize*
(let ((forward (find-if #'forward-referenced-class-p direct-superclasses)))
(when (and forward (eq class (car subs)))
(error "Cannot redefine finalized ~a~%;;; with an undefined ~a" class forward))))
(remove-read-write-methods class)
(unless (lists-match (class-direct-superclasses class) direct-superclasses)
(remove-from-deleted-classes class direct-superclasses)
(mapc #'(lambda (x) (clear-method-table (classes-to-emf-table x)))
(remove-duplicates (mapcar #'method-generic-function (mapappend #'class-direct-methods subs)))))
(apply #'reinitialize-instance class all-keys)
(mapc #'finalize-inheritance (if *lazy-finalize* subs (cdr subs))))
class)
(defmethod ensure-class-using-class ((class null) name &rest all-keys &key (metaclass the-class-standard-class) &allow-other-keys)
(setf (find-class name) (apply #'make-instance metaclass :name name all-keys)))
;;; add forward-referenced-class functionality
(defun not-instantiable-p (class)
(let ((supers (class-direct-superclasses class)))
(or (find-if #'forward-referenced-class-p supers)
(dolist (class supers) (let ((class (not-instantiable-p class))) (when class (return class)))))))
;;; For forward-referenced classes to behave like "identity" elements in a null *lazy-finalize* mode "environment"
;;; we should consider the more general case by defining a generic function say, default-direct-superclass.
(defmethod compute-class-precedence-list ((class standard-class))
(let ((list (call-next-method)))
(if (forward-referenced-class-p (car (last list)))
(nconc (remove-if #'(lambda (x) (member x '#.(list (find-class 'standard-object) (find-class t)))) list)
(list #.(find-class 'standard-object) #.(find-class t)))
list)))
(defmethod finalize-inheritance ((class forward-referenced-class)) (error "Cannot finalize ~a." class))
(defmethod finalize-inheritance :before ((class standard-class)) ; we should actually only finalize classes with shared slots
(when *lazy-finalize* (mapc #'(lambda (x) (unless (class-finalized-p x) (finalize-inheritance x))) (class-direct-superclasses class))))
(defmethod allocate-instance :before ((class standard-class))
(if *lazy-finalize*
(unless (class-finalized-p class) (finalize-inheritance class))
(let ((forward (not-instantiable-p class)))
(when forward (cerror "Continue anyway." "Continuable attempt to instantiate ~a~%;;; with an undefined ~a superclass." class forward)))))
; redefine
(defun canonicalize-direct-superclasses (direct-superclasses) `',direct-superclasses)
(defmethod ensure-class-using-class ((class forward-referenced-class) name &rest all-keys
&key (metaclass the-class-standard-class) &allow-other-keys) (declare (ignore name))
(change-class class metaclass) (apply #'reinitialize-instance class all-keys)
(mapc #'(lambda (x) (when (class-finalized-p x) (finalize-inheritance x))) (collect-subclasses class))
class)
; redefine
(defun ensure-class (name &rest all-keys &key direct-superclasses &allow-other-keys)
(apply #'ensure-class-using-class (find-class name nil) name
:direct-superclasses (mapcar #'(lambda (x) (or (and (symbolp x) (find-class x nil))
(and (clos-instance-p x) x)
(ensure-class-using-class nil x :metaclass (find-class 'forward-referenced-class))))
direct-superclasses)
all-keys))
(defmacro with-slots (slot-entries instance-form &body forms)
(let ((sym (gensym))
(vars '())
(slots '()))
(unless (listp slot-entries)
(error "Invalid WITH-SLOTS slot entry list: ~S" slot-entries))
(dolist (varslot slot-entries)
(typecase varslot
(symbol
(push varslot vars)
(push varslot slots))
(list
(unless (= 2 (length varslot))
(error "Invalid WITH-SLOTS slot entry: ~S" varslot))
(push (first varslot) vars)
(push (second varslot) slots))
(t (error "Invalid WITH-SLOTS slot entry: ~S" varslot))))
`(LET ((,sym ,instance-form))
(SYMBOL-MACROLET
,(mapcar #'(lambda (v s) `(,v (slot-value ,sym ',s)))
(nreverse vars)
(nreverse slots))
,@forms))))
(defun intern-structure-class (name superclass doc)
(ensure-class name
:direct-superclasses (list (or (and superclass (find-class superclass)) #.(find-class 'structure-object)))
:metaclass 'structure-class
:documentation doc))
(defun struct-template (struct-name)
(get struct-name :struct-template))
(defun patch-clos (struct-name)
(setf (elt (struct-template struct-name) 1)
(intern-structure-class struct-name nil (documentation struct-name 'structure))))
;; make sure the following common lisp structures (which are defined before
;; this module is loaded) have CLOS definitions
(patch-clos 'hash-table)
(patch-clos 'random-state)
(patch-clos 'byte)
;; this is internal only, but we will patch it just in case...
(patch-clos 'method-table)
;;; EQL specializer support
;;; Returns a CLOS class representing a type that is specific
;;; for the object. Used in defmethod to implement EQL
;;; specialisers.
(defun intern-eql-specializer (object &optional (intern-form object))
(let* ((singleton (gethash object *clos-singleton-specializers*))
(real (and singleton
(car (member intern-form (class-precedence-list singleton)
:test #'(lambda (x y) (and (eql-specializer-p y) (equal x (class-name y)))))))))
(or real (let ((newsingle (make-instance #.(find-class 'eql-specializer)
:name intern-form :direct-superclasses (list (or singleton (class-of object))))))
(setf (slot-value newsingle 'object) object (gethash object *clos-singleton-specializers*) newsingle)))))
;; need to restore warning here
(setq *COMPILER-WARN-ON-UNDEFINED-FUNCTION* t) ;; restore warnings
;;;
;;; Common Lisp WITH-ACCESSORS macro.
;;;
(defmacro with-accessors (slot-entries instance-form &body forms)
(let ((sym (gensym))
(vars '())
(slots '()))
(unless (listp slot-entries)
(error "Invalid WITH-ACCESSORS slot entry list: ~S" slot-entries))
(dolist (varslot slot-entries)
(typecase varslot
(symbol
(push varslot vars)
(push varslot slots))
(list
(unless (= 2 (length varslot))
(error "Invalid WITH-ACCESSORS slot entry: ~S" varslot))
(push (first varslot) vars)
(push (second varslot) slots))
(t (error "Invalid WITH-ACCESSORS slot entry: ~S" varslot))))
`(LET ((,sym ,instance-form))
(SYMBOL-MACROLET
,(mapcar #'(lambda (v s) `(,v (,s ,sym)))
(nreverse vars)
(nreverse slots))
,@forms))))
;;;
;;; Handle STRUCTURE-derived classes
;;;
(defmethod print-object ((instance structure-object) stream)
(let ((*standard-output* stream))
(cl::write-builtin-object instance)))
;;;
;;; Handle all other Lisp data types
;;;
(defmethod print-object ((instance t) stream)
(let ((*standard-output* stream))
(cl::write-builtin-object instance)))
(defun has-print-object-method (obj)
(let ((gf (find-generic-function 'print-object)))
(> (length (cl::compute-applicable-methods-using-classes gf (list (class-of obj)))) 1)))
;;;
;;; Hook into WRITE so that PRINT-OBJECT may be overridden for builtin objects.
;;;
(defun write-lisp-object (object)
(print-object object *standard-output*))
| true |
;;;;
;;;; File: clos.lisp
;;;; Contents: Corman Lisp CLOS implementation based on Closette
;;;; History: RGC 12/16/98 Added PI:NAME:<NAME>END_PI's WITH-SLOTS implementation.
;;;; RGC 9/8/99 Added STANDARD-CLASS-P.
;;;; Decreased generic function call overhead by 40%
;;;; by building, compiling and caching the generic function
;;;; on the fly.
;;;; RGC 10/14/99 DEFCLASS adds a type descriminator function to
;;;; support TYPEP.
;;;; RGC 12/06/99 Added RATIO builtin class.
;;;; RGC 2/15/01 Modified structures to be integrated better with CLOS.
;;;; i.e. CLASS-OF returns a class unique to that structure type.
;;;; RGC 2/24/01 Added code to patch common lisp structures which are created
;;;; prior to CLOS loading to support method dispatching.
;;;; RGC 7/29/01 Integrated EQL specializer code, optimized per generic function.
;;;; RGC 10/21/01 Integrated generic functions so they are now first-class
;;;; functions, satisfying FUNCTIONP, and callable by FUNCALL and APPLY.
;;;;
;;;; RGC 9/19/03 Incorporated Frank Adrian's modification to DEFGENERIC to support :documentation option.
;;;; RGC 8/17/06 Modified method generation to handle &AUX in argument lists
;;;; LC 9/6/17 Lower EQL specializer overhead and name EQL specializers to their "intern form" for display purposes.
;;;; LC 2/19/18 Class redefinition with propagation to subclasses and instances, :documentation and :default-initargs
;;;; DEFCLASS options, Forward-referenced-class, Built-in-class and other AMOP Metaobjects and guidelines.
;;;; LC 3/3/18 Shared slot fixes.
;;;;
;;;; Note from PI:NAME:<NAME>END_PI, 7/29/2001:
;;;; This file has been hacked and modified for over 5 years by
;;;; me and others. It no longer bears much resemblance to the original,
;;;; but I will leave the following messages from Xerox in anyway.
;;;;
;;;; Optimizations for use with Corman Lisp 1.0 (May 15, 1998)
;;;; Minor modifications for use with PowerLisp 2.0 (May 15, 1996)
;;;;
;;;; Closette Version 1.0 (February 10, 1991)
;;;; Copyright (c) 1990, 1991 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.
;;;;
;;;; Closette is an implementation of a subset of CLOS with a metaobject
;;;; protocol as described in "The Art of The Metaobject Protocol",
;;;; MIT Press, 1991.
;;;;
(provide :clos)
(in-package :common-lisp)
;; need to override warning here -RGC
(setq *COMPILER-WARN-ON-UNDEFINED-FUNCTION* nil)
(defvar exports
'(defclass defgeneric defmethod
find-class class-of
call-next-method next-method-p
slot-value slot-boundp slot-exists-p slot-makunbound
make-instance change-class
initialize-instance reinitialize-instance shared-initialize
update-instance-for-different-class
print-object
standard-object metaobject forward-referenced-class specializer
standard-class standard-generic-function standard-method eql-specializer
class-name
class-direct-superclasses class-direct-slots
class-precedence-list class-slots class-direct-subclasses
class-direct-methods class-direct-default-initargs class-default-initargs
generic-function-name generic-function-lambda-list
generic-function-methods generic-function-discriminating-function
generic-function-method-class
method-lambda-list method-qualifiers method-specializers method-body
method-environment method-generic-function method-function
slot-definition-name slot-definition-initfunction
slot-definition-initform slot-definition-initargs
slot-definition-readers slot-definition-writers
slot-definition-allocation
;;
;; Class-related metaobject protocol
;;
compute-class-precedence-list compute-slots
compute-effective-slot-definition
finalize-inheritance allocate-instance
slot-value-using-class slot-boundp-using-class
slot-exists-p-using-class slot-makunbound-using-class
;;
;; Generic function related metaobject protocol
;;
compute-discriminating-function
compute-applicable-methods-using-classes method-more-specific-p
compute-effective-method-function compute-method-function
apply-methods apply-method
describe-object
find-generic-function ; Necessary artifact of this implementation
))
(export exports)
;;; This hash-table supports CLOS EQL specializers.
(defconstant *clos-singleton-specializers* (make-hash-table :synchronized t))
;; fixed position of required-args in generic-function
(defconstant slot-location-generic-function-name 0)
(defconstant slot-location-generic-function-documentation 1)
(defconstant slot-location-generic-function-lambda-list 2)
(defconstant slot-location-generic-function-required-args 3)
(defconstant slot-location-generic-function-methods 4)
(defconstant slot-location-generic-function-method-class 5)
(defconstant slot-location-generic-function-discriminating-function 6)
(defconstant slot-location-generic-function-classes-to-emf-table 7)
(defconstant slot-location-generic-function-method-combination 8)
(defconstant slot-location-generic-function-method-combination-order 9)
;;;
;;; Utilities
;;;
;;; push-on-end is like push except it uses the other end:
(defmacro push-on-end (value location)
`(setf ,location (nconc ,location (list ,value))))
;;; (setf getf*) is like (setf getf) except that it always changes the list,
;;; which must be non-nil.
(defun (setf getf*) (new-value plist key)
(block body
(do ((x plist (cddr x)))
((null x))
(when (eq (car x) key)
(setf (car (cdr x)) new-value)
(return-from body new-value)))
(push-on-end key plist)
(push-on-end new-value plist)
new-value))
;;; mapappend is like mapcar except that the results are appended together:
(defun mapappend (fun &rest args)
(if (some #'null args)
()
(append (apply fun (mapcar #'car args))
(apply #'mapappend fun (mapcar #'cdr args)))))
;;; mapplist is mapcar for property lists:
(defun mapplist (fun x)
(if (null x)
()
(cons (funcall fun (car x) (cadr x))
(mapplist fun (cddr x)))))
;;; the method table is only used internally--optimize to the max
(proclaim '(optimize (speed 3)(safety 0)))
(defstruct method-table
(method-list nil)
(cached-method nil)
(cached-method-types nil)
(sync (cl::allocate-critical-section))
(eql-specializers nil))
(proclaim '(optimize (speed 0)(safety 3)))
(defun clear-method-table (table)
(with-synchronization (method-table-sync table)
(setf (method-table-method-list table) nil)
(setf (method-table-cached-method table) nil)
(setf (method-table-cached-method-types table) nil))
table)
(defun add-method-table-method (table types method)
(with-synchronization (method-table-sync table)
(setf (method-table-method-list table)
(cons types (cons method (method-table-method-list table))))
(setf (method-table-cached-method table) method)
(setf (method-table-cached-method-types table) types))
table)
(proclaim '(optimize (speed 3)(safety 0)))
(defun lists-match (list1 list2)
(do ((x list1 (cdr x)) (y list2 (cdr y))) ((null x) t)
(unless (eq (car x) (car y)) (return nil))))
(defun find-method-table-method (table eqls-classes)
(with-synchronization (method-table-sync table)
(do ((p (method-table-method-list table) (cddr p))) ((null p) (return nil))
(when (lists-match (car p) eqls-classes) (return (cadr p))))))
(proclaim '(optimize (speed 0)(safety 3)))
;;;
;;; Standard instances
;;;
(defun std-instance-class (x)
(if (clos-instance-p x)
(clos-instance-class x)
(error "Not a CLOS instance: ~S" x)))
(defun (setf std-instance-class) (val x)
(if (clos-instance-p x)
(setf (uref x clos-instance-class-offset) val)
(error "Not a CLOS instance: ~S" x)))
(defun std-instance-slots (x)
(if (clos-instance-p x)
(clos-instance-slots x)
(error "Not a CLOS instance: ~S" x)))
(defun (setf std-instance-slots) (val x)
(if (clos-instance-p x)
(setf (uref x clos-instance-slots-offset) val)
(error "Not a CLOS instance: ~S" x)))
;;; Fortunately there was an empty cell to store class signatures
(defun std-instance-signature (x)
(if (clos-instance-p x) (uref x 3) (error "Not a CLOS instance: ~S" x)))
(defun (setf std-instance-signature) (val x)
(if (clos-instance-p x) (setf (uref x 3) val) (error "Not a CLOS instance: ~S" x)))
(defun allocate-std-instance (class slots)
(let ((x (alloc-clos-instance)))
(setf (uref x clos-instance-class-offset) class)
(setf (uref x clos-instance-slots-offset) slots)
x))
(defun check-update (object)
(when (clos-instance-p object)
(let ((class (class-of object)) (signature (std-instance-signature object)))
(unless (or (eq 0 signature) (eq (car signature) (class-effective-slots class))) (update-instance object class signature)))))
;;; Standard instance allocation
(defparameter secret-unbound-value (list "slot unbound"))
(defun instance-slot-p (slot)
(eq (slot-definition-allocation slot) ':instance))
(defun std-allocate-instance (class)
(allocate-std-instance
class
(allocate-slot-storage
(length (class-effective-slots class)) ; class-effective-slots are the instance-slots-p slots
secret-unbound-value)))
;;; Simple vectors are used for slot storage.
(defun allocate-slot-storage (size initial-value)
(make-array size :initial-element initial-value))
;;; Standard instance slot access
;;; N.B. The location of the effective-slots slots in the class metaobject for
;;; standard-class must be determined without making any further slot
;;; references.
(defvar the-slots-of-standard-class) ;standard-class's class-slots
(defvar the-class-standard-class) ;standard-class's class metaobject
;;;
;;; This now returns null, rather than signal an error, if the slot is not found.
;;; This is to enable further searches for class slots by the functions which
;;; use this. -RGC 8/28/01
;;;
(defun slot-location (class slot-name)
(if (and (eq slot-name 'effective-slots)
(eq class the-class-standard-class))
;; (position 'effective-slots the-slots-of-standard-class :key #'slot-definition-name)
7 ;; for optimization, hard-code this
(let* ((slots (class-effective-slots class)))
(do* ((s slots (cdr s))
(x (car s)(car s))
(pos 0))
((null s))
(when (eq (slot-definition-name x) slot-name)
(return pos))
(if (eq (slot-definition-allocation x) ':instance)
(incf pos))))))
(defun shared-slot-location (class slot-name)
(let* ((slots (class-shared-slot-definitions class)))
(do* ((s slots (cdr s))
(x (car s)(car s))
(pos 0 (+ pos 1)))
((null s))
(when (eq (slot-definition-name x) slot-name)
(return pos)))))
;; optimize these by direct calls to inlined uref
(declaim (inline slot-contents (setf slot-contents)))
(defun slot-contents (slots location) (uref slots (+ location 2)) #|(svref slots location)|#)
(defun (setf slot-contents) (new-value slots location)
(setf (uref slots (+ location 2)) new-value)#|(setf (svref slots location) new-value)|#)
(defun std-slot-value (instance slot-name)
(let* ((class (class-of instance))
(location (slot-location class slot-name))
val)
(if location
(setf val (slot-contents (std-instance-slots instance) location))
(progn
(setf location (shared-slot-location class slot-name))
(if location
(setf val (car (slot-contents (class-shared-slots class) location)))
(error "The slot ~S is missing from the class ~S." slot-name class))))
(if (eq secret-unbound-value val)
(error "The slot ~S is unbound in the object ~S." slot-name instance))
val))
;;; Fast method to determine if a lisp object is a standard object.
;;; By our definition, any object which is not a CLOS instance (lisp
;;; primitive types, for example) are of type standard-class.
;;; CLOS instances are of type standard-class if the classes of their
;;; classes are standard-class.
;;; The number of arguments is not checked.
;;; We assume that the class of any object is a clos instance
;;; (for optimization purposes).
;;;
(ccl:defasm standard-class-p (object)
{
push ebp
mov ebp, esp
mov eax, [ebp + ARGS_OFFSET]
mov edx, eax
and edx, 7
cmp edx, uvector-tag
jne short :t-exit
mov edx, [eax - uvector-tag]
shr edx, 3
and edx, #x1f
cmp edx, cl::uvector-clos-instance-tag
jne short :t-exit
mov eax, [eax + (uvector-offset cl::clos-instance-class-offset)]
mov eax, [eax + (uvector-offset cl::clos-instance-class-offset)]
mov edx, 'cl::the-class-standard-class
mov edx, [edx + (uvector-offset cl::symbol-value-offset)]
mov edx, [edx - cons-tag]
cmp edx, eax
jne short :nil-exit
:t-exit
mov eax, [esi + t-offset]
jmp short :exit
:nil-exit
mov eax, [esi]
:exit
pop ebp
ret
})
;;; Fast method to determine if a lisp object is a standard generic function.
(ccl:defasm standard-generic-function-p (object)
{
push ebp
mov ebp, esp
mov eax, [ebp + ARGS_OFFSET]
mov edx, eax
and edx, 7
cmp edx, uvector-tag
jne short :nil-exit
mov edx, [eax - uvector-tag]
shr edx, 3
and edx, #x1f
cmp edx, cl::uvector-clos-instance-tag
jne short :nil-exit
mov eax, [eax + (uvector-offset cl::clos-instance-class-offset)]
mov edx, 'cl::the-class-standard-gf
mov edx, [edx + (uvector-offset cl::symbol-value-offset)]
mov edx, [edx - cons-tag]
cmp edx, eax
jne short :nil-exit
:t-exit
mov eax, [esi + t-offset]
jmp short :exit
:nil-exit
mov eax, [esi]
:exit
pop ebp
ret
})
;;; now patch (SETF SYMBOL-FUNCTION) to store the generic function
;;; in the symbol's function slot. We call the kernel function
;;; first to ensure that the jump table gets setup with the
;;; address of the discrimination function closure.
;;;
(defparameter +save-set-symbol-function+ (fdefinition '(setf symbol-function)))
(defun (setf symbol-function) (value symbol)
(if (standard-generic-function-p value)
(let ((discrimination-function
(uref
(uref value cl::clos-instance-slots-offset)
(+ 2 cl::slot-location-generic-function-discriminating-function))))
(funcall +save-set-symbol-function+ discrimination-function symbol)
;; now replace the function slot of the symbol
(setf (car (uref symbol cl::symbol-function-offset)) value))
(funcall +save-set-symbol-function+ value symbol)))
(defun slot-value (object slot-name) (check-update object)
(if (standard-class-p object)
(std-slot-value object slot-name)
(slot-value-using-class (class-of object) object slot-name)))
;; For fixed known slot positions (optimization) for std-slots
;;
(defun slot-value-with-index (object slot-name index)
(if (standard-class-p object)
(let* ((slots (std-instance-slots object))
(val (svref slots index)))
(if (eq secret-unbound-value val)
(error "The slot ~S is unbound in the object ~S." slot-name object)
val))
(slot-value-using-class (class-of object) object slot-name)))
(defun (setf slot-value-with-index) (new-value object slot-name index)
(if (standard-class-p object)
(let* ((slots (std-instance-slots object)))
(setf (svref slots index) new-value))
(setf-slot-value-using-class
new-value (class-of object) object slot-name)))
(defun (setf std-slot-value) (new-value instance slot-name)
(let* ((class (class-of instance))
(location (slot-location class slot-name)))
(if location
(setf (slot-contents (std-instance-slots instance) location) new-value)
(progn
(setf location (shared-slot-location class slot-name))
(if location
(setf (car (slot-contents (class-shared-slots class) location)) new-value)
(error "The slot ~S is missing from the class ~S." slot-name class))))))
(defun (setf slot-value) (new-value object slot-name) (check-update object)
(if (standard-class-p object)
(setf (std-slot-value object slot-name) new-value)
(setf-slot-value-using-class
new-value (class-of object) object slot-name)))
(defun std-slot-boundp (instance slot-name)
(let* ((class (class-of instance))
(location (slot-location class slot-name)))
(if location
(not (eq secret-unbound-value (slot-contents (std-instance-slots instance) location)))
(progn
(setf location (shared-slot-location class slot-name))
(if location
(not (eq secret-unbound-value (car (slot-contents (class-shared-slots class) location))))
(error "The slot ~S is missing from the class ~S." slot-name class))))))
(defun slot-boundp (object slot-name) (check-update object)
(if (standard-class-p object)
(std-slot-boundp object slot-name)
(slot-boundp-using-class (class-of object) object slot-name)))
(defun std-slot-makunbound (instance slot-name)
(let* ((class (class-of instance))
(location (slot-location class slot-name)))
(if location
(setf (slot-contents (std-instance-slots instance) location) secret-unbound-value)
(progn
(setf location (shared-slot-location class slot-name))
(if location
(setf (car (slot-contents (class-shared-slots class) location)) secret-unbound-value)
(error "The slot ~S is missing from the class ~S." slot-name class)))))
instance)
(defun slot-makunbound (object slot-name) (check-update object)
(if (standard-class-p object)
(std-slot-makunbound object slot-name)
(slot-makunbound-using-class (class-of object) object slot-name)))
(defun std-slot-exists-p (instance slot-name)
(not (null (find slot-name (class-slots (class-of instance))
:key #'slot-definition-name))))
(defun slot-exists-p (object slot-name)
(if (standard-class-p object)
(std-slot-exists-p object slot-name)
(slot-exists-p-using-class (class-of object) object slot-name)))
;;; class-of
(defun class-of (x)
(if (clos-instance-p x)
(std-instance-class x)
(built-in-class-of x)))
;;; N.B. This version of built-in-class-of is straightforward but very slow.
;;; This is only for booting, a faster method is used later -RGC
;;;
(defun built-in-class-of (x)
(typecase x
(null (find-class 'null))
((and symbol (not null)) (find-class 'symbol))
((complex *) (find-class 'complex))
(integer (find-class 'integer))
((float * *) (find-class 'float))
(cons (find-class 'cons))
(character (find-class 'character))
(hash-table (find-class 'hash-table))
(package (find-class 'package))
(pathname (find-class 'pathname))
(readtable (find-class 'readtable))
(stream (find-class 'stream))
(number (find-class 'number))
((string *) (find-class 'string))
((bit-vector *) (find-class 'bit-vector))
((vector * *) (find-class 'vector))
((array * *) (find-class 'array))
(sequence (find-class 'sequence))
(function (find-class 'function))
(t (find-class 't))))
;;; subclassp and sub-specializer-p
(defun subclassp (c1 c2)
(not (null (find c2 (class-precedence-list c1)))))
(defun sub-specializer-p (c1 c2 c-arg)
(let ((cpl (class-precedence-list c-arg)))
(not (null (find c2 (cdr (member c1 cpl)))))))
;;;
;;; Class metaobjects and standard-class
;;;
(defparameter the-defclass-standard-class ;standard-class's defclass form
'(defclass standard-class (class)
((name :initarg :name) ; :accessor class-name
(documentation :initform () :initarg :documentation) ; :accessor class-documentation
(direct-subclasses :initform ()) ; :accessor class-direct-subclasses
(direct-superclasses ; :accessor class-direct-superclasses
:initarg :direct-superclasses)
(class-precedence-list) ; :accessor class-precedence-list
(direct-methods :initform ()) ; :accessor class-direct-methods
(direct-slots) ; :accessor class-direct-slots
(effective-slots) ; :accessor class-effective-slots
(shared-slot-definitions :initform ()) ; :accessor class-shared-slot-definitions
(shared-slots :initform ()) ; :accessor class-shared-slots
(direct-default-initargs :initform () :initarg :direct-default-initargs) ; :accessor class-direct-default-initargs
(effective-default-initargs :initform ())))) ; :accessor class-default-initargs
;;; Defining the metaobject slot accessor function as regular functions
;;; greatly simplifies the implementation without removing functionality.
(defun class-name (class) (std-slot-value class 'name))
(defun (setf class-name) (new-value class) (setf (slot-value class 'name) new-value))
(defun class-documentation (class) (slot-value class 'documentation))
(defun (setf class-documentation) (new-value class)
(setf (slot-value class 'documentation) new-value))
(defun class-direct-superclasses (class) (slot-value class 'direct-superclasses))
(defun (setf class-direct-superclasses) (new-value class)
(setf (slot-value class 'direct-superclasses) new-value))
(defun class-direct-slots (class) (slot-value class 'direct-slots))
(defun (setf class-direct-slots) (new-value class)
(setf (slot-value class 'direct-slots) new-value))
(defun class-precedence-list (class) (slot-value class 'class-precedence-list))
(defun (setf class-precedence-list) (new-value class)
(setf (slot-value class 'class-precedence-list) new-value))
; class-slots generic defined below
(defun class-effective-slots (class) (slot-value class 'effective-slots))
(defun (setf class-effective-slots) (new-value class)
(setf (slot-value class 'effective-slots) new-value))
(defun class-direct-subclasses (class) (slot-value class 'direct-subclasses))
(defun (setf class-direct-subclasses) (new-value class)
(setf (slot-value class 'direct-subclasses) new-value))
(defun class-direct-methods (class) (slot-value class 'direct-methods))
(defun (setf class-direct-methods) (new-value class)
(setf (slot-value class 'direct-methods) new-value))
(defun class-shared-slots (class) (slot-value class 'shared-slots))
(defun (setf class-shared-slots) (new-value class)
(setf (slot-value class 'shared-slots) new-value))
(defun class-shared-slot-definitions (class) (slot-value class 'shared-slot-definitions))
(defun (setf class-shared-slot-definitions) (new-value class)
(setf (slot-value class 'shared-slot-definitions) new-value))
;;; defclass
(defmacro defclass (name direct-superclasses slot-definitions
&rest options)
`(ensure-class ',name
:direct-superclasses
,(canonicalize-direct-superclasses direct-superclasses)
:direct-slots
,(canonicalize-direct-slots slot-definitions)
,@(canonicalize-defclass-options options)))
(defun canonicalize-direct-slots (slot-definitions)
`(list ,@(mapcar #'canonicalize-direct-slot slot-definitions)))
(defun canonicalize-direct-slot (spec)
(if (symbolp spec) `(list :name ',spec)
(let ((name (car spec))
(initfunction nil)
(initform nil)
(initargs ())
(readers ())
(writers ())
(other-options ()))
(do ((olist (cdr spec) (cddr olist)))
((null olist))
(case (car olist)
(:initform
(setq initfunction
`(function (lambda () ,(cadr olist))))
(setq initform `',(cadr olist)))
(:initarg (push-on-end (cadr olist) initargs))
(:reader (push-on-end (cadr olist) readers))
(:writer (push-on-end (cadr olist) writers))
(:accessor
(push-on-end (cadr olist) readers)
(push-on-end `(setf ,(cadr olist)) writers))
(otherwise
(push-on-end `',(car olist) other-options)
(push-on-end `',(cadr olist) other-options))))
`(list
:name ',name
,@(when initfunction
`(:initform ,initform :initfunction ,initfunction))
,@(when initargs `(:initargs ',initargs))
,@(when readers `(:readers ',readers))
,@(when writers `(:writers ',writers))
,@other-options))))
(defun canonicalize-direct-superclasses (direct-superclasses)
`(list ,@(mapcar #'canonicalize-direct-superclass direct-superclasses)))
(defun canonicalize-direct-superclass (class-name)
`(find-class ',class-name))
(defun canonicalize-defclass-options (options)
(mapappend #'canonicalize-defclass-option options))
(defun canonicalize-defclass-option (option)
(case (car option)
(:metaclass
(list ':metaclass
`(find-class ',(cadr option))))
(:documentation (list ':documentation `',(cadr option)))
(:default-initargs
(list
':direct-default-initargs
`(list ,@(mapplist
#'(lambda (key value)
`(list ',key ',value #'(lambda () ,value)))
(cdr option)))))
(t (list `',(car option) `',(cdr option)))))
;;; find-class
(let ((class-table (make-hash-table :test #'eq :synchronized t)))
(defun find-class (symbol &optional (errorp t)(environment nil))
(declare (ignore environment))
(let ((class (gethash symbol class-table nil)))
(if (and (null class) errorp)
(error "No class named ~S." symbol)
class)))
(defun (setf find-class) (new-value symbol)
(setf (gethash symbol class-table) new-value))
(defun forget-all-classes ()
(clrhash class-table)
(values))
) ;end let class-table
;;; Ensure class
(defun ensure-class (name &rest all-keys
&key (metaclass the-class-standard-class)
&allow-other-keys)
(let ((class (apply (if (eq metaclass the-class-standard-class)
#'make-instance-standard-class
#'make-instance)
metaclass :name name all-keys)))
(setf (find-class name) class)
class))
;;; make-instance-standard-class creates and initializes an instance of
;;; standard-class without falling into method lookup. However, it cannot be
;;; called until standard-class itself exists.
(defun make-instance-standard-class (metaclass
&key name direct-superclasses direct-slots &allow-other-keys)
(declare (ignore metaclass))
(let ((class (std-allocate-instance the-class-standard-class)))
(setf (class-name class) name)
(setf (class-documentation class) ())
(setf (class-direct-subclasses class) ())
(setf (class-direct-methods class) ())
(setf (slot-value class 'direct-default-initargs) ()) ; default initargs accessor methods defined later
(setf (slot-value class 'effective-default-initargs) ())
(std-after-initialization-for-classes class
:direct-slots direct-slots
:direct-superclasses direct-superclasses)
(std-finalize-inheritance class)
class))
(defun std-after-initialization-for-classes (class
&key direct-superclasses direct-slots (documentation nil supp) &allow-other-keys)
;; update class hierarchy
(let ((supers
(or direct-superclasses
(list (find-class 'standard-object)))))
(setf (class-direct-superclasses class) supers)
(dolist (superclass supers)
(pushnew class (class-direct-subclasses superclass)))) ; pushnew to add
(let ((slots
(mapcar #'(lambda (slot-properties)
(apply #'make-direct-slot-definition
slot-properties))
direct-slots)))
(setf (class-direct-slots class) slots)
(dolist (direct-slot slots)
(dolist (reader (slot-definition-readers direct-slot))
(add-reader-method
class reader (slot-definition-name direct-slot)))
(dolist (writer (slot-definition-writers direct-slot))
(add-writer-method
class writer (slot-definition-name direct-slot)))))
(when (and supp (or (stringp documentation) (not documentation))) (setf (documentation (class-name class) 'type) documentation))
(values))
;;; Slot definition metaobjects
;;; N.B. Quietly retain all unknown slot options (rather than signaling an
;;; error), so that it's easy to add new ones.
;;; This is used for shared slots as well. -RGC
(defun make-direct-slot-definition
(&rest properties
&key name (initargs ()) (initform nil) (initfunction nil)
(readers ()) (writers ()) (allocation :instance)
&allow-other-keys)
(let ((slot (copy-list properties))) ; Don't want to side effect &rest list
(setf (getf* slot ':name) name)
(setf (getf* slot ':initargs) initargs)
(setf (getf* slot ':initform) initform)
(setf (getf* slot ':initfunction) initfunction)
(setf (getf* slot ':readers) readers)
(setf (getf* slot ':writers) writers)
(setf (getf* slot ':allocation) allocation)
(when (eq allocation :class) (setf (getf* slot ':shared-slot) (list secret-unbound-value)))
slot))
(defun make-effective-slot-definition
(&rest properties
&key name (initargs ()) (initform nil) (initfunction nil)
(allocation :instance)
&allow-other-keys)
(let ((slot (copy-list properties))) ; Don't want to side effect &rest list
(setf (getf* slot ':name) name)
(setf (getf* slot ':initargs) initargs)
(setf (getf* slot ':initform) initform)
(setf (getf* slot ':initfunction) initfunction)
(setf (getf* slot ':allocation) allocation)
slot))
(defun slot-definition-name (slot) (getf slot ':name))
(defun (setf slot-definition-name) (new-value slot)
(setf (getf* slot ':name) new-value))
(defun slot-definition-initfunction (slot) (getf slot ':initfunction))
(defun (setf slot-definition-initfunction) (new-value slot)
(setf (getf* slot ':initfunction) new-value))
(defun slot-definition-initform (slot) (getf slot ':initform))
(defun (setf slot-definition-initform) (new-value slot)
(setf (getf* slot ':initform) new-value))
(defun slot-definition-initargs (slot) (getf slot ':initargs))
(defun (setf slot-definition-initargs) (new-value slot)
(setf (getf* slot ':initargs) new-value))
(defun slot-definition-readers (slot) (getf slot ':readers))
(defun (setf slot-definition-readers) (new-value slot)
(setf (getf* slot ':readers) new-value))
(defun slot-definition-writers (slot) (getf slot ':writers))
(defun (setf slot-definition-writers) (new-value slot)
(setf (getf* slot ':writers) new-value))
(defun slot-definition-allocation (slot)
(getf slot ':allocation))
(defun (setf slot-definition-allocation) (new-value slot)
(setf (getf* slot ':allocation) new-value))
(defun slot-definition-documentation (slot) (getf slot ':documentation))
(defun (setf slot-definition-documentation) (new-value slot)
(setf (getf* slot ':documentation) new-value))
(defun slot-definition-shared-slot (slot) (getf slot ':shared-slot))
;;; finalize-inheritance
(defun finalize-inheritance (class) (std-finalize-inheritance class))
; Delete either the slot class-shared-slot-definitions or class-shared-slots as shared slots are in both
; but leave for compatibility and speed? for now.
(defun std-finalize-inheritance (class)
(setf (class-precedence-list class) (compute-class-precedence-list class))
(let* ((class-slots (compute-slots class)) (shared-defs (remove-if #'instance-slot-p class-slots))
(shared-slots (when shared-defs (allocate-slot-storage (length shared-defs) ()))))
(setf (class-effective-slots class) (remove-if-not #'instance-slot-p class-slots)
(class-shared-slot-definitions class) shared-defs
(class-shared-slots class) shared-slots)
(dotimes (i (length shared-defs)) (setf (slot-contents shared-slots i) (slot-definition-shared-slot (nth i shared-defs)))))
(values))
(defun class-finalized-p (class) (typecase class (standard-class (and (slot-boundp class 'effective-slots) class)) (specializer class))) ; nil for forward referenced classes
(defun update-instance (instance class signature)
(let* ((local (mapcar #'slot-definition-name (car signature))) (shared (mapcar #'slot-definition-name (cadr signature)))
(p-slot-value (mapappend #'list (append local shared)
(append (coerce (std-instance-slots instance) 'list)
(mapcar #'(lambda (x) (car (slot-definition-shared-slot x))) (cadr signature)))))
(class-effective-slots (class-effective-slots class)) (class-shared-slot-definitions (class-shared-slot-definitions class))
(class-local (mapcar #'slot-definition-name class-effective-slots))
(class-shared (mapcar #'slot-definition-name class-shared-slot-definitions)))
(setf (std-instance-slots instance) (allocate-slot-storage (length class-local) secret-unbound-value))
(setf (std-instance-signature instance)
(list class-effective-slots class-shared-slot-definitions)) ; we'll next use setf on slot-value
(dolist (slot class-local)
(multiple-value-bind (ignore val foundp) (get-properties p-slot-value (list slot)) (declare (ignore ignore))
(and foundp (setf (slot-value instance slot) val))))
(let ((discarded (set-difference local class-local)))
(update-instance-for-redefined-class instance
(set-difference (set-difference class-local local) shared)
(set-difference discarded class-shared)
(apply #'append (mapplist #'(lambda (x y) (when (and (not (eq y secret-unbound-value)) (member x discarded)) (list x y))) p-slot-value))))))
(defun remove-from-deleted-classes (class new-superclasses)
(mapc #'(lambda (x) (setf (class-direct-subclasses x) (remove class (class-direct-subclasses x))))
(set-difference (class-direct-superclasses class) new-superclasses)))
(defun collect-subclasses (class)
(do* ((subs (reverse (class-direct-subclasses class))
(mapappend #'(lambda (x) (reverse (class-direct-subclasses x))) subs))
(all subs (append all subs)))
((not subs) (delete-duplicates all))))
;;; Class precedence lists
(defun compute-class-precedence-list (class) (std-compute-class-precedence-list class))
(defun std-compute-class-precedence-list (class)
(let ((classes-to-order (collect-superclasses* class)))
(topological-sort classes-to-order
(remove-duplicates
(mapappend #'local-precedence-ordering
classes-to-order))
#'std-tie-breaker-rule)))
;;; topological-sort implements the standard algorithm for topologically
;;; sorting an arbitrary set of elements while honoring the precedence
;;; constraints given by a set of (X,Y) pairs that indicate that element
;;; X must precede element Y. The tie-breaker procedure is called when it
;;; is necessary to choose from multiple minimal elements; both a list of
;;; candidates and the ordering so far are provided as arguments.
(defun topological-sort (elements constraints tie-breaker)
(let ((remaining-constraints constraints)
(remaining-elements elements)
(result ()))
(loop
(let ((minimal-elements
(remove-if
#'(lambda (class)
(member class remaining-constraints
:key #'cadr))
remaining-elements)))
(when (null minimal-elements)
(if (null remaining-elements)
(return-from topological-sort result)
(error "Inconsistent precedence graph.")))
(let ((choice (if (null (cdr minimal-elements))
(car minimal-elements)
(funcall tie-breaker
minimal-elements
result))))
(setq result (append result (list choice)))
(setq remaining-elements
(remove choice remaining-elements))
(setq remaining-constraints
(remove choice
remaining-constraints
:test #'member)))))))
;;; In the event of a tie while topologically sorting class precedence lists,
;;; the CLOS Specification says to "select the one that has a direct subclass
;;; rightmost in the class precedence list computed so far." The same result
;;; is obtained by inspecting the partially constructed class precedence list
;;; from right to left, looking for the first minimal element to show up among
;;; the direct superclasses of the class precedence list constituent.
;;; (There's a lemma that shows that this rule yields a unique result.)
(defun std-tie-breaker-rule (minimal-elements cpl-so-far)
(dolist (cpl-constituent (reverse cpl-so-far))
(let* ((supers (class-direct-superclasses cpl-constituent))
(common (intersection minimal-elements supers)))
(when (not (null common))
(return-from std-tie-breaker-rule (car common))))))
;;; This version of collect-superclasses* isn't bothered by cycles in the class
;;; hierarchy, which sometimes happen by accident.
(defun collect-superclasses* (class)
(labels ((all-superclasses-loop (seen superclasses)
(let ((to-be-processed
(set-difference superclasses seen)))
(if (null to-be-processed)
superclasses
(let ((class-to-process
(car to-be-processed)))
(all-superclasses-loop
(cons class-to-process seen)
(union (class-direct-superclasses
class-to-process)
superclasses)))))))
(all-superclasses-loop () (list class))))
;;; The local precedence ordering of a class C with direct superclasses C_1,
;;; C_2, ..., C_n is the set ((C C_1) (C_1 C_2) ...(C_n-1 C_n)).
(defun local-precedence-ordering (class)
(mapcar #'list
(cons class
(butlast (class-direct-superclasses class)))
(class-direct-superclasses class)))
;;; Slot inheritance
(defun compute-slots (class) (std-compute-slots class))
(defun std-compute-slots (class)
(let* ((all-slots (nreverse (mapappend #'class-direct-slots
(reverse (class-precedence-list class)))))
(all-names (remove-duplicates
(mapcar #'slot-definition-name all-slots))))
(nreverse (mapcar #'(lambda (name)
(compute-effective-slot-definition
class
(remove name all-slots
:key #'slot-definition-name
:test-not #'eq)))
all-names))))
(defun compute-effective-slot-definition (class direct-slots) (std-compute-effective-slot-definition class direct-slots))
(defun std-compute-effective-slot-definition (class direct-slots)
(let* ((initer (find-if-not #'null direct-slots
:key #'slot-definition-initfunction))
(doc (find-if-not #'null direct-slots
:key #'slot-definition-documentation))
(first-slot (car direct-slots))
(alloc (slot-definition-allocation first-slot))
(slot (make-effective-slot-definition
:name (slot-definition-name first-slot)
:initform (when initer (slot-definition-initform initer))
:initfunction (when initer (slot-definition-initfunction initer))
:initargs (remove-duplicates (mapappend #'slot-definition-initargs direct-slots))
:allocation alloc)))
(when (eq alloc :class)
(let ((shared-slot (slot-definition-shared-slot first-slot)))
(setf (getf* slot :shared-slot) shared-slot)
(when (member shared-slot (class-direct-slots class) :key #'slot-definition-shared-slot)
(let ((old-shared-slot (and (class-finalized-p class)
(slot-definition-shared-slot (find (slot-definition-name slot) (class-shared-slot-definitions class)
:key #'slot-definition-name)))))
(setf (car shared-slot) (if old-shared-slot (car old-shared-slot) (if initer (funcall (slot-definition-initfunction initer)) secret-unbound-value)))))))
(when doc (setf (getf* slot :documentation) (slot-definition-documentation doc)))
slot))
;;;
;;; Generic function metaobjects and standard-generic-function
;;;
(defparameter the-defclass-generic-function
'(defclass generic-function (metaobject)))
(defparameter the-defclass-standard-generic-function
'(defclass standard-generic-function (generic-function)
( ; (name :initarg :name) ; name from metaobject :accessor generic-function-name
(lambda-list ; :accessor generic-function-lambda-list
:initarg :lambda-list)
(required-args ; :accessor generic-function-required-args
:initarg :required-args)
(methods :initform ()) ; :accessor generic-function-methods
(method-class ; :accessor generic-function-method-class
:initarg :method-class)
(discriminating-function) ; :accessor generic-function-
; -discriminating-function
(classes-to-emf-table ; :accessor classes-to-emf-table
:initform (make-method-table))
(method-combination :initarg :method-combination :initform 'standard) ; :accessor generic-function-method-combination
(method-combination-order :initform ':most-specific-first)))) ; :accessor generic-function-method-combination-order
(defvar the-class-gf) ;generic-function's class metaobject
(defvar the-class-standard-gf) ;standard-generic-function's class metaobject
(defun generic-function-name (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'name slot-location-generic-function-name)
(slot-value gf 'name)))
(defun (setf generic-function-name) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'name slot-location-generic-function-name)
new-value)
(setf (slot-value gf 'name) new-value)))
(defun generic-function-required-args (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'required-args
slot-location-generic-function-required-args)
(slot-value gf 'required-args)))
(defun (setf generic-function-required-args) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf
'required-args slot-location-generic-function-required-args)
new-value)
(setf (slot-value gf 'required-args) new-value)))
(defun generic-function-lambda-list (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'lambda-list
slot-location-generic-function-lambda-list)
(slot-value gf 'lambda-list)))
(defun (setf generic-function-lambda-list) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(progn
(setf (generic-function-required-args gf)
(getf (analyze-lambda-list new-value) ':required-args))
(setf (slot-value-with-index gf 'lambda-list
slot-location-generic-function-lambda-list)
new-value))
(setf (slot-value gf 'lambda-list) new-value)))
(defun generic-function-methods (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'methods slot-location-generic-function-methods)
(slot-value gf 'methods)))
(defun (setf generic-function-methods) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'methods slot-location-generic-function-methods)
new-value)
(setf (slot-value gf 'methods) new-value)))
(defun generic-function-discriminating-function (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'discriminating-function
slot-location-generic-function-discriminating-function)
(slot-value gf 'discriminating-function)))
(defun (setf generic-function-discriminating-function) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'discriminating-function
slot-location-generic-function-discriminating-function)
new-value)
(setf (slot-value gf 'discriminating-function) new-value)))
(defun generic-function-method-class (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'method-class
slot-location-generic-function-method-class)
(slot-value gf 'method-class)))
(defun (setf generic-function-method-class) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'method-class
slot-location-generic-function-method-class)
new-value)
(setf (slot-value gf 'method-class) new-value)))
;;; Internal accessor for effective method function table
(defun classes-to-emf-table (gf)
(if (eq (class-of gf) the-class-standard-gf)
(slot-value-with-index gf 'classes-to-emf-table
slot-location-generic-function-classes-to-emf-table)
(slot-value gf 'classes-to-emf-table)))
(defun (setf classes-to-emf-table) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'classes-to-emf-table
slot-location-generic-function-classes-to-emf-table)
new-value)
(setf (slot-value gf 'classes-to-emf-table) new-value)))
(defun (setf generic-function-method-combination) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'method-combination
slot-location-generic-function-method-combination)
new-value)
(setf (slot-value gf 'method-combination) new-value)))
(defun (setf generic-function-method-combination-order) (new-value gf)
(if (eq (class-of gf) the-class-standard-gf)
(setf (slot-value-with-index gf 'method-combination-order
slot-location-generic-function-method-combination-order)
new-value)
(setf (slot-value gf 'method-combination-order) new-value)))
;;;
;;; Method metaobjects and standard-method
;;;
(defparameter the-defclass-standard-method
'(defclass standard-method (method)
((qualifiers :initarg :qualifiers) ; :accessor method-qualifiers
(lambda-list :initarg :lambda-list) ; :accessor method-lambda-list
(specializers :initarg :specializers) ; :accessor method-specializers
(body :initarg :body) ; :accessor method-body
(generic-function :initform nil) ; :accessor method-generic-function
(function) ; :accessor method-function
(environment :initarg :environment)))) ; :accessor method-environment
(defvar the-class-standard-method) ;standard-method's class metaobject
(defun method-lambda-list (method) (slot-value method 'lambda-list))
(defun (setf method-lambda-list) (new-value method)
(setf (slot-value method 'lambda-list) new-value))
(defun method-qualifiers (method) (slot-value method 'qualifiers))
(defun (setf method-qualifiers) (new-value method)
(setf (slot-value method 'qualifiers) new-value))
(defun method-specializers (method) (slot-value method 'specializers))
(defun (setf method-specializers) (new-value method)
(setf (slot-value method 'specializers) new-value))
(defun method-body (method) (slot-value method 'body))
(defun (setf method-body) (new-value method)
(setf (slot-value method 'body) new-value))
(defun method-environment (method) (slot-value method 'environment))
(defun (setf method-environment) (new-value method)
(setf (slot-value method 'environment) new-value))
(defun method-generic-function (method)
(slot-value method 'generic-function))
(defun (setf method-generic-function) (new-value method)
(setf (slot-value method 'generic-function) new-value))
(defun method-function (method) (slot-value method 'function))
(defun (setf method-function) (new-value method)
(setf (slot-value method 'function) new-value))
;;;
;;; Common Lisp DEFGENERIC macro
;;;
(defmacro defgeneric (function-name lambda-list &rest options)
(flet ((is-method-option (opt) (eq (car opt) :method))
(method-definition-form (opt) `(defmethod ,function-name ,@(cdr opt))))
(let* ((method-definitions (mapcar #'method-definition-form (remove-if (complement #'is-method-option) options)))
(non-method-options (remove-if #'is-method-option options))
(documentation-form
(let ((doc-string (cadr (find-if #'(lambda (opt) (eq (car opt) :documentation)) non-method-options))))
(when doc-string `(setf (documentation ',function-name 'function) ,doc-string)))))
`(prog1
(ensure-generic-function
',function-name
:lambda-list ',lambda-list
,@(canonicalize-defgeneric-options non-method-options))
,(when documentation-form documentation-form)
,@method-definitions
))))
(defun canonicalize-defgeneric-options (options)
(mapappend #'canonicalize-defgeneric-option options))
(defun canonicalize-defgeneric-option (option)
(case (car option)
(:generic-function-class
(list ':generic-function-class
`(find-class ',(cadr option))))
(:method-class
(list ':method-class
`(find-class ',(cadr option))))
(:method-combination
`(:method-combination ',(cadr option)))
(t (list `',(car option) `',(cadr option)))))
;;; find-generic-function looks up a generic function by name. It's an
;;; artifact of the fact that our generic function metaobjects can't legally
;;; be stored a symbol's function value.
(let ((generic-function-table (make-hash-table :test #'equal :synchronized t)))
(defun find-generic-function (symbol &optional (errorp t))
(if (consp symbol)
(if (and (eq (car symbol) 'SETF)(symbolp (cadr symbol)))
(let ((setf-func (get-setf-function (cadr symbol))))
(if (and (symbolp setf-func) (fboundp setf-func))
(setf setf-func (symbol-function setf-func)))
(if (and setf-func (standard-generic-function-p setf-func))
(return-from find-generic-function setf-func)))
(error "Invalid generic function name: ~S" symbol))
(if (fboundp symbol)
(let ((func (symbol-function symbol)))
(if (standard-generic-function-p func)
(return-from find-generic-function func)))))
(let ((gf (gethash symbol generic-function-table nil)))
(if (and (null gf) errorp)
(error "No generic function named ~S." symbol)
gf)))
(defun (setf find-generic-function) (func symbol)
(if (standard-generic-function-p func)
(if (consp symbol)
(if (and (eq (car symbol) 'SETF)(symbolp (cadr symbol)))
(let ((setter-name (cl::setf-function-symbol symbol)))
(setf (symbol-function setter-name) func)
(register-setf-function (cadr symbol) setter-name))
(error "Invalid generic function name: ~S" symbol))
(setf (symbol-function symbol) func))
(setf (gethash symbol generic-function-table) func)))
(defun forget-all-generic-functions ()
(clrhash generic-function-table)
(values))
) ;end let generic-function-table
;;; ensure-generic-function
(defun ensure-generic-function
(function-name
&rest all-keys
&key (generic-function-class the-class-standard-gf)
(method-class the-class-standard-method)
lambda-list
&allow-other-keys)
(if (find-generic-function function-name nil)
(find-generic-function function-name)
(let ((gf (apply (if (eq generic-function-class the-class-standard-gf)
#'make-instance-standard-generic-function
#'make-instance)
generic-function-class
:name function-name
:method-class method-class
:required-args (getf (analyze-lambda-list lambda-list) ':required-args)
all-keys)))
(setf (find-generic-function function-name) gf)
gf)))
;;; finalize-generic-function
;;; Same basic idea as finalize-inheritance.
;;; Takes care of recomputing and storing the discriminating
;;; function, and clearing the effective method function table.
(defun finalize-generic-function (gf)
(setf (generic-function-discriminating-function gf)
(funcall (if (eq (class-of gf) the-class-standard-gf)
#'std-compute-discriminating-function
#'compute-discriminating-function)
gf))
(unless (standard-generic-function-p gf)
(setf (fdefinition (generic-function-name gf))
(generic-function-discriminating-function gf)))
(clear-method-table (classes-to-emf-table gf))
(values))
;;; make-instance-standard-generic-function creates and initializes an
;;; instance of standard-generic-function without falling into method lookup.
;;; However, it cannot be called until standard-generic-function exists.
(defun make-instance-standard-generic-function
(generic-function-class
&key
name
documentation
lambda-list
method-class
(method-combination 'standard)
(method-combination-order ':most-specific-first)
&allow-other-keys)
(declare (ignore generic-function-class))
(let ((gf (std-allocate-instance the-class-standard-gf)))
(setf (generic-function-name gf) name)
(setf (class-documentation gf) documentation)
(setf (generic-function-lambda-list gf) lambda-list)
(setf (generic-function-methods gf) ())
(setf (generic-function-method-class gf) method-class)
(setf (classes-to-emf-table gf) (make-method-table))
(setf (generic-function-method-combination gf) method-combination)
(setf (generic-function-method-combination-order gf) method-combination-order)
(finalize-generic-function gf)
gf))
;;; defmethod
(defmacro defmethod (&rest args)
(multiple-value-bind (function-name qualifiers
lambda-list specializers body)
(parse-defmethod args)
`(ensure-method (find-generic-function ',function-name nil)
:generic-function-name ',function-name
:lambda-list ',lambda-list
:qualifiers ',qualifiers
:specializers ,(canonicalize-specializers specializers)
:body ',body
:environment (funcall (lambda () (cl::capture-compiler-environment)))#| nil |#
#| :eql-specializers (some #'(lambda (x) (and (listp x)(eq (car x) 'EQL))) ',specializers) |#)))
(defun canonicalize-specializers (specializers)
`(list ,@(mapcar #'canonicalize-specializer specializers)))
(defun canonicalize-specializer (specializer)
(if (and (listp specializer) (eq (car specializer) 'eql)) `(intern-eql-specializer ,(cadr specializer) ',(cadr specializer))
`(find-class ',specializer)))
(defun specalization-vars (specialized-lambda-list)
(let ((vars '()))
(dolist (x specialized-lambda-list (nreverse vars))
(if (member x lambda-list-keywords)
(return (nreverse vars))
(if (consp x)
(push (car x) vars))))))
(defun create-ignorable-decls (vars)
`(declare (ignorable ,@vars)))
(defun parse-defmethod (args)
(let ((fn-spec (car args))
(qualifiers ())
(specialized-lambda-list nil)
(body '())
(decls '())
(doc-string nil)
(parse-state :qualifiers))
(do* ((a (cdr args))
(arg (car a)(car a)))
((null a))
(cond
((eq parse-state :qualifiers)
(if (and (atom arg) (not (null arg)))
(progn
(push-on-end arg qualifiers)
(setf a (cdr a)))
(setq parse-state :lambda-list)))
((eq parse-state :lambda-list)
(setq specialized-lambda-list arg)
(setq parse-state :decls-and-doc-string)
(setf a (cdr a)))
((eq parse-state :decls-and-doc-string)
(if (and (null doc-string) (stringp arg))
(setq doc-string arg a (cdr a))
(if (and (consp arg)(eq (car arg) 'declare))
(progn
(push-on-end arg decls)
(setf a (cdr a)))
(setq parse-state :body))))
((eq parse-state :body)
(push-on-end arg body)
(setf a (cdr a)))))
;; watch for case where a literal string is the only item in body--
;; we don't want to mistake it for a doc-string
(if (and (null body) doc-string)
(setf body (list doc-string) doc-string nil))
(values fn-spec
qualifiers
(extract-lambda-list specialized-lambda-list)
(extract-specializers specialized-lambda-list)
;; add IGNORABLE declarations to specializers so they don't cause
;; warnings if they are not referenced in generated lambdas
`(,@(cons (create-ignorable-decls (specalization-vars specialized-lambda-list))
decls)
,@(if doc-string (list doc-string))
(block
,(if (consp fn-spec) (cadr fn-spec) fn-spec)
,@body)))))
;;; Several tedious functions for analyzing lambda lists
(defun gf-required-arglist (gf)
(generic-function-required-args gf))
(defun required-portion (gf args)
(let ((required-args (generic-function-required-args gf))
(new-args nil))
(dolist (x required-args (nreverse new-args))
(declare (ignore x))
(unless (consp args)
(error "Too few arguments to generic function ~S." gf))
(push (car args) new-args)
(setf args (cdr args)))))
(defun num-required-args (gf) (length (generic-function-required-args gf)))
(defun extract-lambda-list (specialized-lambda-list)
(let* ((plist (analyze-lambda-list specialized-lambda-list))
(requireds (getf plist ':required-names))
(rv (getf plist ':rest-var))
(ks (getf plist ':key-args))
(aok (getf plist ':allow-other-keys))
(opts (getf plist ':optional-args))
(auxs (getf plist ':auxiliary-args)))
`(,@requireds
,@(if opts `(&optional ,@opts) ())
,@(if rv `(&rest ,rv) ())
,@(if (or ks aok) `(&key ,@ks) ())
,@(if aok '(&allow-other-keys) ())
,@(if auxs `(&aux ,@auxs) ()))))
(defun extract-specializers (specialized-lambda-list)
(let ((plist (analyze-lambda-list specialized-lambda-list)))
(getf plist ':specializers)))
(defun analyze-lambda-list (lambda-list)
(labels ((make-keyword (symbol)
(intern (symbol-name symbol)
(find-package 'keyword)))
(get-keyword-from-arg (arg)
(if (listp arg)
(if (listp (car arg))
(caar arg)
(make-keyword (car arg)))
(make-keyword arg))))
(let ((keys ()) ; Just the keywords
(key-args ()) ; Keywords argument specs
(required-names ()) ; Just the variable names
(required-args ()) ; Variable names & specializers
(specializers ()) ; Just the specializers
(rest-var nil)
(optionals ())
(auxs ())
(allow-other-keys nil)
(state :parsing-required))
(dolist (arg lambda-list)
(if (member arg lambda-list-keywords)
(ecase arg
(&optional
(setq state :parsing-optional))
(&rest
(setq state :parsing-rest))
(&key
(setq state :parsing-key))
(&allow-other-keys
(setq allow-other-keys 't))
(&aux
(setq state :parsing-aux)))
(case state
(:parsing-required
(push-on-end arg required-args)
(if (listp arg)
(progn (push-on-end (car arg) required-names)
(push-on-end (cadr arg) specializers))
(progn (push-on-end arg required-names)
(push-on-end 't specializers))))
(:parsing-optional (push-on-end arg optionals))
(:parsing-rest (setq rest-var arg))
(:parsing-key
(push-on-end (get-keyword-from-arg arg) keys)
(push-on-end arg key-args))
(:parsing-aux (push-on-end arg auxs)))))
(list :required-names required-names
:required-args required-args
:specializers specializers
:rest-var rest-var
:keywords keys
:key-args key-args
:auxiliary-args auxs
:optional-args optionals
:allow-other-keys allow-other-keys))))
;;; ensure method
(defun ensure-method (gf &rest all-keys #| &key eql-specializers &allow-other-keys |#)
(if (null gf)
;; define a generic function on the fly
(setf gf
(ensure-generic-function
(getf all-keys :generic-function-name)
':lambda-list (getf all-keys :lambda-list))))
;; as soon as we define one method with an EQL specifier, we assume
;; methods of that generic function may specify this way
;(if eql-specializers ** redundantly too soon as add-method has to, for it can be called by the user
; (setf (method-table-eql-specializers (classes-to-emf-table gf)) t))
(let ((new-method
(apply
(if (eq (generic-function-method-class gf)
the-class-standard-method)
#'make-instance-standard-method
#'make-instance)
(generic-function-method-class gf)
all-keys)))
(setf (class-name new-method) (getf all-keys :generic-function-name))
(add-method gf new-method)
new-method))
;;; make-instance-standard-method creates and initializes an instance of
;;; standard-method without falling into method lookup. However, it cannot
;;; be called until standard-method exists.
(defun make-instance-standard-method (method-class
&key lambda-list qualifiers
specializers body environment
&allow-other-keys)
(declare (ignore method-class))
(let ((method (std-allocate-instance the-class-standard-method)))
(setf (method-lambda-list method) lambda-list)
(setf (class-documentation method) (when (stringp (cadr body)) (cadr body)))
(setf (method-qualifiers method) qualifiers)
(setf (method-specializers method) specializers)
(setf (method-body method) body)
(setf (method-environment method) environment)
(setf (method-generic-function method) nil)
(setf (method-function method)
(std-compute-method-function method))
method))
;;; add-method
;;; This version first removes any existing method on the generic function
;;; with the same qualifiers and specializers.
(defun eql-specializer-p (x) (declare (ignore x))) ; redefined below
(defun add-method (gf method)
(let ((old-method
(find-method gf (method-qualifiers method)
(method-specializers method) nil)))
(when old-method (remove-method gf old-method)))
(setf (method-generic-function method) gf)
(push method (generic-function-methods gf))
(dolist (specializer (method-specializers method))
(when (eql-specializer-p specializer)
(setf (method-table-eql-specializers (classes-to-emf-table gf)) t)) ; set to t to recalculate eqls
(pushnew method (class-direct-methods specializer)))
(finalize-generic-function gf)
gf) ; add-method should return gf.
(defun remove-method (gf method)
(setf (generic-function-methods gf)
(remove method (generic-function-methods gf)))
(setf (method-generic-function method) nil)
(dolist (class (method-specializers method))
(when (eql-specializer-p class)
(setf (method-table-eql-specializers (classes-to-emf-table gf)) t)) ; set to t to recalculate eqls
(setf (class-direct-methods class)
(remove method (class-direct-methods class))))
(finalize-generic-function gf)
gf) ; remove-method should return gf. Bug when trying to print a deleted method.
(defun find-method (gf qualifiers specializers
&optional (errorp t))
(let ((method
(find-if #'(lambda (method)
(and (equal qualifiers
(method-qualifiers method))
(equal specializers
(method-specializers method))))
(generic-function-methods gf))))
(if (and (null method) errorp)
(error "No such method for ~S." (generic-function-name gf))
method)))
;;; Reader and write methods
(defun add-reader-method (class fn-name slot-name)
(ensure-method
(ensure-generic-function fn-name :lambda-list '(object))
:lambda-list '(object)
:qualifiers ()
:specializers (list class)
:body `((slot-value object ',slot-name))
:environment (top-level-environment))
(values))
(defun add-class-slot-reader-method (class fn-name slot-name index)
(declare (ignore slot-name))
(ensure-method
(ensure-generic-function fn-name :lambda-list '(object))
:lambda-list '(object)
:qualifiers ()
:specializers (list class)
:body `((let* ((class (class-of object))
(val (car (aref (slot-value class 'shared-slots) ,index))))
(if (eq secret-unbound-value val)
(error "The class slot ~S is unbound in the class ~S." ',slot-name (class-name class))
val)))
:environment (top-level-environment))
(values))
(defun add-writer-method (class fn-name slot-name)
(ensure-method
(ensure-generic-function
fn-name :lambda-list '(new-value object))
:lambda-list '(new-value object)
:qualifiers ()
:specializers (list (find-class 't) class)
:body `((setf (slot-value object ',slot-name)
new-value))
:environment (top-level-environment))
(values))
(defun add-class-slot-writer-method (class fn-name slot-name index)
(declare (ignore slot-name))
(ensure-method
(ensure-generic-function
fn-name :lambda-list '(new-value object))
:lambda-list '(new-value object)
:qualifiers ()
:specializers (list (find-class 't) class)
:body `((setf (car (aref (slot-value (class-of object) 'shared-slots) ,index))
new-value))
:environment (top-level-environment))
(values))
(defun remove-read-write-methods (class)
(mapc #'(lambda (x)
(mapc #'(lambda (x)
(let* ((gf (find-generic-function x))
(meth (find-method gf () (if (= 2 (length (generic-function-required-args gf))) (list (find-class t) class) (list class)) nil)))
(when meth (remove-method gf meth))))
(append (slot-definition-readers x) (slot-definition-writers x))))
(class-direct-slots class)))
(defun convert-function-to-method (function-name method-lambda-list)
(eval (let* ((function-symbol (if (and (consp function-name) (eq 'setf (car function-name)))
(get-setf-function (cadr function-name))
function-name))
(meth (gensym))
(args (analyze-lambda-list method-lambda-list))
(args (append (getf args :required-names)
(mapcar #'(lambda (x) (if (consp x) (car x) x)) (getf args :optional-args))
(mapappend #'list (getf args :keywords) (getf args :key-args)) (list (getf args :rest-var)))))
`(prog1 (defmethod ,meth ,method-lambda-list (apply #',meth ,.(butlast args) ,(car (last args))))
(setf (generic-function-name #',meth) ',function-name
(class-name (car (generic-function-methods #',meth))) ',function-name
(getf (function-info-list (fdefinition ',function-name)) 'function-name) ',meth)
(rotatef (symbol-function ',meth) (symbol-function ',function-symbol))))))
;;;
;;; Generic function invocation
;;;
;;; apply-generic-function
(defun apply-generic-function (gf args)
(apply (generic-function-discriminating-function gf) args))
(defun std-compute-discriminating-function (gf &aux (table (classes-to-emf-table gf)) (num (num-required-args gf)))
#'(lambda (&rest args)
(let* ((tail (let ((tail (- (length args) num))) (if (minusp tail) (error "Too few arguments to generic function ~S." gf) tail)))
(eqls (if (listp (method-table-eql-specializers table)) (method-table-eql-specializers table)
(let ((eqls (make-list num)))
(dolist (meth (generic-function-methods gf) (setf (method-table-eql-specializers table)
(when (member-if #'consp eqls) eqls)))
(do ((specs (method-specializers meth) (cdr specs)) (eqls eqls (cdr eqls)))
((not specs))
(when (eql-specializer-p (car specs))
(pushnew (list (slot-value (car specs) 'object)) (car eqls)
:test #'(lambda (x y) (eql (car x) (car y))))))))))
(eqls-classes (if eqls (mapcar #'(lambda (arg eqls) (or (car (member arg eqls :key #'car)) (class-of arg))) args eqls)
(mapcar #'class-of (butlast args tail)))))
(funcall (or (find-method-table-method table eqls-classes)
(slow-method-lookup gf table args
(if eqls (mapcar #'(lambda (arg eql-class)
(if (consp eql-class)
(gethash arg *clos-singleton-specializers*)
eql-class)) args eqls-classes)
eqls-classes) eqls-classes)) args))))
(defun slow-method-lookup (gf table args classes eqls-classes)
(let* ((applicable-methods (compute-applicable-methods-using-classes gf classes))
(emfun (if (member-if #'primary-method-p applicable-methods)
(if (eq (class-of gf) the-class-standard-gf)
(std-compute-effective-method-function gf applicable-methods)
(compute-effective-method-function gf applicable-methods))
(error "No primary methods for ~S in the ~S." args gf))))
(add-method-table-method table eqls-classes emfun) emfun))
;;; compute-applicable-methods-using-classes
(defun compute-applicable-methods-using-classes
(gf required-classes)
(sort
(copy-list
(remove-if-not #'(lambda (method)
(every #'subclassp
required-classes
(method-specializers method)))
(generic-function-methods gf)))
#'(lambda (m1 m2)
(funcall
(if (eq (class-of gf) the-class-standard-gf)
#'std-method-more-specific-p
#'method-more-specific-p)
gf m1 m2 required-classes))))
;;; method-more-specific-p
;(setq cl::*compiler-warn-on-dynamic-return* nil)
(defun std-method-more-specific-p (gf method1 method2 required-classes)
(declare (ignore gf))
(do* ((specs1 (method-specializers method1)(cdr specs1))
(specs2 (method-specializers method2)(cdr specs2))
(classes required-classes (cdr classes))
(spec1 (car specs1)(car specs1))
(spec2 (car specs2)(car specs2))
(arg-class (car classes)(car classes)))
((or (endp specs1)(endp specs2)(endp classes)) nil)
(unless (eq spec1 spec2)
(return-from std-method-more-specific-p
(sub-specializer-p spec1 spec2 arg-class)))))
;(setq cl::*compiler-warn-on-dynamic-return* t)
;;; apply-methods and compute-effective-method-function
(defun apply-methods (gf args methods)
(funcall (compute-effective-method-function gf methods)
args))
(defun primary-method-p (method)
(null (method-qualifiers method)))
(defun before-method-p (method)
(equal '(:before) (method-qualifiers method)))
(defun after-method-p (method)
(equal '(:after) (method-qualifiers method)))
(defun around-method-p (method)
(equal '(:around) (method-qualifiers method)))
;;; If the name is a list i.e. (SETF FOO) then this creates a symbolic
;;; representation of the name, suitable as a block label.
(defun generic-func-name (gf)
(let ((gfn (generic-function-name gf)))
(if (symbolp gfn)
gfn
(make-symbol (format nil "~A" gfn)))))
;; new way in Corman Lisp 1.5 release
(defun std-compute-effective-method-function (gf methods)
(let ((primaries (remove-if-not #'primary-method-p methods))
(around (find-if #'around-method-p methods)))
(when (null primaries)
(error "No primary methods for the generic function ~S." gf))
(if around
(let ((next-emfun
(if (eq (class-of gf) the-class-standard-gf)
(std-compute-effective-method-function gf (remove around methods))
(compute-effective-method-function gf (remove around methods)))))
#'(lambda (args)
(funcall (method-function around) args next-emfun)))
(let* ((next-emfun (compute-primary-emfun (cdr primaries)))
(befores (remove-if-not #'before-method-p methods))
(reverse-afters
(reverse (remove-if-not #'after-method-p methods)))
(before-calls
(mapcar #'(lambda (before)
`(funcall ,(method-function before) args nil))
befores))
(after-calls
(mapcar #'(lambda (after)
`(funcall ,(method-function after) args nil))
reverse-afters)))
(if after-calls
(compile nil
`(lambda (args)
(block ,(generic-func-name gf) ;; a named block enables the compiler to
,@before-calls ;; tag the compiled code with the name
(multiple-value-prog1 ;; (for debugging, etc.)
(funcall ,(method-function (car primaries)) args ,next-emfun)
,@after-calls))))
(compile nil
`(lambda (args)
(block ,(generic-func-name gf)
,@before-calls
(funcall ,(method-function (car primaries)) args ,next-emfun)))))))))
;;; compute an effective method function from a list of primary methods:
(defun compute-primary-emfun (methods)
(if (null methods)
nil
(let ((next-emfun (compute-primary-emfun (cdr methods))))
#'(lambda (args)
(funcall (method-function (car methods)) args next-emfun)))))
;;; apply-method and compute-method-function
(defun apply-method (method args next-methods)
(funcall (method-function method)
args
(if (null next-methods)
nil
(compute-effective-method-function
(method-generic-function method) next-methods))))
;;; search a tree for a passed symbol or form
(defun search-tree (tree form)
(if tree
(if (eq tree form)
t
(if (consp tree)
(or (search-tree (car tree) form)
(search-tree (cdr tree) form))))))
(defun std-compute-method-function (method)
(let ((form (macroexpand-all (cons 'progn (method-body method))))
(lambda-list (method-lambda-list method)))
(if (or (search-tree form 'call-next-method)
(search-tree form 'next-method-p))
(compile-in-lexical-environment (method-environment method)
`(lambda (args next-emfun)
(flet ((call-next-method (&rest cnm-args)
(if (null next-emfun)
(error "No next method for the~@
generic function ~S."
(method-generic-function ',method))
(funcall next-emfun (or cnm-args args))))
(next-method-p () (not (null next-emfun))))
(apply #'(lambda ,(kludge-arglist lambda-list) ,@(cdr form)) args))))
(compile-in-lexical-environment (method-environment method)
`(lambda (args next-emfun)
(declare (ignore next-emfun))
(apply #'(lambda ,(kludge-arglist lambda-list) ,@(cdr form)) args))))))
;;; N.B. The function kludge-arglist is used to pave over the differences
;;; between argument keyword compatibility for regular functions versus
;;; generic functions.
;;; RGC--17 Aug 2006--modified to handle &aux lambda list variables.
;;;
(defun kludge-arglist (lambda-list)
(let ((aux-vars (member '&aux lambda-list)))
(if aux-vars
(setq lambda-list (subseq lambda-list 0 (position '&aux lambda-list))))
(if (and (member '&key lambda-list)
(not (member '&allow-other-keys lambda-list)))
(append lambda-list '(&allow-other-keys))
(if (and (not (member '&rest lambda-list))
(not (member '&key lambda-list)))
(append lambda-list '(&key &allow-other-keys) aux-vars)
(append lambda-list aux-vars)))))
;;; Run-time environment hacking (Common Lisp ain't got 'em).
(defun top-level-environment ()
nil) ; Bogus top level lexical environment
(defvar compile-methods nil) ; by default, run everything interpreted
(defun compile-in-lexical-environment (env lambda-expr)
(declare (ignore env))
(if compile-methods
(compile nil lambda-expr)
(eval `(function ,lambda-expr ,env))))
;;;;
;;;; Common Lisp FUNCALL function.
;;;; Modified here to allow Standard-Generic-Functions as the
;;;; first argument.
;;;;
(in-package :x86)
(defasm funcall (func &rest args)
{
push ebp
mov ebp, esp
push edi
push ecx
push ebx
push 0 ;; one cell local storage at [ebp - 16]
cmp ecx, 1
jge short :t1
callp _wrong-number-of-args-error
:t1
mov eax, [ebp + ecx*4 + 4] ;; eax = function
mov edx, eax
and edx, 7
cmp edx, uvector-tag ;; see if func arg is a uvector
je short :t2
push eax
callp _not-a-function-error
:t2
mov edx, [eax - uvector-tag] ;; edx = uvector header
shl edx, 24
shr edx, 27
cmp edx, uvector-symbol-tag ;; see if it is a symbol
jne short :t3
;; get the function that is bound to the symbol
mov eax, [eax + (- (* 4 symbol-function-offset) uvector-tag)]
mov eax, [eax - 4]
mov edx, eax
and edx, 7
cmp edx, uvector-tag
je short :t9
push [ebp + ecx*4 + 4]
callp _not-a-function-error
:t9
mov edx, [eax - uvector-tag] ;; edx = uvector header
shl edx, 24
shr edx, 27
:t3 ;; we now know we have a function in eax, and dl is the type
;; push all the arguments
mov [ebp - 16], esp
mov ebx, ecx
dec ecx
:t4
dec ebx
jle short :t5
push [ebp + ebx*4 + 4]
jmp short :t4
:t5
cmp edx, uvector-function-tag
jne short :t6
:t11
mov edi, [eax + (- (* 4 function-environment-offset) uvector-tag)]
callfunc eax
jmp short :t8
:t6
cmp edx, uvector-kfunction-tag
jne short :t10
mov edi, [esi] ;; environment for kfunctions is always NIL
call [eax + (- (* function-code-buffer-offset 4) uvector-tag)]
jmp short :t8
:t10
cmp edx, uvector-clos-instance-tag
jne short :t7
mov edx, [eax + (uvector-offset cl::clos-instance-class-offset)] ;; edx = clos class
mov ebx, 'cl::the-class-standard-gf
mov ebx, [ebx + (uvector-offset cl::symbol-value-offset)]
mov ebx, [ebx - cons-tag]
cmp ebx, edx ;; class = the-class-standard-gf?
jne short :t7
mov eax, [eax + (uvector-offset cl::clos-instance-slots-offset)] ;; eax = clos class slots
mov eax, [eax + (uvector-offset (+ 2 cl::slot-location-generic-function-discriminating-function))]
jmp short :t11
:t7
push eax
callp _not-a-function-error
:t8
mov esp, [ebp - 16]
pop edi
pop ebx
pop edi
pop edi
mov esp, ebp
pop ebp
ret
})
;;;;
;;;; Common Lisp APPLY function.
;;;; Modified here to allow Standard-Generic-Functions as the
;;;; first argument.
;;;;
(defasm apply (func &rest args)
{
push ebp
mov ebp, esp
push edi
push ecx
push ebx
push 0 ;; one cell local storage at [ebp - 16]
cmp ecx, 2
jge short :t1
callp _wrong-number-of-args-error
:t1
mov eax, [ebp + ecx*4 + 4] ;; eax = function
mov edx, eax
and edx, 7
cmp edx, uvector-tag ;; see if func arg is a uvector
je short :t2
push eax
callp _not-a-function-error
:t2
mov edx, [eax - uvector-tag] ;; edx = uvector header
shl edx, 24
shr edx, 27
cmp edx, uvector-symbol-tag ;; see if it is a symbol
jne short :t4
;; get the function that is bound to the symbol
mov eax, [eax + (- (* 4 symbol-function-offset) uvector-tag)]
mov eax, [eax - 4]
mov edx, eax
and edx, 7
cmp edx, uvector-tag
je short :t3
push [ebp + ecx*4 + 4]
callp _not-a-function-error
:t3
mov edx, [eax - uvector-tag] ;; edx = uvector header
shl edx, 24
shr edx, 27
:t4 ;; we now know we have a function in eax, and dl is the type
;; push all the arguments except the last
mov [ebp - 16], esp
dec ecx
mov ebx, ecx
dec ecx
:t5
dec ebx
jle short :t6
push [ebp + ebx*4 + 8]
jmp short :t5
:t6
;; the last argument is a list of remaining arguments
mov edi, [ebp + ARGS_OFFSET]
:t7
mov ebx, edi
and ebx, 7
cmp ebx, cons-tag ;; is a cons cell?
jne short :t8 ;; if not, exit
push [edi - 4]
inc ecx
mov edi, [edi]
jmp short :t7
:t8
cmp edx, uvector-function-tag
jne short :t9
:t13
mov edi, [eax + (- (* 4 function-environment-offset) uvector-tag)]
callfunc eax
jmp short :t11
:t9
cmp edx, uvector-kfunction-tag
jne short :t12
mov edi, [esi] ;; environment for kfunctions is always NIL
call [eax + (- (* function-code-buffer-offset 4) uvector-tag)]
jmp short :t11
:t12
cmp edx, uvector-clos-instance-tag
jne short :t10
mov edx, [eax + (uvector-offset cl::clos-instance-class-offset)] ;; edx = clos class
mov ebx, 'cl::the-class-standard-gf
mov ebx, [ebx + (uvector-offset cl::symbol-value-offset)]
mov ebx, [ebx - cons-tag]
cmp ebx, edx ;; class = the-class-standard-gf?
jne short :t10
mov eax, [eax + (uvector-offset cl::clos-instance-slots-offset)] ;; eax = clos class slots
mov eax, [eax + (uvector-offset (+ 2 cl::slot-location-generic-function-discriminating-function))]
jmp short :t13
:t10
push eax
callp _not-a-function-error
:t11
mov esp, [ebp - 16]
pop edi ;; remove local storage
pop ebx
pop edi
pop edi
mov esp, ebp
pop ebp
ret
})
;;;;
;;;; Common Lisp FUNCTIONP function.
;;;; Redefined here to add support for generic functions.
;;;;
(defasm functionp (x)
{
push ebp
mov ebp, esp
cmp ecx, 1
jz short :next1
callp _wrong-number-of-args-error
:next1
mov edx, [ebp + ARGS_OFFSET] ;; edx = argument
mov eax, edx
and eax, 7
cmp eax, uvector-tag
jne short :nil-exit
mov eax, [edx - uvector-tag]
cmp al, (tag-byte uvector-kfunction-tag)
jbe short :t-exit
cmp al, (tag-byte uvector-clos-instance-tag)
jne short :nil-exit
mov eax, [edx + (uvector-offset cl::clos-instance-class-offset)] ;; eax = clos class
mov edx, 'cl::the-class-standard-gf
mov edx, [edx + (uvector-offset cl::symbol-value-offset)]
mov edx, [edx - cons-tag]
cmp eax, edx ;; class = the-class-standard-gf?
jne short :nil-exit
:t-exit
mov eax, [esi + t-offset]
jmp short :exit
:nil-exit
mov eax, [esi]
:exit
pop ebp
ret
})
(defasm cl::execution-address (func &rest args)
{
push ebp
mov ebp, esp
push edi
push ebx
cmp ecx, 1
je short :t1
callp _wrong-number-of-args-error
:t1
mov eax, [ebp + ARGS_OFFSET] ;; eax = argument
mov edx, eax
and edx, 7
cmp edx, uvector-tag ;; see if func arg is a uvector
je short :t2
push eax
callp _not-a-function-error
:t2
mov edx, [eax - uvector-tag] ;; edx = uvector header
shl edx, 24
shr edx, 27
cmp edx, uvector-symbol-tag ;; see if it is a symbol
jne short :t3
;; get the function that is bound to the symbol
mov eax, [eax + (uvector-offset symbol-function-offset)]
mov eax, [eax - 4]
mov edx, eax
and edx, 7
cmp edx, uvector-tag
je short :t9
push [ebp + ARGS_OFFSET]
callp _not-a-function-error
:t9
mov edx, [eax - uvector-tag] ;; edx = uvector header
shl edx, 24
shr edx, 27
:t3 ;; we should have a function in eax, and dl is the type
cmp edx, uvector-function-tag
jne short :t6
:t11
mov eax, [eax + (uvector-offset function-code-buffer-offset)]
lea eax, [eax + (uvector-offset compiled-code-execution-offset)] ;; eax = exec address
jmp short :got-addr
:t6
cmp edx, uvector-kfunction-tag
jne short :t10
mov eax, [eax + (uvector-offset function-code-buffer-offset)]
jmp short :got-addr
:t10
cmp edx, uvector-clos-instance-tag
jne short :t7
mov edx, [eax + (uvector-offset cl::clos-instance-class-offset)] ;; edx = clos class
mov ebx, 'cl::the-class-standard-gf
mov ebx, [ebx + (uvector-offset cl::symbol-value-offset)]
mov ebx, [ebx - cons-tag]
cmp ebx, edx ;; class = the-class-standard-gf?
jne short :t7
mov eax, [eax + (uvector-offset cl::clos-instance-slots-offset)] ;; eax = clos class slots
mov eax, [eax + (uvector-offset (+ 2 cl::slot-location-generic-function-discriminating-function))]
jmp short :t11
:t7
push eax
callp _not-a-function-error
:got-addr ;; eax = execution address
mov edx, 0
mov dl, [eax]
cmp dl, #xe9 ;; watch for jump table entry: if so, resolve to real address
jne short :t8
add eax, [eax + 1]
add eax, 5
:t8
test eax, #xf0000000
jne :bignum
shl eax, 3
jmp short :exit
:bignum
push eax
push 8
mov ecx, 1
callf cl::alloc-bignum ;; allocate 1 cell
add esp, 4
pop [eax + (uvector-offset cl::bignum-first-cell-offset)]
:exit
pop ebx
pop edi
mov ecx, 1
mov esp, ebp
pop ebp
ret
})
(in-package :cl)
;;;
;;; Bootstrap
;;;
;(progn ; Extends to end-of-file (to avoid printing intermediate results).
;;(format t "Beginning to bootstrap Closette...")
(forget-all-classes)
(forget-all-generic-functions)
;; How to create the class hierarchy in 10 easy steps:
;; 1. Figure out standard-class's slots.
(setq the-slots-of-standard-class
(mapcar #'(lambda (slotd)
(make-effective-slot-definition
:name (car slotd)
:initargs
(let ((a (getf (cdr slotd) ':initarg)))
(if a (list a) ()))
:initform (getf (cdr slotd) ':initform)
:initfunction
(let ((a (getf (cdr slotd) ':initform)))
(if a #'(lambda () (eval a)) nil))
:allocation ':instance))
(nth 3 the-defclass-standard-class)))
;; 2. Create the standard-class metaobject by hand.
(setq the-class-standard-class
(allocate-std-instance
'tba
(make-array (length the-slots-of-standard-class)
:initial-element secret-unbound-value)))
;; 3. Install standard-class's (circular) class-of link.
(setf (std-instance-class the-class-standard-class)
the-class-standard-class)
;; (It's now okay to use class-... accessor).
;; 4. Fill in standard-class's class-slots.
(setf (class-effective-slots the-class-standard-class) the-slots-of-standard-class)
;; (Skeleton built; it's now okay to call make-instance-standard-class.)
;; 5. Hand build the class t so that it has no direct superclasses.
(setf (find-class 't)
(let ((class (std-allocate-instance the-class-standard-class)))
(setf (class-name class) 't)
(setf (class-documentation class) ())
(setf (class-direct-subclasses class) ())
(setf (class-direct-superclasses class) ())
(setf (class-direct-methods class) ())
(setf (class-direct-slots class) ())
(setf (class-precedence-list class) (list class))
(setf (class-effective-slots class) ())
(setf (class-shared-slot-definitions class) ()) ; Shared Slots Bug
(setf (class-shared-slots class) ())
class))
;; (It's now okay to define subclasses of t.)
;; 6. Create the other superclass of standard-class (i.e., standard-object).
(defclass standard-object (t) ())
(defclass metaobject () ((name :initarg :name) (documentation :initform () :initarg :documentation)))
(defclass forward-referenced-class (metaobject) ((direct-subclasses :initform ())))
(defclass specializer (forward-referenced-class)
((direct-superclasses :initarg :direct-superclasses) class-precedence-list (direct-methods :initform ())))
(defclass class (specializer))
;; 7. Define the full-blown version of standard-class.
(setq the-class-standard-class
(defclass standard-class (class)
(direct-slots effective-slots (shared-slot-definitions :initform ()) (shared-slots :initform ())
(direct-default-initargs :initform () :initarg :direct-default-initargs) (effective-default-initargs :initform ()))))
;; 8. Replace all existing pointers to the skeleton with real one.
;; and Declare types (not for t)
(mapc #'(lambda (x) (setf (std-instance-class (find-class x)) the-class-standard-class)
(unless (eq t x)
(install-type-specifier x #'(lambda (s1 s2)
(and (cl::clos-instance-p s1)
(cl::subclassp (class-of s1) (find-class s2)))))))
'(t standard-object metaobject forward-referenced-class specializer class standard-class))
;; (Clear sailing from here on in).
;; 9. Define the other built-in classes.
(defclass symbol (t) ())
(defclass sequence (t) ())
(defclass array (t) ())
(defclass number (t) ())
(defclass character (t) ())
(defclass function (t) ())
; (defclass hash-table (t) ()) defined below
(defclass package (t) ())
(defclass pathname (t) ())
(defclass readtable (t) ())
(defclass stream (t) ())
(defclass list (sequence) ())
(defclass null (symbol list) ())
(defclass cons (list) ())
(defclass vector (array sequence) ())
(defclass bit-vector (vector) ())
(defclass string (vector) ())
(defclass complex (number) ())
(defclass integer (number) ())
(defclass float (number) ())
(defclass ratio (number) ())
;; 10. Define the other standard metaobject classes.
;;; redefine to add type support for TYPEP
(defmacro defclass (name direct-superclasses slot-definitions
&rest options)
(let ((s1 (gensym))(s2 (gensym)))
`(prog1
(ensure-class ',name
:direct-superclasses
,(canonicalize-direct-superclasses direct-superclasses)
:direct-slots
,(canonicalize-direct-slots slot-definitions)
,@(canonicalize-defclass-options options))
(declare-type-specifier ,name (,s1 ,s2)
(and (or (cl::clos-instance-p ,s1) (structurep ,s1))
(cl::subclassp (class-of ,s1) (find-class ,s2)))))))
(defclass eql-specializer (specializer) (object))
(defclass built-in-class (class))
(defclass structure-class (class) ())
(setq the-class-gf (eval the-defclass-generic-function))
(setq the-class-standard-gf (eval the-defclass-standard-generic-function))
(defclass method (metaobject))
(setq the-class-standard-method (eval the-defclass-standard-method))
;; Voila! The class hierarchy is in place.
;;(format t "Class hierarchy created.")
;; (It's now okay to define generic functions and methods.)
(defgeneric print-object (instance stream))
(defmethod print-object ((instance standard-object) stream)
(print-unreadable-object (instance stream :identity t)
(format stream "~:(~S~)"
(class-name (class-of instance))))
instance)
;;; Slot access
(defgeneric slot-value-using-class (class instance slot-name))
(defmethod slot-value-using-class ((class standard-class) instance slot-name)
(declare (ignore class))
(std-slot-value instance slot-name))
(defgeneric (setf slot-value-using-class) (new-value class instance slot-name))
(defmethod (setf slot-value-using-class)
(new-value (class standard-class) instance slot-name)
(declare (ignore class))
(setf (std-slot-value instance slot-name) new-value))
; (values)) ;end progn
;;; N.B. To avoid making a forward reference to a (setf xxx) generic function:
(defun setf-slot-value-using-class (new-value class object slot-name)
(setf (slot-value-using-class class object slot-name) new-value))
(defun forward-referenced-class-p (x) (eq (class-of x) #.(find-class 'forward-referenced-class)))
(defun eql-specializer-p (x) (eq (class-of x) #.(find-class 'eql-specializer)))
(mapc #'(lambda (x) (convert-function-to-method (car x) (cadr x)))
'((class-name ((class metaobject))) ((setf class-name) (new-value (class metaobject))) ; setf gf ansi fun amop
(class-direct-subclasses ((class forward-referenced-class))) ((setf class-direct-subclasses) (new-value (class forward-referenced-class)))
(class-direct-superclasses ((class specializer))) ((setf class-direct-superclasses) (new-value (class specializer)))
(class-direct-methods ((class specializer))) ((setf class-direct-methods) (new-value (class specializer)))
(class-direct-slots ((class standard-class))) ((setf class-direct-slots) (new-value (class standard-class)))
(class-shared-slot-definitions ((class standard-class))) ((setf class-shared-slot-definitions) (new-value (class standard-class)))
(class-shared-slots ((class standard-class))) ((setf class-shared-slots) (new-value (class standard-class)))
(add-method ((generic-function standard-generic-function) (method standard-method)))
(remove-method ((generic-function standard-generic-function) (method standard-method)))
(find-method ((generic-function standard-generic-function) method-qualifiers specializers &optional errorp))))
(defmethod class-direct-superclasses ((x forward-referenced-class))) ; amop
(defmethod class-direct-slots ((class forward-referenced-class))) ; amop
(defmethod (setf class-direct-slots) (new-value (class forward-referenced-class)) (declare (ignore new-value)))
(defmethod class-shared-slot-definitions ((class forward-referenced-class)))
(defmethod (setf class-shared-slot-definitions) (new-value (class forward-referenced-class)) (declare (ignore new-value)))
(defmethod class-shared-slots ((class forward-referenced-class)))
(defmethod (setf class-shared-slots) (new-value (class forward-referenced-class)) (declare (ignore new-value)))
(defmethod class-slots ((class forward-referenced-class)) (declare (ignore class)))
(defmethod class-slots ((class standard-class)) (append (class-effective-slots class) (class-shared-slot-definitions class)))
(defmethod class-direct-default-initargs ((class forward-referenced-class)))
(defmethod class-direct-default-initargs ((class standard-class)) (slot-value class 'direct-default-initargs))
(defmethod class-default-initargs ((class standard-class)) (slot-value class 'effective-default-initargs))
(defun (setf class-default-initargs) (new-value class)
(setf (slot-value class 'effective-default-initargs) new-value))
;(progn
(defgeneric slot-exists-p-using-class (class instance slot-name))
(defmethod slot-exists-p-using-class
((class standard-class) instance slot-name)
(declare (ignore class))
(std-slot-exists-p instance slot-name))
(defgeneric slot-boundp-using-class (class instance slot-name))
(defmethod slot-boundp-using-class
((class standard-class) instance slot-name)
(declare (ignore class))
(std-slot-boundp instance slot-name))
(defgeneric slot-makunbound-using-class (class instance slot-name))
(defmethod slot-makunbound-using-class
((class standard-class) instance slot-name)
(declare (ignore class))
(std-slot-makunbound instance slot-name))
;;; Instance creation and initialization
(defgeneric allocate-instance (class))
(defmethod allocate-instance ((class standard-class))
(let ((instance (std-allocate-instance class)))
(unless ; all subclasses of metaobject except strict subclasses of standard-class,
; standard-generic-function and standard-method. Standard-class only for now.
(and (subclassp class #.(find-class 'metaobject))
(or (eq class the-class-standard-class) (not (subclassp class the-class-standard-class))))
(setf (std-instance-signature instance)
(list (class-effective-slots class) (class-shared-slot-definitions class))))
instance))
(defgeneric make-instance (class &key))
(defmethod make-instance ((class standard-class) &rest initargs)
(let ((instance (allocate-instance class)))
(apply #'initialize-instance instance initargs)
instance))
(defmethod make-instance ((class symbol) &rest initargs)
(apply #'make-instance (find-class class) initargs))
(defgeneric initialize-instance (instance &key))
(defmethod initialize-instance ((instance standard-object) &rest initargs)
(apply #'shared-initialize instance t initargs))
(defgeneric reinitialize-instance (instance &key))
(defmethod reinitialize-instance
((instance standard-object) &rest initargs)
(apply #'shared-initialize instance () initargs))
(defgeneric shared-initialize (instance slot-names &key))
(defmethod shared-initialize ((instance standard-object)
slot-names &rest all-keys)
(dolist (slot (class-slots (class-of instance)))
(let ((slot-name (slot-definition-name slot)))
(multiple-value-bind (init-key init-value foundp)
(get-properties
all-keys (slot-definition-initargs slot))
(declare (ignore init-key))
(if foundp
(setf (slot-value instance slot-name) init-value)
(when (and (not (slot-boundp instance slot-name))
(not (null (slot-definition-initfunction slot)))
(or (eq slot-names t)
(member slot-name slot-names)))
(setf (slot-value instance slot-name)
(funcall (slot-definition-initfunction slot))))))))
instance)
(defmethod update-instance-for-redefined-class ((instance standard-object) added-slots discarded-slots property-list &rest initargs)
(declare (ignore discarded-slots property-list))
(apply #'shared-initialize instance added-slots initargs))
;;; change-class
(defgeneric change-class (instance new-class &key))
(defmethod change-class
((old-instance standard-object)
(new-class standard-class)
&rest initargs)
(let ((new-instance (allocate-instance new-class)))
(dolist (slot-name (mapcar #'slot-definition-name
(class-effective-slots new-class)))
(when (and (slot-exists-p old-instance slot-name)
(slot-boundp old-instance slot-name))
(setf (slot-value new-instance slot-name)
(slot-value old-instance slot-name))))
(rotatef (std-instance-slots new-instance)
(std-instance-slots old-instance))
(rotatef (std-instance-class new-instance)
(std-instance-class old-instance))
(rotatef (std-instance-signature new-instance)
(std-instance-signature old-instance))
(apply #'update-instance-for-different-class
new-instance old-instance initargs)
old-instance))
(defmethod change-class
((instance standard-object) (new-class symbol) &rest initargs)
(apply #'change-class instance (find-class new-class) initargs))
(defgeneric update-instance-for-different-class (old new &key))
(defmethod update-instance-for-different-class
((old standard-object) (new standard-object) &rest initargs)
(let ((added-slots
(remove-if #'(lambda (slot-name)
(slot-exists-p old slot-name))
(mapcar #'slot-definition-name
(class-effective-slots (class-of new))))))
(apply #'shared-initialize new added-slots initargs)))
;;; change-class the built-in classes
(mapc #'(lambda (x) (change-class (find-class x) 'built-in-class))
'(t symbol sequence array number character function package pathname readtable stream
list null cons vector bit-vector string complex integer float ratio))
;;;
;;; Methods having to do with class metaobjects.
;;;
(defmethod print-object ((class metaobject) stream)
(print-unreadable-object (class stream :identity t)
(format stream "~:(~S~) ~S"
(class-name (class-of class))
(class-name class)))
class)
(defmethod initialize-instance :after ((class specializer) &rest args)
(apply #'std-after-initialization-for-classes class args))
;;; Finalize inheritance
(defgeneric finalize-inheritance (class))
(defmethod finalize-inheritance ((class specializer))
(setf (class-precedence-list class)
(compute-class-precedence-list class))
(values))
(defmethod finalize-inheritance ((class standard-class))
(std-finalize-inheritance class)
(values))
;;; Class precedence lists
(defgeneric compute-class-precedence-list (class))
(defmethod compute-class-precedence-list ((class specializer))
(std-compute-class-precedence-list class))
;;; Slot inheritance
(defgeneric compute-slots (class))
(defmethod compute-slots ((class standard-class))
(std-compute-slots class))
(defgeneric compute-effective-slot-definition (class direct-slots))
(defmethod compute-effective-slot-definition
((class standard-class) direct-slots)
(std-compute-effective-slot-definition class direct-slots))
;;;
;;; Methods having to do with generic function metaobjects.
;;;
(defmethod initialize-instance :after ((gf standard-generic-function) &key)
(finalize-generic-function gf))
;;;
;;; Methods having to do with method metaobjects.
;;;
(defmethod print-object ((method standard-method) stream)
(print-unreadable-object (method stream :identity t)
(format stream "~:(~S~) ~S~{ ~S~} ~S"
(class-name (class-of method))
(generic-function-name (method-generic-function method))
(method-qualifiers method)
(mapcar #'(lambda (x) (if (eql-specializer-p x) `(eql ,(class-name x)) (class-name x))) (method-specializers method))))
method)
(defmethod initialize-instance :after ((method standard-method) &key)
(setf (method-function method) (compute-method-function method)))
;;;
;;; Methods having to do with generic function invocation.
;;;
(defgeneric compute-discriminating-function (gf))
(defmethod compute-discriminating-function ((gf standard-generic-function))
(std-compute-discriminating-function gf))
(defgeneric method-more-specific-p (gf method1 method2 required-classes))
(defmethod method-more-specific-p
((gf standard-generic-function) method1 method2 required-classes)
(std-method-more-specific-p gf method1 method2 required-classes))
(defgeneric compute-effective-method-function (gf methods))
(defmethod compute-effective-method-function
((gf standard-generic-function) methods)
(std-compute-effective-method-function gf methods))
(defgeneric compute-method-function (method))
(defmethod compute-method-function ((method standard-method))
(std-compute-method-function method))
;;; describe-object is a handy tool for enquiring minds:
(defgeneric describe-object (object stream))
(defmethod describe-object ((object standard-object) stream)
(format stream "CLOS OBJECT:~%~?~?~?"
"~4T~A:~20T~A~%" (list "printed representation" object)
"~4T~A:~20T~A~%" (list "class" (class-of object))
"~4T~A:~20T#x~X~%" (list "heap address" (%uvector-address object)))
(dolist (sn (mapcar #'slot-definition-name
(class-slots (class-of object))))
(format stream "~4T~A: ~:[not bound~;~S~]~%"
(string-downcase (symbol-name sn))
(slot-boundp object sn)
(and (slot-boundp object sn)
(slot-value object sn))))
(values))
(defmethod describe-object ((object t) stream)
(cl:describe object stream)
(values))
;;(format t "~%Closette is a Knights of the Lambda Calculus production.")
;(values)) ;end progn
;;; add default-initargs functionality
(defmethod compute-default-initargs ((class standard-class))
(remove-duplicates (mapappend #'class-direct-default-initargs (class-precedence-list class)) :from-end t :key #'car))
(defmethod finalize-inheritance :after ((class standard-class))
(setf (class-default-initargs class) (compute-default-initargs class)))
(defmethod make-instance :around ((class standard-class) &rest initargs)
(apply #'call-next-method class
(append initargs (mapappend #'(lambda (def-init)
(let ((key (car def-init)))
(unless (caddr (multiple-value-list (get-properties initargs (list key))))
(list key (funcall (caddr def-init))))))
(class-default-initargs class)))))
;;; add class redefinition functionality
;;; t for the amop. nil can be useful for development.
;;; By carefully violating the amop rules we can get a glance at finalized classes.
(defparameter *lazy-finalize*)
(defmethod initialize-instance :after ((class eql-specializer) &key) (finalize-inheritance class)) ; always finalized
(defmethod reinitialize-instance :after ((class class) &rest args) ; leave open; funcallable-standard-class?
(apply #'std-after-initialization-for-classes class args))
;;;
;;; setup parent class for all structures
;;;
(defmethod initialize-instance :after ((class structure-class) &key) (finalize-inheritance class)) ; always finalized
(defmethod reinitialize-instance :after ((class structure-class) &key) (finalize-inheritance class)) ; not actually needed
(defclass structure-object (t) () (:metaclass structure-class))
(defmethod initialize-instance :after ((class standard-class) &key) (unless *lazy-finalize* (finalize-inheritance class)))
(defmethod reinitialize-instance :after ((class standard-class) &key) (unless *lazy-finalize* (finalize-inheritance class)))
(defmethod ensure-class-using-class ((class class) name &rest all-keys
&key (metaclass the-class-standard-class) direct-superclasses &allow-other-keys)
(declare (ignore name))
(unless (eq (class-of class) (or (and (symbolp metaclass) (find-class metaclass)) metaclass))
(error "~a is not a ~a" class metaclass))
(let ((subs (if *lazy-finalize*
(remove-if-not #'class-finalized-p (cons class (collect-subclasses class)))
(cons class (collect-subclasses class)))))
(when *lazy-finalize*
(let ((forward (find-if #'forward-referenced-class-p direct-superclasses)))
(when (and forward (eq class (car subs)))
(error "Cannot redefine finalized ~a~%;;; with an undefined ~a" class forward))))
(remove-read-write-methods class)
(unless (lists-match (class-direct-superclasses class) direct-superclasses)
(remove-from-deleted-classes class direct-superclasses)
(mapc #'(lambda (x) (clear-method-table (classes-to-emf-table x)))
(remove-duplicates (mapcar #'method-generic-function (mapappend #'class-direct-methods subs)))))
(apply #'reinitialize-instance class all-keys)
(mapc #'finalize-inheritance (if *lazy-finalize* subs (cdr subs))))
class)
(defmethod ensure-class-using-class ((class null) name &rest all-keys &key (metaclass the-class-standard-class) &allow-other-keys)
(setf (find-class name) (apply #'make-instance metaclass :name name all-keys)))
;;; add forward-referenced-class functionality
(defun not-instantiable-p (class)
(let ((supers (class-direct-superclasses class)))
(or (find-if #'forward-referenced-class-p supers)
(dolist (class supers) (let ((class (not-instantiable-p class))) (when class (return class)))))))
;;; For forward-referenced classes to behave like "identity" elements in a null *lazy-finalize* mode "environment"
;;; we should consider the more general case by defining a generic function say, default-direct-superclass.
(defmethod compute-class-precedence-list ((class standard-class))
(let ((list (call-next-method)))
(if (forward-referenced-class-p (car (last list)))
(nconc (remove-if #'(lambda (x) (member x '#.(list (find-class 'standard-object) (find-class t)))) list)
(list #.(find-class 'standard-object) #.(find-class t)))
list)))
(defmethod finalize-inheritance ((class forward-referenced-class)) (error "Cannot finalize ~a." class))
(defmethod finalize-inheritance :before ((class standard-class)) ; we should actually only finalize classes with shared slots
(when *lazy-finalize* (mapc #'(lambda (x) (unless (class-finalized-p x) (finalize-inheritance x))) (class-direct-superclasses class))))
(defmethod allocate-instance :before ((class standard-class))
(if *lazy-finalize*
(unless (class-finalized-p class) (finalize-inheritance class))
(let ((forward (not-instantiable-p class)))
(when forward (cerror "Continue anyway." "Continuable attempt to instantiate ~a~%;;; with an undefined ~a superclass." class forward)))))
; redefine
(defun canonicalize-direct-superclasses (direct-superclasses) `',direct-superclasses)
(defmethod ensure-class-using-class ((class forward-referenced-class) name &rest all-keys
&key (metaclass the-class-standard-class) &allow-other-keys) (declare (ignore name))
(change-class class metaclass) (apply #'reinitialize-instance class all-keys)
(mapc #'(lambda (x) (when (class-finalized-p x) (finalize-inheritance x))) (collect-subclasses class))
class)
; redefine
(defun ensure-class (name &rest all-keys &key direct-superclasses &allow-other-keys)
(apply #'ensure-class-using-class (find-class name nil) name
:direct-superclasses (mapcar #'(lambda (x) (or (and (symbolp x) (find-class x nil))
(and (clos-instance-p x) x)
(ensure-class-using-class nil x :metaclass (find-class 'forward-referenced-class))))
direct-superclasses)
all-keys))
(defmacro with-slots (slot-entries instance-form &body forms)
(let ((sym (gensym))
(vars '())
(slots '()))
(unless (listp slot-entries)
(error "Invalid WITH-SLOTS slot entry list: ~S" slot-entries))
(dolist (varslot slot-entries)
(typecase varslot
(symbol
(push varslot vars)
(push varslot slots))
(list
(unless (= 2 (length varslot))
(error "Invalid WITH-SLOTS slot entry: ~S" varslot))
(push (first varslot) vars)
(push (second varslot) slots))
(t (error "Invalid WITH-SLOTS slot entry: ~S" varslot))))
`(LET ((,sym ,instance-form))
(SYMBOL-MACROLET
,(mapcar #'(lambda (v s) `(,v (slot-value ,sym ',s)))
(nreverse vars)
(nreverse slots))
,@forms))))
(defun intern-structure-class (name superclass doc)
(ensure-class name
:direct-superclasses (list (or (and superclass (find-class superclass)) #.(find-class 'structure-object)))
:metaclass 'structure-class
:documentation doc))
(defun struct-template (struct-name)
(get struct-name :struct-template))
(defun patch-clos (struct-name)
(setf (elt (struct-template struct-name) 1)
(intern-structure-class struct-name nil (documentation struct-name 'structure))))
;; make sure the following common lisp structures (which are defined before
;; this module is loaded) have CLOS definitions
(patch-clos 'hash-table)
(patch-clos 'random-state)
(patch-clos 'byte)
;; this is internal only, but we will patch it just in case...
(patch-clos 'method-table)
;;; EQL specializer support
;;; Returns a CLOS class representing a type that is specific
;;; for the object. Used in defmethod to implement EQL
;;; specialisers.
(defun intern-eql-specializer (object &optional (intern-form object))
(let* ((singleton (gethash object *clos-singleton-specializers*))
(real (and singleton
(car (member intern-form (class-precedence-list singleton)
:test #'(lambda (x y) (and (eql-specializer-p y) (equal x (class-name y)))))))))
(or real (let ((newsingle (make-instance #.(find-class 'eql-specializer)
:name intern-form :direct-superclasses (list (or singleton (class-of object))))))
(setf (slot-value newsingle 'object) object (gethash object *clos-singleton-specializers*) newsingle)))))
;; need to restore warning here
(setq *COMPILER-WARN-ON-UNDEFINED-FUNCTION* t) ;; restore warnings
;;;
;;; Common Lisp WITH-ACCESSORS macro.
;;;
(defmacro with-accessors (slot-entries instance-form &body forms)
(let ((sym (gensym))
(vars '())
(slots '()))
(unless (listp slot-entries)
(error "Invalid WITH-ACCESSORS slot entry list: ~S" slot-entries))
(dolist (varslot slot-entries)
(typecase varslot
(symbol
(push varslot vars)
(push varslot slots))
(list
(unless (= 2 (length varslot))
(error "Invalid WITH-ACCESSORS slot entry: ~S" varslot))
(push (first varslot) vars)
(push (second varslot) slots))
(t (error "Invalid WITH-ACCESSORS slot entry: ~S" varslot))))
`(LET ((,sym ,instance-form))
(SYMBOL-MACROLET
,(mapcar #'(lambda (v s) `(,v (,s ,sym)))
(nreverse vars)
(nreverse slots))
,@forms))))
;;;
;;; Handle STRUCTURE-derived classes
;;;
(defmethod print-object ((instance structure-object) stream)
(let ((*standard-output* stream))
(cl::write-builtin-object instance)))
;;;
;;; Handle all other Lisp data types
;;;
(defmethod print-object ((instance t) stream)
(let ((*standard-output* stream))
(cl::write-builtin-object instance)))
(defun has-print-object-method (obj)
(let ((gf (find-generic-function 'print-object)))
(> (length (cl::compute-applicable-methods-using-classes gf (list (class-of obj)))) 1)))
;;;
;;; Hook into WRITE so that PRINT-OBJECT may be overridden for builtin objects.
;;;
(defun write-lisp-object (object)
(print-object object *standard-output*))
|
[
{
"context": ";;;\n;;; Copyright 2009 Clozure Associates\n;;;\n;;; Licensed under the Apache License, Versio",
"end": 41,
"score": 0.9968238472938538,
"start": 23,
"tag": "NAME",
"value": "Clozure Associates"
}
] |
level-0/X86/X8632/x8632-symbol.lisp
|
digikar99/ccl
| 732 |
;;;
;;; 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 :execute)
(require "X8632-ARCH")
(require "X86-LAPMACROS"))
;;; This assumes that macros & special-operators
;;; have something that's not FUNCTIONP in their
;;; function-cells. It also assumes that NIL
;;; isn't a true symbol, but that NILSYM is.
(defx8632lapfunction %function ((sym arg_z))
(check-nargs 1)
(let ((symaddr temp0))
(movl ($ (+ (target-nil-value) x8632::nilsym-offset)) (% symaddr))
(cmp-reg-to-nil sym)
(cmovne (% sym) (% symaddr))
(trap-unless-typecode= symaddr x8632::subtag-symbol)
(movl (% sym) (% arg_y))
(movl (@ x8632::symbol.fcell (% symaddr)) (% arg_z))
(extract-typecode arg_z imm0)
(cmpb ($ x8632::subtag-function) (%b imm0))
(je.pt @ok)
(uuo-error-udf (% arg_y))
@ok
(single-value-return)))
;;; Traps unless sym is NIL or some other symbol. If NIL, return
;;; nilsym
(defx8632lapfunction %symbol->symptr ((sym arg_z))
(let ((tag imm0))
(movl ($ (+ (target-nil-value) x8632::nilsym-offset)) (% tag))
(cmp-reg-to-nil sym)
(cmove (% tag) (% sym))
(je :done)
(trap-unless-typecode= sym x8632::subtag-symbol)
:done
(single-value-return)))
;;; If symptr is NILSYM, return NIL; else typecheck and return symptr
(defx8632lapfunction %symptr->symbol ((symptr arg_z))
(cmpl ($ (+ (target-nil-value) x8632::nilsym-offset)) (% symptr))
(jne @typecheck)
(movl ($ (target-nil-value)) (% arg_z))
(single-value-return)
@typecheck
(trap-unless-typecode= symptr x8632::subtag-symbol)
(single-value-return))
(defx8632lapfunction %symptr-value ((symptr arg_z))
(jmp-subprim .SPspecref))
(defx8632lapfunction %set-symptr-value ((symptr arg_y) (val arg_z))
(jmp-subprim .SPspecset))
;;; This gets a tagged symbol as an argument.
;;; If there's no thread-local binding, it should return
;;; the underlying symbol vector as a first return value.
(defx8632lapfunction %symptr-binding-address ((symptr arg_z))
(movl (@ x8632::symbol.binding-index (% symptr)) (% arg_y))
(rcmp (% arg_y) (:rcontext x8632::tcr.tlb-limit))
(movl (:rcontext x8632::tcr.tlb-pointer) (% temp0))
(jae @sym)
(cmpb ($ x8632::subtag-no-thread-local-binding) (@ (% temp0) (% arg_y)))
(je @sym)
(shl ($ x8632::word-shift) (% arg_y))
(push (% temp0))
(push (% arg_y))
(set-nargs 2)
(lea (@ '2 (% esp)) (% temp0))
(jmp-subprim .SPvalues)
@sym
(push (% arg_z))
(pushl ($ '#.x8632::symbol.vcell))
(set-nargs 2)
(lea (@ '2 (% esp)) (% temp0))
(jmp-subprim .SPvalues))
(defx8632lapfunction %tcr-binding-location ((tcr arg_y) (sym arg_z))
(movl (@ x8632::symbol.binding-index (% sym)) (% temp0))
(movl ($ (target-nil-value)) (% arg_z))
(rcmp (% temp0) (@ (- x8632::tcr.tlb-limit x8632::tcr-bias) (% tcr)))
(movl (@ (- x8632::tcr.tlb-pointer x8632::tcr-bias) (% tcr)) (% arg_y))
(jae @done)
(lea (@ (% arg_y) (% temp0)) (% arg_y))
;; We're little-endian, so the tag is at the EA with no
;; displacement
(cmpb ($ x8632::subtag-no-thread-local-binding) (@ (% arg_y)))
(cmovnel (% arg_y) (% arg_z))
@done
(single-value-return))
(defx86lapfunction %pname-hash ((str arg_y) (len arg_z))
(let ((accum imm0)
(offset temp0))
(xor (% offset) (% offset))
(xor (% accum) (% accum))
(testl (% len) (% len))
(jz.pn @done)
@loop8
(roll ($ 5) (%l accum))
(xorl (@ x8632::misc-data-offset (% str) (% offset)) (%l accum))
(addl ($ '1) (% offset))
(subl ($ '1) (% len))
(jnz @loop8)
(shll ($ 5) (% accum))
(shrl ($ (- 5 x8632::fixnumshift)) (% accum))
(movl (% accum) (% arg_z))
@done
(single-value-return)))
(defx8632lapfunction %string-hash ((start 4) #|(ra 0)|# (str arg_y) (len arg_z))
(let ((accum imm0)
(offset temp0))
(movl (@ start (% esp)) (% offset))
(xorl (% accum) (% accum))
(testl (% len) (% len))
(jz @done)
@loop8
(roll ($ 5) (%l accum))
(xorl (@ x8632::misc-data-offset (% str) (% offset)) (%l accum))
(addl ($ '1) (% offset))
(subl ($ '1) (% len))
(jnz @loop8)
(shll ($ 5) (% accum))
(shrl ($ (- 5 x8632::fixnumshift)) (% accum))
(movl (% accum) (% arg_z))
@done
(single-value-return 3)))
;;; Ensure that the current thread's thread-local-binding vector
;;; contains room for an entry with index INDEX.
;;; Return the fixnum-tagged tlb vector.
(defx8632lapfunction %ensure-tlb-index ((idx arg_z))
(cmp (:rcontext x8632::tcr.tlb-limit) (% idx))
(jb @ok)
(push (% arg_z)) ; exception handler will pop this
(ud2a) (:byte 1) ; tlb_too_small()
@ok
(mov (:rcontext x8632::tcr.tlb-pointer) (% arg_z))
(single-value-return))
|
53303
|
;;;
;;; 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 :execute)
(require "X8632-ARCH")
(require "X86-LAPMACROS"))
;;; This assumes that macros & special-operators
;;; have something that's not FUNCTIONP in their
;;; function-cells. It also assumes that NIL
;;; isn't a true symbol, but that NILSYM is.
(defx8632lapfunction %function ((sym arg_z))
(check-nargs 1)
(let ((symaddr temp0))
(movl ($ (+ (target-nil-value) x8632::nilsym-offset)) (% symaddr))
(cmp-reg-to-nil sym)
(cmovne (% sym) (% symaddr))
(trap-unless-typecode= symaddr x8632::subtag-symbol)
(movl (% sym) (% arg_y))
(movl (@ x8632::symbol.fcell (% symaddr)) (% arg_z))
(extract-typecode arg_z imm0)
(cmpb ($ x8632::subtag-function) (%b imm0))
(je.pt @ok)
(uuo-error-udf (% arg_y))
@ok
(single-value-return)))
;;; Traps unless sym is NIL or some other symbol. If NIL, return
;;; nilsym
(defx8632lapfunction %symbol->symptr ((sym arg_z))
(let ((tag imm0))
(movl ($ (+ (target-nil-value) x8632::nilsym-offset)) (% tag))
(cmp-reg-to-nil sym)
(cmove (% tag) (% sym))
(je :done)
(trap-unless-typecode= sym x8632::subtag-symbol)
:done
(single-value-return)))
;;; If symptr is NILSYM, return NIL; else typecheck and return symptr
(defx8632lapfunction %symptr->symbol ((symptr arg_z))
(cmpl ($ (+ (target-nil-value) x8632::nilsym-offset)) (% symptr))
(jne @typecheck)
(movl ($ (target-nil-value)) (% arg_z))
(single-value-return)
@typecheck
(trap-unless-typecode= symptr x8632::subtag-symbol)
(single-value-return))
(defx8632lapfunction %symptr-value ((symptr arg_z))
(jmp-subprim .SPspecref))
(defx8632lapfunction %set-symptr-value ((symptr arg_y) (val arg_z))
(jmp-subprim .SPspecset))
;;; This gets a tagged symbol as an argument.
;;; If there's no thread-local binding, it should return
;;; the underlying symbol vector as a first return value.
(defx8632lapfunction %symptr-binding-address ((symptr arg_z))
(movl (@ x8632::symbol.binding-index (% symptr)) (% arg_y))
(rcmp (% arg_y) (:rcontext x8632::tcr.tlb-limit))
(movl (:rcontext x8632::tcr.tlb-pointer) (% temp0))
(jae @sym)
(cmpb ($ x8632::subtag-no-thread-local-binding) (@ (% temp0) (% arg_y)))
(je @sym)
(shl ($ x8632::word-shift) (% arg_y))
(push (% temp0))
(push (% arg_y))
(set-nargs 2)
(lea (@ '2 (% esp)) (% temp0))
(jmp-subprim .SPvalues)
@sym
(push (% arg_z))
(pushl ($ '#.x8632::symbol.vcell))
(set-nargs 2)
(lea (@ '2 (% esp)) (% temp0))
(jmp-subprim .SPvalues))
(defx8632lapfunction %tcr-binding-location ((tcr arg_y) (sym arg_z))
(movl (@ x8632::symbol.binding-index (% sym)) (% temp0))
(movl ($ (target-nil-value)) (% arg_z))
(rcmp (% temp0) (@ (- x8632::tcr.tlb-limit x8632::tcr-bias) (% tcr)))
(movl (@ (- x8632::tcr.tlb-pointer x8632::tcr-bias) (% tcr)) (% arg_y))
(jae @done)
(lea (@ (% arg_y) (% temp0)) (% arg_y))
;; We're little-endian, so the tag is at the EA with no
;; displacement
(cmpb ($ x8632::subtag-no-thread-local-binding) (@ (% arg_y)))
(cmovnel (% arg_y) (% arg_z))
@done
(single-value-return))
(defx86lapfunction %pname-hash ((str arg_y) (len arg_z))
(let ((accum imm0)
(offset temp0))
(xor (% offset) (% offset))
(xor (% accum) (% accum))
(testl (% len) (% len))
(jz.pn @done)
@loop8
(roll ($ 5) (%l accum))
(xorl (@ x8632::misc-data-offset (% str) (% offset)) (%l accum))
(addl ($ '1) (% offset))
(subl ($ '1) (% len))
(jnz @loop8)
(shll ($ 5) (% accum))
(shrl ($ (- 5 x8632::fixnumshift)) (% accum))
(movl (% accum) (% arg_z))
@done
(single-value-return)))
(defx8632lapfunction %string-hash ((start 4) #|(ra 0)|# (str arg_y) (len arg_z))
(let ((accum imm0)
(offset temp0))
(movl (@ start (% esp)) (% offset))
(xorl (% accum) (% accum))
(testl (% len) (% len))
(jz @done)
@loop8
(roll ($ 5) (%l accum))
(xorl (@ x8632::misc-data-offset (% str) (% offset)) (%l accum))
(addl ($ '1) (% offset))
(subl ($ '1) (% len))
(jnz @loop8)
(shll ($ 5) (% accum))
(shrl ($ (- 5 x8632::fixnumshift)) (% accum))
(movl (% accum) (% arg_z))
@done
(single-value-return 3)))
;;; Ensure that the current thread's thread-local-binding vector
;;; contains room for an entry with index INDEX.
;;; Return the fixnum-tagged tlb vector.
(defx8632lapfunction %ensure-tlb-index ((idx arg_z))
(cmp (:rcontext x8632::tcr.tlb-limit) (% idx))
(jb @ok)
(push (% arg_z)) ; exception handler will pop this
(ud2a) (:byte 1) ; tlb_too_small()
@ok
(mov (:rcontext x8632::tcr.tlb-pointer) (% arg_z))
(single-value-return))
| true |
;;;
;;; 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 :execute)
(require "X8632-ARCH")
(require "X86-LAPMACROS"))
;;; This assumes that macros & special-operators
;;; have something that's not FUNCTIONP in their
;;; function-cells. It also assumes that NIL
;;; isn't a true symbol, but that NILSYM is.
(defx8632lapfunction %function ((sym arg_z))
(check-nargs 1)
(let ((symaddr temp0))
(movl ($ (+ (target-nil-value) x8632::nilsym-offset)) (% symaddr))
(cmp-reg-to-nil sym)
(cmovne (% sym) (% symaddr))
(trap-unless-typecode= symaddr x8632::subtag-symbol)
(movl (% sym) (% arg_y))
(movl (@ x8632::symbol.fcell (% symaddr)) (% arg_z))
(extract-typecode arg_z imm0)
(cmpb ($ x8632::subtag-function) (%b imm0))
(je.pt @ok)
(uuo-error-udf (% arg_y))
@ok
(single-value-return)))
;;; Traps unless sym is NIL or some other symbol. If NIL, return
;;; nilsym
(defx8632lapfunction %symbol->symptr ((sym arg_z))
(let ((tag imm0))
(movl ($ (+ (target-nil-value) x8632::nilsym-offset)) (% tag))
(cmp-reg-to-nil sym)
(cmove (% tag) (% sym))
(je :done)
(trap-unless-typecode= sym x8632::subtag-symbol)
:done
(single-value-return)))
;;; If symptr is NILSYM, return NIL; else typecheck and return symptr
(defx8632lapfunction %symptr->symbol ((symptr arg_z))
(cmpl ($ (+ (target-nil-value) x8632::nilsym-offset)) (% symptr))
(jne @typecheck)
(movl ($ (target-nil-value)) (% arg_z))
(single-value-return)
@typecheck
(trap-unless-typecode= symptr x8632::subtag-symbol)
(single-value-return))
(defx8632lapfunction %symptr-value ((symptr arg_z))
(jmp-subprim .SPspecref))
(defx8632lapfunction %set-symptr-value ((symptr arg_y) (val arg_z))
(jmp-subprim .SPspecset))
;;; This gets a tagged symbol as an argument.
;;; If there's no thread-local binding, it should return
;;; the underlying symbol vector as a first return value.
(defx8632lapfunction %symptr-binding-address ((symptr arg_z))
(movl (@ x8632::symbol.binding-index (% symptr)) (% arg_y))
(rcmp (% arg_y) (:rcontext x8632::tcr.tlb-limit))
(movl (:rcontext x8632::tcr.tlb-pointer) (% temp0))
(jae @sym)
(cmpb ($ x8632::subtag-no-thread-local-binding) (@ (% temp0) (% arg_y)))
(je @sym)
(shl ($ x8632::word-shift) (% arg_y))
(push (% temp0))
(push (% arg_y))
(set-nargs 2)
(lea (@ '2 (% esp)) (% temp0))
(jmp-subprim .SPvalues)
@sym
(push (% arg_z))
(pushl ($ '#.x8632::symbol.vcell))
(set-nargs 2)
(lea (@ '2 (% esp)) (% temp0))
(jmp-subprim .SPvalues))
(defx8632lapfunction %tcr-binding-location ((tcr arg_y) (sym arg_z))
(movl (@ x8632::symbol.binding-index (% sym)) (% temp0))
(movl ($ (target-nil-value)) (% arg_z))
(rcmp (% temp0) (@ (- x8632::tcr.tlb-limit x8632::tcr-bias) (% tcr)))
(movl (@ (- x8632::tcr.tlb-pointer x8632::tcr-bias) (% tcr)) (% arg_y))
(jae @done)
(lea (@ (% arg_y) (% temp0)) (% arg_y))
;; We're little-endian, so the tag is at the EA with no
;; displacement
(cmpb ($ x8632::subtag-no-thread-local-binding) (@ (% arg_y)))
(cmovnel (% arg_y) (% arg_z))
@done
(single-value-return))
(defx86lapfunction %pname-hash ((str arg_y) (len arg_z))
(let ((accum imm0)
(offset temp0))
(xor (% offset) (% offset))
(xor (% accum) (% accum))
(testl (% len) (% len))
(jz.pn @done)
@loop8
(roll ($ 5) (%l accum))
(xorl (@ x8632::misc-data-offset (% str) (% offset)) (%l accum))
(addl ($ '1) (% offset))
(subl ($ '1) (% len))
(jnz @loop8)
(shll ($ 5) (% accum))
(shrl ($ (- 5 x8632::fixnumshift)) (% accum))
(movl (% accum) (% arg_z))
@done
(single-value-return)))
(defx8632lapfunction %string-hash ((start 4) #|(ra 0)|# (str arg_y) (len arg_z))
(let ((accum imm0)
(offset temp0))
(movl (@ start (% esp)) (% offset))
(xorl (% accum) (% accum))
(testl (% len) (% len))
(jz @done)
@loop8
(roll ($ 5) (%l accum))
(xorl (@ x8632::misc-data-offset (% str) (% offset)) (%l accum))
(addl ($ '1) (% offset))
(subl ($ '1) (% len))
(jnz @loop8)
(shll ($ 5) (% accum))
(shrl ($ (- 5 x8632::fixnumshift)) (% accum))
(movl (% accum) (% arg_z))
@done
(single-value-return 3)))
;;; Ensure that the current thread's thread-local-binding vector
;;; contains room for an entry with index INDEX.
;;; Return the fixnum-tagged tlb vector.
(defx8632lapfunction %ensure-tlb-index ((idx arg_z))
(cmp (:rcontext x8632::tcr.tlb-limit) (% idx))
(jb @ok)
(push (% arg_z)) ; exception handler will pop this
(ud2a) (:byte 1) ; tlb_too_small()
@ok
(mov (:rcontext x8632::tcr.tlb-pointer) (% arg_z))
(single-value-return))
|
[
{
"context": ";-*- Mode: Lisp -*-\n;;;; Author: Paul Dietz\n;;;; Created: Sat Apr 25 08:06:48 1998\n;;;; Cont",
"end": 49,
"score": 0.9998568892478943,
"start": 39,
"tag": "NAME",
"value": "Paul Dietz"
}
] |
programs/ansi-test/packages/unuse-package.lsp
|
TeamSPoon/wam_common_lisp_devel_workspace
| 8 |
;-*- Mode: Lisp -*-
;;;; Author: Paul Dietz
;;;; Created: Sat Apr 25 08:06:48 1998
;;;; Contains: Tests of UNUSE-PACKAGE
(declaim (optimize (safety 3)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; unuse-package
(deftest unuse-package.1
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G")))
(i 0) x y)
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(unuse-package (progn (setf x (incf i)) pg)
(progn (setf y (incf i)) ph))
(eql i 2) (eql x 1) (eql y 2)
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.2
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(unuse-package "G" ph)
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.3
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(unuse-package :|G| ph)
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.4
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(ignore-errors (unuse-package #\G ph))
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.5
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(unuse-package (list pg) ph)
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.6
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(unuse-package (list "G") ph)
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.7
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(unuse-package (list :|G|) ph)
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.8
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(ignore-errors (unuse-package (list #\G) ph))
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
;; Now test with multiple packages
(deftest unuse-package.9
(progn
(dolist (p '("H1" "H2" "G1" "G2" "G3"))
(safely-delete-package p))
(let* ((pg1 (make-package "G1" :use nil))
(pg2 (make-package "G2" :use nil))
(pg3 (make-package "G3" :use nil))
(ph1 (make-package "H1" :use (list pg1 pg2 pg3)))
(ph2 (make-package "H2" :use (list pg1 pg2 pg3))))
(let ((pubg1 (sort-package-list (package-used-by-list pg1)))
(pubg2 (sort-package-list (package-used-by-list pg2)))
(pubg3 (sort-package-list (package-used-by-list pg3)))
(puh1 (sort-package-list (package-use-list ph1)))
(puh2 (sort-package-list (package-use-list ph2))))
(prog1
(and
(= (length (remove-duplicates (list pg1 pg2 pg3 ph1 ph2)))
5)
(equal (list ph1 ph2) pubg1)
(equal (list ph1 ph2) pubg2)
(equal (list ph1 ph2) pubg3)
(equal (list pg1 pg2 pg3) puh1)
(equal (list pg1 pg2 pg3) puh2)
(unuse-package (list pg1 pg3) ph1)
(equal (package-use-list ph1) (list pg2))
(equal (package-used-by-list pg1) (list ph2))
(equal (package-used-by-list pg3) (list ph2))
(equal (sort-package-list (package-use-list ph2))
(list pg1 pg2 pg3))
(equal (sort-package-list (package-used-by-list pg2))
(list ph1 ph2))
t)
(dolist (p '("H1" "H2" "G1" "G2" "G3"))
(safely-delete-package p))))))
t)
;;; Specialized sequences
(defmacro def-unuse-package-test (test-name &key
(user "H")
(used "G"))
`(deftest ,test-name
(let ((user-name ,user)
(used-name ,used))
(safely-delete-package user-name)
(safely-delete-package used-name)
(let* ((pused (make-package used-name :use nil))
(puser (make-package user-name :use (list used-name))))
(prog1
(and
(equal (package-use-list puser) (list pused))
(equal (package-used-by-list pused) (list puser))
(unuse-package (list used-name) user-name)
(equal (package-use-list puser) nil)
(null (package-used-by-list pused)))
(safely-delete-package user-name)
(safely-delete-package used-name))))
t))
;;; Specialized user package designator
(def-unuse-package-test unuse-package.10
:user (make-array 5 :initial-contents "TEST1" :element-type 'base-char))
(def-unuse-package-test unuse-package.11
:user (make-array 10 :initial-contents "TEST1ABCDE"
:fill-pointer 5 :element-type 'base-char))
(def-unuse-package-test unuse-package.12
:user (make-array 10 :initial-contents "TEST1ABCDE"
:fill-pointer 5 :element-type 'character))
(def-unuse-package-test unuse-package.13
:user (make-array 5 :initial-contents "TEST1"
:adjustable t :element-type 'base-char))
(def-unuse-package-test unuse-package.14
:user (make-array 5 :initial-contents "TEST1"
:adjustable t :element-type 'character))
(def-unuse-package-test unuse-package.15
:user (let* ((etype 'base-char)
(name0 (make-array 10 :element-type etype
:initial-contents "xxxxxTEST1")))
(make-array 5 :element-type etype
:displaced-to name0
:displaced-index-offset 5)))
(def-unuse-package-test unuse-package.16
:user
(let* ((etype 'character)
(name0 (make-array 10 :element-type etype
:initial-contents "xxxxxTEST1")))
(make-array 5 :element-type etype
:displaced-to name0
:displaced-index-offset 5)))
;;; Specialed used package designator
(def-unuse-package-test unuse-package.17
:used (make-array 5 :initial-contents "TEST1" :element-type 'base-char))
(def-unuse-package-test unuse-package.18
:used (make-array 10 :initial-contents "TEST1ABCDE"
:fill-pointer 5 :element-type 'base-char))
(def-unuse-package-test unuse-package.19
:used (make-array 10 :initial-contents "TEST1ABCDE"
:fill-pointer 5 :element-type 'character))
(def-unuse-package-test unuse-package.20
:used (make-array 5 :initial-contents "TEST1"
:adjustable t :element-type 'base-char))
(def-unuse-package-test unuse-package.21
:used (make-array 5 :initial-contents "TEST1"
:adjustable t :element-type 'character))
(def-unuse-package-test unuse-package.22
:used (let* ((etype 'base-char)
(name0 (make-array 10 :element-type etype
:initial-contents "xxxxxTEST1")))
(make-array 5 :element-type etype
:displaced-to name0
:displaced-index-offset 5)))
(def-unuse-package-test unuse-package.23
:used
(let* ((etype 'character)
(name0 (make-array 10 :element-type etype
:initial-contents "xxxxxTEST1")))
(make-array 5 :element-type etype
:displaced-to name0
:displaced-index-offset 5)))
;;; Error tests
(deftest unuse-package.error.1
(signals-error (unuse-package) program-error)
t)
(deftest unuse-package.error.2
(progn
(safely-delete-package "UPE2A")
(safely-delete-package "UPE2")
(make-package "UPE2" :use ())
(make-package "UPE2A" :use '("UPE2"))
(signals-error (unuse-package "UPE2" "UPE2A" nil) program-error))
t)
|
43537
|
;-*- Mode: Lisp -*-
;;;; Author: <NAME>
;;;; Created: Sat Apr 25 08:06:48 1998
;;;; Contains: Tests of UNUSE-PACKAGE
(declaim (optimize (safety 3)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; unuse-package
(deftest unuse-package.1
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G")))
(i 0) x y)
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(unuse-package (progn (setf x (incf i)) pg)
(progn (setf y (incf i)) ph))
(eql i 2) (eql x 1) (eql y 2)
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.2
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(unuse-package "G" ph)
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.3
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(unuse-package :|G| ph)
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.4
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(ignore-errors (unuse-package #\G ph))
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.5
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(unuse-package (list pg) ph)
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.6
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(unuse-package (list "G") ph)
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.7
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(unuse-package (list :|G|) ph)
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.8
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(ignore-errors (unuse-package (list #\G) ph))
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
;; Now test with multiple packages
(deftest unuse-package.9
(progn
(dolist (p '("H1" "H2" "G1" "G2" "G3"))
(safely-delete-package p))
(let* ((pg1 (make-package "G1" :use nil))
(pg2 (make-package "G2" :use nil))
(pg3 (make-package "G3" :use nil))
(ph1 (make-package "H1" :use (list pg1 pg2 pg3)))
(ph2 (make-package "H2" :use (list pg1 pg2 pg3))))
(let ((pubg1 (sort-package-list (package-used-by-list pg1)))
(pubg2 (sort-package-list (package-used-by-list pg2)))
(pubg3 (sort-package-list (package-used-by-list pg3)))
(puh1 (sort-package-list (package-use-list ph1)))
(puh2 (sort-package-list (package-use-list ph2))))
(prog1
(and
(= (length (remove-duplicates (list pg1 pg2 pg3 ph1 ph2)))
5)
(equal (list ph1 ph2) pubg1)
(equal (list ph1 ph2) pubg2)
(equal (list ph1 ph2) pubg3)
(equal (list pg1 pg2 pg3) puh1)
(equal (list pg1 pg2 pg3) puh2)
(unuse-package (list pg1 pg3) ph1)
(equal (package-use-list ph1) (list pg2))
(equal (package-used-by-list pg1) (list ph2))
(equal (package-used-by-list pg3) (list ph2))
(equal (sort-package-list (package-use-list ph2))
(list pg1 pg2 pg3))
(equal (sort-package-list (package-used-by-list pg2))
(list ph1 ph2))
t)
(dolist (p '("H1" "H2" "G1" "G2" "G3"))
(safely-delete-package p))))))
t)
;;; Specialized sequences
(defmacro def-unuse-package-test (test-name &key
(user "H")
(used "G"))
`(deftest ,test-name
(let ((user-name ,user)
(used-name ,used))
(safely-delete-package user-name)
(safely-delete-package used-name)
(let* ((pused (make-package used-name :use nil))
(puser (make-package user-name :use (list used-name))))
(prog1
(and
(equal (package-use-list puser) (list pused))
(equal (package-used-by-list pused) (list puser))
(unuse-package (list used-name) user-name)
(equal (package-use-list puser) nil)
(null (package-used-by-list pused)))
(safely-delete-package user-name)
(safely-delete-package used-name))))
t))
;;; Specialized user package designator
(def-unuse-package-test unuse-package.10
:user (make-array 5 :initial-contents "TEST1" :element-type 'base-char))
(def-unuse-package-test unuse-package.11
:user (make-array 10 :initial-contents "TEST1ABCDE"
:fill-pointer 5 :element-type 'base-char))
(def-unuse-package-test unuse-package.12
:user (make-array 10 :initial-contents "TEST1ABCDE"
:fill-pointer 5 :element-type 'character))
(def-unuse-package-test unuse-package.13
:user (make-array 5 :initial-contents "TEST1"
:adjustable t :element-type 'base-char))
(def-unuse-package-test unuse-package.14
:user (make-array 5 :initial-contents "TEST1"
:adjustable t :element-type 'character))
(def-unuse-package-test unuse-package.15
:user (let* ((etype 'base-char)
(name0 (make-array 10 :element-type etype
:initial-contents "xxxxxTEST1")))
(make-array 5 :element-type etype
:displaced-to name0
:displaced-index-offset 5)))
(def-unuse-package-test unuse-package.16
:user
(let* ((etype 'character)
(name0 (make-array 10 :element-type etype
:initial-contents "xxxxxTEST1")))
(make-array 5 :element-type etype
:displaced-to name0
:displaced-index-offset 5)))
;;; Specialed used package designator
(def-unuse-package-test unuse-package.17
:used (make-array 5 :initial-contents "TEST1" :element-type 'base-char))
(def-unuse-package-test unuse-package.18
:used (make-array 10 :initial-contents "TEST1ABCDE"
:fill-pointer 5 :element-type 'base-char))
(def-unuse-package-test unuse-package.19
:used (make-array 10 :initial-contents "TEST1ABCDE"
:fill-pointer 5 :element-type 'character))
(def-unuse-package-test unuse-package.20
:used (make-array 5 :initial-contents "TEST1"
:adjustable t :element-type 'base-char))
(def-unuse-package-test unuse-package.21
:used (make-array 5 :initial-contents "TEST1"
:adjustable t :element-type 'character))
(def-unuse-package-test unuse-package.22
:used (let* ((etype 'base-char)
(name0 (make-array 10 :element-type etype
:initial-contents "xxxxxTEST1")))
(make-array 5 :element-type etype
:displaced-to name0
:displaced-index-offset 5)))
(def-unuse-package-test unuse-package.23
:used
(let* ((etype 'character)
(name0 (make-array 10 :element-type etype
:initial-contents "xxxxxTEST1")))
(make-array 5 :element-type etype
:displaced-to name0
:displaced-index-offset 5)))
;;; Error tests
(deftest unuse-package.error.1
(signals-error (unuse-package) program-error)
t)
(deftest unuse-package.error.2
(progn
(safely-delete-package "UPE2A")
(safely-delete-package "UPE2")
(make-package "UPE2" :use ())
(make-package "UPE2A" :use '("UPE2"))
(signals-error (unuse-package "UPE2" "UPE2A" nil) program-error))
t)
| true |
;-*- Mode: Lisp -*-
;;;; Author: PI:NAME:<NAME>END_PI
;;;; Created: Sat Apr 25 08:06:48 1998
;;;; Contains: Tests of UNUSE-PACKAGE
(declaim (optimize (safety 3)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; unuse-package
(deftest unuse-package.1
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G")))
(i 0) x y)
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(unuse-package (progn (setf x (incf i)) pg)
(progn (setf y (incf i)) ph))
(eql i 2) (eql x 1) (eql y 2)
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.2
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(unuse-package "G" ph)
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.3
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(unuse-package :|G| ph)
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.4
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(ignore-errors (unuse-package #\G ph))
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.5
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(unuse-package (list pg) ph)
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.6
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(unuse-package (list "G") ph)
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.7
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(unuse-package (list :|G|) ph)
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
(deftest unuse-package.8
(progn
(safely-delete-package "H")
(safely-delete-package "G")
(let* ((pg (make-package "G" :use nil))
(ph (make-package "H" :use '("G"))))
(prog1
(and
(equal (package-use-list ph) (list pg))
(equal (package-used-by-list pg) (list ph))
(ignore-errors (unuse-package (list #\G) ph))
(equal (package-use-list ph) nil)
(null (package-used-by-list pg)))
(safely-delete-package "H")
(safely-delete-package "G"))))
t)
;; Now test with multiple packages
(deftest unuse-package.9
(progn
(dolist (p '("H1" "H2" "G1" "G2" "G3"))
(safely-delete-package p))
(let* ((pg1 (make-package "G1" :use nil))
(pg2 (make-package "G2" :use nil))
(pg3 (make-package "G3" :use nil))
(ph1 (make-package "H1" :use (list pg1 pg2 pg3)))
(ph2 (make-package "H2" :use (list pg1 pg2 pg3))))
(let ((pubg1 (sort-package-list (package-used-by-list pg1)))
(pubg2 (sort-package-list (package-used-by-list pg2)))
(pubg3 (sort-package-list (package-used-by-list pg3)))
(puh1 (sort-package-list (package-use-list ph1)))
(puh2 (sort-package-list (package-use-list ph2))))
(prog1
(and
(= (length (remove-duplicates (list pg1 pg2 pg3 ph1 ph2)))
5)
(equal (list ph1 ph2) pubg1)
(equal (list ph1 ph2) pubg2)
(equal (list ph1 ph2) pubg3)
(equal (list pg1 pg2 pg3) puh1)
(equal (list pg1 pg2 pg3) puh2)
(unuse-package (list pg1 pg3) ph1)
(equal (package-use-list ph1) (list pg2))
(equal (package-used-by-list pg1) (list ph2))
(equal (package-used-by-list pg3) (list ph2))
(equal (sort-package-list (package-use-list ph2))
(list pg1 pg2 pg3))
(equal (sort-package-list (package-used-by-list pg2))
(list ph1 ph2))
t)
(dolist (p '("H1" "H2" "G1" "G2" "G3"))
(safely-delete-package p))))))
t)
;;; Specialized sequences
(defmacro def-unuse-package-test (test-name &key
(user "H")
(used "G"))
`(deftest ,test-name
(let ((user-name ,user)
(used-name ,used))
(safely-delete-package user-name)
(safely-delete-package used-name)
(let* ((pused (make-package used-name :use nil))
(puser (make-package user-name :use (list used-name))))
(prog1
(and
(equal (package-use-list puser) (list pused))
(equal (package-used-by-list pused) (list puser))
(unuse-package (list used-name) user-name)
(equal (package-use-list puser) nil)
(null (package-used-by-list pused)))
(safely-delete-package user-name)
(safely-delete-package used-name))))
t))
;;; Specialized user package designator
(def-unuse-package-test unuse-package.10
:user (make-array 5 :initial-contents "TEST1" :element-type 'base-char))
(def-unuse-package-test unuse-package.11
:user (make-array 10 :initial-contents "TEST1ABCDE"
:fill-pointer 5 :element-type 'base-char))
(def-unuse-package-test unuse-package.12
:user (make-array 10 :initial-contents "TEST1ABCDE"
:fill-pointer 5 :element-type 'character))
(def-unuse-package-test unuse-package.13
:user (make-array 5 :initial-contents "TEST1"
:adjustable t :element-type 'base-char))
(def-unuse-package-test unuse-package.14
:user (make-array 5 :initial-contents "TEST1"
:adjustable t :element-type 'character))
(def-unuse-package-test unuse-package.15
:user (let* ((etype 'base-char)
(name0 (make-array 10 :element-type etype
:initial-contents "xxxxxTEST1")))
(make-array 5 :element-type etype
:displaced-to name0
:displaced-index-offset 5)))
(def-unuse-package-test unuse-package.16
:user
(let* ((etype 'character)
(name0 (make-array 10 :element-type etype
:initial-contents "xxxxxTEST1")))
(make-array 5 :element-type etype
:displaced-to name0
:displaced-index-offset 5)))
;;; Specialed used package designator
(def-unuse-package-test unuse-package.17
:used (make-array 5 :initial-contents "TEST1" :element-type 'base-char))
(def-unuse-package-test unuse-package.18
:used (make-array 10 :initial-contents "TEST1ABCDE"
:fill-pointer 5 :element-type 'base-char))
(def-unuse-package-test unuse-package.19
:used (make-array 10 :initial-contents "TEST1ABCDE"
:fill-pointer 5 :element-type 'character))
(def-unuse-package-test unuse-package.20
:used (make-array 5 :initial-contents "TEST1"
:adjustable t :element-type 'base-char))
(def-unuse-package-test unuse-package.21
:used (make-array 5 :initial-contents "TEST1"
:adjustable t :element-type 'character))
(def-unuse-package-test unuse-package.22
:used (let* ((etype 'base-char)
(name0 (make-array 10 :element-type etype
:initial-contents "xxxxxTEST1")))
(make-array 5 :element-type etype
:displaced-to name0
:displaced-index-offset 5)))
(def-unuse-package-test unuse-package.23
:used
(let* ((etype 'character)
(name0 (make-array 10 :element-type etype
:initial-contents "xxxxxTEST1")))
(make-array 5 :element-type etype
:displaced-to name0
:displaced-index-offset 5)))
;;; Error tests
(deftest unuse-package.error.1
(signals-error (unuse-package) program-error)
t)
(deftest unuse-package.error.2
(progn
(safely-delete-package "UPE2A")
(safely-delete-package "UPE2")
(make-package "UPE2" :use ())
(make-package "UPE2A" :use '("UPE2"))
(signals-error (unuse-package "UPE2" "UPE2A" nil) program-error))
t)
|
[
{
"context": "e libwayland bindings for Common Lisp\"\n :author \"Malcolm Still\"\n :license \"BSD 3-Clause\"\n :depends-on (#:cffi ",
"end": 154,
"score": 0.9998774528503418,
"start": 141,
"tag": "NAME",
"value": "Malcolm Still"
}
] |
cl-wayland-generate-bindings.asd
|
earl-ducaine/cl-wayland
| 0 |
;;;; cl-wayland.asd
(asdf:defsystem #:cl-wayland-generate-bindings
:description "generate libwayland bindings for Common Lisp"
:author "Malcolm Still"
:license "BSD 3-Clause"
:depends-on (#:cffi #:closer-mop)
:serial t
:components ((:file "wayland-util")
(:file "wayland-client-core")
(:file "generate-bindings")
(:file "run-generate-bindings")))
|
48524
|
;;;; cl-wayland.asd
(asdf:defsystem #:cl-wayland-generate-bindings
:description "generate libwayland bindings for Common Lisp"
:author "<NAME>"
:license "BSD 3-Clause"
:depends-on (#:cffi #:closer-mop)
:serial t
:components ((:file "wayland-util")
(:file "wayland-client-core")
(:file "generate-bindings")
(:file "run-generate-bindings")))
| true |
;;;; cl-wayland.asd
(asdf:defsystem #:cl-wayland-generate-bindings
:description "generate libwayland bindings for Common Lisp"
:author "PI:NAME:<NAME>END_PI"
:license "BSD 3-Clause"
:depends-on (#:cffi #:closer-mop)
:serial t
:components ((:file "wayland-util")
(:file "wayland-client-core")
(:file "generate-bindings")
(:file "run-generate-bindings")))
|
[
{
"context": "Theorems about bvchop.\n;\n; Copyright (C) 2008-2011 Eric Smith and Stanford University\n; Copyright (C) 2013-2022",
"end": 75,
"score": 0.9996620416641235,
"start": 65,
"tag": "NAME",
"value": "Eric Smith"
},
{
"context": "ense. See the file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;",
"end": 236,
"score": 0.9995977878570557,
"start": 226,
"tag": "NAME",
"value": "Eric Smith"
},
{
"context": " file books/3BSD-mod.txt.\n;\n; Author: Eric Smith ([email protected])\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 260,
"score": 0.9999333620071411,
"start": 238,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
books/kestrel/bv/bvchop.lisp
|
mayankmanj/acl2
| 0 |
; BV Library: Theorems about bvchop.
;
; Copyright (C) 2008-2011 Eric Smith and Stanford University
; Copyright (C) 2013-2022 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 "bvchop-def")
(include-book "../arithmetic-light/power-of-2p")
(local (include-book "unsigned-byte-p"))
(local (include-book "../arithmetic-light/expt2"))
(local (include-book "../arithmetic-light/times"))
(local (include-book "../arithmetic-light/times-and-divides"))
(local (include-book "../arithmetic-light/divides"))
(local (include-book "../arithmetic-light/plus"))
(local (include-book "../arithmetic-light/floor"))
(local (include-book "../arithmetic-light/mod"))
(local (include-book "../arithmetic-light/mod-and-expt"))
;move
(defthm unsigned-byte-p-of-0-arg1
(equal (unsigned-byte-p 0 x)
(equal 0 x))
:hints (("Goal" :in-theory (enable unsigned-byte-p))))
(in-theory (disable unsigned-byte-p))
;(in-theory (disable BACKCHAIN-SIGNED-BYTE-P-TO-UNSIGNED-BYTE-P)) ;slow
(in-theory (disable mod floor))
;move
(defthm integerp-of-bvchop
(integerp (bvchop size x))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm natp-of-bvchop
(natp (bvchop n x))
:rule-classes :type-prescription)
(in-theory (disable (:t bvchop))) ;natp-of-bvchop is at least as good
(defthm bvchop-with-n-not-an-integer
(implies (not (integerp n))
(equal (bvchop n x) 0))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-when-not-natp-arg1-cheap
(implies (not (natp n))
(equal (bvchop n x)
0))
:rule-classes ((:rewrite :backchain-limit-lst (0)))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-when-i-is-not-an-integer
(implies (not (integerp i))
(equal (bvchop size i)
0))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-with-n-negative
(implies (<= n 0)
(equal (bvchop n x)
0))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-size-0-better
(equal (bvchop size 0)
0)
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-upper-bound
(< (bvchop n x) (expt 2 n))
:rule-classes (:rewrite :linear)
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-upper-bound-linear-strong
(implies (natp n)
(<= (bvchop n x) (+ -1 (expt 2 n))))
:rule-classes :linear)
(local
(defthm bvchop-of-bvchop2
(implies (and (<= 0 size1)
(integerp size1)
(integerp size)
(<= 0 size))
(equal (bvchop size1 (bvchop size i))
(if (< size1 size)
(bvchop size1 i)
(bvchop size i))))
:hints (("Goal" :cases ((integerp i))
:in-theory (enable bvchop mod-of-mod-when-mult)))))
;this one has the advantage of being a "simple" rule
(defthm bvchop-of-bvchop-same
(equal (bvchop n (bvchop n x))
(bvchop n x))
:hints (("Goal" :cases ((natp n) (not (integerp n))))))
(local
(defthm bvchop-bvchop-better-helper
(implies (and (>= size1 0)
(integerp size1)
(>= size 0)
(integerp size)
)
(equal (bvchop size1 (bvchop size i))
(if (< size1 size)
(bvchop size1 i)
(bvchop size i))))
:hints (("Goal" :cases ((integerp i))))))
(defthm bvchop-of-bvchop
(equal (bvchop size1 (bvchop size i))
(if (< (ifix size1) (ifix size))
(bvchop size1 i)
(bvchop size i)))
:hints (("Goal" :use (:instance bvchop-bvchop-better-helper (size (ifix size)) (size1 (ifix size1)))
:in-theory (disable bvchop-bvchop-better-helper))))
;allow the sizes to differ?
;or just use the meta rule...
(defthm bvchop-of-*-of-bvchop
(implies (and (integerp x)
(integerp y))
(equal (bvchop size (* (bvchop size x) y))
(bvchop size (* x y))))
:hints (("Goal" :do-not '(generalize eliminate-destructors)
:in-theory (enable bvchop))))
(defthm bvchop-of-*-of-bvchop-arg2
(implies (and (integerp x)
(integerp y))
(equal (bvchop size (* x (bvchop size y)))
(bvchop size (* x y))))
:hints (("Goal" :do-not '(generalize eliminate-destructors)
:in-theory (enable bvchop))))
;rename
(defthm bvchop-+-bvchop-better
(implies (and (integerp i)
(integerp j))
(equal (bvchop size (+ i (bvchop size j)))
(bvchop size (+ i j))))
:hints (("Goal" :in-theory (enable bvchop))))
;might help if natp is not enabled
(defthm bvchop-when-size-is-not-natp
(implies (not (natp size))
(equal (bvchop size i)
0))
:rule-classes ((:rewrite :backchain-limit-lst (0)))
:hints (("Goal" :in-theory (e/d (bvchop) (;FLOOR-MINUS-ERIC-BETTER ;drop the disable once this is fixed
)))))
(defthm unsigned-byte-p-of-bvchop
(implies (<= size size1)
(equal (unsigned-byte-p size1 (bvchop size i))
(and (>= size1 0)
(integerp size1))))
:hints (("Goal" :in-theory (enable bvchop UNSIGNED-BYTE-P))))
;bozo drop any special cases
(defthm bvchop-bound
(implies (and (syntaxp (and (quotep k)
(quotep n)))
(<= (expt 2 n) k))
(< (bvchop n x) k))
:hints (("Goal" :use (:instance unsigned-byte-p-of-bvchop (i x) (size n) (size1 n))
:do-not '(generalize eliminate-destructors)
:in-theory (e/d (zip bvchop)
(unsigned-byte-p-of-bvchop)))))
;; Do not remove: helps justify the correctness of some operations done by Axe.
(defthm bvchop-of-ifix
(equal (bvchop size (ifix x))
(bvchop size x))
:hints (("Goal" :in-theory (enable bvchop-when-i-is-not-an-integer))))
(defthm bvchop-of-0-arg1
(equal (bvchop 0 i)
0))
(defthm bvchop-does-nothing-rewrite
(equal (equal x (bvchop n x))
(if (natp n)
(unsigned-byte-p n x)
(equal 0 x)))
:hints (("Goal" :in-theory (enable bvchop unsigned-byte-p))))
;rename
(defthm bvchop-shift
(implies (integerp x)
(equal (bvchop n (* 2 x))
(if (posp n)
(* 2 (bvchop (+ -1 n) x))
0)))
:hints (("Goal" :in-theory (enable bvchop mod-expt-split))))
(defthm bvchop-when-i-is-not-an-integer-cheap
(implies (not (integerp i))
(equal (bvchop size i)
0))
:rule-classes ((:rewrite :backchain-limit-lst (0)))
:hints (("Goal" :in-theory (enable bvchop-when-i-is-not-an-integer))))
;allow the n's to differ
(defthm bvchop-of-expt-2-n
(equal (bvchop n (expt 2 n))
0)
:hints (("Goal" :in-theory (enable bvchop))))
(defthm equal-constant-when-bvchop-equal-constant-false
(implies (and (syntaxp (quotep const))
(equal free (bvchop freesize x))
(syntaxp (quotep free))
(syntaxp (quotep freesize))
;gets computed:
(not (equal free (bvchop freesize const))))
(not (equal const x))))
(defthm bvchop-of-1
(equal (bvchop n 1)
(if (zp n)
0
1))
:hints (("Goal" :in-theory (enable bvchop))))
(defthmd bvchop-of-sum-cases
(implies (and (integerp i2)
(integerp i1))
(equal (bvchop size (+ i1 i2))
(if (not (natp size))
0
(if (< (+ (bvchop size i1) (bvchop size i2)) (expt 2 size))
(+ (bvchop size i1) (bvchop size i2))
(+ (- (expt 2 size)) (bvchop size i1) (bvchop size i2))))))
:hints (("Goal" :in-theory (enable bvchop mod-sum-cases))))
(defthm bvchop-of-minus-of-bvchop
(equal (bvchop size (- (bvchop size x)))
(bvchop size (- x)))
:hints (("Goal" :cases ((integerp x))
:in-theory (e/d (bvchop) (mod-cancel)))))
;hope this split is okay
(defthmd bvchop-of-minus-helper
(equal (bvchop size (- x))
(if (equal 0 (bvchop size x))
0
(- (expt 2 size) (bvchop size x))))
:hints (("Goal" :in-theory (e/d (bvchop) (mod-cancel)))))
(defthm bvchop-when-size-is-not-posp
(implies (not (posp size))
(equal (bvchop size i) 0))
:rule-classes ((:rewrite :backchain-limit-lst (0)))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-of-minus
(equal (bvchop size (- x))
(if (or (not (natp size))
(equal 0 (bvchop size x)))
0
(- (expt 2 size) (bvchop size x))))
:hints (("Goal" :use ((:instance bvchop-when-size-is-not-natp (i (- x)))
(:instance bvchop-of-minus-helper))
:in-theory (disable bvchop-when-size-is-not-posp
bvchop-when-size-is-not-posp
expt))))
;i guess this one is an abbreviation rule
(defthm unsigned-byte-p-bvchop-same
(equal (unsigned-byte-p size (bvchop size i))
(natp size))
:hints (("Goal" :in-theory (enable unsigned-byte-p))))
;rename
(defthm bvchop-shift-gen
(implies (and (integerp x)
(integerp n)
(natp m))
(equal (bvchop n (* (expt 2 m) x))
(if (<= m n)
(* (expt 2 m) (bvchop (- n m) x))
0)))
:hints (("Goal"
:use (:instance integerp-of-expt-when-natp (i (+ m (- n))) (r 2))
:in-theory (e/d (bvchop mod-cancel
expt-of-+)
(integerp-of-expt-when-natp)))))
(defthm bvchop-shift-gen-alt
(implies (and (integerp x)
(integerp n)
(natp m))
(equal (bvchop n (* x (expt 2 m)))
(if (<= m n)
(* (expt 2 m) (bvchop (- n m) x))
0)))
:hints (("Goal"
:use (:instance integerp-of-expt-when-natp (i (+ m (- n))) (r 2))
:in-theory (e/d (bvchop mod-cancel
expt-of-+)
(integerp-of-expt-when-natp)))))
(defthm bvchop-sum-drop-bvchop
(implies (and (<= m n)
(integerp n)
(integerp z))
(equal (bvchop m (+ (bvchop n y) z))
(bvchop m (+ (ifix y) z))))
:hints (("Goal"
:in-theory (e/d (bvchop mod-of-mod-when-mult) (mod-cancel)))))
(defthm bvchop-sum-drop-bvchop-alt
(implies (and (<= m n)
(integerp n)
(integerp z))
(equal (bvchop m (+ z (bvchop n y)))
(bvchop m (+ (ifix y) z))))
:hints (("Goal" :use (:instance bvchop-sum-drop-bvchop) :in-theory (disable bvchop-sum-drop-bvchop))))
(defthm bvchop-of-expt-hack
(equal (bvchop (+ -1 n) (expt 2 n))
0)
:hints (("Goal" :in-theory (enable bvchop equal-of-0-and-mod))))
;gen
(defthm bvchop-of-expt-hack2
(implies (posp n)
(equal (bvchop 1 (expt 2 n))
0))
:hints (("Goal" :in-theory (enable bvchop floor-when-multiple))))
(defthm bvchop-of-minus-1
(implies (natp n)
(equal (bvchop n -1)
(+ -1 (expt 2 n))))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-of-mask
(implies (and (<= size1 size2)
(natp size1)
(integerp size2))
(equal (bvchop size2 (+ -1 (expt 2 size1)))
(+ -1 (expt 2 size1))))
:hints (("Goal" :in-theory (enable zip unsigned-byte-p))))
;combine with the other
(defthm bvchop-of-mask-other
(implies (and (<= size2 size1)
(natp size2)
(integerp size1))
(equal (bvchop size2 (+ -1 (expt 2 size1)))
(+ -1 (expt 2 size2))))
:hints (("Goal" :induct t ;for speed
:in-theory (enable (:i expt)
bvchop ;mod-cancel
mod-of-mod-when-mult
unsigned-byte-p
mod-sum-cases))))
;make a constant version? maybe not for this one?
(defthm bvchop-of-mask-gen
(implies (and (natp size1)
(natp size2))
(equal (bvchop size2 (+ -1 (expt 2 size1)))
(if (<= size1 size2)
(+ -1 (expt 2 size1))
(+ -1 (expt 2 size2))))))
;gen to any bv...
(defthm bvchop-impossible-value
(implies (and (syntaxp (quotep k))
(not (unsigned-byte-p size k))
(natp size))
(not (equal k (bvchop size x)))))
(defthm bvchop-of-expt-0
(implies (and (<= size1 size2)
(integerp size1)
(integerp size2))
(equal (bvchop size1 (expt 2 size2))
0))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-sum-subst-const
(implies (and (equal (bvchop n x) k)
(syntaxp (and (quotep k)
(not (quotep x))))
(integerp x)
(integerp y))
(equal (bvchop n (+ x y))
(bvchop n (+ k y)))))
(defthm bvchop-sum-subst-const-arg2
(implies (and (equal (bvchop n x) k)
(syntaxp (and (quotep k)
(not (quotep x))))
(integerp x)
(integerp y))
(equal (bvchop n (+ y x))
(bvchop n (+ y k)))))
;gen
;strength reduction
(defthmd mod-by-4-becomes-bvchop
(implies (integerp i)
(equal (mod i 4)
(bvchop 2 i)))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-+-cancel-better
(implies (and (integerp i)
(integerp j)
(integerp k))
(equal (equal (bvchop size (+ i j))
(bvchop size (+ i k)))
(equal (bvchop size j)
(bvchop size k))))
:hints (("Goal" :in-theory (enable bvchop))))
;(in-theory (disable BVCHOP-+-CANCEL))
(defthm bvchop-of-+-cancel-1-2
(implies (and (integerp x)
(integerp y)
(integerp z)
(integerp z2))
(equal (equal (bvchop size (+ x y)) (bvchop size (+ z x z2)))
(equal (bvchop size y) (bvchop size (+ z z2))))))
(defthm bvchop-of-+-cancel-2-2-alt
(implies (and (integerp x)
(integerp y)
(integerp z)
(integerp z2))
(equal (equal (bvchop size (+ y x z)) (bvchop size (+ z2 x)))
(equal (bvchop size (+ y z)) (bvchop size z2)))))
(defthm bvchop-of-+-cancel-1-1
(implies (and (integerp x)
(integerp y)
(integerp z))
(equal (equal (bvchop size (+ x y)) (bvchop size (+ x z)))
(equal (bvchop size y) (bvchop size z)))))
(defthmd bvchop-plus-minus-1-split-gen
(implies (and (syntaxp (quotep k))
(equal k (+ -1 (expt 2 size)))
(integerp x)
(posp size))
(equal (bvchop size (+ k x))
(if (equal 0 (bvchop size x))
(+ -1 (expt 2 size))
(+ -1 (bvchop size x)))))
:hints (("Goal" :in-theory (enable bvchop-of-sum-cases))))
;rename
(defthm bvchop-chop-leading-constant
(implies (and (syntaxp (and (quotep k)
(quotep size)))
(not (unsigned-byte-p size k))
(integerp k)
(integerp x)
;; (natp size)
)
(equal (bvchop size (+ k x))
(bvchop size (+ (bvchop size k) x))))
:hints (("Goal" :cases ((natp size)))))
;rename
(defthm bvchop-times-cancel-better
(implies (and (<= m n)
(integerp x)
(integerp y)
(natp n))
(equal (bvchop m (* (bvchop n x) y))
(bvchop m (* x y))))
:hints (("Goal" :in-theory (e/d (bvchop) (mod-of-*-of-mod))
:use ((:instance mod-of-*-of-mod (z (expt 2 m)) (x y) (y x))
(:instance mod-of-*-of-mod (z (expt 2 m)) (x y) (y (mod x (expt 2 n))))))))
;rename
(defthm bvchop-times-cancel-better-alt
(implies (and (<= m n)
(integerp x)
(integerp y)
(natp n))
(equal (bvchop m (* y (bvchop n x)))
(bvchop m (* y x))))
:hints (("Goal" :use (:instance bvchop-times-cancel-better)
:in-theory (disable bvchop-times-cancel-better))))
(defthm bvchop-of-+-of-expt
(implies (integerp x)
(equal (bvchop size (+ x (expt 2 size)))
(bvchop size x)))
:hints (("Goal":in-theory (enable bvchop))))
(defthm bvchop-of-+-of-expt-alt
(implies (integerp x)
(equal (bvchop size (+ (expt 2 size) x))
(bvchop size x)))
:hints (("Goal" :cases ((natp size)))))
;rename?
;see also <-lemma-for-known-operators2 but that one probably requires a constant for the width
(defthm bvchop-numeric-bound
(implies (and (syntaxp (quotep k))
(<= k 0))
(not (< (bvchop size x) k))))
(defthm bvchop-subst-constant
(implies (and (syntaxp (not (quotep x)))
(equal k (bvchop free x))
(syntaxp (quotep k))
(<= size free)
;(natp size)
(integerp free))
(equal (bvchop size x)
(bvchop size k))))
;subsumes the -0 version
(defthm bvchop-of-expt
(implies (and (integerp size1)
(natp size2))
(equal (bvchop size1 (expt 2 size2))
(if (<= size1 size2)
0
(expt 2 size2))))
:hints (("Goal" :in-theory (e/d (bvchop) (;mod-of-expt-of-2-constant-version mod-of-expt-of-2
)))))
;can this be expensive?
;rename?
(defthm bvchop-bound-rw
(implies (<= 0 x)
(not (< x (bvchop size x))))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm <=-of-bvchop-same-linear
(implies (<= 0 x)
(<= (bvchop n x) x))
:rule-classes :linear)
(defthm <-of-bvchop-and-bvchop-same
(implies (and (<= s1 s2)
(natp s1)
(integerp s2))
(not (< (bvchop s2 x) (bvchop s1 x))))
:hints (("Goal"
:use (:instance bvchop-bound-rw (x (bvchop s2 x)) (size s1))
:in-theory (disable bvchop-bound-rw))))
;Not sure this will fire if SMALL and BIG are constants, due to the free var.
(defthm <=-of-bvchop-same-linear-2
(implies (and (<= small big)
(natp small)
(integerp big))
(<= (bvchop small x) (bvchop big x)))
:rule-classes ((:linear))
:hints (("Goal" :in-theory (enable natp))))
(defthm bvchop-of-nfix
(equal (bvchop (nfix n) x)
(bvchop n x)))
(defthm not-<-of-expt-and-bvchop
(not (< (expt 2 size) (bvchop size x))))
(defthm bvchop-identity
(implies (unsigned-byte-p size i)
(equal (bvchop size i)
i))
:hints (("Goal" :in-theory (enable unsigned-byte-p))))
(defthm bvchop-of-mod-of-expt
(implies (and (<= size j)
(integerp j)
(natp size))
(equal (bvchop size (mod i (expt 2 j)))
(bvchop size i)))
:hints (("Goal" :cases ((rationalp i))
:in-theory (enable bvchop))))
(defthm bvchop-of-+-of-*-of-expt
(implies (and (integerp x)
(natp size))
(equal (bvchop size (+ (* x (expt 2 size)) y))
(bvchop size y)))
:hints (("Goal" :in-theory (enable bvchop equal-of-0-and-mod
mod-sum-cases))))
(defthm bvchop-of-+-of-minus-of-expt
(implies (and (integerp x)
(natp size))
(equal (bvchop size (+ x (- (expt 2 size))))
(bvchop size x)))
:hints (("Goal" :in-theory (enable bvchop
mod-sum-cases))))
(defthm bvchop-of-mod-of-expt-2
(implies (and (< j size)
(integerp size)
(integerp x)
(natp j))
(equal (bvchop size (mod x (expt 2 j)))
(bvchop j x)))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-+-cancel-0
(implies (and (force (integerp j))
(integerp i)
(natp size)
)
(equal (equal (bvchop size (+ i j))
(bvchop size i))
(equal (bvchop size j) 0)))
:hints (("Goal" :use (:instance bvchop-+-cancel-better (k 0))
:in-theory (disable bvchop-+-cancel-better))))
(defthm bvchop-+-cancel-0-alt
(implies (and (force (integerp j))
(integerp i)
(natp size)
)
(equal (equal (bvchop size (+ j i))
(bvchop size i))
(equal (bvchop size j) 0)))
:hints (("Goal" :use (:instance bvchop-+-cancel-better (k 0))
:in-theory (disable bvchop-+-cancel-better))))
(defthmd mod-of-expt-of-2
(implies (and (integerp x)
(natp m))
(equal (mod x (expt 2 m))
(bvchop m x)))
:hints (("Goal" :in-theory (enable bvchop))))
(theory-invariant (incompatible (:definition bvchop)
(:rewrite mod-of-expt-of-2)))
(defthm unsigned-byte-p-of-bvchop-when-already
(implies (unsigned-byte-p n x)
(unsigned-byte-p n (bvchop m x)))
:hints (("Goal" :in-theory (enable unsigned-byte-p))))
;; Replaces mod with bvchop
;; rename
;kill the version with 4 hard-coded
(defthmd mod-of-expt-of-2-constant-version
(implies (and (syntaxp (quotep k)) ;new..
(power-of-2p k) ;(equal k (expt 2 (+ -1 (integer-length k))))
(integerp x)
;(natp k)
)
(equal (mod x k)
(bvchop (+ -1 (integer-length k)) x)))
:hints (("Goal" :in-theory (e/d (power-of-2p) (mod-of-expt-of-2))
:use (:instance mod-of-expt-of-2
(m (+ -1 (integer-length k)))))))
(theory-invariant (incompatible (:definition bvchop) (:rewrite MOD-OF-EXPT-OF-2-CONSTANT-VERSION)))
(defthm bitp-of-bvchop-of-1
(bitp (acl2::bvchop 1 x)))
(defthm bvchop-+-cancel-cross
(implies (and (force (integerp i))
(force (integerp j))
(force (integerp k)))
(equal (equal (bvchop size (+ j i))
(bvchop size (+ i k)))
(equal (bvchop size j)
(bvchop size k)))))
(defthm bvchop-+-cancel-cross2
(implies (and (force (integerp i))
(force (integerp j))
(force (integerp k)))
(equal (equal (bvchop size (+ i j))
(bvchop size (+ k i)))
(equal (bvchop size j)
(bvchop size k)))))
(defthm bvchop-of-*-of-expt-when-<=
(implies (and (<= size n)
(integerp x)
(natp n)
;(natp size)
)
(equal (bvchop size (* x (expt 2 n)))
0))
:hints (("Goal" :cases ((natp size)))))
(defthm bvchop-identity-cheap
(implies (and (unsigned-byte-p freesize i)
(<= freesize size)
(integerp size))
(equal (bvchop size i)
i))
:hints (("Goal" :in-theory (enable unsigned-byte-p))))
(defthm bvchop-of-both-sides
(implies (equal x y)
(equal (bvchop size x)
(bvchop size y)))
:rule-classes nil)
(defthmd bvchop-upper-bound-3
(implies (and (<= (+ -1 (expt 2 n)) k)
(natp n))
(not (< k (bvchop n x))))
:hints (("Goal" :cases ((<= low high))
:use (:instance bound-when-usb (x (bvchop n x)))
:in-theory (disable bound-when-usb))))
;bozo more like this?
(defthmd bvchop-upper-bound-3-constant-version
(implies (and (syntaxp (quotep k))
(<= (+ -1 (expt 2 n)) k)
(natp n))
(not (< k (bvchop n x))))
:hints (("Goal" :cases ((<= low high))
:use (:instance bound-when-usb (x (bvchop n x)))
:in-theory (disable bound-when-usb))))
(defthmd bvchop-of-*-when-unsigned-byte-p-of-*-of-bvchop-and-bvchop
(implies (and (integerp x)
(integerp y))
(implies (unsigned-byte-p size (* (bvchop size x) (bvchop size y)))
(equal (bvchop size (* x y))
(* (bvchop size x) (bvchop size y)))))
:hints (("Goal" :use ((:instance bvchop-of-*-of-bvchop)
(:instance bvchop-of-*-of-bvchop-arg2
(x (bvchop size x))))
:in-theory (disable bvchop-of-*-of-bvchop
bvchop-of-*-of-bvchop-arg2
bvchop-times-cancel-better-alt))))
;gen the exponent
(defthm bvchop-of-plus-of-expt-bigger
(implies (and (posp size)
(integerp x))
(equal (bvchop (+ -1 size) (+ x (expt 2 size)))
(bvchop (+ -1 size) x))))
(defthm bvchop-of-+-of-bvchop-arg3
(implies (and (integerp x)
(integerp y)
(integerp z))
(equal (bvchop size (+ x y (bvchop size z)))
(bvchop size (+ x y z))))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-of-+-of-*-of-bvchop
(implies (and (integerp x)
(integerp y)
(integerp z))
(equal (bvchop size (+ x (* y (bvchop size z))))
(bvchop size (+ x (* y z))))))
(defthm bvchop-of-*-of-expt-arg3
(implies (and (<= size size2)
(integerp x)
(integerp y)
(natp size)
(natp size2))
(equal (bvchop size (* x y (expt 2 size2)))
0))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-of-+-of-expt-arg2-arg3
(implies (and (<= size size2)
(integerp x)
(integerp y)
(integerp z)
(natp size)
(natp size2))
(equal (bvchop size (+ x (* y z (expt 2 size2))))
(bvchop size x))))
;gen?
(defthm bvchop-31-of-*-of-2147483648
(IMPLIES (INTEGERP X)
(EQUAL (BVCHOP 31 (* 2147483648 X))
0))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-of-+-of---of-*-of-expt
(implies (and (integerp x)
(integerp y)
(natp size))
(equal (bvchop size (+ (- (* x (expt 2 size))) y))
(bvchop size y))))
(local
(defthmd mod-both-sides
(implies (equal x1 x2)
(equal (mod x1 y) (mod x2 y)))))
(defthm bvchops-same-when-bvchops-same
(implies (and (equal (bvchop free x) (bvchop free y))
(<= n free)
(natp free)
(natp n)
)
(equal (equal (bvchop n x) (bvchop n y))
t))
:hints (("Goal" :use ((:instance BVCHOP-OF-BVCHOP (size1 n) (size free) (i x))
(:instance BVCHOP-OF-BVCHOP (size1 n) (size free) (i y)))
:in-theory (disable BVCHOP-OF-BVCHOP))))
(defthm bvchop-of-1-and-+-of-1-and-expt
(implies (posp i)
(equal (BVCHOP 1 (+ 1 (EXPT 2 i)))
1))
:hints (("Goal" :in-theory (enable bvchop))))
|
32109
|
; BV Library: Theorems about bvchop.
;
; Copyright (C) 2008-2011 <NAME> and Stanford University
; Copyright (C) 2013-2022 Kestrel Institute
;
; License: A 3-clause BSD license. See the file books/3BSD-mod.txt.
;
; Author: <NAME> (<EMAIL>)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "ACL2")
(include-book "bvchop-def")
(include-book "../arithmetic-light/power-of-2p")
(local (include-book "unsigned-byte-p"))
(local (include-book "../arithmetic-light/expt2"))
(local (include-book "../arithmetic-light/times"))
(local (include-book "../arithmetic-light/times-and-divides"))
(local (include-book "../arithmetic-light/divides"))
(local (include-book "../arithmetic-light/plus"))
(local (include-book "../arithmetic-light/floor"))
(local (include-book "../arithmetic-light/mod"))
(local (include-book "../arithmetic-light/mod-and-expt"))
;move
(defthm unsigned-byte-p-of-0-arg1
(equal (unsigned-byte-p 0 x)
(equal 0 x))
:hints (("Goal" :in-theory (enable unsigned-byte-p))))
(in-theory (disable unsigned-byte-p))
;(in-theory (disable BACKCHAIN-SIGNED-BYTE-P-TO-UNSIGNED-BYTE-P)) ;slow
(in-theory (disable mod floor))
;move
(defthm integerp-of-bvchop
(integerp (bvchop size x))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm natp-of-bvchop
(natp (bvchop n x))
:rule-classes :type-prescription)
(in-theory (disable (:t bvchop))) ;natp-of-bvchop is at least as good
(defthm bvchop-with-n-not-an-integer
(implies (not (integerp n))
(equal (bvchop n x) 0))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-when-not-natp-arg1-cheap
(implies (not (natp n))
(equal (bvchop n x)
0))
:rule-classes ((:rewrite :backchain-limit-lst (0)))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-when-i-is-not-an-integer
(implies (not (integerp i))
(equal (bvchop size i)
0))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-with-n-negative
(implies (<= n 0)
(equal (bvchop n x)
0))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-size-0-better
(equal (bvchop size 0)
0)
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-upper-bound
(< (bvchop n x) (expt 2 n))
:rule-classes (:rewrite :linear)
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-upper-bound-linear-strong
(implies (natp n)
(<= (bvchop n x) (+ -1 (expt 2 n))))
:rule-classes :linear)
(local
(defthm bvchop-of-bvchop2
(implies (and (<= 0 size1)
(integerp size1)
(integerp size)
(<= 0 size))
(equal (bvchop size1 (bvchop size i))
(if (< size1 size)
(bvchop size1 i)
(bvchop size i))))
:hints (("Goal" :cases ((integerp i))
:in-theory (enable bvchop mod-of-mod-when-mult)))))
;this one has the advantage of being a "simple" rule
(defthm bvchop-of-bvchop-same
(equal (bvchop n (bvchop n x))
(bvchop n x))
:hints (("Goal" :cases ((natp n) (not (integerp n))))))
(local
(defthm bvchop-bvchop-better-helper
(implies (and (>= size1 0)
(integerp size1)
(>= size 0)
(integerp size)
)
(equal (bvchop size1 (bvchop size i))
(if (< size1 size)
(bvchop size1 i)
(bvchop size i))))
:hints (("Goal" :cases ((integerp i))))))
(defthm bvchop-of-bvchop
(equal (bvchop size1 (bvchop size i))
(if (< (ifix size1) (ifix size))
(bvchop size1 i)
(bvchop size i)))
:hints (("Goal" :use (:instance bvchop-bvchop-better-helper (size (ifix size)) (size1 (ifix size1)))
:in-theory (disable bvchop-bvchop-better-helper))))
;allow the sizes to differ?
;or just use the meta rule...
(defthm bvchop-of-*-of-bvchop
(implies (and (integerp x)
(integerp y))
(equal (bvchop size (* (bvchop size x) y))
(bvchop size (* x y))))
:hints (("Goal" :do-not '(generalize eliminate-destructors)
:in-theory (enable bvchop))))
(defthm bvchop-of-*-of-bvchop-arg2
(implies (and (integerp x)
(integerp y))
(equal (bvchop size (* x (bvchop size y)))
(bvchop size (* x y))))
:hints (("Goal" :do-not '(generalize eliminate-destructors)
:in-theory (enable bvchop))))
;rename
(defthm bvchop-+-bvchop-better
(implies (and (integerp i)
(integerp j))
(equal (bvchop size (+ i (bvchop size j)))
(bvchop size (+ i j))))
:hints (("Goal" :in-theory (enable bvchop))))
;might help if natp is not enabled
(defthm bvchop-when-size-is-not-natp
(implies (not (natp size))
(equal (bvchop size i)
0))
:rule-classes ((:rewrite :backchain-limit-lst (0)))
:hints (("Goal" :in-theory (e/d (bvchop) (;FLOOR-MINUS-ERIC-BETTER ;drop the disable once this is fixed
)))))
(defthm unsigned-byte-p-of-bvchop
(implies (<= size size1)
(equal (unsigned-byte-p size1 (bvchop size i))
(and (>= size1 0)
(integerp size1))))
:hints (("Goal" :in-theory (enable bvchop UNSIGNED-BYTE-P))))
;bozo drop any special cases
(defthm bvchop-bound
(implies (and (syntaxp (and (quotep k)
(quotep n)))
(<= (expt 2 n) k))
(< (bvchop n x) k))
:hints (("Goal" :use (:instance unsigned-byte-p-of-bvchop (i x) (size n) (size1 n))
:do-not '(generalize eliminate-destructors)
:in-theory (e/d (zip bvchop)
(unsigned-byte-p-of-bvchop)))))
;; Do not remove: helps justify the correctness of some operations done by Axe.
(defthm bvchop-of-ifix
(equal (bvchop size (ifix x))
(bvchop size x))
:hints (("Goal" :in-theory (enable bvchop-when-i-is-not-an-integer))))
(defthm bvchop-of-0-arg1
(equal (bvchop 0 i)
0))
(defthm bvchop-does-nothing-rewrite
(equal (equal x (bvchop n x))
(if (natp n)
(unsigned-byte-p n x)
(equal 0 x)))
:hints (("Goal" :in-theory (enable bvchop unsigned-byte-p))))
;rename
(defthm bvchop-shift
(implies (integerp x)
(equal (bvchop n (* 2 x))
(if (posp n)
(* 2 (bvchop (+ -1 n) x))
0)))
:hints (("Goal" :in-theory (enable bvchop mod-expt-split))))
(defthm bvchop-when-i-is-not-an-integer-cheap
(implies (not (integerp i))
(equal (bvchop size i)
0))
:rule-classes ((:rewrite :backchain-limit-lst (0)))
:hints (("Goal" :in-theory (enable bvchop-when-i-is-not-an-integer))))
;allow the n's to differ
(defthm bvchop-of-expt-2-n
(equal (bvchop n (expt 2 n))
0)
:hints (("Goal" :in-theory (enable bvchop))))
(defthm equal-constant-when-bvchop-equal-constant-false
(implies (and (syntaxp (quotep const))
(equal free (bvchop freesize x))
(syntaxp (quotep free))
(syntaxp (quotep freesize))
;gets computed:
(not (equal free (bvchop freesize const))))
(not (equal const x))))
(defthm bvchop-of-1
(equal (bvchop n 1)
(if (zp n)
0
1))
:hints (("Goal" :in-theory (enable bvchop))))
(defthmd bvchop-of-sum-cases
(implies (and (integerp i2)
(integerp i1))
(equal (bvchop size (+ i1 i2))
(if (not (natp size))
0
(if (< (+ (bvchop size i1) (bvchop size i2)) (expt 2 size))
(+ (bvchop size i1) (bvchop size i2))
(+ (- (expt 2 size)) (bvchop size i1) (bvchop size i2))))))
:hints (("Goal" :in-theory (enable bvchop mod-sum-cases))))
(defthm bvchop-of-minus-of-bvchop
(equal (bvchop size (- (bvchop size x)))
(bvchop size (- x)))
:hints (("Goal" :cases ((integerp x))
:in-theory (e/d (bvchop) (mod-cancel)))))
;hope this split is okay
(defthmd bvchop-of-minus-helper
(equal (bvchop size (- x))
(if (equal 0 (bvchop size x))
0
(- (expt 2 size) (bvchop size x))))
:hints (("Goal" :in-theory (e/d (bvchop) (mod-cancel)))))
(defthm bvchop-when-size-is-not-posp
(implies (not (posp size))
(equal (bvchop size i) 0))
:rule-classes ((:rewrite :backchain-limit-lst (0)))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-of-minus
(equal (bvchop size (- x))
(if (or (not (natp size))
(equal 0 (bvchop size x)))
0
(- (expt 2 size) (bvchop size x))))
:hints (("Goal" :use ((:instance bvchop-when-size-is-not-natp (i (- x)))
(:instance bvchop-of-minus-helper))
:in-theory (disable bvchop-when-size-is-not-posp
bvchop-when-size-is-not-posp
expt))))
;i guess this one is an abbreviation rule
(defthm unsigned-byte-p-bvchop-same
(equal (unsigned-byte-p size (bvchop size i))
(natp size))
:hints (("Goal" :in-theory (enable unsigned-byte-p))))
;rename
(defthm bvchop-shift-gen
(implies (and (integerp x)
(integerp n)
(natp m))
(equal (bvchop n (* (expt 2 m) x))
(if (<= m n)
(* (expt 2 m) (bvchop (- n m) x))
0)))
:hints (("Goal"
:use (:instance integerp-of-expt-when-natp (i (+ m (- n))) (r 2))
:in-theory (e/d (bvchop mod-cancel
expt-of-+)
(integerp-of-expt-when-natp)))))
(defthm bvchop-shift-gen-alt
(implies (and (integerp x)
(integerp n)
(natp m))
(equal (bvchop n (* x (expt 2 m)))
(if (<= m n)
(* (expt 2 m) (bvchop (- n m) x))
0)))
:hints (("Goal"
:use (:instance integerp-of-expt-when-natp (i (+ m (- n))) (r 2))
:in-theory (e/d (bvchop mod-cancel
expt-of-+)
(integerp-of-expt-when-natp)))))
(defthm bvchop-sum-drop-bvchop
(implies (and (<= m n)
(integerp n)
(integerp z))
(equal (bvchop m (+ (bvchop n y) z))
(bvchop m (+ (ifix y) z))))
:hints (("Goal"
:in-theory (e/d (bvchop mod-of-mod-when-mult) (mod-cancel)))))
(defthm bvchop-sum-drop-bvchop-alt
(implies (and (<= m n)
(integerp n)
(integerp z))
(equal (bvchop m (+ z (bvchop n y)))
(bvchop m (+ (ifix y) z))))
:hints (("Goal" :use (:instance bvchop-sum-drop-bvchop) :in-theory (disable bvchop-sum-drop-bvchop))))
(defthm bvchop-of-expt-hack
(equal (bvchop (+ -1 n) (expt 2 n))
0)
:hints (("Goal" :in-theory (enable bvchop equal-of-0-and-mod))))
;gen
(defthm bvchop-of-expt-hack2
(implies (posp n)
(equal (bvchop 1 (expt 2 n))
0))
:hints (("Goal" :in-theory (enable bvchop floor-when-multiple))))
(defthm bvchop-of-minus-1
(implies (natp n)
(equal (bvchop n -1)
(+ -1 (expt 2 n))))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-of-mask
(implies (and (<= size1 size2)
(natp size1)
(integerp size2))
(equal (bvchop size2 (+ -1 (expt 2 size1)))
(+ -1 (expt 2 size1))))
:hints (("Goal" :in-theory (enable zip unsigned-byte-p))))
;combine with the other
(defthm bvchop-of-mask-other
(implies (and (<= size2 size1)
(natp size2)
(integerp size1))
(equal (bvchop size2 (+ -1 (expt 2 size1)))
(+ -1 (expt 2 size2))))
:hints (("Goal" :induct t ;for speed
:in-theory (enable (:i expt)
bvchop ;mod-cancel
mod-of-mod-when-mult
unsigned-byte-p
mod-sum-cases))))
;make a constant version? maybe not for this one?
(defthm bvchop-of-mask-gen
(implies (and (natp size1)
(natp size2))
(equal (bvchop size2 (+ -1 (expt 2 size1)))
(if (<= size1 size2)
(+ -1 (expt 2 size1))
(+ -1 (expt 2 size2))))))
;gen to any bv...
(defthm bvchop-impossible-value
(implies (and (syntaxp (quotep k))
(not (unsigned-byte-p size k))
(natp size))
(not (equal k (bvchop size x)))))
(defthm bvchop-of-expt-0
(implies (and (<= size1 size2)
(integerp size1)
(integerp size2))
(equal (bvchop size1 (expt 2 size2))
0))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-sum-subst-const
(implies (and (equal (bvchop n x) k)
(syntaxp (and (quotep k)
(not (quotep x))))
(integerp x)
(integerp y))
(equal (bvchop n (+ x y))
(bvchop n (+ k y)))))
(defthm bvchop-sum-subst-const-arg2
(implies (and (equal (bvchop n x) k)
(syntaxp (and (quotep k)
(not (quotep x))))
(integerp x)
(integerp y))
(equal (bvchop n (+ y x))
(bvchop n (+ y k)))))
;gen
;strength reduction
(defthmd mod-by-4-becomes-bvchop
(implies (integerp i)
(equal (mod i 4)
(bvchop 2 i)))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-+-cancel-better
(implies (and (integerp i)
(integerp j)
(integerp k))
(equal (equal (bvchop size (+ i j))
(bvchop size (+ i k)))
(equal (bvchop size j)
(bvchop size k))))
:hints (("Goal" :in-theory (enable bvchop))))
;(in-theory (disable BVCHOP-+-CANCEL))
(defthm bvchop-of-+-cancel-1-2
(implies (and (integerp x)
(integerp y)
(integerp z)
(integerp z2))
(equal (equal (bvchop size (+ x y)) (bvchop size (+ z x z2)))
(equal (bvchop size y) (bvchop size (+ z z2))))))
(defthm bvchop-of-+-cancel-2-2-alt
(implies (and (integerp x)
(integerp y)
(integerp z)
(integerp z2))
(equal (equal (bvchop size (+ y x z)) (bvchop size (+ z2 x)))
(equal (bvchop size (+ y z)) (bvchop size z2)))))
(defthm bvchop-of-+-cancel-1-1
(implies (and (integerp x)
(integerp y)
(integerp z))
(equal (equal (bvchop size (+ x y)) (bvchop size (+ x z)))
(equal (bvchop size y) (bvchop size z)))))
(defthmd bvchop-plus-minus-1-split-gen
(implies (and (syntaxp (quotep k))
(equal k (+ -1 (expt 2 size)))
(integerp x)
(posp size))
(equal (bvchop size (+ k x))
(if (equal 0 (bvchop size x))
(+ -1 (expt 2 size))
(+ -1 (bvchop size x)))))
:hints (("Goal" :in-theory (enable bvchop-of-sum-cases))))
;rename
(defthm bvchop-chop-leading-constant
(implies (and (syntaxp (and (quotep k)
(quotep size)))
(not (unsigned-byte-p size k))
(integerp k)
(integerp x)
;; (natp size)
)
(equal (bvchop size (+ k x))
(bvchop size (+ (bvchop size k) x))))
:hints (("Goal" :cases ((natp size)))))
;rename
(defthm bvchop-times-cancel-better
(implies (and (<= m n)
(integerp x)
(integerp y)
(natp n))
(equal (bvchop m (* (bvchop n x) y))
(bvchop m (* x y))))
:hints (("Goal" :in-theory (e/d (bvchop) (mod-of-*-of-mod))
:use ((:instance mod-of-*-of-mod (z (expt 2 m)) (x y) (y x))
(:instance mod-of-*-of-mod (z (expt 2 m)) (x y) (y (mod x (expt 2 n))))))))
;rename
(defthm bvchop-times-cancel-better-alt
(implies (and (<= m n)
(integerp x)
(integerp y)
(natp n))
(equal (bvchop m (* y (bvchop n x)))
(bvchop m (* y x))))
:hints (("Goal" :use (:instance bvchop-times-cancel-better)
:in-theory (disable bvchop-times-cancel-better))))
(defthm bvchop-of-+-of-expt
(implies (integerp x)
(equal (bvchop size (+ x (expt 2 size)))
(bvchop size x)))
:hints (("Goal":in-theory (enable bvchop))))
(defthm bvchop-of-+-of-expt-alt
(implies (integerp x)
(equal (bvchop size (+ (expt 2 size) x))
(bvchop size x)))
:hints (("Goal" :cases ((natp size)))))
;rename?
;see also <-lemma-for-known-operators2 but that one probably requires a constant for the width
(defthm bvchop-numeric-bound
(implies (and (syntaxp (quotep k))
(<= k 0))
(not (< (bvchop size x) k))))
(defthm bvchop-subst-constant
(implies (and (syntaxp (not (quotep x)))
(equal k (bvchop free x))
(syntaxp (quotep k))
(<= size free)
;(natp size)
(integerp free))
(equal (bvchop size x)
(bvchop size k))))
;subsumes the -0 version
(defthm bvchop-of-expt
(implies (and (integerp size1)
(natp size2))
(equal (bvchop size1 (expt 2 size2))
(if (<= size1 size2)
0
(expt 2 size2))))
:hints (("Goal" :in-theory (e/d (bvchop) (;mod-of-expt-of-2-constant-version mod-of-expt-of-2
)))))
;can this be expensive?
;rename?
(defthm bvchop-bound-rw
(implies (<= 0 x)
(not (< x (bvchop size x))))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm <=-of-bvchop-same-linear
(implies (<= 0 x)
(<= (bvchop n x) x))
:rule-classes :linear)
(defthm <-of-bvchop-and-bvchop-same
(implies (and (<= s1 s2)
(natp s1)
(integerp s2))
(not (< (bvchop s2 x) (bvchop s1 x))))
:hints (("Goal"
:use (:instance bvchop-bound-rw (x (bvchop s2 x)) (size s1))
:in-theory (disable bvchop-bound-rw))))
;Not sure this will fire if SMALL and BIG are constants, due to the free var.
(defthm <=-of-bvchop-same-linear-2
(implies (and (<= small big)
(natp small)
(integerp big))
(<= (bvchop small x) (bvchop big x)))
:rule-classes ((:linear))
:hints (("Goal" :in-theory (enable natp))))
(defthm bvchop-of-nfix
(equal (bvchop (nfix n) x)
(bvchop n x)))
(defthm not-<-of-expt-and-bvchop
(not (< (expt 2 size) (bvchop size x))))
(defthm bvchop-identity
(implies (unsigned-byte-p size i)
(equal (bvchop size i)
i))
:hints (("Goal" :in-theory (enable unsigned-byte-p))))
(defthm bvchop-of-mod-of-expt
(implies (and (<= size j)
(integerp j)
(natp size))
(equal (bvchop size (mod i (expt 2 j)))
(bvchop size i)))
:hints (("Goal" :cases ((rationalp i))
:in-theory (enable bvchop))))
(defthm bvchop-of-+-of-*-of-expt
(implies (and (integerp x)
(natp size))
(equal (bvchop size (+ (* x (expt 2 size)) y))
(bvchop size y)))
:hints (("Goal" :in-theory (enable bvchop equal-of-0-and-mod
mod-sum-cases))))
(defthm bvchop-of-+-of-minus-of-expt
(implies (and (integerp x)
(natp size))
(equal (bvchop size (+ x (- (expt 2 size))))
(bvchop size x)))
:hints (("Goal" :in-theory (enable bvchop
mod-sum-cases))))
(defthm bvchop-of-mod-of-expt-2
(implies (and (< j size)
(integerp size)
(integerp x)
(natp j))
(equal (bvchop size (mod x (expt 2 j)))
(bvchop j x)))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-+-cancel-0
(implies (and (force (integerp j))
(integerp i)
(natp size)
)
(equal (equal (bvchop size (+ i j))
(bvchop size i))
(equal (bvchop size j) 0)))
:hints (("Goal" :use (:instance bvchop-+-cancel-better (k 0))
:in-theory (disable bvchop-+-cancel-better))))
(defthm bvchop-+-cancel-0-alt
(implies (and (force (integerp j))
(integerp i)
(natp size)
)
(equal (equal (bvchop size (+ j i))
(bvchop size i))
(equal (bvchop size j) 0)))
:hints (("Goal" :use (:instance bvchop-+-cancel-better (k 0))
:in-theory (disable bvchop-+-cancel-better))))
(defthmd mod-of-expt-of-2
(implies (and (integerp x)
(natp m))
(equal (mod x (expt 2 m))
(bvchop m x)))
:hints (("Goal" :in-theory (enable bvchop))))
(theory-invariant (incompatible (:definition bvchop)
(:rewrite mod-of-expt-of-2)))
(defthm unsigned-byte-p-of-bvchop-when-already
(implies (unsigned-byte-p n x)
(unsigned-byte-p n (bvchop m x)))
:hints (("Goal" :in-theory (enable unsigned-byte-p))))
;; Replaces mod with bvchop
;; rename
;kill the version with 4 hard-coded
(defthmd mod-of-expt-of-2-constant-version
(implies (and (syntaxp (quotep k)) ;new..
(power-of-2p k) ;(equal k (expt 2 (+ -1 (integer-length k))))
(integerp x)
;(natp k)
)
(equal (mod x k)
(bvchop (+ -1 (integer-length k)) x)))
:hints (("Goal" :in-theory (e/d (power-of-2p) (mod-of-expt-of-2))
:use (:instance mod-of-expt-of-2
(m (+ -1 (integer-length k)))))))
(theory-invariant (incompatible (:definition bvchop) (:rewrite MOD-OF-EXPT-OF-2-CONSTANT-VERSION)))
(defthm bitp-of-bvchop-of-1
(bitp (acl2::bvchop 1 x)))
(defthm bvchop-+-cancel-cross
(implies (and (force (integerp i))
(force (integerp j))
(force (integerp k)))
(equal (equal (bvchop size (+ j i))
(bvchop size (+ i k)))
(equal (bvchop size j)
(bvchop size k)))))
(defthm bvchop-+-cancel-cross2
(implies (and (force (integerp i))
(force (integerp j))
(force (integerp k)))
(equal (equal (bvchop size (+ i j))
(bvchop size (+ k i)))
(equal (bvchop size j)
(bvchop size k)))))
(defthm bvchop-of-*-of-expt-when-<=
(implies (and (<= size n)
(integerp x)
(natp n)
;(natp size)
)
(equal (bvchop size (* x (expt 2 n)))
0))
:hints (("Goal" :cases ((natp size)))))
(defthm bvchop-identity-cheap
(implies (and (unsigned-byte-p freesize i)
(<= freesize size)
(integerp size))
(equal (bvchop size i)
i))
:hints (("Goal" :in-theory (enable unsigned-byte-p))))
(defthm bvchop-of-both-sides
(implies (equal x y)
(equal (bvchop size x)
(bvchop size y)))
:rule-classes nil)
(defthmd bvchop-upper-bound-3
(implies (and (<= (+ -1 (expt 2 n)) k)
(natp n))
(not (< k (bvchop n x))))
:hints (("Goal" :cases ((<= low high))
:use (:instance bound-when-usb (x (bvchop n x)))
:in-theory (disable bound-when-usb))))
;bozo more like this?
(defthmd bvchop-upper-bound-3-constant-version
(implies (and (syntaxp (quotep k))
(<= (+ -1 (expt 2 n)) k)
(natp n))
(not (< k (bvchop n x))))
:hints (("Goal" :cases ((<= low high))
:use (:instance bound-when-usb (x (bvchop n x)))
:in-theory (disable bound-when-usb))))
(defthmd bvchop-of-*-when-unsigned-byte-p-of-*-of-bvchop-and-bvchop
(implies (and (integerp x)
(integerp y))
(implies (unsigned-byte-p size (* (bvchop size x) (bvchop size y)))
(equal (bvchop size (* x y))
(* (bvchop size x) (bvchop size y)))))
:hints (("Goal" :use ((:instance bvchop-of-*-of-bvchop)
(:instance bvchop-of-*-of-bvchop-arg2
(x (bvchop size x))))
:in-theory (disable bvchop-of-*-of-bvchop
bvchop-of-*-of-bvchop-arg2
bvchop-times-cancel-better-alt))))
;gen the exponent
(defthm bvchop-of-plus-of-expt-bigger
(implies (and (posp size)
(integerp x))
(equal (bvchop (+ -1 size) (+ x (expt 2 size)))
(bvchop (+ -1 size) x))))
(defthm bvchop-of-+-of-bvchop-arg3
(implies (and (integerp x)
(integerp y)
(integerp z))
(equal (bvchop size (+ x y (bvchop size z)))
(bvchop size (+ x y z))))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-of-+-of-*-of-bvchop
(implies (and (integerp x)
(integerp y)
(integerp z))
(equal (bvchop size (+ x (* y (bvchop size z))))
(bvchop size (+ x (* y z))))))
(defthm bvchop-of-*-of-expt-arg3
(implies (and (<= size size2)
(integerp x)
(integerp y)
(natp size)
(natp size2))
(equal (bvchop size (* x y (expt 2 size2)))
0))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-of-+-of-expt-arg2-arg3
(implies (and (<= size size2)
(integerp x)
(integerp y)
(integerp z)
(natp size)
(natp size2))
(equal (bvchop size (+ x (* y z (expt 2 size2))))
(bvchop size x))))
;gen?
(defthm bvchop-31-of-*-of-2147483648
(IMPLIES (INTEGERP X)
(EQUAL (BVCHOP 31 (* 2147483648 X))
0))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-of-+-of---of-*-of-expt
(implies (and (integerp x)
(integerp y)
(natp size))
(equal (bvchop size (+ (- (* x (expt 2 size))) y))
(bvchop size y))))
(local
(defthmd mod-both-sides
(implies (equal x1 x2)
(equal (mod x1 y) (mod x2 y)))))
(defthm bvchops-same-when-bvchops-same
(implies (and (equal (bvchop free x) (bvchop free y))
(<= n free)
(natp free)
(natp n)
)
(equal (equal (bvchop n x) (bvchop n y))
t))
:hints (("Goal" :use ((:instance BVCHOP-OF-BVCHOP (size1 n) (size free) (i x))
(:instance BVCHOP-OF-BVCHOP (size1 n) (size free) (i y)))
:in-theory (disable BVCHOP-OF-BVCHOP))))
(defthm bvchop-of-1-and-+-of-1-and-expt
(implies (posp i)
(equal (BVCHOP 1 (+ 1 (EXPT 2 i)))
1))
:hints (("Goal" :in-theory (enable bvchop))))
| true |
; BV Library: Theorems about bvchop.
;
; Copyright (C) 2008-2011 PI:NAME:<NAME>END_PI and Stanford University
; Copyright (C) 2013-2022 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 "bvchop-def")
(include-book "../arithmetic-light/power-of-2p")
(local (include-book "unsigned-byte-p"))
(local (include-book "../arithmetic-light/expt2"))
(local (include-book "../arithmetic-light/times"))
(local (include-book "../arithmetic-light/times-and-divides"))
(local (include-book "../arithmetic-light/divides"))
(local (include-book "../arithmetic-light/plus"))
(local (include-book "../arithmetic-light/floor"))
(local (include-book "../arithmetic-light/mod"))
(local (include-book "../arithmetic-light/mod-and-expt"))
;move
(defthm unsigned-byte-p-of-0-arg1
(equal (unsigned-byte-p 0 x)
(equal 0 x))
:hints (("Goal" :in-theory (enable unsigned-byte-p))))
(in-theory (disable unsigned-byte-p))
;(in-theory (disable BACKCHAIN-SIGNED-BYTE-P-TO-UNSIGNED-BYTE-P)) ;slow
(in-theory (disable mod floor))
;move
(defthm integerp-of-bvchop
(integerp (bvchop size x))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm natp-of-bvchop
(natp (bvchop n x))
:rule-classes :type-prescription)
(in-theory (disable (:t bvchop))) ;natp-of-bvchop is at least as good
(defthm bvchop-with-n-not-an-integer
(implies (not (integerp n))
(equal (bvchop n x) 0))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-when-not-natp-arg1-cheap
(implies (not (natp n))
(equal (bvchop n x)
0))
:rule-classes ((:rewrite :backchain-limit-lst (0)))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-when-i-is-not-an-integer
(implies (not (integerp i))
(equal (bvchop size i)
0))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-with-n-negative
(implies (<= n 0)
(equal (bvchop n x)
0))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-size-0-better
(equal (bvchop size 0)
0)
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-upper-bound
(< (bvchop n x) (expt 2 n))
:rule-classes (:rewrite :linear)
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-upper-bound-linear-strong
(implies (natp n)
(<= (bvchop n x) (+ -1 (expt 2 n))))
:rule-classes :linear)
(local
(defthm bvchop-of-bvchop2
(implies (and (<= 0 size1)
(integerp size1)
(integerp size)
(<= 0 size))
(equal (bvchop size1 (bvchop size i))
(if (< size1 size)
(bvchop size1 i)
(bvchop size i))))
:hints (("Goal" :cases ((integerp i))
:in-theory (enable bvchop mod-of-mod-when-mult)))))
;this one has the advantage of being a "simple" rule
(defthm bvchop-of-bvchop-same
(equal (bvchop n (bvchop n x))
(bvchop n x))
:hints (("Goal" :cases ((natp n) (not (integerp n))))))
(local
(defthm bvchop-bvchop-better-helper
(implies (and (>= size1 0)
(integerp size1)
(>= size 0)
(integerp size)
)
(equal (bvchop size1 (bvchop size i))
(if (< size1 size)
(bvchop size1 i)
(bvchop size i))))
:hints (("Goal" :cases ((integerp i))))))
(defthm bvchop-of-bvchop
(equal (bvchop size1 (bvchop size i))
(if (< (ifix size1) (ifix size))
(bvchop size1 i)
(bvchop size i)))
:hints (("Goal" :use (:instance bvchop-bvchop-better-helper (size (ifix size)) (size1 (ifix size1)))
:in-theory (disable bvchop-bvchop-better-helper))))
;allow the sizes to differ?
;or just use the meta rule...
(defthm bvchop-of-*-of-bvchop
(implies (and (integerp x)
(integerp y))
(equal (bvchop size (* (bvchop size x) y))
(bvchop size (* x y))))
:hints (("Goal" :do-not '(generalize eliminate-destructors)
:in-theory (enable bvchop))))
(defthm bvchop-of-*-of-bvchop-arg2
(implies (and (integerp x)
(integerp y))
(equal (bvchop size (* x (bvchop size y)))
(bvchop size (* x y))))
:hints (("Goal" :do-not '(generalize eliminate-destructors)
:in-theory (enable bvchop))))
;rename
(defthm bvchop-+-bvchop-better
(implies (and (integerp i)
(integerp j))
(equal (bvchop size (+ i (bvchop size j)))
(bvchop size (+ i j))))
:hints (("Goal" :in-theory (enable bvchop))))
;might help if natp is not enabled
(defthm bvchop-when-size-is-not-natp
(implies (not (natp size))
(equal (bvchop size i)
0))
:rule-classes ((:rewrite :backchain-limit-lst (0)))
:hints (("Goal" :in-theory (e/d (bvchop) (;FLOOR-MINUS-ERIC-BETTER ;drop the disable once this is fixed
)))))
(defthm unsigned-byte-p-of-bvchop
(implies (<= size size1)
(equal (unsigned-byte-p size1 (bvchop size i))
(and (>= size1 0)
(integerp size1))))
:hints (("Goal" :in-theory (enable bvchop UNSIGNED-BYTE-P))))
;bozo drop any special cases
(defthm bvchop-bound
(implies (and (syntaxp (and (quotep k)
(quotep n)))
(<= (expt 2 n) k))
(< (bvchop n x) k))
:hints (("Goal" :use (:instance unsigned-byte-p-of-bvchop (i x) (size n) (size1 n))
:do-not '(generalize eliminate-destructors)
:in-theory (e/d (zip bvchop)
(unsigned-byte-p-of-bvchop)))))
;; Do not remove: helps justify the correctness of some operations done by Axe.
(defthm bvchop-of-ifix
(equal (bvchop size (ifix x))
(bvchop size x))
:hints (("Goal" :in-theory (enable bvchop-when-i-is-not-an-integer))))
(defthm bvchop-of-0-arg1
(equal (bvchop 0 i)
0))
(defthm bvchop-does-nothing-rewrite
(equal (equal x (bvchop n x))
(if (natp n)
(unsigned-byte-p n x)
(equal 0 x)))
:hints (("Goal" :in-theory (enable bvchop unsigned-byte-p))))
;rename
(defthm bvchop-shift
(implies (integerp x)
(equal (bvchop n (* 2 x))
(if (posp n)
(* 2 (bvchop (+ -1 n) x))
0)))
:hints (("Goal" :in-theory (enable bvchop mod-expt-split))))
(defthm bvchop-when-i-is-not-an-integer-cheap
(implies (not (integerp i))
(equal (bvchop size i)
0))
:rule-classes ((:rewrite :backchain-limit-lst (0)))
:hints (("Goal" :in-theory (enable bvchop-when-i-is-not-an-integer))))
;allow the n's to differ
(defthm bvchop-of-expt-2-n
(equal (bvchop n (expt 2 n))
0)
:hints (("Goal" :in-theory (enable bvchop))))
(defthm equal-constant-when-bvchop-equal-constant-false
(implies (and (syntaxp (quotep const))
(equal free (bvchop freesize x))
(syntaxp (quotep free))
(syntaxp (quotep freesize))
;gets computed:
(not (equal free (bvchop freesize const))))
(not (equal const x))))
(defthm bvchop-of-1
(equal (bvchop n 1)
(if (zp n)
0
1))
:hints (("Goal" :in-theory (enable bvchop))))
(defthmd bvchop-of-sum-cases
(implies (and (integerp i2)
(integerp i1))
(equal (bvchop size (+ i1 i2))
(if (not (natp size))
0
(if (< (+ (bvchop size i1) (bvchop size i2)) (expt 2 size))
(+ (bvchop size i1) (bvchop size i2))
(+ (- (expt 2 size)) (bvchop size i1) (bvchop size i2))))))
:hints (("Goal" :in-theory (enable bvchop mod-sum-cases))))
(defthm bvchop-of-minus-of-bvchop
(equal (bvchop size (- (bvchop size x)))
(bvchop size (- x)))
:hints (("Goal" :cases ((integerp x))
:in-theory (e/d (bvchop) (mod-cancel)))))
;hope this split is okay
(defthmd bvchop-of-minus-helper
(equal (bvchop size (- x))
(if (equal 0 (bvchop size x))
0
(- (expt 2 size) (bvchop size x))))
:hints (("Goal" :in-theory (e/d (bvchop) (mod-cancel)))))
(defthm bvchop-when-size-is-not-posp
(implies (not (posp size))
(equal (bvchop size i) 0))
:rule-classes ((:rewrite :backchain-limit-lst (0)))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-of-minus
(equal (bvchop size (- x))
(if (or (not (natp size))
(equal 0 (bvchop size x)))
0
(- (expt 2 size) (bvchop size x))))
:hints (("Goal" :use ((:instance bvchop-when-size-is-not-natp (i (- x)))
(:instance bvchop-of-minus-helper))
:in-theory (disable bvchop-when-size-is-not-posp
bvchop-when-size-is-not-posp
expt))))
;i guess this one is an abbreviation rule
(defthm unsigned-byte-p-bvchop-same
(equal (unsigned-byte-p size (bvchop size i))
(natp size))
:hints (("Goal" :in-theory (enable unsigned-byte-p))))
;rename
(defthm bvchop-shift-gen
(implies (and (integerp x)
(integerp n)
(natp m))
(equal (bvchop n (* (expt 2 m) x))
(if (<= m n)
(* (expt 2 m) (bvchop (- n m) x))
0)))
:hints (("Goal"
:use (:instance integerp-of-expt-when-natp (i (+ m (- n))) (r 2))
:in-theory (e/d (bvchop mod-cancel
expt-of-+)
(integerp-of-expt-when-natp)))))
(defthm bvchop-shift-gen-alt
(implies (and (integerp x)
(integerp n)
(natp m))
(equal (bvchop n (* x (expt 2 m)))
(if (<= m n)
(* (expt 2 m) (bvchop (- n m) x))
0)))
:hints (("Goal"
:use (:instance integerp-of-expt-when-natp (i (+ m (- n))) (r 2))
:in-theory (e/d (bvchop mod-cancel
expt-of-+)
(integerp-of-expt-when-natp)))))
(defthm bvchop-sum-drop-bvchop
(implies (and (<= m n)
(integerp n)
(integerp z))
(equal (bvchop m (+ (bvchop n y) z))
(bvchop m (+ (ifix y) z))))
:hints (("Goal"
:in-theory (e/d (bvchop mod-of-mod-when-mult) (mod-cancel)))))
(defthm bvchop-sum-drop-bvchop-alt
(implies (and (<= m n)
(integerp n)
(integerp z))
(equal (bvchop m (+ z (bvchop n y)))
(bvchop m (+ (ifix y) z))))
:hints (("Goal" :use (:instance bvchop-sum-drop-bvchop) :in-theory (disable bvchop-sum-drop-bvchop))))
(defthm bvchop-of-expt-hack
(equal (bvchop (+ -1 n) (expt 2 n))
0)
:hints (("Goal" :in-theory (enable bvchop equal-of-0-and-mod))))
;gen
(defthm bvchop-of-expt-hack2
(implies (posp n)
(equal (bvchop 1 (expt 2 n))
0))
:hints (("Goal" :in-theory (enable bvchop floor-when-multiple))))
(defthm bvchop-of-minus-1
(implies (natp n)
(equal (bvchop n -1)
(+ -1 (expt 2 n))))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-of-mask
(implies (and (<= size1 size2)
(natp size1)
(integerp size2))
(equal (bvchop size2 (+ -1 (expt 2 size1)))
(+ -1 (expt 2 size1))))
:hints (("Goal" :in-theory (enable zip unsigned-byte-p))))
;combine with the other
(defthm bvchop-of-mask-other
(implies (and (<= size2 size1)
(natp size2)
(integerp size1))
(equal (bvchop size2 (+ -1 (expt 2 size1)))
(+ -1 (expt 2 size2))))
:hints (("Goal" :induct t ;for speed
:in-theory (enable (:i expt)
bvchop ;mod-cancel
mod-of-mod-when-mult
unsigned-byte-p
mod-sum-cases))))
;make a constant version? maybe not for this one?
(defthm bvchop-of-mask-gen
(implies (and (natp size1)
(natp size2))
(equal (bvchop size2 (+ -1 (expt 2 size1)))
(if (<= size1 size2)
(+ -1 (expt 2 size1))
(+ -1 (expt 2 size2))))))
;gen to any bv...
(defthm bvchop-impossible-value
(implies (and (syntaxp (quotep k))
(not (unsigned-byte-p size k))
(natp size))
(not (equal k (bvchop size x)))))
(defthm bvchop-of-expt-0
(implies (and (<= size1 size2)
(integerp size1)
(integerp size2))
(equal (bvchop size1 (expt 2 size2))
0))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-sum-subst-const
(implies (and (equal (bvchop n x) k)
(syntaxp (and (quotep k)
(not (quotep x))))
(integerp x)
(integerp y))
(equal (bvchop n (+ x y))
(bvchop n (+ k y)))))
(defthm bvchop-sum-subst-const-arg2
(implies (and (equal (bvchop n x) k)
(syntaxp (and (quotep k)
(not (quotep x))))
(integerp x)
(integerp y))
(equal (bvchop n (+ y x))
(bvchop n (+ y k)))))
;gen
;strength reduction
(defthmd mod-by-4-becomes-bvchop
(implies (integerp i)
(equal (mod i 4)
(bvchop 2 i)))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-+-cancel-better
(implies (and (integerp i)
(integerp j)
(integerp k))
(equal (equal (bvchop size (+ i j))
(bvchop size (+ i k)))
(equal (bvchop size j)
(bvchop size k))))
:hints (("Goal" :in-theory (enable bvchop))))
;(in-theory (disable BVCHOP-+-CANCEL))
(defthm bvchop-of-+-cancel-1-2
(implies (and (integerp x)
(integerp y)
(integerp z)
(integerp z2))
(equal (equal (bvchop size (+ x y)) (bvchop size (+ z x z2)))
(equal (bvchop size y) (bvchop size (+ z z2))))))
(defthm bvchop-of-+-cancel-2-2-alt
(implies (and (integerp x)
(integerp y)
(integerp z)
(integerp z2))
(equal (equal (bvchop size (+ y x z)) (bvchop size (+ z2 x)))
(equal (bvchop size (+ y z)) (bvchop size z2)))))
(defthm bvchop-of-+-cancel-1-1
(implies (and (integerp x)
(integerp y)
(integerp z))
(equal (equal (bvchop size (+ x y)) (bvchop size (+ x z)))
(equal (bvchop size y) (bvchop size z)))))
(defthmd bvchop-plus-minus-1-split-gen
(implies (and (syntaxp (quotep k))
(equal k (+ -1 (expt 2 size)))
(integerp x)
(posp size))
(equal (bvchop size (+ k x))
(if (equal 0 (bvchop size x))
(+ -1 (expt 2 size))
(+ -1 (bvchop size x)))))
:hints (("Goal" :in-theory (enable bvchop-of-sum-cases))))
;rename
(defthm bvchop-chop-leading-constant
(implies (and (syntaxp (and (quotep k)
(quotep size)))
(not (unsigned-byte-p size k))
(integerp k)
(integerp x)
;; (natp size)
)
(equal (bvchop size (+ k x))
(bvchop size (+ (bvchop size k) x))))
:hints (("Goal" :cases ((natp size)))))
;rename
(defthm bvchop-times-cancel-better
(implies (and (<= m n)
(integerp x)
(integerp y)
(natp n))
(equal (bvchop m (* (bvchop n x) y))
(bvchop m (* x y))))
:hints (("Goal" :in-theory (e/d (bvchop) (mod-of-*-of-mod))
:use ((:instance mod-of-*-of-mod (z (expt 2 m)) (x y) (y x))
(:instance mod-of-*-of-mod (z (expt 2 m)) (x y) (y (mod x (expt 2 n))))))))
;rename
(defthm bvchop-times-cancel-better-alt
(implies (and (<= m n)
(integerp x)
(integerp y)
(natp n))
(equal (bvchop m (* y (bvchop n x)))
(bvchop m (* y x))))
:hints (("Goal" :use (:instance bvchop-times-cancel-better)
:in-theory (disable bvchop-times-cancel-better))))
(defthm bvchop-of-+-of-expt
(implies (integerp x)
(equal (bvchop size (+ x (expt 2 size)))
(bvchop size x)))
:hints (("Goal":in-theory (enable bvchop))))
(defthm bvchop-of-+-of-expt-alt
(implies (integerp x)
(equal (bvchop size (+ (expt 2 size) x))
(bvchop size x)))
:hints (("Goal" :cases ((natp size)))))
;rename?
;see also <-lemma-for-known-operators2 but that one probably requires a constant for the width
(defthm bvchop-numeric-bound
(implies (and (syntaxp (quotep k))
(<= k 0))
(not (< (bvchop size x) k))))
(defthm bvchop-subst-constant
(implies (and (syntaxp (not (quotep x)))
(equal k (bvchop free x))
(syntaxp (quotep k))
(<= size free)
;(natp size)
(integerp free))
(equal (bvchop size x)
(bvchop size k))))
;subsumes the -0 version
(defthm bvchop-of-expt
(implies (and (integerp size1)
(natp size2))
(equal (bvchop size1 (expt 2 size2))
(if (<= size1 size2)
0
(expt 2 size2))))
:hints (("Goal" :in-theory (e/d (bvchop) (;mod-of-expt-of-2-constant-version mod-of-expt-of-2
)))))
;can this be expensive?
;rename?
(defthm bvchop-bound-rw
(implies (<= 0 x)
(not (< x (bvchop size x))))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm <=-of-bvchop-same-linear
(implies (<= 0 x)
(<= (bvchop n x) x))
:rule-classes :linear)
(defthm <-of-bvchop-and-bvchop-same
(implies (and (<= s1 s2)
(natp s1)
(integerp s2))
(not (< (bvchop s2 x) (bvchop s1 x))))
:hints (("Goal"
:use (:instance bvchop-bound-rw (x (bvchop s2 x)) (size s1))
:in-theory (disable bvchop-bound-rw))))
;Not sure this will fire if SMALL and BIG are constants, due to the free var.
(defthm <=-of-bvchop-same-linear-2
(implies (and (<= small big)
(natp small)
(integerp big))
(<= (bvchop small x) (bvchop big x)))
:rule-classes ((:linear))
:hints (("Goal" :in-theory (enable natp))))
(defthm bvchop-of-nfix
(equal (bvchop (nfix n) x)
(bvchop n x)))
(defthm not-<-of-expt-and-bvchop
(not (< (expt 2 size) (bvchop size x))))
(defthm bvchop-identity
(implies (unsigned-byte-p size i)
(equal (bvchop size i)
i))
:hints (("Goal" :in-theory (enable unsigned-byte-p))))
(defthm bvchop-of-mod-of-expt
(implies (and (<= size j)
(integerp j)
(natp size))
(equal (bvchop size (mod i (expt 2 j)))
(bvchop size i)))
:hints (("Goal" :cases ((rationalp i))
:in-theory (enable bvchop))))
(defthm bvchop-of-+-of-*-of-expt
(implies (and (integerp x)
(natp size))
(equal (bvchop size (+ (* x (expt 2 size)) y))
(bvchop size y)))
:hints (("Goal" :in-theory (enable bvchop equal-of-0-and-mod
mod-sum-cases))))
(defthm bvchop-of-+-of-minus-of-expt
(implies (and (integerp x)
(natp size))
(equal (bvchop size (+ x (- (expt 2 size))))
(bvchop size x)))
:hints (("Goal" :in-theory (enable bvchop
mod-sum-cases))))
(defthm bvchop-of-mod-of-expt-2
(implies (and (< j size)
(integerp size)
(integerp x)
(natp j))
(equal (bvchop size (mod x (expt 2 j)))
(bvchop j x)))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-+-cancel-0
(implies (and (force (integerp j))
(integerp i)
(natp size)
)
(equal (equal (bvchop size (+ i j))
(bvchop size i))
(equal (bvchop size j) 0)))
:hints (("Goal" :use (:instance bvchop-+-cancel-better (k 0))
:in-theory (disable bvchop-+-cancel-better))))
(defthm bvchop-+-cancel-0-alt
(implies (and (force (integerp j))
(integerp i)
(natp size)
)
(equal (equal (bvchop size (+ j i))
(bvchop size i))
(equal (bvchop size j) 0)))
:hints (("Goal" :use (:instance bvchop-+-cancel-better (k 0))
:in-theory (disable bvchop-+-cancel-better))))
(defthmd mod-of-expt-of-2
(implies (and (integerp x)
(natp m))
(equal (mod x (expt 2 m))
(bvchop m x)))
:hints (("Goal" :in-theory (enable bvchop))))
(theory-invariant (incompatible (:definition bvchop)
(:rewrite mod-of-expt-of-2)))
(defthm unsigned-byte-p-of-bvchop-when-already
(implies (unsigned-byte-p n x)
(unsigned-byte-p n (bvchop m x)))
:hints (("Goal" :in-theory (enable unsigned-byte-p))))
;; Replaces mod with bvchop
;; rename
;kill the version with 4 hard-coded
(defthmd mod-of-expt-of-2-constant-version
(implies (and (syntaxp (quotep k)) ;new..
(power-of-2p k) ;(equal k (expt 2 (+ -1 (integer-length k))))
(integerp x)
;(natp k)
)
(equal (mod x k)
(bvchop (+ -1 (integer-length k)) x)))
:hints (("Goal" :in-theory (e/d (power-of-2p) (mod-of-expt-of-2))
:use (:instance mod-of-expt-of-2
(m (+ -1 (integer-length k)))))))
(theory-invariant (incompatible (:definition bvchop) (:rewrite MOD-OF-EXPT-OF-2-CONSTANT-VERSION)))
(defthm bitp-of-bvchop-of-1
(bitp (acl2::bvchop 1 x)))
(defthm bvchop-+-cancel-cross
(implies (and (force (integerp i))
(force (integerp j))
(force (integerp k)))
(equal (equal (bvchop size (+ j i))
(bvchop size (+ i k)))
(equal (bvchop size j)
(bvchop size k)))))
(defthm bvchop-+-cancel-cross2
(implies (and (force (integerp i))
(force (integerp j))
(force (integerp k)))
(equal (equal (bvchop size (+ i j))
(bvchop size (+ k i)))
(equal (bvchop size j)
(bvchop size k)))))
(defthm bvchop-of-*-of-expt-when-<=
(implies (and (<= size n)
(integerp x)
(natp n)
;(natp size)
)
(equal (bvchop size (* x (expt 2 n)))
0))
:hints (("Goal" :cases ((natp size)))))
(defthm bvchop-identity-cheap
(implies (and (unsigned-byte-p freesize i)
(<= freesize size)
(integerp size))
(equal (bvchop size i)
i))
:hints (("Goal" :in-theory (enable unsigned-byte-p))))
(defthm bvchop-of-both-sides
(implies (equal x y)
(equal (bvchop size x)
(bvchop size y)))
:rule-classes nil)
(defthmd bvchop-upper-bound-3
(implies (and (<= (+ -1 (expt 2 n)) k)
(natp n))
(not (< k (bvchop n x))))
:hints (("Goal" :cases ((<= low high))
:use (:instance bound-when-usb (x (bvchop n x)))
:in-theory (disable bound-when-usb))))
;bozo more like this?
(defthmd bvchop-upper-bound-3-constant-version
(implies (and (syntaxp (quotep k))
(<= (+ -1 (expt 2 n)) k)
(natp n))
(not (< k (bvchop n x))))
:hints (("Goal" :cases ((<= low high))
:use (:instance bound-when-usb (x (bvchop n x)))
:in-theory (disable bound-when-usb))))
(defthmd bvchop-of-*-when-unsigned-byte-p-of-*-of-bvchop-and-bvchop
(implies (and (integerp x)
(integerp y))
(implies (unsigned-byte-p size (* (bvchop size x) (bvchop size y)))
(equal (bvchop size (* x y))
(* (bvchop size x) (bvchop size y)))))
:hints (("Goal" :use ((:instance bvchop-of-*-of-bvchop)
(:instance bvchop-of-*-of-bvchop-arg2
(x (bvchop size x))))
:in-theory (disable bvchop-of-*-of-bvchop
bvchop-of-*-of-bvchop-arg2
bvchop-times-cancel-better-alt))))
;gen the exponent
(defthm bvchop-of-plus-of-expt-bigger
(implies (and (posp size)
(integerp x))
(equal (bvchop (+ -1 size) (+ x (expt 2 size)))
(bvchop (+ -1 size) x))))
(defthm bvchop-of-+-of-bvchop-arg3
(implies (and (integerp x)
(integerp y)
(integerp z))
(equal (bvchop size (+ x y (bvchop size z)))
(bvchop size (+ x y z))))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-of-+-of-*-of-bvchop
(implies (and (integerp x)
(integerp y)
(integerp z))
(equal (bvchop size (+ x (* y (bvchop size z))))
(bvchop size (+ x (* y z))))))
(defthm bvchop-of-*-of-expt-arg3
(implies (and (<= size size2)
(integerp x)
(integerp y)
(natp size)
(natp size2))
(equal (bvchop size (* x y (expt 2 size2)))
0))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-of-+-of-expt-arg2-arg3
(implies (and (<= size size2)
(integerp x)
(integerp y)
(integerp z)
(natp size)
(natp size2))
(equal (bvchop size (+ x (* y z (expt 2 size2))))
(bvchop size x))))
;gen?
(defthm bvchop-31-of-*-of-2147483648
(IMPLIES (INTEGERP X)
(EQUAL (BVCHOP 31 (* 2147483648 X))
0))
:hints (("Goal" :in-theory (enable bvchop))))
(defthm bvchop-of-+-of---of-*-of-expt
(implies (and (integerp x)
(integerp y)
(natp size))
(equal (bvchop size (+ (- (* x (expt 2 size))) y))
(bvchop size y))))
(local
(defthmd mod-both-sides
(implies (equal x1 x2)
(equal (mod x1 y) (mod x2 y)))))
(defthm bvchops-same-when-bvchops-same
(implies (and (equal (bvchop free x) (bvchop free y))
(<= n free)
(natp free)
(natp n)
)
(equal (equal (bvchop n x) (bvchop n y))
t))
:hints (("Goal" :use ((:instance BVCHOP-OF-BVCHOP (size1 n) (size free) (i x))
(:instance BVCHOP-OF-BVCHOP (size1 n) (size free) (i y)))
:in-theory (disable BVCHOP-OF-BVCHOP))))
(defthm bvchop-of-1-and-+-of-1-and-expt
(implies (posp i)
(equal (BVCHOP 1 (+ 1 (EXPT 2 i)))
1))
:hints (("Goal" :in-theory (enable bvchop))))
|
[
{
"context": ";; Copyright 2010-2018 Ben Lambert\n\n;; Licensed under the Apache License, Version 2.",
"end": 34,
"score": 0.9998335242271423,
"start": 23,
"tag": "NAME",
"value": "Ben Lambert"
}
] |
optimization/src/iterative-scaling.lisp
|
belambert/cl-machine-learning
| 1 |
;; Copyright 2010-2018 Ben Lambert
;; 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 :optimization)
(defun iterative-scaling (&key objective-function feature-expectation-function model data (iterations 10))
"Run the iterative scaling algorithm. This requires an objective function, an initial array of parameter values,
a feature expectation function, model, data, and iterations. Convergence is *not* detected automatically."
(let* ((x (parameters model))
(f 0.0d0))
(dotimes (i iterations)
(format t "iteration: ~S~%" i)
(setf f (funcall objective-function x model data))
(format t "Objective function value = ~10,5F~%" f)
(let ((expected-counts (funcall feature-expectation-function model data)))
(is-param-update model expected-counts)))))
(defun is-param-update (model model-predicted-feature-counts)
"Itertive scaling parmeter update. The update rule is: 1/M * log (data-exp/model-exp) .... where M=1??? (for boolean features?)"
(map-into model-predicted-feature-counts '/ (feature-counts model) model-predicted-feature-counts)
(map-into model-predicted-feature-counts (lambda (x) (if (> x 0)
(log x)
0.0d0))
model-predicted-feature-counts)
;; do the update here
(map-into (parameters model) '+ (parameters model) model-predicted-feature-counts))
;;;;TODO: The following, the step size, is needed for improved iterative scaling?
(defun get-approximate-step-size-vector (model data)
"???? Not implemented... but this is important for efficiency?"
(declare (ignore model data))
(error "Not implemented."))
|
54486
|
;; Copyright 2010-2018 <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 :optimization)
(defun iterative-scaling (&key objective-function feature-expectation-function model data (iterations 10))
"Run the iterative scaling algorithm. This requires an objective function, an initial array of parameter values,
a feature expectation function, model, data, and iterations. Convergence is *not* detected automatically."
(let* ((x (parameters model))
(f 0.0d0))
(dotimes (i iterations)
(format t "iteration: ~S~%" i)
(setf f (funcall objective-function x model data))
(format t "Objective function value = ~10,5F~%" f)
(let ((expected-counts (funcall feature-expectation-function model data)))
(is-param-update model expected-counts)))))
(defun is-param-update (model model-predicted-feature-counts)
"Itertive scaling parmeter update. The update rule is: 1/M * log (data-exp/model-exp) .... where M=1??? (for boolean features?)"
(map-into model-predicted-feature-counts '/ (feature-counts model) model-predicted-feature-counts)
(map-into model-predicted-feature-counts (lambda (x) (if (> x 0)
(log x)
0.0d0))
model-predicted-feature-counts)
;; do the update here
(map-into (parameters model) '+ (parameters model) model-predicted-feature-counts))
;;;;TODO: The following, the step size, is needed for improved iterative scaling?
(defun get-approximate-step-size-vector (model data)
"???? Not implemented... but this is important for efficiency?"
(declare (ignore model data))
(error "Not implemented."))
| true |
;; Copyright 2010-2018 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 :optimization)
(defun iterative-scaling (&key objective-function feature-expectation-function model data (iterations 10))
"Run the iterative scaling algorithm. This requires an objective function, an initial array of parameter values,
a feature expectation function, model, data, and iterations. Convergence is *not* detected automatically."
(let* ((x (parameters model))
(f 0.0d0))
(dotimes (i iterations)
(format t "iteration: ~S~%" i)
(setf f (funcall objective-function x model data))
(format t "Objective function value = ~10,5F~%" f)
(let ((expected-counts (funcall feature-expectation-function model data)))
(is-param-update model expected-counts)))))
(defun is-param-update (model model-predicted-feature-counts)
"Itertive scaling parmeter update. The update rule is: 1/M * log (data-exp/model-exp) .... where M=1??? (for boolean features?)"
(map-into model-predicted-feature-counts '/ (feature-counts model) model-predicted-feature-counts)
(map-into model-predicted-feature-counts (lambda (x) (if (> x 0)
(log x)
0.0d0))
model-predicted-feature-counts)
;; do the update here
(map-into (parameters model) '+ (parameters model) model-predicted-feature-counts))
;;;;TODO: The following, the step size, is needed for improved iterative scaling?
(defun get-approximate-step-size-vector (model data)
"???? Not implemented... but this is important for efficiency?"
(declare (ignore model data))
(error "Not implemented."))
|
[
{
"context": ";; spec-plot.lsp -- spectral plot function\n;;\n;; Roger B. Dannenberg, May 2016\n;;\n\n(setf *spec-plot-bw* 8000.0) ;; hig",
"end": 68,
"score": 0.9998654127120972,
"start": 49,
"tag": "NAME",
"value": "Roger B. Dannenberg"
}
] |
nyquist/spec-plot.lsp
|
joshrose/audacity
| 7,892 |
;; spec-plot.lsp -- spectral plot function
;;
;; Roger B. Dannenberg, May 2016
;;
(setf *spec-plot-bw* 8000.0) ;; higest frequency to plot (default)
(setf *spec-plot-res* 20.0) ;; bin size (default)
(setf *spec-plot-db* nil) ;; plot dB? (default)
;; We want to allow round-number bin-sizes so plot will be more readable
;; Assuming 20Hz as an example, the FFT size would have to be
;; 44100/20 = 2205, but that's not a power of 2, so we should resample
;; the signal down so that the FFT size is 2048 (or up to 4096). This
;; would result in sample rates of 2048*20 = 40960 or 81120. We should
;; pick the smaller one if it is at least 2x *spec-plot-bw*.
(defun spec-plot (sound &optional offset &key (res *spec-plot-res*)
(bw *spec-plot-bw*)
(db *spec-plot-db*))
(ny:typecheck (not (soundp sound))
(ny:error "SPEC-PLOT" 1 '((SOUND) nil) sound))
(ny:typecheck (not (or (null offset) (numberp offset)))
(ny:error "SPEC-PLOT" 2 '((NUMBER NULL) nil) offset))
(let (newsr sa fft-size power2)
(setf fft-size (/ (snd-srate sound) res))
(setf power2 8) ;; find integer size for FFT
(while (< power2 fft-size)
(setf power2 (* 2 power2)))
;; now power2 >= fft-size
(cond ((> power2 fft-size) ;; not equal, must resample
;; if half power2 * res is above 2 * bw,
;; use half power2 as fft size
(cond ((> (* power2 res) (* 4 bw))
(setf power2 (/ power2 2))))
(setf sound (snd-resample sound (* power2 res)))
(setf fft-size power2)))
;; we only need fft-dur samples, but allow an extra second just to
;; avoid any rounding errors
(if offset
(setf sound (extract offset (+ 1.0 offset (/ (snd-srate sound)
fft-size)) sound)))
(setf sa (sa-init :resolution res :input sound))
(setf mag (sa-magnitude (sa-next sa)))
(setf mag (snd-from-array 0 (/ 1.0 res) mag))
(if db (setf mag (linear-to-db mag)))
(s-plot mag bw (round (/ (float bw) res)))))
|
47398
|
;; spec-plot.lsp -- spectral plot function
;;
;; <NAME>, May 2016
;;
(setf *spec-plot-bw* 8000.0) ;; higest frequency to plot (default)
(setf *spec-plot-res* 20.0) ;; bin size (default)
(setf *spec-plot-db* nil) ;; plot dB? (default)
;; We want to allow round-number bin-sizes so plot will be more readable
;; Assuming 20Hz as an example, the FFT size would have to be
;; 44100/20 = 2205, but that's not a power of 2, so we should resample
;; the signal down so that the FFT size is 2048 (or up to 4096). This
;; would result in sample rates of 2048*20 = 40960 or 81120. We should
;; pick the smaller one if it is at least 2x *spec-plot-bw*.
(defun spec-plot (sound &optional offset &key (res *spec-plot-res*)
(bw *spec-plot-bw*)
(db *spec-plot-db*))
(ny:typecheck (not (soundp sound))
(ny:error "SPEC-PLOT" 1 '((SOUND) nil) sound))
(ny:typecheck (not (or (null offset) (numberp offset)))
(ny:error "SPEC-PLOT" 2 '((NUMBER NULL) nil) offset))
(let (newsr sa fft-size power2)
(setf fft-size (/ (snd-srate sound) res))
(setf power2 8) ;; find integer size for FFT
(while (< power2 fft-size)
(setf power2 (* 2 power2)))
;; now power2 >= fft-size
(cond ((> power2 fft-size) ;; not equal, must resample
;; if half power2 * res is above 2 * bw,
;; use half power2 as fft size
(cond ((> (* power2 res) (* 4 bw))
(setf power2 (/ power2 2))))
(setf sound (snd-resample sound (* power2 res)))
(setf fft-size power2)))
;; we only need fft-dur samples, but allow an extra second just to
;; avoid any rounding errors
(if offset
(setf sound (extract offset (+ 1.0 offset (/ (snd-srate sound)
fft-size)) sound)))
(setf sa (sa-init :resolution res :input sound))
(setf mag (sa-magnitude (sa-next sa)))
(setf mag (snd-from-array 0 (/ 1.0 res) mag))
(if db (setf mag (linear-to-db mag)))
(s-plot mag bw (round (/ (float bw) res)))))
| true |
;; spec-plot.lsp -- spectral plot function
;;
;; PI:NAME:<NAME>END_PI, May 2016
;;
(setf *spec-plot-bw* 8000.0) ;; higest frequency to plot (default)
(setf *spec-plot-res* 20.0) ;; bin size (default)
(setf *spec-plot-db* nil) ;; plot dB? (default)
;; We want to allow round-number bin-sizes so plot will be more readable
;; Assuming 20Hz as an example, the FFT size would have to be
;; 44100/20 = 2205, but that's not a power of 2, so we should resample
;; the signal down so that the FFT size is 2048 (or up to 4096). This
;; would result in sample rates of 2048*20 = 40960 or 81120. We should
;; pick the smaller one if it is at least 2x *spec-plot-bw*.
(defun spec-plot (sound &optional offset &key (res *spec-plot-res*)
(bw *spec-plot-bw*)
(db *spec-plot-db*))
(ny:typecheck (not (soundp sound))
(ny:error "SPEC-PLOT" 1 '((SOUND) nil) sound))
(ny:typecheck (not (or (null offset) (numberp offset)))
(ny:error "SPEC-PLOT" 2 '((NUMBER NULL) nil) offset))
(let (newsr sa fft-size power2)
(setf fft-size (/ (snd-srate sound) res))
(setf power2 8) ;; find integer size for FFT
(while (< power2 fft-size)
(setf power2 (* 2 power2)))
;; now power2 >= fft-size
(cond ((> power2 fft-size) ;; not equal, must resample
;; if half power2 * res is above 2 * bw,
;; use half power2 as fft size
(cond ((> (* power2 res) (* 4 bw))
(setf power2 (/ power2 2))))
(setf sound (snd-resample sound (* power2 res)))
(setf fft-size power2)))
;; we only need fft-dur samples, but allow an extra second just to
;; avoid any rounding errors
(if offset
(setf sound (extract offset (+ 1.0 offset (/ (snd-srate sound)
fft-size)) sound)))
(setf sa (sa-init :resolution res :input sound))
(setf mag (sa-magnitude (sa-next sa)))
(setf mag (snd-from-array 0 (/ 1.0 res) mag))
(if db (setf mag (linear-to-db mag)))
(s-plot mag bw (round (/ (float bw) res)))))
|
[
{
"context": ";An ACL2 Library of Floating Point Arithmetic\n\n;;;David M. Russinoff\n;;;Advanced Micro Devices, Inc.\n;;;February, 1998",
"end": 137,
"score": 0.9998579025268555,
"start": 119,
"tag": "NAME",
"value": "David M. Russinoff"
}
] |
books/rtl/rel1/support/odd.lisp
|
ragerdl/acl2-defthm-rc2
| 1 |
;;;***************************************************************
;;;An ACL2 Library of Floating Point Arithmetic
;;;David M. Russinoff
;;;Advanced Micro Devices, Inc.
;;;February, 1998
;;;***************************************************************
(in-package "ACL2")
(include-book "near")
(defun odd (x n)
(let ((z (fl (* (expt 2 (1- n)) (sig x)))))
(if (evenp z)
(* (sgn x) (1+ z) (expt 2 (- (1+ (expo x)) n)))
(* (sgn x) z (expt 2 (- (1+ (expo x)) n))))))
(defthm odd-pos
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 0))
(> (odd x n) 0))
:rule-classes ()
:hints (("Goal" :in-theory (disable expo sig fl-weakly-monotonic)
:use ((:instance sig-lower-bound)
(:instance pos*
(x (fl (* (sig x) (expt 2 (1- n)))))
(y (expt 2 (- (1+ (expo x)) n))))
(:instance pos*
(x (1+ (fl (* (sig x) (expt 2 (1- n))))))
(y (expt 2 (- (1+ (expo x)) n))))
(:instance sgn+1)
(:instance expo-monotone (x 1) (y (1- n)))
(:instance n<=fl (x (sig x)) (n 1))))))
(defthm odd>=trunc
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 0))
(>= (odd x n) (trunc x n)))
:rule-classes ()
:hints (("Goal" :in-theory (disable expt-pos)
:use ((:instance trunc)
(:instance expt-pos (x (- (1+ (expo x)) n)))))))
(defthm odd-rewrite
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 0))
(equal (odd x n)
(let ((z (fl (* (expt 2 (- (1- n) (expo x))) x))))
(if (evenp z)
(* (1+ z) (expt 2 (- (1+ (expo x)) n)))
(* z (expt 2 (- (1+ (expo x)) n)))))))
:rule-classes ()
:hints (("Goal" :in-theory (enable sig expo sgn))))
(in-theory (disable odd))
(defthm hack2
(implies (and (integerp n)
(rationalp x))
(= (fl (* 1/2 x (expt 2 n)))
(fl (* x (expt 2 (1- n))))))
:rule-classes ())
(defthm odd-other-1
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (trunc x (1- n))
(* (fl (/ (* (expt 2 (- (1- n) (expo x))) x) 2))
(expt 2 (- (+ 2 (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :in-theory (enable trunc-pos-rewrite)
:use ((:instance hack2 (n (- (1- n) (expo x))))))))
(defthm odd-other-2
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (trunc x (1- n))
(* (fl (/ (fl (* (expt 2 (- (1- n) (expo x))) x)) 2))
(expt 2 (- (+ 2 (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :in-theory (disable fl/int)
:use ((:instance odd-other-1)
(:instance fl/int (x (* (expt 2 (- (1- n) (expo x))) x)) (n 2))))))
(defthm fl/2
(implies (integerp z)
(= (fl (/ z 2))
(if (evenp z)
(/ z 2)
(/ (1- z) 2))))
:rule-classes ())
(defthm odd-other-3
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1)
(= z (fl (* (expt 2 (- (1- n) (expo x))) x)))
(evenp z))
(= (trunc x (1- n))
(* z (expt 2 (- (1+ (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance fl/2)
(:instance expo+ (n (- (1+ (expo x)) n)) (m 1))
(:instance odd-other-2)))))
(defthm odd-other-4
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1)
(= z (fl (* (expt 2 (- (1- n) (expo x))) x)))
(not (evenp z)))
(= (* (fl (/ (fl (* (expt 2 (- (1- n) (expo x))) x)) 2))
(expt 2 (- (+ 2 (expo x)) n)))
(* (fl (/ z 2)) (expt 2 (- (+ 2 (expo x)) n)))))
:rule-classes ())
(defthm odd-other-5
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1)
(= z (fl (* (expt 2 (- (1- n) (expo x))) x)))
(not (evenp z)))
(= (trunc x (1- n))
(* (fl (/ z 2)) (expt 2 (- (+ 2 (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance odd-other-2)
(:instance odd-other-4)))))
(defthm hack3
(implies (and (rationalp x)
(rationalp y)
(rationalp z)
(equal x y))
(= (* x z) (* y z)))
:rule-classes ())
(defthm odd-other-6
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1)
(= z (fl (* (expt 2 (- (1- n) (expo x))) x)))
(not (evenp z)))
(= (trunc x (1- n))
(* (/ (1- z) 2) (expt 2 (- (+ 2 (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance fl/2)
(:instance odd-other-5)
(:instance hack3
(x (/ (1- z) 2))
(y (fl (/ z 2)))
(z (expt 2 (- (+ 2 (expo x)) n))))))))
(defthm odd-other-7
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1)
(= z (fl (* (expt 2 (- (1- n) (expo x))) x)))
(not (evenp z)))
(= (trunc x (1- n))
(* (1- z) (expt 2 (- (1+ (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance odd-other-6)
(:instance expo+ (n (- (1+ (expo x)) n)) (m 1))))))
(defthm odd-other
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (odd x n)
(+ (trunc x (1- n))
(expt 2 (- (1+ (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance odd-other-3 (z (fl (* (expt 2 (- (1- n) (expo x))) x))))
(:instance odd-other-7 (z (fl (* (expt 2 (- (1- n) (expo x))) x))))
(:instance odd-rewrite)))))
(defthm expo-odd-1
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 0))
(< (trunc x n) (expt 2 (1+ (expo x)))))
:rule-classes ()
:hints (("Goal" :in-theory (disable expo-trunc abs-trunc)
:use ((:instance expo-trunc)
(:instance trunc-pos)
(:instance expo-upper-bound (x (trunc x n)))))))
(defthm expo-odd-2
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(< (odd x n) (expt 2 (1+ (expo x)))))
:rule-classes ()
:hints (("Goal" :in-theory (disable expo-trunc abs-trunc)
:use ((:instance expo-odd-1 (n (1- n)))
(:instance odd-other)
(:instance exactp-2**n (m (1- n)) (n (1+ (expo x))))
(:instance expo-trunc (n (1- n)))
(:instance expt-strong-monotone (n (- (1+ (expo x)) n)) (m (- (1+ (expo x)) (1- n))))
(:instance trunc-pos (n (1- n)))
(:instance fp+1 (n (1- n)) (x (trunc x (1- n))) (y (expt 2 (1+ (expo x)))))))))
(defthm expo-odd-3
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(<= (expo (odd x n)) (expo x)))
:rule-classes ()
:hints (("Goal" :use ((:instance expo-odd-2)
(:instance odd-pos)
(:instance expo-upper-2 (x (odd x n)) (n (1+ (expo x))))))))
(defthm expo-odd
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(equal (expo (odd x n)) (expo x)))
:hints (("Goal" :in-theory (disable expt-pos abs-trunc)
:use ((:instance expo-odd-3)
(:instance odd-other)
(:instance expt-pos (x (- (1+ (expo x)) n)))
(:instance expo-monotone (y (odd x n)) (x (trunc x (1- n))))
(:instance odd-pos)
(:instance trunc-pos (n (1- n)))))))
(defthm exactp-odd-1
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(= (* (+ (trunc x (1- n))
(expt 2 (- (1+ (expo x)) n)))
(expt 2 (- (1- n) (expo x))))
(1+ (* (trunc x (1- n)) (expt 2 (- (1- n) (expo x)))))))
:rule-classes ()
:hints (("Goal" :in-theory (disable expt-pos abs-trunc)
:use ((:instance expo+ (n (- (1- n) (expo x))) (m (- (1+ (expo x)) n)))))))
(defthm exactp-odd-2
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(= (* (odd x n) (expt 2 (- (1- n) (expo x))))
(1+ (* (trunc x (1- n)) (expt 2 (- (1- n) (expo x)))))))
:rule-classes ()
:hints (("Goal" :in-theory (disable expt-pos abs-trunc)
:use ((:instance odd-other)
(:instance exactp-odd-1)))))
(defthm exactp-odd-3
(implies (and (rationalp x)
(integerp n))
(= (expt 2 (- (1- n) (expo x)))
(* 2 (expt 2 (- (- n 2) (expo x))))))
:rule-classes ()
:hints (("Goal" :use ((:instance expo+ (n (- (- n 2) (expo x))) (m 1))))))
(defthm exactp-odd-4
(implies (and (rationalp x)
(rationalp y)
(integerp n))
(= (* y 2 (expt 2 (- (- n 2) (expo x))))
(* 2 y (expt 2 (- (- n 2) (expo x))))))
:rule-classes ())
(defthm exactp-odd-5
(implies (and (rationalp x)
(integerp n))
(= (* (trunc x (1- n)) (expt 2 (- (1- n) (expo x))))
(* 2 (trunc x (1- n)) (expt 2 (- (- n 2) (expo x))))))
:rule-classes ()
:hints (("Goal" :use ((:instance exactp-odd-3)
(:instance exactp-odd-4 (y (trunc x (1- n))))))))
(defthm exactp-odd-6
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(= (* (odd x n) (expt 2 (- (1- n) (expo x))))
(1+ (* 2 (* (trunc x (1- n)) (expt 2 (- (- n 2) (expo x))))))))
:rule-classes ()
:hints (("Goal" :in-theory (disable expt-pos abs-trunc)
:use ((:instance exactp-odd-2)
(:instance exactp-odd-5)))))
(defthm exactp-odd
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(exactp (odd x n) n))
:rule-classes ()
:hints (("Goal" :in-theory (disable expt-pos abs-trunc)
:use ((:instance exactp-odd-6)
(:instance exactp2 (x (odd x n)))
(:instance exactp2 (x (trunc x (1- n))) (n (1- n)))))))
(defthm not-exactp-odd-1
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(= (* (+ (trunc x (1- n)) (expt 2 (- (1+ (expo x)) n)))
(expt 2 (- (- n 2) (expo x))))
(+ (* (trunc x (1- n)) (expt 2 (- (- n 2) (expo x)))) 1/2)))
:rule-classes ()
:hints (("Goal" :use ((:instance expo+ (m (- (- n 2) (expo x))) (n (- (1+ (expo x)) n)))))))
(defthm not-exactp-odd-2
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(= (* (odd x n)
(expt 2 (- (- n 2) (expo x))))
(+ (* (trunc x (1- n)) (expt 2 (- (- n 2) (expo x)))) 1/2)))
:rule-classes ()
:hints (("Goal" :use ((:instance odd-other)
(:instance not-exactp-odd-1)))))
(defthm not-exactp-odd
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(not (exactp (odd x n) (1- n))))
:rule-classes ()
:hints (("Goal" :in-theory (disable expt-pos abs-trunc)
:use ((:instance not-exactp-odd-2)
(:instance exactp2 (x (odd x n)) (n (1- n)))
(:instance exactp2 (x (trunc x (1- n))) (n (1- n)))))))
(defthm trunc-odd-1
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (trunc (odd x n) (1- n))
(* (fl (* (expt 2 (- (- n 2) (expo x)))
(+ (* (fl (* (expt 2 (- (- n 2) (expo x)))
x))
(expt 2 (- (+ (expo x) 2) n)))
(expt 2 (- (1+ (expo x)) n)))))
(expt 2 (- (+ (expo x) 2) n)))))
:rule-classes ()
:hints (("Goal" :in-theory (enable trunc-pos-rewrite)
:use ((:instance odd-other)
(:instance odd-pos)))))
(defthm trunc-odd-2
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (trunc (odd x n) (1- n))
(* (fl (+ (fl (* (expt 2 (- (- n 2) (expo x)))
x))
1/2))
(expt 2 (- (+ (expo x) 2) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance trunc-odd-1)
(:instance expo+ (m (- (- n 2) (expo x))) (n (- (+ (expo x) 2) n)))
(:instance expo+ (m (- (- n 2) (expo x))) (n (- (+ (expo x) 1) n)))))))
(defthm trunc-odd-3
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (trunc (odd x n) (1- n))
(* (fl (* (expt 2 (- (- n 2) (expo x)))
x))
(expt 2 (- (+ (expo x) 2) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance trunc-odd-2)))))
(defthm trunc-odd-4
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (trunc (odd x n) (1- n))
(trunc x (1- n))))
:rule-classes ()
:hints (("Goal" :in-theory (enable trunc-pos-rewrite)
:use ((:instance trunc-odd-3)))))
(defthm trunc-odd
(implies (and (rationalp x)
(> x 0)
(integerp n)
(integerp m)
(> m 0)
(> n m))
(= (trunc (odd x n) m)
(trunc x m)))
:rule-classes ()
:hints (("Goal" :use ((:instance trunc-odd-4)
(:instance odd-pos)
(:instance trunc-trunc (n (1- n)))
(:instance trunc-trunc (n (1- n)) (x (odd x n)))))))
(defun kp (k x y)
(+ k (- (expo (+ x y)) (expo y))))
(defthm odd-plus
(implies (and (rationalp x)
(rationalp y)
(integerp k)
(> x 0)
(> y 0)
(> k 1)
(> (+ (1- k) (- (expo x) (expo y))) 0)
(exactp x (+ (1- k) (- (expo x) (expo y)))))
(= (+ x (odd y k))
(odd (+ x y) (kp k x y))))
:rule-classes ()
:hints (("Goal" :use ((:instance odd-other (n k) (x y))
(:instance expo-monotone (x y) (y (+ x y)))
(:instance plus-trunc (k (1- k)) (n (+ (1- k) (- (expo x) (expo y)))))
(:instance odd-other (x (+ x y)) (n (kp k x y)))))))
(defthm trunc-trunc-odd
(implies (and (rationalp x)
(rationalp y)
(integerp m)
(integerp k)
(> x y)
(> y 0)
(> k 0)
(>= (- m 2) k))
(>= (trunc x k) (trunc (odd y m) k)))
:rule-classes ()
:hints (("Goal" :use ((:instance trunc-odd (x y) (m k) (n m))
(:instance trunc-monotone (x y) (y x) (n k))))))
(defthm away-away-odd-1
(implies (and (rationalp x)
(rationalp y)
(integerp m)
(integerp k)
(> x y)
(> y 0)
(> k 0)
(>= (- m 2) k))
(> (away x k) (trunc y (1- m))))
:rule-classes ()
:hints (("Goal" :use ((:instance away-lower-pos (n k))
(:instance trunc-upper-pos (x y) (n (1- m)))))))
(defthm away-away-odd-2
(implies (and (rationalp x)
(rationalp y)
(integerp m)
(integerp k)
(> x y)
(> y 0)
(> k 0)
(>= (- m 2) k))
(>= (away x k) (+ (trunc y (1- m)) (expt 2 (- (+ (expo y) 2) m)))))
:rule-classes ()
:hints (("Goal" :use ((:instance away-away-odd-1)
(:instance fp+1 (x (trunc y (1- m))) (y (away x k)) (n (1- m)))
(:instance expo-trunc (x y) (n (1- m)))
(:instance trunc-exactp-b (x y) (n (1- m)))
(:instance away-exactp-b (n k))
(:instance trunc-pos (x y) (n (1- m)))
(:instance exactp-<= (x (away x k)) (m k) (n (1- m)))))))
(defthm away-away-odd-3
(implies (and (rationalp x)
(rationalp y)
(integerp m)
(integerp k)
(> x y)
(> y 0)
(> k 0)
(>= (- m 2) k))
(> (away x k) (odd y m)))
:rule-classes ()
:hints (("Goal" :use ((:instance away-away-odd-2)
(:instance odd-other (x y) (n m))
(:instance expt-strong-monotone (n (- (1+ (expo y)) m)) (m (- (+ (expo y) 2) m)))))))
(defthm away-away-odd
(implies (and (rationalp x)
(rationalp y)
(integerp m)
(integerp k)
(> x y)
(> y 0)
(> k 0)
(>= (- m 2) k))
(>= (away x k) (away (odd y m) k)))
:rule-classes ()
:hints (("Goal" :use ((:instance away-away-odd-3)
(:instance odd-pos (x y) (n m))
(:instance away-exactp-c (a (away x k)) (x (odd y m)) (n k))
(:instance away-exactp-b (n k))))))
(defthm near-near-odd
(implies (and (rationalp x)
(rationalp y)
(integerp m)
(integerp k)
(> x y)
(> y 0)
(> k 0)
(>= (- m 2) k))
(>= (near x k) (near (odd y m) k)))
:rule-classes ()
:hints (("Goal" :use ((:instance trunc-exactp-b (n (1- m)) (x y))
(:instance odd-pos (x y) (n m))
(:instance trunc-pos (x y) (n (1- m)))
(:instance trunc-upper-pos (x y) (n (1- m)))
(:instance expo-trunc (x y) (n (1- m)))
(:instance odd-other (x y) (n m))
(:instance expt-strong-monotone
(n (- (1+ (expo y)) m))
(m (- (+ 2 (expo y)) m)))
(:instance near-near
(n (- m 2))
(a (trunc y (1- m)))
(y (odd y m)))))))
|
74182
|
;;;***************************************************************
;;;An ACL2 Library of Floating Point Arithmetic
;;;<NAME>
;;;Advanced Micro Devices, Inc.
;;;February, 1998
;;;***************************************************************
(in-package "ACL2")
(include-book "near")
(defun odd (x n)
(let ((z (fl (* (expt 2 (1- n)) (sig x)))))
(if (evenp z)
(* (sgn x) (1+ z) (expt 2 (- (1+ (expo x)) n)))
(* (sgn x) z (expt 2 (- (1+ (expo x)) n))))))
(defthm odd-pos
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 0))
(> (odd x n) 0))
:rule-classes ()
:hints (("Goal" :in-theory (disable expo sig fl-weakly-monotonic)
:use ((:instance sig-lower-bound)
(:instance pos*
(x (fl (* (sig x) (expt 2 (1- n)))))
(y (expt 2 (- (1+ (expo x)) n))))
(:instance pos*
(x (1+ (fl (* (sig x) (expt 2 (1- n))))))
(y (expt 2 (- (1+ (expo x)) n))))
(:instance sgn+1)
(:instance expo-monotone (x 1) (y (1- n)))
(:instance n<=fl (x (sig x)) (n 1))))))
(defthm odd>=trunc
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 0))
(>= (odd x n) (trunc x n)))
:rule-classes ()
:hints (("Goal" :in-theory (disable expt-pos)
:use ((:instance trunc)
(:instance expt-pos (x (- (1+ (expo x)) n)))))))
(defthm odd-rewrite
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 0))
(equal (odd x n)
(let ((z (fl (* (expt 2 (- (1- n) (expo x))) x))))
(if (evenp z)
(* (1+ z) (expt 2 (- (1+ (expo x)) n)))
(* z (expt 2 (- (1+ (expo x)) n)))))))
:rule-classes ()
:hints (("Goal" :in-theory (enable sig expo sgn))))
(in-theory (disable odd))
(defthm hack2
(implies (and (integerp n)
(rationalp x))
(= (fl (* 1/2 x (expt 2 n)))
(fl (* x (expt 2 (1- n))))))
:rule-classes ())
(defthm odd-other-1
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (trunc x (1- n))
(* (fl (/ (* (expt 2 (- (1- n) (expo x))) x) 2))
(expt 2 (- (+ 2 (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :in-theory (enable trunc-pos-rewrite)
:use ((:instance hack2 (n (- (1- n) (expo x))))))))
(defthm odd-other-2
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (trunc x (1- n))
(* (fl (/ (fl (* (expt 2 (- (1- n) (expo x))) x)) 2))
(expt 2 (- (+ 2 (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :in-theory (disable fl/int)
:use ((:instance odd-other-1)
(:instance fl/int (x (* (expt 2 (- (1- n) (expo x))) x)) (n 2))))))
(defthm fl/2
(implies (integerp z)
(= (fl (/ z 2))
(if (evenp z)
(/ z 2)
(/ (1- z) 2))))
:rule-classes ())
(defthm odd-other-3
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1)
(= z (fl (* (expt 2 (- (1- n) (expo x))) x)))
(evenp z))
(= (trunc x (1- n))
(* z (expt 2 (- (1+ (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance fl/2)
(:instance expo+ (n (- (1+ (expo x)) n)) (m 1))
(:instance odd-other-2)))))
(defthm odd-other-4
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1)
(= z (fl (* (expt 2 (- (1- n) (expo x))) x)))
(not (evenp z)))
(= (* (fl (/ (fl (* (expt 2 (- (1- n) (expo x))) x)) 2))
(expt 2 (- (+ 2 (expo x)) n)))
(* (fl (/ z 2)) (expt 2 (- (+ 2 (expo x)) n)))))
:rule-classes ())
(defthm odd-other-5
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1)
(= z (fl (* (expt 2 (- (1- n) (expo x))) x)))
(not (evenp z)))
(= (trunc x (1- n))
(* (fl (/ z 2)) (expt 2 (- (+ 2 (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance odd-other-2)
(:instance odd-other-4)))))
(defthm hack3
(implies (and (rationalp x)
(rationalp y)
(rationalp z)
(equal x y))
(= (* x z) (* y z)))
:rule-classes ())
(defthm odd-other-6
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1)
(= z (fl (* (expt 2 (- (1- n) (expo x))) x)))
(not (evenp z)))
(= (trunc x (1- n))
(* (/ (1- z) 2) (expt 2 (- (+ 2 (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance fl/2)
(:instance odd-other-5)
(:instance hack3
(x (/ (1- z) 2))
(y (fl (/ z 2)))
(z (expt 2 (- (+ 2 (expo x)) n))))))))
(defthm odd-other-7
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1)
(= z (fl (* (expt 2 (- (1- n) (expo x))) x)))
(not (evenp z)))
(= (trunc x (1- n))
(* (1- z) (expt 2 (- (1+ (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance odd-other-6)
(:instance expo+ (n (- (1+ (expo x)) n)) (m 1))))))
(defthm odd-other
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (odd x n)
(+ (trunc x (1- n))
(expt 2 (- (1+ (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance odd-other-3 (z (fl (* (expt 2 (- (1- n) (expo x))) x))))
(:instance odd-other-7 (z (fl (* (expt 2 (- (1- n) (expo x))) x))))
(:instance odd-rewrite)))))
(defthm expo-odd-1
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 0))
(< (trunc x n) (expt 2 (1+ (expo x)))))
:rule-classes ()
:hints (("Goal" :in-theory (disable expo-trunc abs-trunc)
:use ((:instance expo-trunc)
(:instance trunc-pos)
(:instance expo-upper-bound (x (trunc x n)))))))
(defthm expo-odd-2
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(< (odd x n) (expt 2 (1+ (expo x)))))
:rule-classes ()
:hints (("Goal" :in-theory (disable expo-trunc abs-trunc)
:use ((:instance expo-odd-1 (n (1- n)))
(:instance odd-other)
(:instance exactp-2**n (m (1- n)) (n (1+ (expo x))))
(:instance expo-trunc (n (1- n)))
(:instance expt-strong-monotone (n (- (1+ (expo x)) n)) (m (- (1+ (expo x)) (1- n))))
(:instance trunc-pos (n (1- n)))
(:instance fp+1 (n (1- n)) (x (trunc x (1- n))) (y (expt 2 (1+ (expo x)))))))))
(defthm expo-odd-3
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(<= (expo (odd x n)) (expo x)))
:rule-classes ()
:hints (("Goal" :use ((:instance expo-odd-2)
(:instance odd-pos)
(:instance expo-upper-2 (x (odd x n)) (n (1+ (expo x))))))))
(defthm expo-odd
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(equal (expo (odd x n)) (expo x)))
:hints (("Goal" :in-theory (disable expt-pos abs-trunc)
:use ((:instance expo-odd-3)
(:instance odd-other)
(:instance expt-pos (x (- (1+ (expo x)) n)))
(:instance expo-monotone (y (odd x n)) (x (trunc x (1- n))))
(:instance odd-pos)
(:instance trunc-pos (n (1- n)))))))
(defthm exactp-odd-1
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(= (* (+ (trunc x (1- n))
(expt 2 (- (1+ (expo x)) n)))
(expt 2 (- (1- n) (expo x))))
(1+ (* (trunc x (1- n)) (expt 2 (- (1- n) (expo x)))))))
:rule-classes ()
:hints (("Goal" :in-theory (disable expt-pos abs-trunc)
:use ((:instance expo+ (n (- (1- n) (expo x))) (m (- (1+ (expo x)) n)))))))
(defthm exactp-odd-2
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(= (* (odd x n) (expt 2 (- (1- n) (expo x))))
(1+ (* (trunc x (1- n)) (expt 2 (- (1- n) (expo x)))))))
:rule-classes ()
:hints (("Goal" :in-theory (disable expt-pos abs-trunc)
:use ((:instance odd-other)
(:instance exactp-odd-1)))))
(defthm exactp-odd-3
(implies (and (rationalp x)
(integerp n))
(= (expt 2 (- (1- n) (expo x)))
(* 2 (expt 2 (- (- n 2) (expo x))))))
:rule-classes ()
:hints (("Goal" :use ((:instance expo+ (n (- (- n 2) (expo x))) (m 1))))))
(defthm exactp-odd-4
(implies (and (rationalp x)
(rationalp y)
(integerp n))
(= (* y 2 (expt 2 (- (- n 2) (expo x))))
(* 2 y (expt 2 (- (- n 2) (expo x))))))
:rule-classes ())
(defthm exactp-odd-5
(implies (and (rationalp x)
(integerp n))
(= (* (trunc x (1- n)) (expt 2 (- (1- n) (expo x))))
(* 2 (trunc x (1- n)) (expt 2 (- (- n 2) (expo x))))))
:rule-classes ()
:hints (("Goal" :use ((:instance exactp-odd-3)
(:instance exactp-odd-4 (y (trunc x (1- n))))))))
(defthm exactp-odd-6
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(= (* (odd x n) (expt 2 (- (1- n) (expo x))))
(1+ (* 2 (* (trunc x (1- n)) (expt 2 (- (- n 2) (expo x))))))))
:rule-classes ()
:hints (("Goal" :in-theory (disable expt-pos abs-trunc)
:use ((:instance exactp-odd-2)
(:instance exactp-odd-5)))))
(defthm exactp-odd
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(exactp (odd x n) n))
:rule-classes ()
:hints (("Goal" :in-theory (disable expt-pos abs-trunc)
:use ((:instance exactp-odd-6)
(:instance exactp2 (x (odd x n)))
(:instance exactp2 (x (trunc x (1- n))) (n (1- n)))))))
(defthm not-exactp-odd-1
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(= (* (+ (trunc x (1- n)) (expt 2 (- (1+ (expo x)) n)))
(expt 2 (- (- n 2) (expo x))))
(+ (* (trunc x (1- n)) (expt 2 (- (- n 2) (expo x)))) 1/2)))
:rule-classes ()
:hints (("Goal" :use ((:instance expo+ (m (- (- n 2) (expo x))) (n (- (1+ (expo x)) n)))))))
(defthm not-exactp-odd-2
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(= (* (odd x n)
(expt 2 (- (- n 2) (expo x))))
(+ (* (trunc x (1- n)) (expt 2 (- (- n 2) (expo x)))) 1/2)))
:rule-classes ()
:hints (("Goal" :use ((:instance odd-other)
(:instance not-exactp-odd-1)))))
(defthm not-exactp-odd
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(not (exactp (odd x n) (1- n))))
:rule-classes ()
:hints (("Goal" :in-theory (disable expt-pos abs-trunc)
:use ((:instance not-exactp-odd-2)
(:instance exactp2 (x (odd x n)) (n (1- n)))
(:instance exactp2 (x (trunc x (1- n))) (n (1- n)))))))
(defthm trunc-odd-1
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (trunc (odd x n) (1- n))
(* (fl (* (expt 2 (- (- n 2) (expo x)))
(+ (* (fl (* (expt 2 (- (- n 2) (expo x)))
x))
(expt 2 (- (+ (expo x) 2) n)))
(expt 2 (- (1+ (expo x)) n)))))
(expt 2 (- (+ (expo x) 2) n)))))
:rule-classes ()
:hints (("Goal" :in-theory (enable trunc-pos-rewrite)
:use ((:instance odd-other)
(:instance odd-pos)))))
(defthm trunc-odd-2
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (trunc (odd x n) (1- n))
(* (fl (+ (fl (* (expt 2 (- (- n 2) (expo x)))
x))
1/2))
(expt 2 (- (+ (expo x) 2) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance trunc-odd-1)
(:instance expo+ (m (- (- n 2) (expo x))) (n (- (+ (expo x) 2) n)))
(:instance expo+ (m (- (- n 2) (expo x))) (n (- (+ (expo x) 1) n)))))))
(defthm trunc-odd-3
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (trunc (odd x n) (1- n))
(* (fl (* (expt 2 (- (- n 2) (expo x)))
x))
(expt 2 (- (+ (expo x) 2) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance trunc-odd-2)))))
(defthm trunc-odd-4
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (trunc (odd x n) (1- n))
(trunc x (1- n))))
:rule-classes ()
:hints (("Goal" :in-theory (enable trunc-pos-rewrite)
:use ((:instance trunc-odd-3)))))
(defthm trunc-odd
(implies (and (rationalp x)
(> x 0)
(integerp n)
(integerp m)
(> m 0)
(> n m))
(= (trunc (odd x n) m)
(trunc x m)))
:rule-classes ()
:hints (("Goal" :use ((:instance trunc-odd-4)
(:instance odd-pos)
(:instance trunc-trunc (n (1- n)))
(:instance trunc-trunc (n (1- n)) (x (odd x n)))))))
(defun kp (k x y)
(+ k (- (expo (+ x y)) (expo y))))
(defthm odd-plus
(implies (and (rationalp x)
(rationalp y)
(integerp k)
(> x 0)
(> y 0)
(> k 1)
(> (+ (1- k) (- (expo x) (expo y))) 0)
(exactp x (+ (1- k) (- (expo x) (expo y)))))
(= (+ x (odd y k))
(odd (+ x y) (kp k x y))))
:rule-classes ()
:hints (("Goal" :use ((:instance odd-other (n k) (x y))
(:instance expo-monotone (x y) (y (+ x y)))
(:instance plus-trunc (k (1- k)) (n (+ (1- k) (- (expo x) (expo y)))))
(:instance odd-other (x (+ x y)) (n (kp k x y)))))))
(defthm trunc-trunc-odd
(implies (and (rationalp x)
(rationalp y)
(integerp m)
(integerp k)
(> x y)
(> y 0)
(> k 0)
(>= (- m 2) k))
(>= (trunc x k) (trunc (odd y m) k)))
:rule-classes ()
:hints (("Goal" :use ((:instance trunc-odd (x y) (m k) (n m))
(:instance trunc-monotone (x y) (y x) (n k))))))
(defthm away-away-odd-1
(implies (and (rationalp x)
(rationalp y)
(integerp m)
(integerp k)
(> x y)
(> y 0)
(> k 0)
(>= (- m 2) k))
(> (away x k) (trunc y (1- m))))
:rule-classes ()
:hints (("Goal" :use ((:instance away-lower-pos (n k))
(:instance trunc-upper-pos (x y) (n (1- m)))))))
(defthm away-away-odd-2
(implies (and (rationalp x)
(rationalp y)
(integerp m)
(integerp k)
(> x y)
(> y 0)
(> k 0)
(>= (- m 2) k))
(>= (away x k) (+ (trunc y (1- m)) (expt 2 (- (+ (expo y) 2) m)))))
:rule-classes ()
:hints (("Goal" :use ((:instance away-away-odd-1)
(:instance fp+1 (x (trunc y (1- m))) (y (away x k)) (n (1- m)))
(:instance expo-trunc (x y) (n (1- m)))
(:instance trunc-exactp-b (x y) (n (1- m)))
(:instance away-exactp-b (n k))
(:instance trunc-pos (x y) (n (1- m)))
(:instance exactp-<= (x (away x k)) (m k) (n (1- m)))))))
(defthm away-away-odd-3
(implies (and (rationalp x)
(rationalp y)
(integerp m)
(integerp k)
(> x y)
(> y 0)
(> k 0)
(>= (- m 2) k))
(> (away x k) (odd y m)))
:rule-classes ()
:hints (("Goal" :use ((:instance away-away-odd-2)
(:instance odd-other (x y) (n m))
(:instance expt-strong-monotone (n (- (1+ (expo y)) m)) (m (- (+ (expo y) 2) m)))))))
(defthm away-away-odd
(implies (and (rationalp x)
(rationalp y)
(integerp m)
(integerp k)
(> x y)
(> y 0)
(> k 0)
(>= (- m 2) k))
(>= (away x k) (away (odd y m) k)))
:rule-classes ()
:hints (("Goal" :use ((:instance away-away-odd-3)
(:instance odd-pos (x y) (n m))
(:instance away-exactp-c (a (away x k)) (x (odd y m)) (n k))
(:instance away-exactp-b (n k))))))
(defthm near-near-odd
(implies (and (rationalp x)
(rationalp y)
(integerp m)
(integerp k)
(> x y)
(> y 0)
(> k 0)
(>= (- m 2) k))
(>= (near x k) (near (odd y m) k)))
:rule-classes ()
:hints (("Goal" :use ((:instance trunc-exactp-b (n (1- m)) (x y))
(:instance odd-pos (x y) (n m))
(:instance trunc-pos (x y) (n (1- m)))
(:instance trunc-upper-pos (x y) (n (1- m)))
(:instance expo-trunc (x y) (n (1- m)))
(:instance odd-other (x y) (n m))
(:instance expt-strong-monotone
(n (- (1+ (expo y)) m))
(m (- (+ 2 (expo y)) m)))
(:instance near-near
(n (- m 2))
(a (trunc y (1- m)))
(y (odd y m)))))))
| true |
;;;***************************************************************
;;;An ACL2 Library of Floating Point Arithmetic
;;;PI:NAME:<NAME>END_PI
;;;Advanced Micro Devices, Inc.
;;;February, 1998
;;;***************************************************************
(in-package "ACL2")
(include-book "near")
(defun odd (x n)
(let ((z (fl (* (expt 2 (1- n)) (sig x)))))
(if (evenp z)
(* (sgn x) (1+ z) (expt 2 (- (1+ (expo x)) n)))
(* (sgn x) z (expt 2 (- (1+ (expo x)) n))))))
(defthm odd-pos
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 0))
(> (odd x n) 0))
:rule-classes ()
:hints (("Goal" :in-theory (disable expo sig fl-weakly-monotonic)
:use ((:instance sig-lower-bound)
(:instance pos*
(x (fl (* (sig x) (expt 2 (1- n)))))
(y (expt 2 (- (1+ (expo x)) n))))
(:instance pos*
(x (1+ (fl (* (sig x) (expt 2 (1- n))))))
(y (expt 2 (- (1+ (expo x)) n))))
(:instance sgn+1)
(:instance expo-monotone (x 1) (y (1- n)))
(:instance n<=fl (x (sig x)) (n 1))))))
(defthm odd>=trunc
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 0))
(>= (odd x n) (trunc x n)))
:rule-classes ()
:hints (("Goal" :in-theory (disable expt-pos)
:use ((:instance trunc)
(:instance expt-pos (x (- (1+ (expo x)) n)))))))
(defthm odd-rewrite
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 0))
(equal (odd x n)
(let ((z (fl (* (expt 2 (- (1- n) (expo x))) x))))
(if (evenp z)
(* (1+ z) (expt 2 (- (1+ (expo x)) n)))
(* z (expt 2 (- (1+ (expo x)) n)))))))
:rule-classes ()
:hints (("Goal" :in-theory (enable sig expo sgn))))
(in-theory (disable odd))
(defthm hack2
(implies (and (integerp n)
(rationalp x))
(= (fl (* 1/2 x (expt 2 n)))
(fl (* x (expt 2 (1- n))))))
:rule-classes ())
(defthm odd-other-1
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (trunc x (1- n))
(* (fl (/ (* (expt 2 (- (1- n) (expo x))) x) 2))
(expt 2 (- (+ 2 (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :in-theory (enable trunc-pos-rewrite)
:use ((:instance hack2 (n (- (1- n) (expo x))))))))
(defthm odd-other-2
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (trunc x (1- n))
(* (fl (/ (fl (* (expt 2 (- (1- n) (expo x))) x)) 2))
(expt 2 (- (+ 2 (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :in-theory (disable fl/int)
:use ((:instance odd-other-1)
(:instance fl/int (x (* (expt 2 (- (1- n) (expo x))) x)) (n 2))))))
(defthm fl/2
(implies (integerp z)
(= (fl (/ z 2))
(if (evenp z)
(/ z 2)
(/ (1- z) 2))))
:rule-classes ())
(defthm odd-other-3
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1)
(= z (fl (* (expt 2 (- (1- n) (expo x))) x)))
(evenp z))
(= (trunc x (1- n))
(* z (expt 2 (- (1+ (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance fl/2)
(:instance expo+ (n (- (1+ (expo x)) n)) (m 1))
(:instance odd-other-2)))))
(defthm odd-other-4
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1)
(= z (fl (* (expt 2 (- (1- n) (expo x))) x)))
(not (evenp z)))
(= (* (fl (/ (fl (* (expt 2 (- (1- n) (expo x))) x)) 2))
(expt 2 (- (+ 2 (expo x)) n)))
(* (fl (/ z 2)) (expt 2 (- (+ 2 (expo x)) n)))))
:rule-classes ())
(defthm odd-other-5
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1)
(= z (fl (* (expt 2 (- (1- n) (expo x))) x)))
(not (evenp z)))
(= (trunc x (1- n))
(* (fl (/ z 2)) (expt 2 (- (+ 2 (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance odd-other-2)
(:instance odd-other-4)))))
(defthm hack3
(implies (and (rationalp x)
(rationalp y)
(rationalp z)
(equal x y))
(= (* x z) (* y z)))
:rule-classes ())
(defthm odd-other-6
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1)
(= z (fl (* (expt 2 (- (1- n) (expo x))) x)))
(not (evenp z)))
(= (trunc x (1- n))
(* (/ (1- z) 2) (expt 2 (- (+ 2 (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance fl/2)
(:instance odd-other-5)
(:instance hack3
(x (/ (1- z) 2))
(y (fl (/ z 2)))
(z (expt 2 (- (+ 2 (expo x)) n))))))))
(defthm odd-other-7
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1)
(= z (fl (* (expt 2 (- (1- n) (expo x))) x)))
(not (evenp z)))
(= (trunc x (1- n))
(* (1- z) (expt 2 (- (1+ (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance odd-other-6)
(:instance expo+ (n (- (1+ (expo x)) n)) (m 1))))))
(defthm odd-other
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (odd x n)
(+ (trunc x (1- n))
(expt 2 (- (1+ (expo x)) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance odd-other-3 (z (fl (* (expt 2 (- (1- n) (expo x))) x))))
(:instance odd-other-7 (z (fl (* (expt 2 (- (1- n) (expo x))) x))))
(:instance odd-rewrite)))))
(defthm expo-odd-1
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 0))
(< (trunc x n) (expt 2 (1+ (expo x)))))
:rule-classes ()
:hints (("Goal" :in-theory (disable expo-trunc abs-trunc)
:use ((:instance expo-trunc)
(:instance trunc-pos)
(:instance expo-upper-bound (x (trunc x n)))))))
(defthm expo-odd-2
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(< (odd x n) (expt 2 (1+ (expo x)))))
:rule-classes ()
:hints (("Goal" :in-theory (disable expo-trunc abs-trunc)
:use ((:instance expo-odd-1 (n (1- n)))
(:instance odd-other)
(:instance exactp-2**n (m (1- n)) (n (1+ (expo x))))
(:instance expo-trunc (n (1- n)))
(:instance expt-strong-monotone (n (- (1+ (expo x)) n)) (m (- (1+ (expo x)) (1- n))))
(:instance trunc-pos (n (1- n)))
(:instance fp+1 (n (1- n)) (x (trunc x (1- n))) (y (expt 2 (1+ (expo x)))))))))
(defthm expo-odd-3
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(<= (expo (odd x n)) (expo x)))
:rule-classes ()
:hints (("Goal" :use ((:instance expo-odd-2)
(:instance odd-pos)
(:instance expo-upper-2 (x (odd x n)) (n (1+ (expo x))))))))
(defthm expo-odd
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(equal (expo (odd x n)) (expo x)))
:hints (("Goal" :in-theory (disable expt-pos abs-trunc)
:use ((:instance expo-odd-3)
(:instance odd-other)
(:instance expt-pos (x (- (1+ (expo x)) n)))
(:instance expo-monotone (y (odd x n)) (x (trunc x (1- n))))
(:instance odd-pos)
(:instance trunc-pos (n (1- n)))))))
(defthm exactp-odd-1
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(= (* (+ (trunc x (1- n))
(expt 2 (- (1+ (expo x)) n)))
(expt 2 (- (1- n) (expo x))))
(1+ (* (trunc x (1- n)) (expt 2 (- (1- n) (expo x)))))))
:rule-classes ()
:hints (("Goal" :in-theory (disable expt-pos abs-trunc)
:use ((:instance expo+ (n (- (1- n) (expo x))) (m (- (1+ (expo x)) n)))))))
(defthm exactp-odd-2
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(= (* (odd x n) (expt 2 (- (1- n) (expo x))))
(1+ (* (trunc x (1- n)) (expt 2 (- (1- n) (expo x)))))))
:rule-classes ()
:hints (("Goal" :in-theory (disable expt-pos abs-trunc)
:use ((:instance odd-other)
(:instance exactp-odd-1)))))
(defthm exactp-odd-3
(implies (and (rationalp x)
(integerp n))
(= (expt 2 (- (1- n) (expo x)))
(* 2 (expt 2 (- (- n 2) (expo x))))))
:rule-classes ()
:hints (("Goal" :use ((:instance expo+ (n (- (- n 2) (expo x))) (m 1))))))
(defthm exactp-odd-4
(implies (and (rationalp x)
(rationalp y)
(integerp n))
(= (* y 2 (expt 2 (- (- n 2) (expo x))))
(* 2 y (expt 2 (- (- n 2) (expo x))))))
:rule-classes ())
(defthm exactp-odd-5
(implies (and (rationalp x)
(integerp n))
(= (* (trunc x (1- n)) (expt 2 (- (1- n) (expo x))))
(* 2 (trunc x (1- n)) (expt 2 (- (- n 2) (expo x))))))
:rule-classes ()
:hints (("Goal" :use ((:instance exactp-odd-3)
(:instance exactp-odd-4 (y (trunc x (1- n))))))))
(defthm exactp-odd-6
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(= (* (odd x n) (expt 2 (- (1- n) (expo x))))
(1+ (* 2 (* (trunc x (1- n)) (expt 2 (- (- n 2) (expo x))))))))
:rule-classes ()
:hints (("Goal" :in-theory (disable expt-pos abs-trunc)
:use ((:instance exactp-odd-2)
(:instance exactp-odd-5)))))
(defthm exactp-odd
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(exactp (odd x n) n))
:rule-classes ()
:hints (("Goal" :in-theory (disable expt-pos abs-trunc)
:use ((:instance exactp-odd-6)
(:instance exactp2 (x (odd x n)))
(:instance exactp2 (x (trunc x (1- n))) (n (1- n)))))))
(defthm not-exactp-odd-1
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(= (* (+ (trunc x (1- n)) (expt 2 (- (1+ (expo x)) n)))
(expt 2 (- (- n 2) (expo x))))
(+ (* (trunc x (1- n)) (expt 2 (- (- n 2) (expo x)))) 1/2)))
:rule-classes ()
:hints (("Goal" :use ((:instance expo+ (m (- (- n 2) (expo x))) (n (- (1+ (expo x)) n)))))))
(defthm not-exactp-odd-2
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(= (* (odd x n)
(expt 2 (- (- n 2) (expo x))))
(+ (* (trunc x (1- n)) (expt 2 (- (- n 2) (expo x)))) 1/2)))
:rule-classes ()
:hints (("Goal" :use ((:instance odd-other)
(:instance not-exactp-odd-1)))))
(defthm not-exactp-odd
(implies (and (rationalp x)
(integerp n)
(> x 0)
(> n 1))
(not (exactp (odd x n) (1- n))))
:rule-classes ()
:hints (("Goal" :in-theory (disable expt-pos abs-trunc)
:use ((:instance not-exactp-odd-2)
(:instance exactp2 (x (odd x n)) (n (1- n)))
(:instance exactp2 (x (trunc x (1- n))) (n (1- n)))))))
(defthm trunc-odd-1
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (trunc (odd x n) (1- n))
(* (fl (* (expt 2 (- (- n 2) (expo x)))
(+ (* (fl (* (expt 2 (- (- n 2) (expo x)))
x))
(expt 2 (- (+ (expo x) 2) n)))
(expt 2 (- (1+ (expo x)) n)))))
(expt 2 (- (+ (expo x) 2) n)))))
:rule-classes ()
:hints (("Goal" :in-theory (enable trunc-pos-rewrite)
:use ((:instance odd-other)
(:instance odd-pos)))))
(defthm trunc-odd-2
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (trunc (odd x n) (1- n))
(* (fl (+ (fl (* (expt 2 (- (- n 2) (expo x)))
x))
1/2))
(expt 2 (- (+ (expo x) 2) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance trunc-odd-1)
(:instance expo+ (m (- (- n 2) (expo x))) (n (- (+ (expo x) 2) n)))
(:instance expo+ (m (- (- n 2) (expo x))) (n (- (+ (expo x) 1) n)))))))
(defthm trunc-odd-3
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (trunc (odd x n) (1- n))
(* (fl (* (expt 2 (- (- n 2) (expo x)))
x))
(expt 2 (- (+ (expo x) 2) n)))))
:rule-classes ()
:hints (("Goal" :use ((:instance trunc-odd-2)))))
(defthm trunc-odd-4
(implies (and (rationalp x)
(> x 0)
(integerp n)
(> n 1))
(= (trunc (odd x n) (1- n))
(trunc x (1- n))))
:rule-classes ()
:hints (("Goal" :in-theory (enable trunc-pos-rewrite)
:use ((:instance trunc-odd-3)))))
(defthm trunc-odd
(implies (and (rationalp x)
(> x 0)
(integerp n)
(integerp m)
(> m 0)
(> n m))
(= (trunc (odd x n) m)
(trunc x m)))
:rule-classes ()
:hints (("Goal" :use ((:instance trunc-odd-4)
(:instance odd-pos)
(:instance trunc-trunc (n (1- n)))
(:instance trunc-trunc (n (1- n)) (x (odd x n)))))))
(defun kp (k x y)
(+ k (- (expo (+ x y)) (expo y))))
(defthm odd-plus
(implies (and (rationalp x)
(rationalp y)
(integerp k)
(> x 0)
(> y 0)
(> k 1)
(> (+ (1- k) (- (expo x) (expo y))) 0)
(exactp x (+ (1- k) (- (expo x) (expo y)))))
(= (+ x (odd y k))
(odd (+ x y) (kp k x y))))
:rule-classes ()
:hints (("Goal" :use ((:instance odd-other (n k) (x y))
(:instance expo-monotone (x y) (y (+ x y)))
(:instance plus-trunc (k (1- k)) (n (+ (1- k) (- (expo x) (expo y)))))
(:instance odd-other (x (+ x y)) (n (kp k x y)))))))
(defthm trunc-trunc-odd
(implies (and (rationalp x)
(rationalp y)
(integerp m)
(integerp k)
(> x y)
(> y 0)
(> k 0)
(>= (- m 2) k))
(>= (trunc x k) (trunc (odd y m) k)))
:rule-classes ()
:hints (("Goal" :use ((:instance trunc-odd (x y) (m k) (n m))
(:instance trunc-monotone (x y) (y x) (n k))))))
(defthm away-away-odd-1
(implies (and (rationalp x)
(rationalp y)
(integerp m)
(integerp k)
(> x y)
(> y 0)
(> k 0)
(>= (- m 2) k))
(> (away x k) (trunc y (1- m))))
:rule-classes ()
:hints (("Goal" :use ((:instance away-lower-pos (n k))
(:instance trunc-upper-pos (x y) (n (1- m)))))))
(defthm away-away-odd-2
(implies (and (rationalp x)
(rationalp y)
(integerp m)
(integerp k)
(> x y)
(> y 0)
(> k 0)
(>= (- m 2) k))
(>= (away x k) (+ (trunc y (1- m)) (expt 2 (- (+ (expo y) 2) m)))))
:rule-classes ()
:hints (("Goal" :use ((:instance away-away-odd-1)
(:instance fp+1 (x (trunc y (1- m))) (y (away x k)) (n (1- m)))
(:instance expo-trunc (x y) (n (1- m)))
(:instance trunc-exactp-b (x y) (n (1- m)))
(:instance away-exactp-b (n k))
(:instance trunc-pos (x y) (n (1- m)))
(:instance exactp-<= (x (away x k)) (m k) (n (1- m)))))))
(defthm away-away-odd-3
(implies (and (rationalp x)
(rationalp y)
(integerp m)
(integerp k)
(> x y)
(> y 0)
(> k 0)
(>= (- m 2) k))
(> (away x k) (odd y m)))
:rule-classes ()
:hints (("Goal" :use ((:instance away-away-odd-2)
(:instance odd-other (x y) (n m))
(:instance expt-strong-monotone (n (- (1+ (expo y)) m)) (m (- (+ (expo y) 2) m)))))))
(defthm away-away-odd
(implies (and (rationalp x)
(rationalp y)
(integerp m)
(integerp k)
(> x y)
(> y 0)
(> k 0)
(>= (- m 2) k))
(>= (away x k) (away (odd y m) k)))
:rule-classes ()
:hints (("Goal" :use ((:instance away-away-odd-3)
(:instance odd-pos (x y) (n m))
(:instance away-exactp-c (a (away x k)) (x (odd y m)) (n k))
(:instance away-exactp-b (n k))))))
(defthm near-near-odd
(implies (and (rationalp x)
(rationalp y)
(integerp m)
(integerp k)
(> x y)
(> y 0)
(> k 0)
(>= (- m 2) k))
(>= (near x k) (near (odd y m) k)))
:rule-classes ()
:hints (("Goal" :use ((:instance trunc-exactp-b (n (1- m)) (x y))
(:instance odd-pos (x y) (n m))
(:instance trunc-pos (x y) (n (1- m)))
(:instance trunc-upper-pos (x y) (n (1- m)))
(:instance expo-trunc (x y) (n (1- m)))
(:instance odd-other (x y) (n m))
(:instance expt-strong-monotone
(n (- (1+ (expo y)) m))
(m (- (+ 2 (expo y)) m)))
(:instance near-near
(n (- m 2))
(a (trunc y (1- m)))
(y (odd y m)))))))
|
[
{
"context": ";;; setf.lisp\n;;;\n;;; Copyright (C) 2003-2006 Peter Graves\n;;; $Id$\n;;;\n;;; This program is free software; y",
"end": 58,
"score": 0.9996563792228699,
"start": 46,
"tag": "NAME",
"value": "Peter Graves"
}
] |
platform/src/org/armedbear/lisp/setf.lisp
|
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD
| 10 |
;;; setf.lisp
;;;
;;; Copyright (C) 2003-2006 Peter Graves
;;; $Id$
;;;
;;; 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; if not, write to the Free Software
;;; Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
;;;
;;; As a special exception, the copyright holders of this library give you
;;; permission to link this library with independent modules to produce an
;;; executable, regardless of the license terms of these independent
;;; modules, and to copy and distribute the resulting executable under
;;; terms of your choice, provided that you also meet, for each linked
;;; independent module, the terms and conditions of the license of that
;;; module. An independent module is a module which is not derived from
;;; or based on this library. If you modify this library, you may extend
;;; this exception to your version of the library, but you are not
;;; obligated to do so. If you do not wish to do so, delete this
;;; exception statement from your version.
(in-package #:system)
(defun get-setf-method-inverse (form inverse setf-function)
(let ((new-var (gensym))
(vars nil)
(vals nil))
(dolist (x (cdr form))
(push (gensym) vars)
(push x vals))
(setq vals (nreverse vals))
(values vars vals (list new-var)
(if setf-function
`(,@inverse ,new-var ,@vars)
(if (functionp (car inverse))
`(funcall ,@inverse ,@vars ,new-var)
`(,@inverse ,@vars ,new-var)))
`(,(car form) ,@vars))))
;;; If a macro, expand one level and try again. If not, go for the
;;; SETF function.
(defun expand-or-get-setf-inverse (form environment)
(multiple-value-bind (expansion expanded)
(macroexpand-1 form environment)
(if expanded
(get-setf-expansion expansion environment)
(get-setf-method-inverse form `(funcall #'(setf ,(car form)))
t))))
(defun get-setf-expansion (form &optional environment)
(let (temp)
(cond ((symbolp form)
(multiple-value-bind (expansion expanded)
(macroexpand-1 form environment)
(if expanded
(get-setf-expansion expansion environment)
(let ((new-var (gensym)))
(values nil nil (list new-var)
`(setq ,form ,new-var) form)))))
((setq temp (get (car form) 'setf-inverse))
(get-setf-method-inverse form `(,temp) nil))
((setq temp (get (car form) 'setf-expander))
(funcall temp form environment))
(t
(expand-or-get-setf-inverse form environment)))))
(defmacro setf (&rest args &environment environment)
(let ((numargs (length args)))
(cond
((= numargs 2)
(let ((place (first args))
(value-form (second args)))
(if (atom place)
`(setq ,place ,value-form)
(progn
(multiple-value-bind (dummies vals store-vars setter getter)
(get-setf-expansion place environment)
(let ((inverse (get (car place) 'setf-inverse)))
(if (and inverse (eq inverse (car setter)))
(if (functionp inverse)
`(funcall ,inverse ,@(cdr place) ,value-form)
`(,inverse ,@(cdr place) ,value-form))
(if (or (null store-vars) (cdr store-vars))
`(let* (,@(mapcar #'list dummies vals))
(multiple-value-bind ,store-vars ,value-form
,setter))
`(let* (,@(mapcar #'list dummies vals)
,(list (car store-vars) value-form))
,setter)))))))))
((oddp numargs)
(error "Odd number of arguments to SETF."))
(t
(do ((a args (cddr a)) (l nil))
((null a) `(progn ,@(nreverse l)))
(setq l (cons (list 'setf (car a) (cadr a)) l)))))))
;;; Redefined in define-modify-macro.lisp.
(defmacro incf (place &optional (delta 1))
`(setf ,place (+ ,place ,delta)))
;;; Redefined in define-modify-macro.lisp.
(defmacro decf (place &optional (delta 1))
`(setf ,place (- ,place ,delta)))
;; (defsetf subseq (sequence start &optional (end nil)) (v)
;; `(progn (replace ,sequence ,v :start1 ,start :end1 ,end)
;; ,v))
(defun %set-subseq (sequence start &rest rest)
(let ((end nil) v)
(ecase (length rest)
(1
(setq v (car rest)))
(2
(setq end (car rest)
v (cadr rest))))
(progn
(replace sequence v :start1 start :end1 end)
v)))
(defun %define-setf-macro (name expander inverse doc)
(declare (ignore doc)) ; FIXME
(when inverse
(put name 'setf-inverse inverse))
(when expander
(put name 'setf-expander expander))
name)
(defmacro defsetf (access-function update-function)
`(eval-when (:load-toplevel :compile-toplevel :execute)
(put ',access-function 'setf-inverse ',update-function)))
(defun %set-caar (x v) (set-car (car x) v))
(defun %set-cadr (x v) (set-car (cdr x) v))
(defun %set-cdar (x v) (set-cdr (car x) v))
(defun %set-cddr (x v) (set-cdr (cdr x) v))
(defun %set-caaar (x v) (set-car (caar x) v))
(defun %set-cadar (x v) (set-car (cdar x) v))
(defun %set-cdaar (x v) (set-cdr (caar x) v))
(defun %set-cddar (x v) (set-cdr (cdar x) v))
(defun %set-caadr (x v) (set-car (cadr x) v))
(defun %set-caddr (x v) (set-car (cddr x) v))
(defun %set-cdadr (x v) (set-cdr (cadr x) v))
(defun %set-cdddr (x v) (set-cdr (cddr x) v))
(defun %set-caaaar (x v) (set-car (caaar x) v))
(defun %set-cadaar (x v) (set-car (cdaar x) v))
(defun %set-cdaaar (x v) (set-cdr (caaar x) v))
(defun %set-cddaar (x v) (set-cdr (cdaar x) v))
(defun %set-caadar (x v) (set-car (cadar x) v))
(defun %set-caddar (x v) (set-car (cddar x) v))
(defun %set-cdadar (x v) (set-cdr (cadar x) v))
(defun %set-cdddar (x v) (set-cdr (cddar x) v))
(defun %set-caaadr (x v) (set-car (caadr x) v))
(defun %set-cadadr (x v) (set-car (cdadr x) v))
(defun %set-cdaadr (x v) (set-cdr (caadr x) v))
(defun %set-cddadr (x v) (set-cdr (cdadr x) v))
(defun %set-caaddr (x v) (set-car (caddr x) v))
(defun %set-cadddr (x v) (set-car (cdddr x) v))
(defun %set-cdaddr (x v) (set-cdr (caddr x) v))
(defun %set-cddddr (x v) (set-cdr (cdddr x) v))
(defsetf car set-car)
(defsetf cdr set-cdr)
(defsetf caar %set-caar)
(defsetf cadr %set-cadr)
(defsetf cdar %set-cdar)
(defsetf cddr %set-cddr)
(defsetf caaar %set-caaar)
(defsetf cadar %set-cadar)
(defsetf cdaar %set-cdaar)
(defsetf cddar %set-cddar)
(defsetf caadr %set-caadr)
(defsetf caddr %set-caddr)
(defsetf cdadr %set-cdadr)
(defsetf cdddr %set-cdddr)
(defsetf caaaar %set-caaaar)
(defsetf cadaar %set-cadaar)
(defsetf cdaaar %set-cdaaar)
(defsetf cddaar %set-cddaar)
(defsetf caadar %set-caadar)
(defsetf caddar %set-caddar)
(defsetf cdadar %set-cdadar)
(defsetf cdddar %set-cdddar)
(defsetf caaadr %set-caaadr)
(defsetf cadadr %set-cadadr)
(defsetf cdaadr %set-cdaadr)
(defsetf cddadr %set-cddadr)
(defsetf caaddr %set-caaddr)
(defsetf cadddr %set-cadddr)
(defsetf cdaddr %set-cdaddr)
(defsetf cddddr %set-cddddr)
(defsetf first set-car)
(defsetf second %set-cadr)
(defsetf third %set-caddr)
(defsetf fourth %set-cadddr)
(defun %set-fifth (x v) (set-car (cddddr x) v))
(defsetf fifth %set-fifth)
(defun %set-sixth (x v) (set-car (cdr (cddddr x)) v))
(defsetf sixth %set-sixth)
(defun %set-seventh (x v) (set-car (cddr (cddddr x)) v))
(defsetf seventh %set-seventh)
(defun %set-eighth (x v) (set-car (cdddr (cddddr x)) v))
(defsetf eighth %set-eighth)
(defun %set-ninth (x v) (set-car (cddddr (cddddr x)) v))
(defsetf ninth %set-ninth)
(defun %set-tenth (x v) (set-car (cdr (cddddr (cddddr x))) v))
(defsetf tenth %set-tenth)
(defsetf rest set-cdr)
;;Redefined in extensible-sequences-base.lisp
(defsetf elt %set-elt)
(defsetf nth %set-nth)
(defsetf svref svset)
(defsetf fill-pointer %set-fill-pointer)
(defsetf subseq %set-subseq)
(defsetf symbol-value set)
(defsetf symbol-function %set-symbol-function)
(defsetf symbol-plist %set-symbol-plist)
(defsetf get put)
(defsetf gethash puthash)
(defsetf char set-char)
(defsetf schar set-schar)
(defsetf logical-pathname-translations %set-logical-pathname-translations)
(defsetf readtable-case %set-readtable-case)
(defsetf function-info %set-function-info)
(defsetf stream-external-format %set-stream-external-format)
(defsetf structure-ref structure-set)
|
28416
|
;;; setf.lisp
;;;
;;; Copyright (C) 2003-2006 <NAME>
;;; $Id$
;;;
;;; 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; if not, write to the Free Software
;;; Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
;;;
;;; As a special exception, the copyright holders of this library give you
;;; permission to link this library with independent modules to produce an
;;; executable, regardless of the license terms of these independent
;;; modules, and to copy and distribute the resulting executable under
;;; terms of your choice, provided that you also meet, for each linked
;;; independent module, the terms and conditions of the license of that
;;; module. An independent module is a module which is not derived from
;;; or based on this library. If you modify this library, you may extend
;;; this exception to your version of the library, but you are not
;;; obligated to do so. If you do not wish to do so, delete this
;;; exception statement from your version.
(in-package #:system)
(defun get-setf-method-inverse (form inverse setf-function)
(let ((new-var (gensym))
(vars nil)
(vals nil))
(dolist (x (cdr form))
(push (gensym) vars)
(push x vals))
(setq vals (nreverse vals))
(values vars vals (list new-var)
(if setf-function
`(,@inverse ,new-var ,@vars)
(if (functionp (car inverse))
`(funcall ,@inverse ,@vars ,new-var)
`(,@inverse ,@vars ,new-var)))
`(,(car form) ,@vars))))
;;; If a macro, expand one level and try again. If not, go for the
;;; SETF function.
(defun expand-or-get-setf-inverse (form environment)
(multiple-value-bind (expansion expanded)
(macroexpand-1 form environment)
(if expanded
(get-setf-expansion expansion environment)
(get-setf-method-inverse form `(funcall #'(setf ,(car form)))
t))))
(defun get-setf-expansion (form &optional environment)
(let (temp)
(cond ((symbolp form)
(multiple-value-bind (expansion expanded)
(macroexpand-1 form environment)
(if expanded
(get-setf-expansion expansion environment)
(let ((new-var (gensym)))
(values nil nil (list new-var)
`(setq ,form ,new-var) form)))))
((setq temp (get (car form) 'setf-inverse))
(get-setf-method-inverse form `(,temp) nil))
((setq temp (get (car form) 'setf-expander))
(funcall temp form environment))
(t
(expand-or-get-setf-inverse form environment)))))
(defmacro setf (&rest args &environment environment)
(let ((numargs (length args)))
(cond
((= numargs 2)
(let ((place (first args))
(value-form (second args)))
(if (atom place)
`(setq ,place ,value-form)
(progn
(multiple-value-bind (dummies vals store-vars setter getter)
(get-setf-expansion place environment)
(let ((inverse (get (car place) 'setf-inverse)))
(if (and inverse (eq inverse (car setter)))
(if (functionp inverse)
`(funcall ,inverse ,@(cdr place) ,value-form)
`(,inverse ,@(cdr place) ,value-form))
(if (or (null store-vars) (cdr store-vars))
`(let* (,@(mapcar #'list dummies vals))
(multiple-value-bind ,store-vars ,value-form
,setter))
`(let* (,@(mapcar #'list dummies vals)
,(list (car store-vars) value-form))
,setter)))))))))
((oddp numargs)
(error "Odd number of arguments to SETF."))
(t
(do ((a args (cddr a)) (l nil))
((null a) `(progn ,@(nreverse l)))
(setq l (cons (list 'setf (car a) (cadr a)) l)))))))
;;; Redefined in define-modify-macro.lisp.
(defmacro incf (place &optional (delta 1))
`(setf ,place (+ ,place ,delta)))
;;; Redefined in define-modify-macro.lisp.
(defmacro decf (place &optional (delta 1))
`(setf ,place (- ,place ,delta)))
;; (defsetf subseq (sequence start &optional (end nil)) (v)
;; `(progn (replace ,sequence ,v :start1 ,start :end1 ,end)
;; ,v))
(defun %set-subseq (sequence start &rest rest)
(let ((end nil) v)
(ecase (length rest)
(1
(setq v (car rest)))
(2
(setq end (car rest)
v (cadr rest))))
(progn
(replace sequence v :start1 start :end1 end)
v)))
(defun %define-setf-macro (name expander inverse doc)
(declare (ignore doc)) ; FIXME
(when inverse
(put name 'setf-inverse inverse))
(when expander
(put name 'setf-expander expander))
name)
(defmacro defsetf (access-function update-function)
`(eval-when (:load-toplevel :compile-toplevel :execute)
(put ',access-function 'setf-inverse ',update-function)))
(defun %set-caar (x v) (set-car (car x) v))
(defun %set-cadr (x v) (set-car (cdr x) v))
(defun %set-cdar (x v) (set-cdr (car x) v))
(defun %set-cddr (x v) (set-cdr (cdr x) v))
(defun %set-caaar (x v) (set-car (caar x) v))
(defun %set-cadar (x v) (set-car (cdar x) v))
(defun %set-cdaar (x v) (set-cdr (caar x) v))
(defun %set-cddar (x v) (set-cdr (cdar x) v))
(defun %set-caadr (x v) (set-car (cadr x) v))
(defun %set-caddr (x v) (set-car (cddr x) v))
(defun %set-cdadr (x v) (set-cdr (cadr x) v))
(defun %set-cdddr (x v) (set-cdr (cddr x) v))
(defun %set-caaaar (x v) (set-car (caaar x) v))
(defun %set-cadaar (x v) (set-car (cdaar x) v))
(defun %set-cdaaar (x v) (set-cdr (caaar x) v))
(defun %set-cddaar (x v) (set-cdr (cdaar x) v))
(defun %set-caadar (x v) (set-car (cadar x) v))
(defun %set-caddar (x v) (set-car (cddar x) v))
(defun %set-cdadar (x v) (set-cdr (cadar x) v))
(defun %set-cdddar (x v) (set-cdr (cddar x) v))
(defun %set-caaadr (x v) (set-car (caadr x) v))
(defun %set-cadadr (x v) (set-car (cdadr x) v))
(defun %set-cdaadr (x v) (set-cdr (caadr x) v))
(defun %set-cddadr (x v) (set-cdr (cdadr x) v))
(defun %set-caaddr (x v) (set-car (caddr x) v))
(defun %set-cadddr (x v) (set-car (cdddr x) v))
(defun %set-cdaddr (x v) (set-cdr (caddr x) v))
(defun %set-cddddr (x v) (set-cdr (cdddr x) v))
(defsetf car set-car)
(defsetf cdr set-cdr)
(defsetf caar %set-caar)
(defsetf cadr %set-cadr)
(defsetf cdar %set-cdar)
(defsetf cddr %set-cddr)
(defsetf caaar %set-caaar)
(defsetf cadar %set-cadar)
(defsetf cdaar %set-cdaar)
(defsetf cddar %set-cddar)
(defsetf caadr %set-caadr)
(defsetf caddr %set-caddr)
(defsetf cdadr %set-cdadr)
(defsetf cdddr %set-cdddr)
(defsetf caaaar %set-caaaar)
(defsetf cadaar %set-cadaar)
(defsetf cdaaar %set-cdaaar)
(defsetf cddaar %set-cddaar)
(defsetf caadar %set-caadar)
(defsetf caddar %set-caddar)
(defsetf cdadar %set-cdadar)
(defsetf cdddar %set-cdddar)
(defsetf caaadr %set-caaadr)
(defsetf cadadr %set-cadadr)
(defsetf cdaadr %set-cdaadr)
(defsetf cddadr %set-cddadr)
(defsetf caaddr %set-caaddr)
(defsetf cadddr %set-cadddr)
(defsetf cdaddr %set-cdaddr)
(defsetf cddddr %set-cddddr)
(defsetf first set-car)
(defsetf second %set-cadr)
(defsetf third %set-caddr)
(defsetf fourth %set-cadddr)
(defun %set-fifth (x v) (set-car (cddddr x) v))
(defsetf fifth %set-fifth)
(defun %set-sixth (x v) (set-car (cdr (cddddr x)) v))
(defsetf sixth %set-sixth)
(defun %set-seventh (x v) (set-car (cddr (cddddr x)) v))
(defsetf seventh %set-seventh)
(defun %set-eighth (x v) (set-car (cdddr (cddddr x)) v))
(defsetf eighth %set-eighth)
(defun %set-ninth (x v) (set-car (cddddr (cddddr x)) v))
(defsetf ninth %set-ninth)
(defun %set-tenth (x v) (set-car (cdr (cddddr (cddddr x))) v))
(defsetf tenth %set-tenth)
(defsetf rest set-cdr)
;;Redefined in extensible-sequences-base.lisp
(defsetf elt %set-elt)
(defsetf nth %set-nth)
(defsetf svref svset)
(defsetf fill-pointer %set-fill-pointer)
(defsetf subseq %set-subseq)
(defsetf symbol-value set)
(defsetf symbol-function %set-symbol-function)
(defsetf symbol-plist %set-symbol-plist)
(defsetf get put)
(defsetf gethash puthash)
(defsetf char set-char)
(defsetf schar set-schar)
(defsetf logical-pathname-translations %set-logical-pathname-translations)
(defsetf readtable-case %set-readtable-case)
(defsetf function-info %set-function-info)
(defsetf stream-external-format %set-stream-external-format)
(defsetf structure-ref structure-set)
| true |
;;; setf.lisp
;;;
;;; Copyright (C) 2003-2006 PI:NAME:<NAME>END_PI
;;; $Id$
;;;
;;; 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; if not, write to the Free Software
;;; Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
;;;
;;; As a special exception, the copyright holders of this library give you
;;; permission to link this library with independent modules to produce an
;;; executable, regardless of the license terms of these independent
;;; modules, and to copy and distribute the resulting executable under
;;; terms of your choice, provided that you also meet, for each linked
;;; independent module, the terms and conditions of the license of that
;;; module. An independent module is a module which is not derived from
;;; or based on this library. If you modify this library, you may extend
;;; this exception to your version of the library, but you are not
;;; obligated to do so. If you do not wish to do so, delete this
;;; exception statement from your version.
(in-package #:system)
(defun get-setf-method-inverse (form inverse setf-function)
(let ((new-var (gensym))
(vars nil)
(vals nil))
(dolist (x (cdr form))
(push (gensym) vars)
(push x vals))
(setq vals (nreverse vals))
(values vars vals (list new-var)
(if setf-function
`(,@inverse ,new-var ,@vars)
(if (functionp (car inverse))
`(funcall ,@inverse ,@vars ,new-var)
`(,@inverse ,@vars ,new-var)))
`(,(car form) ,@vars))))
;;; If a macro, expand one level and try again. If not, go for the
;;; SETF function.
(defun expand-or-get-setf-inverse (form environment)
(multiple-value-bind (expansion expanded)
(macroexpand-1 form environment)
(if expanded
(get-setf-expansion expansion environment)
(get-setf-method-inverse form `(funcall #'(setf ,(car form)))
t))))
(defun get-setf-expansion (form &optional environment)
(let (temp)
(cond ((symbolp form)
(multiple-value-bind (expansion expanded)
(macroexpand-1 form environment)
(if expanded
(get-setf-expansion expansion environment)
(let ((new-var (gensym)))
(values nil nil (list new-var)
`(setq ,form ,new-var) form)))))
((setq temp (get (car form) 'setf-inverse))
(get-setf-method-inverse form `(,temp) nil))
((setq temp (get (car form) 'setf-expander))
(funcall temp form environment))
(t
(expand-or-get-setf-inverse form environment)))))
(defmacro setf (&rest args &environment environment)
(let ((numargs (length args)))
(cond
((= numargs 2)
(let ((place (first args))
(value-form (second args)))
(if (atom place)
`(setq ,place ,value-form)
(progn
(multiple-value-bind (dummies vals store-vars setter getter)
(get-setf-expansion place environment)
(let ((inverse (get (car place) 'setf-inverse)))
(if (and inverse (eq inverse (car setter)))
(if (functionp inverse)
`(funcall ,inverse ,@(cdr place) ,value-form)
`(,inverse ,@(cdr place) ,value-form))
(if (or (null store-vars) (cdr store-vars))
`(let* (,@(mapcar #'list dummies vals))
(multiple-value-bind ,store-vars ,value-form
,setter))
`(let* (,@(mapcar #'list dummies vals)
,(list (car store-vars) value-form))
,setter)))))))))
((oddp numargs)
(error "Odd number of arguments to SETF."))
(t
(do ((a args (cddr a)) (l nil))
((null a) `(progn ,@(nreverse l)))
(setq l (cons (list 'setf (car a) (cadr a)) l)))))))
;;; Redefined in define-modify-macro.lisp.
(defmacro incf (place &optional (delta 1))
`(setf ,place (+ ,place ,delta)))
;;; Redefined in define-modify-macro.lisp.
(defmacro decf (place &optional (delta 1))
`(setf ,place (- ,place ,delta)))
;; (defsetf subseq (sequence start &optional (end nil)) (v)
;; `(progn (replace ,sequence ,v :start1 ,start :end1 ,end)
;; ,v))
(defun %set-subseq (sequence start &rest rest)
(let ((end nil) v)
(ecase (length rest)
(1
(setq v (car rest)))
(2
(setq end (car rest)
v (cadr rest))))
(progn
(replace sequence v :start1 start :end1 end)
v)))
(defun %define-setf-macro (name expander inverse doc)
(declare (ignore doc)) ; FIXME
(when inverse
(put name 'setf-inverse inverse))
(when expander
(put name 'setf-expander expander))
name)
(defmacro defsetf (access-function update-function)
`(eval-when (:load-toplevel :compile-toplevel :execute)
(put ',access-function 'setf-inverse ',update-function)))
(defun %set-caar (x v) (set-car (car x) v))
(defun %set-cadr (x v) (set-car (cdr x) v))
(defun %set-cdar (x v) (set-cdr (car x) v))
(defun %set-cddr (x v) (set-cdr (cdr x) v))
(defun %set-caaar (x v) (set-car (caar x) v))
(defun %set-cadar (x v) (set-car (cdar x) v))
(defun %set-cdaar (x v) (set-cdr (caar x) v))
(defun %set-cddar (x v) (set-cdr (cdar x) v))
(defun %set-caadr (x v) (set-car (cadr x) v))
(defun %set-caddr (x v) (set-car (cddr x) v))
(defun %set-cdadr (x v) (set-cdr (cadr x) v))
(defun %set-cdddr (x v) (set-cdr (cddr x) v))
(defun %set-caaaar (x v) (set-car (caaar x) v))
(defun %set-cadaar (x v) (set-car (cdaar x) v))
(defun %set-cdaaar (x v) (set-cdr (caaar x) v))
(defun %set-cddaar (x v) (set-cdr (cdaar x) v))
(defun %set-caadar (x v) (set-car (cadar x) v))
(defun %set-caddar (x v) (set-car (cddar x) v))
(defun %set-cdadar (x v) (set-cdr (cadar x) v))
(defun %set-cdddar (x v) (set-cdr (cddar x) v))
(defun %set-caaadr (x v) (set-car (caadr x) v))
(defun %set-cadadr (x v) (set-car (cdadr x) v))
(defun %set-cdaadr (x v) (set-cdr (caadr x) v))
(defun %set-cddadr (x v) (set-cdr (cdadr x) v))
(defun %set-caaddr (x v) (set-car (caddr x) v))
(defun %set-cadddr (x v) (set-car (cdddr x) v))
(defun %set-cdaddr (x v) (set-cdr (caddr x) v))
(defun %set-cddddr (x v) (set-cdr (cdddr x) v))
(defsetf car set-car)
(defsetf cdr set-cdr)
(defsetf caar %set-caar)
(defsetf cadr %set-cadr)
(defsetf cdar %set-cdar)
(defsetf cddr %set-cddr)
(defsetf caaar %set-caaar)
(defsetf cadar %set-cadar)
(defsetf cdaar %set-cdaar)
(defsetf cddar %set-cddar)
(defsetf caadr %set-caadr)
(defsetf caddr %set-caddr)
(defsetf cdadr %set-cdadr)
(defsetf cdddr %set-cdddr)
(defsetf caaaar %set-caaaar)
(defsetf cadaar %set-cadaar)
(defsetf cdaaar %set-cdaaar)
(defsetf cddaar %set-cddaar)
(defsetf caadar %set-caadar)
(defsetf caddar %set-caddar)
(defsetf cdadar %set-cdadar)
(defsetf cdddar %set-cdddar)
(defsetf caaadr %set-caaadr)
(defsetf cadadr %set-cadadr)
(defsetf cdaadr %set-cdaadr)
(defsetf cddadr %set-cddadr)
(defsetf caaddr %set-caaddr)
(defsetf cadddr %set-cadddr)
(defsetf cdaddr %set-cdaddr)
(defsetf cddddr %set-cddddr)
(defsetf first set-car)
(defsetf second %set-cadr)
(defsetf third %set-caddr)
(defsetf fourth %set-cadddr)
(defun %set-fifth (x v) (set-car (cddddr x) v))
(defsetf fifth %set-fifth)
(defun %set-sixth (x v) (set-car (cdr (cddddr x)) v))
(defsetf sixth %set-sixth)
(defun %set-seventh (x v) (set-car (cddr (cddddr x)) v))
(defsetf seventh %set-seventh)
(defun %set-eighth (x v) (set-car (cdddr (cddddr x)) v))
(defsetf eighth %set-eighth)
(defun %set-ninth (x v) (set-car (cddddr (cddddr x)) v))
(defsetf ninth %set-ninth)
(defun %set-tenth (x v) (set-car (cdr (cddddr (cddddr x))) v))
(defsetf tenth %set-tenth)
(defsetf rest set-cdr)
;;Redefined in extensible-sequences-base.lisp
(defsetf elt %set-elt)
(defsetf nth %set-nth)
(defsetf svref svset)
(defsetf fill-pointer %set-fill-pointer)
(defsetf subseq %set-subseq)
(defsetf symbol-value set)
(defsetf symbol-function %set-symbol-function)
(defsetf symbol-plist %set-symbol-plist)
(defsetf get put)
(defsetf gethash puthash)
(defsetf char set-char)
(defsetf schar set-schar)
(defsetf logical-pathname-translations %set-logical-pathname-translations)
(defsetf readtable-case %set-readtable-case)
(defsetf function-info %set-function-info)
(defsetf stream-external-format %set-stream-external-format)
(defsetf structure-ref structure-set)
|
[
{
"context": "nces.lisp\n;;;; Description: \n;;;; Author: Frode Vatvedt Fjeld <[email protected]>\n;;;; Created at: Tue Sep 11 1",
"end": 356,
"score": 0.9998493194580078,
"start": 337,
"tag": "NAME",
"value": "Frode Vatvedt Fjeld"
},
{
"context": "tion: \n;;;; Author: Frode Vatvedt Fjeld <[email protected]>\n;;;; Created at: Tue Sep 11 14:19:23 2001\n;;;",
"end": 372,
"score": 0.9999303817749023,
"start": 358,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "\n\t \n;;; MERGE-LISTS* originally written by Jim Large.\n;;; \t\t modified to return a pointer to the end",
"end": 60434,
"score": 0.9998627305030823,
"start": 60425,
"tag": "NAME",
"value": "Jim Large"
}
] |
losp/muerte/sequences.lisp
|
russell/movitz
| 4 |
;;;;------------------------------------------------------------------
;;;;
;;;; Copyright (C) 2001-2005,
;;;; Department of Computer Science, University of Tromso, Norway.
;;;;
;;;; For distribution policy, see the accompanying file COPYING.
;;;;
;;;; Filename: sequences.lisp
;;;; Description:
;;;; Author: Frode Vatvedt Fjeld <[email protected]>
;;;; Created at: Tue Sep 11 14:19:23 2001
;;;;
;;;; $Id$
;;;;
;;;;------------------------------------------------------------------
(require :muerte/basic-macros)
(provide :muerte/sequences)
(in-package muerte)
(defun sequencep (x)
(or (typep x 'vector)
(typep x 'cons)))
(defmacro do-sequence-dispatch (sequence-var (type0 &body forms0) (type1 &body forms1))
(cond
((and (eq 'list type0) (eq 'vector type1))
`(if (typep ,sequence-var 'list)
(progn ,@forms0)
(progn (check-type ,sequence-var vector)
,@forms1)))
((and (eq 'vector type0) (eq 'list type1))
`(if (not (typep ,sequence-var 'list))
(progn (check-type ,sequence-var vector)
,@forms0)
(progn ,@forms1)))
(t (error "do-sequence-dispatch only understands list and vector types, not ~W and ~W."
type0 type1))))
(defmacro with-tester ((test test-not) &body body)
(let ((function (gensym "with-test-"))
(notter (gensym "with-test-notter-")))
`(multiple-value-bind (,function ,notter)
(progn ;; the (values function boolean)
(ensure-tester ,test ,test-not))
(macrolet ((,test (&rest args)
`(xor (funcall%unsafe ,',function ,@args)
,',notter)))
,@body))))
(defun ensure-tester (test test-not)
(cond
(test-not
(when test
(error "Both test and test-not specified."))
(values (ensure-funcallable test-not)
t))
(test
(values (ensure-funcallable test)
nil))
(t (values #'eql
nil))))
(defun sequence-double-dispatch-error (seq0 seq1)
(error "The type-set (~A, ~A) has not been implemented in this sequence-double-dispatch."
(type-of seq0)
(type-of seq1)))
(defmacro sequence-double-dispatch ((seq0 seq1) &rest clauses)
`(case (logior (if (typep ,seq0 'list) 2 0)
(if (typep ,seq1 'list) 1 0))
,@(mapcar (lambda (clause)
(destructuring-bind ((type0 type1) . forms)
clause
(list* (logior (ecase type0 (list 2) (vector 0))
(ecase type1 (list 1) (vector 0)))
forms)))
clauses)
(t (sequence-double-dispatch-error ,seq0 ,seq1))))
(defun length (sequence)
(etypecase sequence
(list
(do ((x sequence (cdr x))
(length 0 (1+ length)))
((null x) length)
(declare (index length))))
(indirect-vector
(memref sequence (movitz-type-slot-offset 'movitz-basic-vector 'data)
:index 2))
((simple-array * 1)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :ebx) sequence)
(:movl (:ebx (:offset movitz-basic-vector num-elements))
:eax)
(:testl ,(logxor #xffffffff (1- (expt 2 14))) :eax)
(:jnz 'basic-vector-length-ok)
(:movzxw (:ebx (:offset movitz-basic-vector fill-pointer))
:eax)
basic-vector-length-ok)))
(do-it)))))
(defun length%list (sequence)
(do ((length 0 (1+ length))
(x sequence (cdr x)))
((null x) length)
(declare (type index length))))
(defun elt (sequence index)
(do-sequence-dispatch sequence
(vector (aref sequence index))
(list (nth index sequence))))
(defun (setf elt) (value sequence index)
(do-sequence-dispatch sequence
(vector (setf (aref sequence index) value))
(list (setf (nth index sequence) value))))
(defun reduce (function sequence &key (key 'identity) from-end
(start 0) (end (length sequence))
(initial-value nil initial-value-p))
(numargs-case
(2 (function sequence)
(with-funcallable (funcall-function function)
(do-sequence-dispatch sequence
(list
(cond
((null sequence)
(funcall-function))
((null (cdr sequence))
(car sequence))
(t (do* ((list sequence)
(result (funcall-function (pop list) (pop list))
(funcall-function result (pop list))))
((endp list)
result)))))
(vector
(let ((end (length sequence)))
(case end
(0 (funcall-function))
(1 (aref sequence 0))
(t (with-subvector-accessor (sequence-ref sequence 0 end)
(do* ((index 0)
(result (funcall-function (sequence-ref (prog1 index (incf index)))
(sequence-ref (prog1 index (incf index))))
(funcall-function result (sequence-ref (prog1 index (incf index))))))
((= index end) result)
(declare (index index)))))))))))
(t (function sequence &key (key 'identity) from-end
(start 0) end
(initial-value nil initial-value-p))
(let ((start (check-the index start)))
(with-funcallable (funcall-function function)
(with-funcallable (key)
(do-sequence-dispatch sequence
(list
(let ((list (nthcdr start sequence)))
(cond
((null list)
(if initial-value-p
initial-value
(funcall-function)))
((null (cdr list))
(if initial-value-p
(funcall-function initial-value (key (car list)))
(key (car list))))
((not from-end)
(if (not end)
(do ((result (funcall-function (if initial-value-p
initial-value
(key (pop list)))
(key (pop list)))
(funcall-function result (key (pop list)))))
((null list) result))
(do ((counter (1+ start) (1+ counter))
(result (funcall-function (if initial-value-p
initial-value
(key (pop list)))
(key (pop list)))
(funcall-function result (key (pop list)))))
((or (null list)
(= end counter))
result)
(declare (index counter)))))
(from-end
(do* ((end (or end (+ start (length list))))
(counter (1+ start) (1+ counter))
(list (nreverse (subseq sequence start end)))
(result (funcall-function (key (pop list))
(if initial-value-p
initial-value
(key (pop list))))
(funcall-function (key (pop list)) result)))
((or (null list)
(= end counter))
result)
(declare (index counter)))))))
(vector
(when from-end
(error "REDUCE from-end on vectors is not implemented."))
(let ((end (or (check-the index end)
(length sequence))))
(case (- end start)
(0 (if initial-value-p
initial-value
(funcall-function)))
(1 (if initial-value-p
(funcall-function initial-value (key (elt sequence start)))
(key (elt sequence start))))
(t (with-subvector-accessor (sequence-ref sequence start end)
(do* ((index start)
(result (funcall-function (if initial-value-p
initial-value
(key (sequence-ref (prog1 index (incf index)))))
(key (sequence-ref (prog1 index (incf index)))))
(funcall-function result (sequence-ref (prog1 index (incf index))))))
((= index end) result)
(declare (index index)))))))))))))))
(defun subseq (sequence start &optional end)
(do-sequence-dispatch sequence
(vector
(unless end
(setf end (length sequence)))
(with-subvector-accessor (old-ref sequence start end)
(let ((new-vector (make-array (- end start) :element-type (array-element-type sequence))))
(replace new-vector sequence :start2 start :end2 end)
#+ignore (with-subvector-accessor (new-ref new-vector)
(do ((i start (1+ i))
(j 0 (1+ j)))
((>= i end) new-vector)
(setf (new-ref j) (old-ref i))))
)))
(list
(let ((list-start (nthcdr start sequence)))
(cond
((not end)
(copy-list list-start))
((> start end)
(error "Start ~A is greater than end ~A." start end))
((endp list-start) nil)
((= start end) nil)
(t (do* ((p (cdr list-start) (cdr p))
(i (1+ start) (1+ i))
(head (cons (car list-start) nil))
(tail head))
((or (endp p) (>= i end)) head)
(declare (index i))
(setf (cdr tail) (cons (car p) nil)
tail (cdr tail)))))))))
(defsetf subseq (sequence start &optional (end nil end-p)) (new-sequence)
`(progn (replace ,sequence ,new-sequence :start1 ,start
,@(when end-p `(:end1 ,end)))
,new-sequence))
(defun copy-seq (sequence)
(subseq sequence 0))
(defun position (item sequence &key from-end test test-not (start 0) end (key 'identity))
(numargs-case
(2 (item sequence)
(do-sequence-dispatch sequence
(vector
(with-subvector-accessor (sequence-ref sequence)
(do ((end (length sequence))
(i 0 (1+ i)))
((>= i end))
(declare (index i end))
(when (eql (sequence-ref i) item)
(return i)))))
(list
(do ((i 0 (1+ i)))
((null sequence) nil)
(declare (index i))
(when (eql (pop sequence) item)
(return i))))))
(t (item sequence &key from-end test test-not (start 0) end (key 'identity))
(with-funcallable (key)
(with-tester (test test-not)
(do-sequence-dispatch sequence
(vector
(unless end
(setf end (length sequence)))
(with-subvector-accessor (sequence-ref sequence start end)
(cond
((not from-end)
(do ((i start (1+ i)))
((>= i end))
(declare (index i))
(when (test (key (sequence-ref i)) item)
(return i))))
(t (do ((i (1- end) (1- i)))
((< i start))
(declare (index i))
(when (test (key (sequence-ref i)) item)
(return i)))))))
(list
(cond
((not end)
(do ((p (nthcdr start sequence))
(i start (1+ i)))
((null p) nil)
(declare (index i))
(when (test (key (pop p)) item)
(return (if (not from-end)
i
(let ((next-i (position item p :key key :from-end t
:test test :test-not test-not)))
(if next-i (+ i 1 next-i ) i)))))))
(t (do ((p (nthcdr start sequence))
(i start (1+ i)))
((or (null p) (>= i end)) nil)
(declare (index i))
(when (test (key (pop p)) item)
(return (if (not from-end) i
(let ((next-i (position item p :end (- end 1 i) :from-end t
:key key :test test :test-not test-not)))
(if next-i (+ i 1 next-i ) i)))))))))))))))
(defun position-if (predicate sequence &key (start 0) end (key 'identity) from-end)
(numargs-case
(2 (predicate sequence)
(with-funcallable (predicate)
(do-sequence-dispatch sequence
(vector
(with-subvector-accessor (sequence-ref sequence)
(do ((end (length sequence))
(i 0 (1+ i)))
((>= i end))
(declare (index i end))
(when (predicate (sequence-ref i))
(return i)))))
(list
(do ((p sequence)
(i 0 (1+ i)))
((null p))
(declare (index i))
(when (predicate (pop p))
(return i)))))))
(t (predicate sequence &key (start 0) end (key 'identity) from-end)
(with-funcallable (predicate)
(with-funcallable (key)
(do-sequence-dispatch sequence
(vector
(setf end (or end (length sequence)))
(with-subvector-accessor (sequence-ref sequence start end)
(cond
((not from-end)
(do ((i start (1+ i)))
((>= i end))
(declare (index i))
(when (predicate (key (sequence-ref i)))
(return i))))
(t (do ((i (1- end) (1- i)))
((< i start))
(declare (index i))
(when (predicate (key (sequence-ref i)))
(return i)))))))
(list
(cond
(end
(do ((p (nthcdr start sequence))
(i start (1+ i)))
((or (>= i end) (null p)))
(declare (index i))
(when (predicate (key (pop p)))
(return (if (not from-end) i
(let ((next-i (position-if predicate p :key key
:from-end t :end (- end i 1))))
(if next-i (+ i 1 next-i) i)))))))
(t (do ((p (nthcdr start sequence))
(i start (1+ i)))
((null p))
(declare (index i))
(when (predicate (key (pop p)))
(return (if (not from-end) i
(let ((next-i (position-if predicate p :key key :from-end t)))
(if next-i (+ i 1 next-i) i)))))))))))))))
(defun position-if-not (predicate sequence &rest key-args)
(declare (dynamic-extent key-args))
(apply #'position-if (complement predicate) sequence key-args))
(defun nreverse (sequence)
(do-sequence-dispatch sequence
(list
(do ((prev-cons nil current-cons)
(next-cons (cdr sequence) (cdr next-cons))
(current-cons sequence next-cons))
((null current-cons) prev-cons)
(setf (cdr current-cons) prev-cons)))
(vector
(with-subvector-accessor (sequence-ref sequence)
(do ((i 0 (1+ i))
(j (1- (length sequence)) (1- j)))
((<= j i))
(declare (index i j))
(let ((x (sequence-ref i)))
(setf (sequence-ref i) (sequence-ref j)
(sequence-ref j) x))))
sequence)))
(defun reverse (sequence)
(do-sequence-dispatch sequence
(list
(let ((result nil))
(dolist (x sequence)
(push x result))
result))
(vector
(nreverse (copy-seq sequence)))))
(defun mismatch-eql-identity (sequence-1 sequence-2 start1 start2 end1 end2)
(do-sequence-dispatch sequence-1
(vector
(unless end1 (setf end1 (length sequence-1)))
(with-subvector-accessor (seq1-ref sequence-1 start1 end1)
(do-sequence-dispatch sequence-2
(vector
(unless end2 (setf end2 (length sequence-2)))
(with-subvector-accessor (seq2-ref sequence-2 start2 end2)
(macrolet ((test-return (index1 index2)
`(unless (eql (seq1-ref ,index1) (seq2-ref ,index2))
(return ,index1))))
(let ((length1 (- end1 start1))
(length2 (- end2 start2)))
(cond
((= length1 length2)
(do* ((i start1 (1+ i))
(j start2 (1+ j)))
((>= i end1) nil)
(declare (index i j))
(test-return i j)))
((< length1 length2)
(do* ((i start1 (1+ i))
(j start2 (1+ j)))
((>= i end1) end1)
(declare (index i j))
(test-return i j)))
((> length1 length2)
(do* ((i start1 (1+ i))
(j start2 (1+ j)))
((>= j end2) i)
(declare (index i j))
(test-return i j))))))))
(list
(let ((length1 (- end1 start1))
(start-cons2 (nthcdr start2 sequence-2)))
(cond
((and (zerop length1) (null start-cons2))
(if (and end2 (> end2 start2)) start1 nil))
((not end2)
(do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((>= i1 end1) (if (null p2) nil i1))
(declare (index i1))
(unless (and p2 (eql (seq1-ref i1) (car p2)))
(return i1))))
((< length1 (- end2 start2))
(do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((>= i1 end1) end1)
(declare (index i1))
(unless (eql (seq1-ref i1) (car p2))
(return i1))))
((> length1 (- end2 start2))
(do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((null p2) end1)
(declare (index i1))
(unless (eql (seq1-ref i1) (car p2))
(return i1))))
(t (do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((null p2) nil)
(declare (index i1))
(unless (eql (seq1-ref i1) (car p2))
(return i1))))))))))
(list
(do-sequence-dispatch sequence-2
(vector
(let ((mismatch-2 (mismatch-eql-identity sequence-2 sequence-1 start2 start1 end2 end1)))
(if (not mismatch-2)
nil
(+ start1 (- mismatch-2 start2)))))
(list
(let ((start-cons1 (nthcdr start1 sequence-1))
(start-cons2 (nthcdr start2 sequence-2)))
(assert (and start-cons1 start-cons2) (start1 start2) "Illegal bounding indexes.")
(cond
((and (not end1) (not end2))
(do ((p1 start-cons1 (cdr p1))
(p2 start-cons2 (cdr p2))
(i1 start1 (1+ i1)))
((null p1) (if (null p2) nil i1))
(declare (index i1))
(unless (and p2 (eql (car p1) (car p2)))
(return i1))))
(t (do ((p1 start-cons1 (cdr p1))
(p2 start-cons2 (cdr p2))
(i1 start1 (1+ i1))
(i2 start2 (1+ i2)))
((if end1 (>= i1 end1) (null p1))
(if (if end2 (>= i2 end2) (null p2)) nil i1))
(declare (index i1 i2))
(unless (and (or (not end2) (< i1 end2))
(eql (car p1) (car p2)))
(return i1)))))))))))
(define-compiler-macro mismatch (&whole form sequence-1 sequence-2
&key (start1 0) (start2 0) end1 end2
(test 'eql test-p) (key 'identity key-p) from-end)
(declare (ignore key test))
(cond
((and (not test-p) (not key-p))
(assert (not from-end) ()
"Mismatch :from-end not implemented.")
`(mismatch-eql-identity ,sequence-1 ,sequence-2 ,start1 ,start2 ,end1 ,end2))
(t form)))
(defun mismatch (sequence-1 sequence-2 &key (start1 0) (start2 0) end1 end2
test test-not (key 'identity) from-end)
(numargs-case
(2 (s1 s2)
(mismatch-eql-identity s1 s2 0 0 nil nil))
(t (sequence-1 sequence-2 &key (start1 0) (start2 0) end1 end2
test test-not (key 'identity) from-end)
(assert (not from-end) ()
"Mismatch :from-end not implemented.")
(with-tester (test test-not)
(with-funcallable (key)
(do-sequence-dispatch sequence-1
(vector
(unless end1 (setf end1 (length sequence-1)))
(with-subvector-accessor (sequence-1-ref sequence-1 start1 end1)
(do-sequence-dispatch sequence-2
(vector
(let ((end2 (check-the index (or end2 (length sequence-2)))))
(with-subvector-accessor (sequence-2-ref sequence-2 start2 end2)
(macrolet ((test-return (index1 index2)
`(unless (test (key (sequence-1-ref ,index1))
(key (sequence-2-ref ,index2)))
(return-from mismatch ,index1))))
(let ((length1 (- end1 start1))
(length2 (- end2 start2)))
(cond
((< length1 length2)
(dotimes (i length1)
(declare (index i))
(test-return (+ start1 i) (+ start2 i)))
end1)
((> length1 length2)
(dotimes (i length2)
(declare (index i))
(test-return (+ start1 i) (+ start2 i)))
(+ start1 length2))
(t (dotimes (i length1)
(declare (index i))
(test-return (+ start1 i) (+ start2 i)))
nil)))))))
(list
(let ((length1 (- end1 start1))
(start-cons2 (nthcdr start2 sequence-2)))
(cond
((and (zerop length1) (null start-cons2))
(if (and end2 (> end2 start2)) start1 nil))
((not end2)
(do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((>= i1 end1) (if (null p2) nil i1))
(declare (index i1))
(unless (and p2 (test (key (sequence-1-ref i1)) (key (car p2))))
(return-from mismatch i1))))
((< length1 (- end2 start2))
(do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((>= i1 end1) end1)
(declare (index i1))
(unless (test (key (sequence-1-ref i1)) (key (car p2)))
(return-from mismatch i1))))
((> length1 (- end2 start2))
(do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((null p2) end1)
(declare (index i1))
(unless (test (key (sequence-1-ref i1)) (key (car p2)))
(return-from mismatch i1))))
(t (do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((null p2) nil)
(declare (index i1))
(unless (test (key (sequence-1-ref i1)) (key (car p2)))
(return-from mismatch i1))))))))))
(list
(do-sequence-dispatch sequence-2
(vector
(let ((mismatch-2 (mismatch sequence-2 sequence-1 :from-end from-end :test test :key key
:start1 start2 :end1 end2 :start2 start1 :end2 end1)))
(if (not mismatch-2)
nil
(+ start1 (- mismatch-2 start2)))))
(list
(let ((start-cons1 (nthcdr start1 sequence-1))
(start-cons2 (nthcdr start2 sequence-2)))
(assert (and start-cons1 start-cons2) (start1 start2) "Illegal bounding indexes.")
(cond
((and (not end1) (not end2))
(do ((p1 start-cons1 (cdr p1))
(p2 start-cons2 (cdr p2))
(i1 start1 (1+ i1)))
((null p1) (if (null p2) nil i1))
(declare (index i1))
(unless (and p2 (test (key (car p1)) (key (car p2))))
(return i1))))
(t (do ((p1 start-cons1 (cdr p1))
(p2 start-cons2 (cdr p2))
(i1 start1 (1+ i1))
(i2 start2 (1+ i2)))
((if end1 (>= i1 end1) (null p1))
(if (if end2 (>= i2 end2) (null p2)) nil i1))
(declare (index i1 i2))
(unless p2
(if end2
(error "Illegal end2 bounding index.")
(return i1)))
(unless (and (or (not end2) (< i1 end2))
(test (key (car p1)) (key (car p2))))
(return i1)))))))))))))))
(defun map-into (result-sequence function first-sequence &rest more-sequences)
(declare (dynamic-extent more-sequences))
(assert (null more-sequences) ()
"MAP-INTO not implemented.")
(with-funcallable (map function)
(sequence-double-dispatch (result-sequence first-sequence)
((vector vector)
(let ((length (min (length result-sequence)
(length first-sequence))))
(with-subvector-accessor (result-ref result-sequence 0 length)
(with-subvector-accessor (first-sequence-ref first-sequence 0 length)
(dotimes (i length result-sequence)
(setf (result-ref i)
(map (first-sequence-ref i))))))))
((list list)
(do ((p result-sequence (cdr p))
(q first-sequence (cdr q)))
((or (null p) (null q))
result-sequence)
(setf (car p) (map (car q)))))
((vector list)
(with-subvector-accessor (result-ref result-sequence)
(do ((end (length result-sequence))
(i 0 (1+ i))
(p first-sequence (cdr p)))
((or (endp p) (>= i end)) result-sequence)
(declare (index i))
(setf (result-ref i) (map (car p))))))
((list vector)
(with-subvector-accessor (first-ref first-sequence)
(do ((end (length first-sequence))
(i 0 (1+ i))
(p result-sequence (cdr p)))
((or (endp p) (>= i end)) result-sequence)
(declare (index i))
(setf (car p) (map (first-ref i)))))))))
(defun map-for-nil (function first-sequence &rest more-sequences)
(numargs-case
(2 (function first-sequence)
(with-funcallable (mapf function)
(do-sequence-dispatch first-sequence
(list
(dolist (x first-sequence)
(mapf x)))
(vector
(with-subvector-accessor (sequence-ref first-sequence)
(dotimes (i (length first-sequence))
(mapf (sequence-ref i))))))))
(3 (function first-sequence second-sequence)
(with-funcallable (mapf function)
(sequence-double-dispatch (first-sequence second-sequence)
((list list)
(do ((p first-sequence (cdr p))
(q second-sequence (cdr q)))
((or (endp p) (endp q)))
(mapf (car p) (car q))))
((vector vector)
(with-subvector-accessor (first-sequence-ref first-sequence)
(with-subvector-accessor (second-sequence-ref second-sequence)
(do ((len1 (length first-sequence))
(len2 (length second-sequence))
(i 0 (1+ i))
(j 0 (1+ j)))
((or (>= i len1)
(>= j len2)))
(declare (index i j))
(mapf (first-sequence-ref i) (second-sequence-ref j))))))
)))
(t (function first-sequence &rest more-sequences)
(declare (ignore function first-sequence more-sequences))
(error "MAP not implemented."))))
(defun map-for-list (function first-sequence &rest more-sequences)
(numargs-case
(2 (function first-sequence)
(with-funcallable (mapf function)
(do-sequence-dispatch first-sequence
(list
(mapcar function first-sequence))
(vector
(with-subvector-accessor (sequence-ref first-sequence)
(let ((result nil))
(dotimes (i (length first-sequence))
(push (mapf (sequence-ref i))
result))
(nreverse result)))))))
(3 (function first-sequence second-sequence)
(sequence-double-dispatch (first-sequence second-sequence)
((list list)
(mapcar function first-sequence second-sequence))
((vector vector)
(with-funcallable (mapf function)
(with-subvector-accessor (first-sequence-ref first-sequence)
(with-subvector-accessor (second-sequence-ref second-sequence)
(do ((result nil)
(len1 (length first-sequence))
(len2 (length second-sequence))
(i 0 (1+ i))
(j 0 (1+ j)))
((or (>= i len1)
(>= j len2))
(nreverse result))
(declare (index i j))
(push (mapf (first-sequence-ref i) (second-sequence-ref j))
result))))))
((list vector)
(with-funcallable (mapf function)
(with-subvector-accessor (second-sequence-ref second-sequence)
(do ((result nil)
(len2 (length second-sequence))
(p first-sequence (cdr p))
(j 0 (1+ j)))
((or (endp p) (>= j len2))
(nreverse result))
(declare (index j))
(push (mapf (car p) (second-sequence-ref j))
result)))))
((vector list)
(with-funcallable (mapf function)
(with-subvector-accessor (first-sequence-ref first-sequence)
(do ((result nil)
(len1 (length first-sequence))
(p second-sequence (cdr p))
(j 0 (1+ j)))
((or (endp p) (>= j len1))
(nreverse result))
(declare (index j))
(push (mapf (first-sequence-ref j) (car p))
result)))))))
(t (function first-sequence &rest more-sequences)
(declare (dynamic-extent more-sequences)
(ignore function first-sequence more-sequences))
(error "MAP not implemented."))))
(defun map-for-vector (result function first-sequence &rest more-sequences)
(numargs-case
(3 (result function first-sequence)
(with-funcallable (mapf function)
(do-sequence-dispatch first-sequence
(vector
(do ((i 0 (1+ i)))
((>= i (length result)) result)
(declare (index i))
(setf (aref result i) (mapf (aref first-sequence i)))))
(list
(do ((i 0 (1+ i)))
((>= i (length result)) result)
(declare (index i))
(setf (aref result i) (mapf (pop first-sequence))))))))
(t (function first-sequence &rest more-sequences)
(declare (ignore function first-sequence more-sequences))
(error "MAP not implemented."))))
(defun map (result-type function first-sequence &rest more-sequences)
"=> result"
(declare (dynamic-extent more-sequences))
(cond
((null result-type)
(apply 'map-for-nil function first-sequence more-sequences))
((eq 'list result-type)
(apply 'map-for-list function first-sequence more-sequences))
((member result-type '(string simple-string))
(apply 'map-for-vector
(make-string (length first-sequence))
function first-sequence more-sequences))
((member result-type '(vector simple-vector))
(apply 'map-for-vector
(make-array (length first-sequence))
function first-sequence more-sequences))
(t (error "MAP not implemented."))))
(defun fill (sequence item &key (start 0) end)
"=> sequence"
(let ((start (check-the index start)))
(etypecase sequence
(list
(do ((p (nthcdr start sequence) (cdr p))
(i start (1+ i)))
((or (null p) (and end (>= i end))))
(declare (index i))
(setf (car p) item)))
((simple-array (unsigned-byte 32) 1)
(let* ((length (array-dimension sequence 0))
(end (or end length)))
(unless (<= 0 end length)
(error 'index-out-of-range :index end :range length))
(do ((i start (1+ i)))
((>= i end))
(declare (index i))
(setf (memref sequence (movitz-type-slot-offset 'movitz-basic-vector 'data)
:index i
:type :unsigned-byte32)
item))))
(vector
(let ((end (or end (length sequence))))
(with-subvector-accessor (sequence-ref sequence start end)
(do ((i start (1+ i)))
((>= i end))
(declare (index i))
(setf (sequence-ref i) item)))))))
sequence)
(defun replace (sequence-1 sequence-2 &key (start1 0) end1 (start2 0) end2)
(let ((start1 (check-the index start1))
(start2 (check-the index start2)))
(cond
((and (eq sequence-1 sequence-2)
(<= start2 start1 (or end2 start1)))
(if (= start1 start2)
sequence-1 ; no need to copy anything
;; must copy in reverse direction
(do-sequence-dispatch sequence-1
(vector
(let ((l (length sequence-1)))
(setf end1 (or end1 l)
end2 (or end2 l))
(assert (<= 0 start2 end2 l)))
(with-subvector-accessor (sequence-1-ref sequence-1 start1 end1)
(do* ((length (min (- end1 start1) (- end2 start2)))
(i (+ start1 length -1) (1- i))
(j (+ start2 length -1) (1- j)))
((< i start1) sequence-1)
(declare (index i j length))
(setf (sequence-1-ref i)
(sequence-1-ref j)))))
(list
(let* ((length (length sequence-1))
(reverse-list (nreverse sequence-1))
(size (min (- (or end1 length) start1) (- (or end2 length) start2))))
(do ((p (nthcdr (- length start1 size) reverse-list) (cdr p))
(q (nthcdr (- length start2 size) reverse-list) (cdr q))
(i 0 (1+ i)))
((>= i size) (nreverse reverse-list))
(declare (index i))
(setf (car p) (car q))))))))
;; (not (eq sequence-1 sequence-2)) ..
(t (do-sequence-dispatch sequence-1
(vector
(setf end1 (or end1 (length sequence-1)))
(do-sequence-dispatch sequence-2
(vector
(setf end2 (or end2 (length sequence-2)))
(with-subvector-accessor (sequence-1-ref sequence-1 start1 end1)
(with-subvector-accessor (sequence-2-ref sequence-2 start2 end2)
(cond
((< (- end1 start1) (- end2 start2))
(do ((i start1 (1+ i))
(j start2 (1+ j)))
((>= i end1) sequence-1)
(declare (index i j))
(setf (sequence-1-ref i) (sequence-2-ref j))))
(t (do ((i start1 (1+ i))
(j start2 (1+ j)))
((>= j end2) sequence-1)
(declare (index i j))
(setf (sequence-1-ref i) (sequence-2-ref j))))))))
(list
(with-subvector-accessor (sequence-1-ref sequence-1 start1 end1)
(if (not end2)
(do ((i start1 (1+ i))
(p (nthcdr start2 sequence-2) (cdr p)))
((or (null p) (>= i end1)) sequence-1)
(declare (index i))
(setf (sequence-1-ref i) (car p)))
(do ((i start1 (1+ i))
(j start2 (1+ j))
(p (nthcdr start2 sequence-2) (cdr p)))
((or (>= i end1) (endp p) (>= j end2)) sequence-1)
(declare (index i j))
(setf (sequence-1-ref i) (car p))))))))
(list
(do-sequence-dispatch sequence-2
(vector
(setf end2 (or end2 (length sequence-2)))
(with-subvector-accessor (sequence-2-ref sequence-2 start2 end2)
(do ((p (nthcdr start1 sequence-1) (cdr p))
(i start1 (1+ i))
(j start2 (1+ j)))
((or (endp p) (>= j end2) (and end1 (>= i end1)))
sequence-1)
(declare (index i j))
(setf (car p) (sequence-2-ref j)))))
(list
(do ((i start1 (1+ i))
(j start2 (1+ j))
(p (nthcdr start1 sequence-1) (cdr p))
(q (nthcdr start2 sequence-2) (cdr q)))
((or (endp p) (endp q)
(and end1 (>= i end1))
(and end2 (>= j end2)))
sequence-1)
(declare (index i j))
(setf (car p) (car q)))))))
sequence-1))))
(defun find (item sequence &key from-end (start 0) end (key 'identity) test test-not)
(numargs-case
(2 (item sequence)
(do-sequence-dispatch sequence
(vector
(with-subvector-accessor (sequence-ref sequence)
(dotimes (i (length sequence))
(when (eql item (sequence-ref i))
(return item)))))
(list
(dolist (x sequence)
(when (eql item x)
(return x))))))
(t (item sequence &key from-end (start 0) end (key 'identity) test test-not)
(let ((start (check-the index start)))
(with-tester (test test-not)
(with-funcallable (key)
(do-sequence-dispatch sequence
(vector
(setf end (or end (length sequence)))
(with-subvector-accessor (sequence-ref sequence start end)
(if (not from-end)
(do ((i start (1+ i)))
((>= i end) nil)
(declare (index i))
(when (test item (key (aref sequence i)))
(return (sequence-ref i))))
(do ((i (1- end) (1- i)))
((< i start) nil)
(declare (index i))
(when (test item (key (sequence-ref i)))
(return (sequence-ref i)))))))
(list
(if end
(do ((p (nthcdr start sequence) (cdr p))
(i start (1+ i)))
((or (>= i end) (endp p)) nil)
(declare (index i))
(when (test item (key (car p)))
(return (or (and from-end
(find item (cdr p)
:from-end t :test test
:key key :end (- end i 1)))
(car p)))))
(do ((p (nthcdr start sequence) (cdr p)))
((endp p) nil)
(when (test item (key (car p)))
(return (or (and from-end (find item (cdr p) :from-end t :test test :key key))
(car p))))))))))))))
(defun find-if (predicate sequence &key from-end (start 0) end (key 'identity))
(numargs-case
(2 (predicate sequence)
(with-funcallable (predicate)
(do-sequence-dispatch sequence
(vector
(let ((end (length sequence)))
(with-subvector-accessor (sequence-ref sequence 0 end)
(do ((i 0 (1+ i)))
((>= i end))
(declare (index i))
(let ((x (sequence-ref i)))
(when (predicate x) (return x)))))))
(list
(do ((p sequence (cdr p)))
((endp p) nil)
(let ((x (car p)))
(when (predicate x) (return x))))))))
(t (predicate sequence &key from-end (start 0) end (key 'identity))
(let ((start (check-the index start)))
(with-funcallable (predicate)
(with-funcallable (key)
(do-sequence-dispatch sequence
(vector
(setf end (or end (length sequence)))
(with-subvector-accessor (sequence-ref sequence start end)
(cond
((not from-end)
(do ((i start (1+ i)))
((>= i end))
(declare (index i))
(when (predicate (key (sequence-ref i)))
(return (sequence-ref i)))))
(t (do ((i (1- end) (1- i)))
((< i start))
(declare (index i))
(when (predicate (key (sequence-ref i)))
(return (sequence-ref i))))))))
(list
(cond
(end
(do ((p (nthcdr start sequence) (cdr p))
(i start (1+ i)))
((or (>= i end) (endp p)) nil)
(declare (index i))
(when (predicate (key (car p)))
(return (or (and from-end
(find-if predicate (cdr p) :end (- end i 1) :key key :from-end t))
(car p))))))
(t (do ((p (nthcdr start sequence) (cdr p)))
((endp p) nil)
(when (predicate (key (car p)))
(return (or (and from-end
(find-if predicate (cdr p) :key key :from-end t))
(car p)))))))))))))))
(defun find-if-not (predicate sequence &rest key-args)
(declare (dynamic-extent key-args))
(apply #'find-if (complement predicate) sequence key-args))
(defun count (item sequence &key (start 0) end (key 'identity) test test-not from-end)
(let ((start (check-the index start)))
(with-tester (test test-not)
(with-funcallable (key)
(do-sequence-dispatch sequence
(vector
(let ((end (check-the index (or end (length sequence)))))
(with-subvector-accessor (sequence-ref sequence start end)
(cond
((not from-end)
(do ((i start (1+ i))
(n 0))
((>= i end) n)
(declare (index i n))
(when (test item (key (sequence-ref i)))
(incf n))))
(t (do ((i (1- end) (1- i))
(n 0))
((< i start) n)
(declare (index i n))
(when (test item (key (sequence-ref i)))
(incf n))))))))
(list
(cond
((not end)
(do ((p (nthcdr start sequence) (cdr p))
(n 0))
((endp p) n)
(declare (index n))
(when (test item (key (car p)))
(incf n))))
(t (do ((p (nthcdr start sequence) (cdr p))
(i start (1+ i))
(n 0))
((or (endp p) (>= i end)) n)
(declare (index i n))
(when (test item (key (car p)))
(incf n)))))))))))
(defun count-if (predicate sequence &key (start 0) end (key 'identity) from-end)
(numargs-case
(2 (predicate sequence)
(with-funcallable (predicate)
(do-sequence-dispatch sequence
(list
(let ((count 0))
(declare (index count))
(dolist (x sequence)
(when (predicate x)
(incf count)))
count))
(vector
(with-subvector-accessor (sequence-ref sequence)
(let ((count 0))
(declare (index count))
(dotimes (i (length sequence))
(when (predicate (sequence-ref i))
(incf count)))
count))))))
(t (predicate sequence &key (start 0) end (key 'identity) from-end)
(when from-end
(error "count-if from-end not implemented."))
(let ((start (check-the index start)))
(with-funcallable (predicate)
(with-funcallable (key)
(do-sequence-dispatch sequence
(list
(if (not end)
(do ((n 0)
(p (nthcdr start sequence) (cdr p)))
((endp p) n)
(declare (index n))
(when (predicate (key (car p)))
(incf n)))
(let ((end (check-the index end)))
(do ((n 0)
(i start (1+ i))
(p (nthcdr start sequence) (cdr p)))
((or (endp p) (>= i end)) n)
(declare (index i n))
(when (predicate (key (car p)))
(incf n))))))
(vector
(error "vector count-if not implemented.")))))))))
(defun count-if-not (predicate sequence &key (start 0) end (key 'identity) from-end)
(numargs-case
(2 (predicate sequence)
(with-funcallable (predicate)
(do-sequence-dispatch sequence
(list
(let ((count 0))
(declare (index count))
(dolist (x sequence)
(when (not (predicate x))
(incf count)))
count))
(vector
(with-subvector-accessor (sequence-ref sequence)
(let ((count 0))
(declare (index count))
(dotimes (i (length sequence))
(when (not (predicate (sequence-ref i)))
(incf count)))
count))))))
(t (predicate sequence &rest keys)
(apply #'count-if
(complement predicate)
sequence
keys))))
(macrolet ((every-some-body ()
"This function body is shared between every and some."
`(with-funcallable (predicate)
(cond
((null more-sequences) ; 1 sequence case
(do-sequence-dispatch first-sequence
(list
(do ((p first-sequence (cdr p)))
((null p) (default-value))
(test-return (predicate (car p)))))
(vector
(do* ((l (length first-sequence))
(i 0 (1+ i)))
((= l i) (default-value))
(declare (index i l))
(test-return (predicate (aref first-sequence i)))))))
((null (cdr more-sequences)) ; 2 sequences case
(let ((second-sequence (first more-sequences)))
(sequence-double-dispatch (first-sequence second-sequence)
((list list)
(do ((p0 first-sequence (cdr p0))
(p1 second-sequence (cdr p1)))
((or (endp p0) (endp p1)) (default-value))
(test-return (predicate (car p0) (car p1)))))
((vector vector)
(do ((end (min (length first-sequence) (length second-sequence)))
(i 0 (1+ i)))
((>= i end) (default-value))
(declare (index i))
(test-return (predicate (aref first-sequence i)
(aref second-sequence i)))))
((list vector)
(do ((end (length second-sequence))
(i 0 (1+ i))
(p first-sequence (cdr p)))
((or (endp p) (>= i end)) (default-value))
(declare (index i))
(test-return (predicate (car p) (aref second-sequence i)))))
((vector list)
(do ((end (length first-sequence))
(i 0 (1+ i))
(p second-sequence (cdr p)))
((or (endp p) (>= i end)) (default-value))
(declare (index i))
(test-return (predicate (aref first-sequence i) (car p))))))))
(t (flet ((next (p)
(do-sequence-dispatch p
(list (cdr p))
(vector p)))
(seqend (p i)
(do-sequence-dispatch p
(list (null p))
(vector (>= i (length p)))))
(seqelt (p i)
(do-sequence-dispatch p
(list (car p))
(vector (aref p i)))))
(do* ((i 0 (1+ i)) ; 3 or more sequences, conses at 4 or more.
(p0 first-sequence (next p0))
(p1 (car more-sequences) (next p1))
(p2 (cadr more-sequences) (next p2))
(p3+ (cddr more-sequences) (map-into p3+ #'next p3+)) ;a list of pointers
(arg3+ (make-list (length p3+))))
((or (seqend p0 i)
(seqend p1 i)
(seqend p2 i)
(dolist (p p3+ nil)
(when (seqend p i)
(return t))))
(default-value))
(declare (index i))
(do ((x arg3+ (cdr x))
(y p3+ (cdr y)))
((null x))
(setf (car x) (seqelt (car y) i)))
(test-return (apply predicate (seqelt p0 i) (seqelt p1 i)
(seqelt p2 i) arg3+)))))))))
(defun some (predicate first-sequence &rest more-sequences)
(declare (dynamic-extent more-sequences))
(macrolet ((test-return (form)
`(let ((x ,form)) (when x (return x))))
(default-value () nil))
(every-some-body)))
(defun every (predicate first-sequence &rest more-sequences)
(declare (dynamic-extent more-sequences))
(macrolet ((test-return (form)
`(unless ,form (return nil)))
(default-value () t))
(every-some-body))))
(defun notany (predicate first-sequence &rest more-sequences)
(declare (dynamic-extent more-sequences))
(not (apply 'some predicate first-sequence more-sequences)))
(defun notevery (predicate first-sequence &rest more-sequences)
(declare (dynamic-extent more-sequences))
(not (apply 'every predicate first-sequence more-sequences)))
(defun list-remove (item list test test-not key end count)
"Implements remove for lists. Assumes (not from-end)."
(cond
((endp list)
nil)
((eq 0 count)
list)
(t (with-tester (test test-not)
(with-funcallable (key)
(if (test item (key (car list)))
(list-remove item (cdr list) test test-not key
(when end (1- end))
(when count (1- count)))
(do ((i 1 (1+ i))
(p0 list (cdr p0))
(p1 (cdr list) (cdr p1)))
((or (endp p1) (and end (>= i end))) list)
(declare (index i))
(when (test item (key (car p1)))
(return
;; reiterate from <list> to <p1>, consing up a copy, with
;; the copy's tail being the recursive call to list-remove.
(do* ((new-list (cons (car list) nil))
(x (cdr list) (cdr x))
(new-x new-list))
((eq x p1)
(setf (cdr new-x) (list-remove item (cdr p1) test test-not key
(when end (- end i 1))
(when count (1- count))))
new-list)
(setf new-x
(setf (cdr new-x)
(cons (car x) nil)))))))))))))
(defun list-remove-simple (item list)
"The same as list-remove, without count, end, or key, with test=eql."
(cond
((endp list)
nil)
((eql item (car list))
(list-remove-simple item (cdr list)))
(t (do ((i 1 (1+ i))
(p0 list (cdr p0))
(p1 (cdr list) (cdr p1)))
((endp p1) list)
(declare (index i))
(when (eql item (car p1))
(return
;; reiterate from <list> to <p1>, consing up a copy, with
;; the copy's tail being the recursive call to list-remove.
(do* ((new-list (cons (car list) nil))
(x (cdr list) (cdr x))
(new-x new-list))
((eq x p1)
(setf (cdr new-x) (list-remove-simple item (cdr p1)))
new-list)
(setf new-x
(setf (cdr new-x)
(cons (car x) nil))))))))))
(defun remove (item sequence &key test test-not (start 0) end count (key 'identity) from-end)
(when test-not
(setf test (complement test-not)))
(do-sequence-dispatch sequence
(list
(setf sequence (nthcdr start sequence))
(when end (decf end start))
(cond
((endp sequence)
nil)
((not from-end)
(if (and (eq test 'eql)
(not end)
(not count)
(eq key 'identity))
(list-remove-simple item sequence)
(list-remove item sequence test test-not key end count)))
(t (error "from-end not implemented."))))
(vector
(error "vector remove not implemented."))))
(defun list-remove-if (test test-not list key end count)
"Implements remove-if for lists. Assumes (not from-end)."
(cond
((endp list)
nil)
((eq 0 count)
list)
(t (with-tester (test test-not)
(with-funcallable (key)
(and (do () ((or (endp list)
(and end (<= end 0))
(not (test (key (car list))))
(and count (<= (decf count) 0)))
list)
(when end (decf end))
(setf list (cdr list)))
(do ((i 1 (1+ i))
(p0 list (cdr p0))
(p1 (cdr list) (cdr p1)))
((or (endp p1) (and end (>= i end))) list)
(declare (index i))
(when (test (key (car p1)))
(return
;; reiterate from <list> to <p1>, consing up a copy, with
;; the copy's tail being the recursive call to list-remove.
(do* ((new-list (cons (car list) nil))
(x (cdr list) (cdr x))
(new-x new-list))
((eq x p1)
(setf (cdr new-x) (list-remove-if test test-not (cdr p1) key
(when end (- end i 1))
(when count (1- count))))
new-list)
(setf new-x
(setf (cdr new-x)
(cons (car x) nil)))))))))))))
(defun remove-if (test sequence &key from-end (start 0) end count (key 'identity))
(do-sequence-dispatch sequence
(list
(setf sequence (nthcdr start sequence))
(when end (decf end start))
(cond
((endp sequence)
nil)
((not from-end)
(list-remove-if test nil sequence key end count))
(t (error "from-end not implemented."))))
(vector
(error "vector remove not implemented."))))
(defun remove-if-not (test sequence &rest args)
(declare (dynamic-extent args))
(apply 'remove-if (complement test) sequence args))
(defun list-delete (item list test test-not key start end count)
"Implements delete-if for lists. Assumes (not from-end)."
(cond
((null list)
nil)
((eq 0 count)
list)
((eq start end)
list)
(t (with-tester (test test-not)
(with-funcallable (key)
(let ((i 0) ; for end checking
(c 0)) ; for count checking
(declare (index i c))
(cond
((= 0 start)
;; delete from head..
(do ()
((not (test item (key (car list)))))
(when (or (endp (setf list (cdr list)))
(eq (incf i) end)
(eq (incf c) count))
(return-from list-delete list)))
(setq start 1))
(t (incf i (1- start))))
;; now delete "inside" list
(do* ((p (nthcdr (1- start) list))
(q (cdr p)))
((or (endp q)
(eq (incf i) end))
list)
(cond
((test item (key (car q)))
(setf q (cdr q)
(cdr p) q)
(when (eq (incf c) count)
(return list)))
(t (setf p q
q (cdr q)))))))))))
(defun list-delete-if (test list key start end count)
"Implements delete-if for lists. Assumes (not from-end)."
(cond
((null list)
nil)
((eq 0 count)
list)
((eq start end)
list)
(t (with-funcallable (test)
(with-funcallable (key)
(let ((i 0) ; for end checking
(c 0)) ; for count checking
(declare (index i c))
(cond
((= 0 start)
;; delete from head..
(do ()
((not (test (key (car list)))))
(when (or (endp (setf list (cdr list)))
(eq (incf i) end)
(eq (incf c) count))
(return-from list-delete-if list)))
(setq start 1))
(t (incf i (1- start))))
;; now delete "inside" list
(do* ((p (nthcdr (1- start) list))
(q (cdr p)))
((or (endp q)
(eq (incf i) end))
list)
(cond
((test (key (car q)))
(setf q (cdr q)
(cdr p) q)
(when (eq (incf c) count)
(return list)))
(t (setf p q
q (cdr q)))))))))))
(defun delete (item sequence &key test test-not from-end (start 0) end count (key 'identity))
(do-sequence-dispatch sequence
(list
(when from-end
(error "from-end not implemented."))
(list-delete item sequence test test-not key start end count))
(vector
(error "vector delete not implemented."))))
(defun delete-if (test sequence &key from-end (start 0) end count (key 'identity))
(do-sequence-dispatch sequence
(list
(when from-end
(error "from-end not implemented."))
(list-delete-if test sequence key start end count))
(vector
(error "vector delete-if not implemented."))))
(defun delete-if-not (test sequence &rest key-args)
(declare (dynamic-extent key-args))
(apply 'delete-if (complement test) sequence key-args))
(defun remove-duplicates (sequence &key (test 'eql) (key 'identity) (start 0) end test-not from-end)
(when test-not
(setf test (complement test-not)))
(do-sequence-dispatch sequence
(list
(let ((list (nthcdr start sequence)))
(cond
((endp list)
nil)
((and (not end) (not from-end))
(do ((r nil))
((endp list) (nreverse r))
(let ((x (pop list)))
(unless (member x list :key key :test test)
(push x r)))))
(t (error "remove-duplicates not implemented.")))))
(vector
(error "vector remove-duplicates not implemented."))))
(defun delete-duplicates (sequence &key from-end (test 'eql) (key 'identity) test-not (start 0) end)
(let ((test (if test-not
(complement test-not)
test)))
(do-sequence-dispatch sequence
(list
(cond
(from-end
(error "from-end not implemented."))
((not end)
(when (not (endp sequence))
(when (= 0 start)
;; delete from head
(do ()
((not (find (car sequence) (cdr sequence) :test test :key key)))
(setf sequence (cdr sequence))))
(do* ((p (nthcdr start sequence))
(q (cdr p) (cdr p)))
((endp q) sequence)
(if (find (car q) (cdr q) :test test :key key)
(setf (cdr p) (cdr q))
(setf p (cdr p))))))
(t (error "delete-duplicates end parameter not implemented."))))
(vector
;;; (unless end
;;; (setf end (length sequence)))
;;; (do ((i start (1+ i))
;;; (c 0))
;;; ((>= i end)
;;; (cond
;;; ((= 0 c) sequence)
(error "vector delete-duplicates not implemented.")))))
(defun search (sequence-1 sequence-2 &key (test 'eql) (key 'identity)
(start1 0) end1 (start2 0) end2 test-not from-end)
(let ((test (if test-not
(complement test-not)
test)))
(declare (dynamic-extent test))
(let ((start1 (check-the index start1))
(start2 (check-the index start2)))
(do-sequence-dispatch sequence-2
(vector
(let ((end1 (check-the index (or end1 (length sequence-1))))
(end2 (check-the index (or end2 (length sequence-2)))))
(do ((stop (- end2 (- end1 start1 1)))
(i start2 (1+ i)))
((>= i stop) nil)
(declare (index i))
(let ((mismatch-position (mismatch sequence-1 sequence-2
:start1 start1 :end1 end1
:start2 i :end2 end2
:key key :test test)))
(when (or (not mismatch-position)
(= mismatch-position end1))
(return (or (and from-end
(search sequence-1 sequence-2
:from-end t :test test :key key
:start1 start1 :end1 end1
:start2 (1+ i) :end2 end2))
i)))))))
(list
(let ((end1 (check-the index (or end1 (length sequence-1)))))
(do ((stop (and end2 (- end2 start2 (- end1 start1 1))))
(p (nthcdr start2 sequence-2) (cdr p))
(i 0 (1+ i)))
((or (endp p) (and stop (>= i stop))) nil)
(declare (index i))
(let ((mismatch-position (mismatch sequence-1 p
:start1 start1 :end1 end1
:key key :test test)))
(when (or (not mismatch-position)
(= mismatch-position end1))
(return (+ start2 i
(or (and from-end
(search sequence-1 p
:start2 1 :end2 (and end2 (- end2 i start2))
:from-end t :test test :key key
:start1 start1 :end1 end1))
0))))))))))))
(defun insertion-sort (vector predicate key start end)
"Insertion-sort is used for stable-sort, and as a finalizer for
quick-sort with cut-off greater than 1."
(let ((start (check-the index start))
(end (check-the index end)))
(with-funcallable (predicate)
(with-subvector-accessor (vector-ref vector start end)
(if (not key)
(do ((i (1+ start) (1+ i)))
((>= i end))
(declare (index i))
;; insert vector[i] into [start...i-1]
(let ((v (vector-ref i))
(j (1- i)))
(when (predicate v (vector-ref j))
(setf (vector-ref i) (vector-ref j))
(do* ((j+1 j (1- j+1))
(j (1- j) (1- j)))
((or (< j start)
(not (predicate v (vector-ref j))))
(setf (vector-ref j+1) v))
(declare (index j j+1))
(setf (vector-ref j+1) (vector-ref j))))))
(with-funcallable (key)
(do ((i (1+ start) (1+ i))) ; the same, only with a key-function..
((>= i end))
(declare (index i))
;; insert vector[i] into [start...i-1]
(do* ((v (vector-ref i))
(vk (key v))
(j (1- i) (1- j))
(j+1 i (1- j+1)))
((or (<= j+1 start)
(not (predicate vk (key (vector-ref j)))))
(setf (vector-ref j+1) v))
(declare (index j j+1))
(setf (vector-ref j+1) (vector-ref j)))))))))
vector)
(defun quick-sort (vector predicate key start end cut-off)
(let ((start (check-the index start))
(end (check-the index end)))
(macrolet ((do-while (p &body body)
`(do () ((not ,p)) ,@body)))
(when (> (- end start) cut-off)
(with-subvector-accessor (vector-ref vector start end)
(with-funcallable (predicate)
(with-funcallable (key)
(prog* ((pivot (vector-ref start)) ; should do median-of-three here..
(keyed-pivot (key pivot))
(left (1+ start))
(right (1- end))
left-item right-item)
(declare (index left right))
;; do median-of-three..
(let ((p1 (vector-ref start))
(p2 (vector-ref (+ start cut-off -1)))
(p3 (vector-ref (1- end))))
(let ((kp1 (key p1))
(kp2 (key p2))
(kp3 (key p3)))
(cond
((predicate p1 p2)
(if (predicate p2 p3)
(setf pivot p2 keyed-pivot kp2)
(if (predicate p1 p3)
(setf pivot p3 keyed-pivot kp3)
(setf pivot p1 keyed-pivot kp1))))
((predicate p2 p3)
(if (predicate p1 p3)
(setf pivot p1 keyed-pivot kp1)
(setf pivot p3 keyed-pivot kp3)))
(t (setf pivot p2 keyed-pivot kp2)))))
partitioning-loop
(do-while (not (predicate keyed-pivot (key (setf left-item (vector-ref left)))))
(incf left)
(when (>= left end)
(setf right-item (vector-ref right))
(go partitioning-complete)))
(do-while (predicate keyed-pivot (key (setf right-item (vector-ref right))))
(decf right))
(when (< left right)
(setf (vector-ref left) right-item
(vector-ref right) left-item)
(incf left)
(decf right)
(go partitioning-loop))
partitioning-complete
(setf (vector-ref start) right-item ; (aref vector right)
(vector-ref right) pivot)
(when (and (> cut-off (- right start))
(> cut-off (- end right)))
(quick-sort vector predicate key start right cut-off)
(quick-sort vector predicate key (1+ right) end cut-off)))))))))
vector)
(defun sort (sequence predicate &key (key 'identity))
(do-sequence-dispatch sequence
(list
(sort-list sequence predicate key))
(vector
(quick-sort sequence predicate key 0 (length sequence) 9)
(insertion-sort sequence predicate key 0 (length sequence)))))
(defun stable-sort (sequence predicate &key key)
(do-sequence-dispatch sequence
(list
(error "Stable-sort not implemented for lists."))
(vector
(insertion-sort sequence predicate key 0 (length sequence)))))
(defun merge (result-type sequence-1 sequence-2 predicate &key (key 'identity))
(ecase result-type
(list
(sequence-double-dispatch (sequence-1 sequence-2)
((list list)
(merge-list-list sequence-1 sequence-2 predicate key))))))
(defun merge-list-list (list1 list2 predicate key)
(cond
((null list1)
list2)
((null list2)
list1)
(t (with-funcallable (predicate)
(with-funcallable (key)
(macrolet ((xpop (var)
`(let ((x ,var)) (setf ,var (cdr x)) x)))
(do* ((result (if (predicate (key (car list1)) (key (car list2)))
(xpop list1)
(xpop list2)))
(r result))
((null (setf r
(setf (cdr r)
(cond
((null list1) (xpop list2))
((null list2) (xpop list1))
((predicate (key (car list1)) (key (car list2)))
(xpop list1))
(t (xpop list2))))))
result))))))))
;;; Most of list-sorting snipped from cmucl.
;;; MERGE-LISTS* originally written by Jim Large.
;;; modified to return a pointer to the end of the result
;;; and to not cons header each time its called.
;;; It destructively merges list-1 with list-2. In the resulting
;;; list, elements of list-2 are guaranteed to come after equal elements
;;; of list-1.
(defun merge-lists* (list-1 list-2 predicate key merge-lists-header)
(with-funcallable (predicate)
(with-funcallable (key)
(do* ((result merge-lists-header)
(P result)) ; P points to last cell of result
((or (null list-1) (null list-2)) ; done when either list used up
(if (null list-1) ; in which case, append the
(rplacd p list-2) ; other list
(rplacd p list-1))
(do ((drag p lead)
(lead (cdr p) (cdr lead)))
((null lead)
(values (prog1 (cdr result) ; return the result sans header
(rplacd result nil)) ; (free memory, be careful)
drag)))) ; and return pointer to last element
(cond ((predicate (key (car list-2)) (key (car list-1)))
(rplacd p list-2) ; append the lesser list to last cell of
(setq p (cdr p)) ; result. Note: test must bo done for
(pop list-2)) ; list-2 < list-1 so merge will be
(t (rplacd p list-1) ; stable for list-1
(setq p (cdr p))
(pop list-1)))))))
;;; SORT-LIST uses a bottom up merge sort. First a pass is made over
;;; the list grabbing one element at a time and merging it with the next one
;;; form pairs of sorted elements. Then n is doubled, and elements are taken
;;; in runs of two, merging one run with the next to form quadruples of sorted
;;; elements. This continues until n is large enough that the inner loop only
;;; runs for one iteration; that is, there are only two runs that can be merged,
;;; the first run starting at the beginning of the list, and the second being
;;; the remaining elements.
(defun sort-list (list pred key)
(let ((head (cons :header list)) ; head holds on to everything
(n 1) ; bottom-up size of lists to be merged
unsorted ; unsorted is the remaining list to be
; broken into n size lists and merged
list-1 ; list-1 is one length n list to be merged
last ; last points to the last visited cell
(merge-lists-header (list :header)))
(declare (index n))
(do () (nil)
;; start collecting runs of n at the first element
(setf unsorted (cdr head))
;; tack on the first merge of two n-runs to the head holder
(setf last head)
(let ((n-1 (1- n)))
(do () (nil)
(setf list-1 unsorted)
(let ((temp (nthcdr n-1 list-1))
list-2)
(cond (temp
;; there are enough elements for a second run
(setf list-2 (cdr temp))
(setf (cdr temp) nil)
(setf temp (nthcdr n-1 list-2))
(cond (temp
(setf unsorted (cdr temp))
(setf (cdr temp) nil))
;; the second run goes off the end of the list
(t (setf unsorted nil)))
(multiple-value-bind (merged-head merged-last)
(merge-lists* list-1 list-2 pred key
merge-lists-header)
(setf (cdr last) merged-head)
(setf last merged-last))
(if (null unsorted) (return)))
;; if there is only one run, then tack it on to the end
(t (setf (cdr last) list-1)
(return)))))
(setf n (+ n n))
;; If the inner loop only executed once, then there were only enough
;; elements for two runs given n, so all the elements have been merged
;; into one list. This may waste one outer iteration to realize.
(if (eq list-1 (cdr head))
(return list-1))))))
(defun make-sequence (result-type size &key (initial-element nil initial-element-p))
"=> sequence"
(ecase result-type
(string
(if (not initial-element-p)
(make-string size)
(make-string size :initial-element initial-element)))
(vector
(make-array size :initial-element initial-element))
(list
(make-list size :initial-element initial-element))))
(defun concatenate (result-type &rest sequences)
"=> result-sequence"
(declare (dynamic-extent sequences))
(cond
((null sequences)
(make-sequence result-type 0))
((and (null (rest sequences))
(typep (first sequences) result-type))
(copy-seq (first sequences)))
((= 0 (length (first sequences)))
(apply #'concatenate result-type (cdr sequences)))
((member result-type '(vector string))
(let* ((r (make-sequence result-type
(let ((length 0))
(dolist (s sequences length)
(incf length (length s))))))
(i 0))
(declare (index i))
(dolist (s sequences)
(replace r s :start1 i)
(incf i (length s)))
r))
(t (error "Can't concatenate ~S yet: ~:S"
result-type
(copy-list sequences))))) ; no more dynamic-extent.
(defun substitute (newitem olditem sequence
&key (test 'eql) test-not (start 0) end count (key 'identity) from-end)
"=> result-sequence"
(when test-not
(setf test (complement test-not)))
(with-funcallable (test (if test-not (complement test-not) test))
(substitute-if newitem (lambda (x) (test olditem x)) sequence
:start start :end end
:count count :key key
:from-end from-end)))
(defun nsubstitute (newitem olditem sequence
&key (test 'eql) test-not (start 0) end count (key 'identity) from-end)
"=> result-sequence"
(when test-not
(setf test (complement test-not)))
(with-funcallable (test (if test-not (complement test-not) test))
(nsubstitute-if newitem (lambda (x) (test olditem x)) sequence
:start start :end end
:count count :key key
:from-end from-end)))
(defun substitute-if (newitem predicate sequence &rest args
&key (start 0) end count (key 'identity) from-end)
"=> result-sequence"
(declare (dynamic-extent args))
(with-funcallable (predicate)
(with-funcallable (key)
(do-sequence-dispatch sequence
(vector
(apply 'nsubstitute-if newitem predicate (copy-seq sequence) args))
(list
(if from-end
(apply 'nsubstitute-if newitem predicate (copy-list sequence) args)
(if (or (null sequence)
(and end (<= end start)))
nil
(multiple-value-bind (new-list new-tail)
(if (= 0 start)
(let ((new-list (list #0=(let ((x (pop sequence)))
(if (predicate (key x))
newitem
x)))))
(values new-list new-list))
(do* ((new-list (list (pop sequence)))
(new-tail new-list (cdr new-tail))
(i 1 (1+ i)))
((or (endp sequence) (>= i start))
(values new-list new-tail))
(setf (cdr new-tail) (list (pop sequence)))))
(cond
((and (not end) (not count))
(do ()
((endp sequence) new-list)
(setf new-tail
(setf (cdr new-tail) (list #0#)))))
((and end (not count))
(do ((i (- end start 1) (1- i)))
((or (endp sequence) (<= i 0))
(setf (cdr new-tail) (copy-list sequence))
new-list)
(setf new-tail
(setf (cdr new-tail) (list #0#)))))
((and (not end) count)
(do ((c 0))
((or (endp sequence) (>= c count))
(setf (cdr new-tail) (copy-list sequence))
new-list)
(setf new-tail
(setf (cdr new-tail) #1=(list (let ((x (pop sequence)))
(if (predicate (key x))
(progn (incf c) newitem)
x)))))))
((and end count)
(do ((i (- end start 1) (1- i))
(c 0))
((or (endp sequence) (<= i 0) (>= c count))
(setf (cdr new-tail)
(copy-list sequence))
new-list)
(setf new-tail
(setf (cdr new-tail) #1#))))
((error 'program-error)))))))))))
(defun nsubstitute-if (newitem predicate sequence &key (start 0) end count (key 'identity) from-end)
"=> sequence"
(if (<= count 0)
sequence
(with-funcallable (predicate)
(with-funcallable (key)
(do-sequence-dispatch sequence
(vector
(let ((end (or end (length sequence))))
(with-subvector-accessor (ref sequence start end)
(cond
((and (not count) (not from-end))
(do ((i start (1+ i)))
((>= i end) sequence)
(declare (index i))
(when (predicate (key (ref i)))
(setf (ref i) newitem))))
((and count (not from-end))
(do ((c 0)
(i start (1+ i)))
((>= i end) sequence)
(declare (index i c))
(when (predicate (key (ref i)))
(setf (ref i) newitem)
(when (>= (incf c) count)
(return sequence)))))
((and (not count) from-end)
(do ((i (1- end) (1- i)))
((< i start) sequence)
(declare (index i))
(when (predicate (key (ref i)))
(setf (ref i) newitem))))
((and count from-end)
(do ((c 0)
(i (1- end) (1- i)))
((< i start) sequence)
(declare (index c i))
(when (predicate (key (ref i)))
(setf (ref i) newitem)
(when (>= (incf c) count)
(return sequence)))))
((error 'program-error))))))
(list
(let ((p (nthcdr start sequence)))
(cond
(from-end
(nreverse (nsubstitute-if newitem predicate (nreverse sequence)
:start (if (not end) 0 (- (length sequence) end))
:end (if (plusp start) nil (- (length sequence) start))
:count count :key key)))
#+ignore ((and from-end count)
(let* ((end (and end (- end start)))
(existing-count (count-if predicate p :key key :end end)))
(do ((i count))
((>= i existing-count)
(nsubstitute-if newitem predicate p :end end :key key)
sequence)
(declare (index i))
(when (predicate (key (car p)))
(incf i))
(setf p (cdr p)))))
((and (not end) (not count))
(do ((p p (cdr p)))
((endp p) sequence)
(when (predicate (key (car p)))
(setf (car p) newitem))))
((and end (not count))
(do ((i start (1+ i))
(p p (cdr p)))
((or (endp p) (>= i end)) sequence)
(declare (index i))
(when (predicate (key (car p)))
(setf (car p) newitem))))
((and (not end) count)
(do ((c 0)
(p p (cdr p)))
((endp p) sequence)
(declare (index c))
(when (predicate (key (car p)))
(setf (car p) newitem)
(when (>= (incf c) count)
(return sequence)))))
((and end count)
(do ((c 0)
(i start (1+ i))
(p p (cdr p)))
((or (endp p) (>= i end)) sequence)
(declare (index c i))
(when (predicate (key (car p)))
(setf (car p) newitem)
(when (>= (incf c) count)
(return sequence)))))
((error 'program-error))))))))))
(defun substitute-if-not (newitem predicate sequence &rest keyargs)
(declare (dynamic-extent keyargs))
(apply #'substitute-if newitem (complement predicate) sequence keyargs))
(defun nsubstitute-if-not (newitem predicate sequence &rest keyargs)
(declare (dynamic-extent keyargs))
(apply #'nsubstitute-if newitem (complement predicate) sequence keyargs))
|
46914
|
;;;;------------------------------------------------------------------
;;;;
;;;; Copyright (C) 2001-2005,
;;;; Department of Computer Science, University of Tromso, Norway.
;;;;
;;;; For distribution policy, see the accompanying file COPYING.
;;;;
;;;; Filename: sequences.lisp
;;;; Description:
;;;; Author: <NAME> <<EMAIL>>
;;;; Created at: Tue Sep 11 14:19:23 2001
;;;;
;;;; $Id$
;;;;
;;;;------------------------------------------------------------------
(require :muerte/basic-macros)
(provide :muerte/sequences)
(in-package muerte)
(defun sequencep (x)
(or (typep x 'vector)
(typep x 'cons)))
(defmacro do-sequence-dispatch (sequence-var (type0 &body forms0) (type1 &body forms1))
(cond
((and (eq 'list type0) (eq 'vector type1))
`(if (typep ,sequence-var 'list)
(progn ,@forms0)
(progn (check-type ,sequence-var vector)
,@forms1)))
((and (eq 'vector type0) (eq 'list type1))
`(if (not (typep ,sequence-var 'list))
(progn (check-type ,sequence-var vector)
,@forms0)
(progn ,@forms1)))
(t (error "do-sequence-dispatch only understands list and vector types, not ~W and ~W."
type0 type1))))
(defmacro with-tester ((test test-not) &body body)
(let ((function (gensym "with-test-"))
(notter (gensym "with-test-notter-")))
`(multiple-value-bind (,function ,notter)
(progn ;; the (values function boolean)
(ensure-tester ,test ,test-not))
(macrolet ((,test (&rest args)
`(xor (funcall%unsafe ,',function ,@args)
,',notter)))
,@body))))
(defun ensure-tester (test test-not)
(cond
(test-not
(when test
(error "Both test and test-not specified."))
(values (ensure-funcallable test-not)
t))
(test
(values (ensure-funcallable test)
nil))
(t (values #'eql
nil))))
(defun sequence-double-dispatch-error (seq0 seq1)
(error "The type-set (~A, ~A) has not been implemented in this sequence-double-dispatch."
(type-of seq0)
(type-of seq1)))
(defmacro sequence-double-dispatch ((seq0 seq1) &rest clauses)
`(case (logior (if (typep ,seq0 'list) 2 0)
(if (typep ,seq1 'list) 1 0))
,@(mapcar (lambda (clause)
(destructuring-bind ((type0 type1) . forms)
clause
(list* (logior (ecase type0 (list 2) (vector 0))
(ecase type1 (list 1) (vector 0)))
forms)))
clauses)
(t (sequence-double-dispatch-error ,seq0 ,seq1))))
(defun length (sequence)
(etypecase sequence
(list
(do ((x sequence (cdr x))
(length 0 (1+ length)))
((null x) length)
(declare (index length))))
(indirect-vector
(memref sequence (movitz-type-slot-offset 'movitz-basic-vector 'data)
:index 2))
((simple-array * 1)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :ebx) sequence)
(:movl (:ebx (:offset movitz-basic-vector num-elements))
:eax)
(:testl ,(logxor #xffffffff (1- (expt 2 14))) :eax)
(:jnz 'basic-vector-length-ok)
(:movzxw (:ebx (:offset movitz-basic-vector fill-pointer))
:eax)
basic-vector-length-ok)))
(do-it)))))
(defun length%list (sequence)
(do ((length 0 (1+ length))
(x sequence (cdr x)))
((null x) length)
(declare (type index length))))
(defun elt (sequence index)
(do-sequence-dispatch sequence
(vector (aref sequence index))
(list (nth index sequence))))
(defun (setf elt) (value sequence index)
(do-sequence-dispatch sequence
(vector (setf (aref sequence index) value))
(list (setf (nth index sequence) value))))
(defun reduce (function sequence &key (key 'identity) from-end
(start 0) (end (length sequence))
(initial-value nil initial-value-p))
(numargs-case
(2 (function sequence)
(with-funcallable (funcall-function function)
(do-sequence-dispatch sequence
(list
(cond
((null sequence)
(funcall-function))
((null (cdr sequence))
(car sequence))
(t (do* ((list sequence)
(result (funcall-function (pop list) (pop list))
(funcall-function result (pop list))))
((endp list)
result)))))
(vector
(let ((end (length sequence)))
(case end
(0 (funcall-function))
(1 (aref sequence 0))
(t (with-subvector-accessor (sequence-ref sequence 0 end)
(do* ((index 0)
(result (funcall-function (sequence-ref (prog1 index (incf index)))
(sequence-ref (prog1 index (incf index))))
(funcall-function result (sequence-ref (prog1 index (incf index))))))
((= index end) result)
(declare (index index)))))))))))
(t (function sequence &key (key 'identity) from-end
(start 0) end
(initial-value nil initial-value-p))
(let ((start (check-the index start)))
(with-funcallable (funcall-function function)
(with-funcallable (key)
(do-sequence-dispatch sequence
(list
(let ((list (nthcdr start sequence)))
(cond
((null list)
(if initial-value-p
initial-value
(funcall-function)))
((null (cdr list))
(if initial-value-p
(funcall-function initial-value (key (car list)))
(key (car list))))
((not from-end)
(if (not end)
(do ((result (funcall-function (if initial-value-p
initial-value
(key (pop list)))
(key (pop list)))
(funcall-function result (key (pop list)))))
((null list) result))
(do ((counter (1+ start) (1+ counter))
(result (funcall-function (if initial-value-p
initial-value
(key (pop list)))
(key (pop list)))
(funcall-function result (key (pop list)))))
((or (null list)
(= end counter))
result)
(declare (index counter)))))
(from-end
(do* ((end (or end (+ start (length list))))
(counter (1+ start) (1+ counter))
(list (nreverse (subseq sequence start end)))
(result (funcall-function (key (pop list))
(if initial-value-p
initial-value
(key (pop list))))
(funcall-function (key (pop list)) result)))
((or (null list)
(= end counter))
result)
(declare (index counter)))))))
(vector
(when from-end
(error "REDUCE from-end on vectors is not implemented."))
(let ((end (or (check-the index end)
(length sequence))))
(case (- end start)
(0 (if initial-value-p
initial-value
(funcall-function)))
(1 (if initial-value-p
(funcall-function initial-value (key (elt sequence start)))
(key (elt sequence start))))
(t (with-subvector-accessor (sequence-ref sequence start end)
(do* ((index start)
(result (funcall-function (if initial-value-p
initial-value
(key (sequence-ref (prog1 index (incf index)))))
(key (sequence-ref (prog1 index (incf index)))))
(funcall-function result (sequence-ref (prog1 index (incf index))))))
((= index end) result)
(declare (index index)))))))))))))))
(defun subseq (sequence start &optional end)
(do-sequence-dispatch sequence
(vector
(unless end
(setf end (length sequence)))
(with-subvector-accessor (old-ref sequence start end)
(let ((new-vector (make-array (- end start) :element-type (array-element-type sequence))))
(replace new-vector sequence :start2 start :end2 end)
#+ignore (with-subvector-accessor (new-ref new-vector)
(do ((i start (1+ i))
(j 0 (1+ j)))
((>= i end) new-vector)
(setf (new-ref j) (old-ref i))))
)))
(list
(let ((list-start (nthcdr start sequence)))
(cond
((not end)
(copy-list list-start))
((> start end)
(error "Start ~A is greater than end ~A." start end))
((endp list-start) nil)
((= start end) nil)
(t (do* ((p (cdr list-start) (cdr p))
(i (1+ start) (1+ i))
(head (cons (car list-start) nil))
(tail head))
((or (endp p) (>= i end)) head)
(declare (index i))
(setf (cdr tail) (cons (car p) nil)
tail (cdr tail)))))))))
(defsetf subseq (sequence start &optional (end nil end-p)) (new-sequence)
`(progn (replace ,sequence ,new-sequence :start1 ,start
,@(when end-p `(:end1 ,end)))
,new-sequence))
(defun copy-seq (sequence)
(subseq sequence 0))
(defun position (item sequence &key from-end test test-not (start 0) end (key 'identity))
(numargs-case
(2 (item sequence)
(do-sequence-dispatch sequence
(vector
(with-subvector-accessor (sequence-ref sequence)
(do ((end (length sequence))
(i 0 (1+ i)))
((>= i end))
(declare (index i end))
(when (eql (sequence-ref i) item)
(return i)))))
(list
(do ((i 0 (1+ i)))
((null sequence) nil)
(declare (index i))
(when (eql (pop sequence) item)
(return i))))))
(t (item sequence &key from-end test test-not (start 0) end (key 'identity))
(with-funcallable (key)
(with-tester (test test-not)
(do-sequence-dispatch sequence
(vector
(unless end
(setf end (length sequence)))
(with-subvector-accessor (sequence-ref sequence start end)
(cond
((not from-end)
(do ((i start (1+ i)))
((>= i end))
(declare (index i))
(when (test (key (sequence-ref i)) item)
(return i))))
(t (do ((i (1- end) (1- i)))
((< i start))
(declare (index i))
(when (test (key (sequence-ref i)) item)
(return i)))))))
(list
(cond
((not end)
(do ((p (nthcdr start sequence))
(i start (1+ i)))
((null p) nil)
(declare (index i))
(when (test (key (pop p)) item)
(return (if (not from-end)
i
(let ((next-i (position item p :key key :from-end t
:test test :test-not test-not)))
(if next-i (+ i 1 next-i ) i)))))))
(t (do ((p (nthcdr start sequence))
(i start (1+ i)))
((or (null p) (>= i end)) nil)
(declare (index i))
(when (test (key (pop p)) item)
(return (if (not from-end) i
(let ((next-i (position item p :end (- end 1 i) :from-end t
:key key :test test :test-not test-not)))
(if next-i (+ i 1 next-i ) i)))))))))))))))
(defun position-if (predicate sequence &key (start 0) end (key 'identity) from-end)
(numargs-case
(2 (predicate sequence)
(with-funcallable (predicate)
(do-sequence-dispatch sequence
(vector
(with-subvector-accessor (sequence-ref sequence)
(do ((end (length sequence))
(i 0 (1+ i)))
((>= i end))
(declare (index i end))
(when (predicate (sequence-ref i))
(return i)))))
(list
(do ((p sequence)
(i 0 (1+ i)))
((null p))
(declare (index i))
(when (predicate (pop p))
(return i)))))))
(t (predicate sequence &key (start 0) end (key 'identity) from-end)
(with-funcallable (predicate)
(with-funcallable (key)
(do-sequence-dispatch sequence
(vector
(setf end (or end (length sequence)))
(with-subvector-accessor (sequence-ref sequence start end)
(cond
((not from-end)
(do ((i start (1+ i)))
((>= i end))
(declare (index i))
(when (predicate (key (sequence-ref i)))
(return i))))
(t (do ((i (1- end) (1- i)))
((< i start))
(declare (index i))
(when (predicate (key (sequence-ref i)))
(return i)))))))
(list
(cond
(end
(do ((p (nthcdr start sequence))
(i start (1+ i)))
((or (>= i end) (null p)))
(declare (index i))
(when (predicate (key (pop p)))
(return (if (not from-end) i
(let ((next-i (position-if predicate p :key key
:from-end t :end (- end i 1))))
(if next-i (+ i 1 next-i) i)))))))
(t (do ((p (nthcdr start sequence))
(i start (1+ i)))
((null p))
(declare (index i))
(when (predicate (key (pop p)))
(return (if (not from-end) i
(let ((next-i (position-if predicate p :key key :from-end t)))
(if next-i (+ i 1 next-i) i)))))))))))))))
(defun position-if-not (predicate sequence &rest key-args)
(declare (dynamic-extent key-args))
(apply #'position-if (complement predicate) sequence key-args))
(defun nreverse (sequence)
(do-sequence-dispatch sequence
(list
(do ((prev-cons nil current-cons)
(next-cons (cdr sequence) (cdr next-cons))
(current-cons sequence next-cons))
((null current-cons) prev-cons)
(setf (cdr current-cons) prev-cons)))
(vector
(with-subvector-accessor (sequence-ref sequence)
(do ((i 0 (1+ i))
(j (1- (length sequence)) (1- j)))
((<= j i))
(declare (index i j))
(let ((x (sequence-ref i)))
(setf (sequence-ref i) (sequence-ref j)
(sequence-ref j) x))))
sequence)))
(defun reverse (sequence)
(do-sequence-dispatch sequence
(list
(let ((result nil))
(dolist (x sequence)
(push x result))
result))
(vector
(nreverse (copy-seq sequence)))))
(defun mismatch-eql-identity (sequence-1 sequence-2 start1 start2 end1 end2)
(do-sequence-dispatch sequence-1
(vector
(unless end1 (setf end1 (length sequence-1)))
(with-subvector-accessor (seq1-ref sequence-1 start1 end1)
(do-sequence-dispatch sequence-2
(vector
(unless end2 (setf end2 (length sequence-2)))
(with-subvector-accessor (seq2-ref sequence-2 start2 end2)
(macrolet ((test-return (index1 index2)
`(unless (eql (seq1-ref ,index1) (seq2-ref ,index2))
(return ,index1))))
(let ((length1 (- end1 start1))
(length2 (- end2 start2)))
(cond
((= length1 length2)
(do* ((i start1 (1+ i))
(j start2 (1+ j)))
((>= i end1) nil)
(declare (index i j))
(test-return i j)))
((< length1 length2)
(do* ((i start1 (1+ i))
(j start2 (1+ j)))
((>= i end1) end1)
(declare (index i j))
(test-return i j)))
((> length1 length2)
(do* ((i start1 (1+ i))
(j start2 (1+ j)))
((>= j end2) i)
(declare (index i j))
(test-return i j))))))))
(list
(let ((length1 (- end1 start1))
(start-cons2 (nthcdr start2 sequence-2)))
(cond
((and (zerop length1) (null start-cons2))
(if (and end2 (> end2 start2)) start1 nil))
((not end2)
(do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((>= i1 end1) (if (null p2) nil i1))
(declare (index i1))
(unless (and p2 (eql (seq1-ref i1) (car p2)))
(return i1))))
((< length1 (- end2 start2))
(do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((>= i1 end1) end1)
(declare (index i1))
(unless (eql (seq1-ref i1) (car p2))
(return i1))))
((> length1 (- end2 start2))
(do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((null p2) end1)
(declare (index i1))
(unless (eql (seq1-ref i1) (car p2))
(return i1))))
(t (do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((null p2) nil)
(declare (index i1))
(unless (eql (seq1-ref i1) (car p2))
(return i1))))))))))
(list
(do-sequence-dispatch sequence-2
(vector
(let ((mismatch-2 (mismatch-eql-identity sequence-2 sequence-1 start2 start1 end2 end1)))
(if (not mismatch-2)
nil
(+ start1 (- mismatch-2 start2)))))
(list
(let ((start-cons1 (nthcdr start1 sequence-1))
(start-cons2 (nthcdr start2 sequence-2)))
(assert (and start-cons1 start-cons2) (start1 start2) "Illegal bounding indexes.")
(cond
((and (not end1) (not end2))
(do ((p1 start-cons1 (cdr p1))
(p2 start-cons2 (cdr p2))
(i1 start1 (1+ i1)))
((null p1) (if (null p2) nil i1))
(declare (index i1))
(unless (and p2 (eql (car p1) (car p2)))
(return i1))))
(t (do ((p1 start-cons1 (cdr p1))
(p2 start-cons2 (cdr p2))
(i1 start1 (1+ i1))
(i2 start2 (1+ i2)))
((if end1 (>= i1 end1) (null p1))
(if (if end2 (>= i2 end2) (null p2)) nil i1))
(declare (index i1 i2))
(unless (and (or (not end2) (< i1 end2))
(eql (car p1) (car p2)))
(return i1)))))))))))
(define-compiler-macro mismatch (&whole form sequence-1 sequence-2
&key (start1 0) (start2 0) end1 end2
(test 'eql test-p) (key 'identity key-p) from-end)
(declare (ignore key test))
(cond
((and (not test-p) (not key-p))
(assert (not from-end) ()
"Mismatch :from-end not implemented.")
`(mismatch-eql-identity ,sequence-1 ,sequence-2 ,start1 ,start2 ,end1 ,end2))
(t form)))
(defun mismatch (sequence-1 sequence-2 &key (start1 0) (start2 0) end1 end2
test test-not (key 'identity) from-end)
(numargs-case
(2 (s1 s2)
(mismatch-eql-identity s1 s2 0 0 nil nil))
(t (sequence-1 sequence-2 &key (start1 0) (start2 0) end1 end2
test test-not (key 'identity) from-end)
(assert (not from-end) ()
"Mismatch :from-end not implemented.")
(with-tester (test test-not)
(with-funcallable (key)
(do-sequence-dispatch sequence-1
(vector
(unless end1 (setf end1 (length sequence-1)))
(with-subvector-accessor (sequence-1-ref sequence-1 start1 end1)
(do-sequence-dispatch sequence-2
(vector
(let ((end2 (check-the index (or end2 (length sequence-2)))))
(with-subvector-accessor (sequence-2-ref sequence-2 start2 end2)
(macrolet ((test-return (index1 index2)
`(unless (test (key (sequence-1-ref ,index1))
(key (sequence-2-ref ,index2)))
(return-from mismatch ,index1))))
(let ((length1 (- end1 start1))
(length2 (- end2 start2)))
(cond
((< length1 length2)
(dotimes (i length1)
(declare (index i))
(test-return (+ start1 i) (+ start2 i)))
end1)
((> length1 length2)
(dotimes (i length2)
(declare (index i))
(test-return (+ start1 i) (+ start2 i)))
(+ start1 length2))
(t (dotimes (i length1)
(declare (index i))
(test-return (+ start1 i) (+ start2 i)))
nil)))))))
(list
(let ((length1 (- end1 start1))
(start-cons2 (nthcdr start2 sequence-2)))
(cond
((and (zerop length1) (null start-cons2))
(if (and end2 (> end2 start2)) start1 nil))
((not end2)
(do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((>= i1 end1) (if (null p2) nil i1))
(declare (index i1))
(unless (and p2 (test (key (sequence-1-ref i1)) (key (car p2))))
(return-from mismatch i1))))
((< length1 (- end2 start2))
(do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((>= i1 end1) end1)
(declare (index i1))
(unless (test (key (sequence-1-ref i1)) (key (car p2)))
(return-from mismatch i1))))
((> length1 (- end2 start2))
(do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((null p2) end1)
(declare (index i1))
(unless (test (key (sequence-1-ref i1)) (key (car p2)))
(return-from mismatch i1))))
(t (do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((null p2) nil)
(declare (index i1))
(unless (test (key (sequence-1-ref i1)) (key (car p2)))
(return-from mismatch i1))))))))))
(list
(do-sequence-dispatch sequence-2
(vector
(let ((mismatch-2 (mismatch sequence-2 sequence-1 :from-end from-end :test test :key key
:start1 start2 :end1 end2 :start2 start1 :end2 end1)))
(if (not mismatch-2)
nil
(+ start1 (- mismatch-2 start2)))))
(list
(let ((start-cons1 (nthcdr start1 sequence-1))
(start-cons2 (nthcdr start2 sequence-2)))
(assert (and start-cons1 start-cons2) (start1 start2) "Illegal bounding indexes.")
(cond
((and (not end1) (not end2))
(do ((p1 start-cons1 (cdr p1))
(p2 start-cons2 (cdr p2))
(i1 start1 (1+ i1)))
((null p1) (if (null p2) nil i1))
(declare (index i1))
(unless (and p2 (test (key (car p1)) (key (car p2))))
(return i1))))
(t (do ((p1 start-cons1 (cdr p1))
(p2 start-cons2 (cdr p2))
(i1 start1 (1+ i1))
(i2 start2 (1+ i2)))
((if end1 (>= i1 end1) (null p1))
(if (if end2 (>= i2 end2) (null p2)) nil i1))
(declare (index i1 i2))
(unless p2
(if end2
(error "Illegal end2 bounding index.")
(return i1)))
(unless (and (or (not end2) (< i1 end2))
(test (key (car p1)) (key (car p2))))
(return i1)))))))))))))))
(defun map-into (result-sequence function first-sequence &rest more-sequences)
(declare (dynamic-extent more-sequences))
(assert (null more-sequences) ()
"MAP-INTO not implemented.")
(with-funcallable (map function)
(sequence-double-dispatch (result-sequence first-sequence)
((vector vector)
(let ((length (min (length result-sequence)
(length first-sequence))))
(with-subvector-accessor (result-ref result-sequence 0 length)
(with-subvector-accessor (first-sequence-ref first-sequence 0 length)
(dotimes (i length result-sequence)
(setf (result-ref i)
(map (first-sequence-ref i))))))))
((list list)
(do ((p result-sequence (cdr p))
(q first-sequence (cdr q)))
((or (null p) (null q))
result-sequence)
(setf (car p) (map (car q)))))
((vector list)
(with-subvector-accessor (result-ref result-sequence)
(do ((end (length result-sequence))
(i 0 (1+ i))
(p first-sequence (cdr p)))
((or (endp p) (>= i end)) result-sequence)
(declare (index i))
(setf (result-ref i) (map (car p))))))
((list vector)
(with-subvector-accessor (first-ref first-sequence)
(do ((end (length first-sequence))
(i 0 (1+ i))
(p result-sequence (cdr p)))
((or (endp p) (>= i end)) result-sequence)
(declare (index i))
(setf (car p) (map (first-ref i)))))))))
(defun map-for-nil (function first-sequence &rest more-sequences)
(numargs-case
(2 (function first-sequence)
(with-funcallable (mapf function)
(do-sequence-dispatch first-sequence
(list
(dolist (x first-sequence)
(mapf x)))
(vector
(with-subvector-accessor (sequence-ref first-sequence)
(dotimes (i (length first-sequence))
(mapf (sequence-ref i))))))))
(3 (function first-sequence second-sequence)
(with-funcallable (mapf function)
(sequence-double-dispatch (first-sequence second-sequence)
((list list)
(do ((p first-sequence (cdr p))
(q second-sequence (cdr q)))
((or (endp p) (endp q)))
(mapf (car p) (car q))))
((vector vector)
(with-subvector-accessor (first-sequence-ref first-sequence)
(with-subvector-accessor (second-sequence-ref second-sequence)
(do ((len1 (length first-sequence))
(len2 (length second-sequence))
(i 0 (1+ i))
(j 0 (1+ j)))
((or (>= i len1)
(>= j len2)))
(declare (index i j))
(mapf (first-sequence-ref i) (second-sequence-ref j))))))
)))
(t (function first-sequence &rest more-sequences)
(declare (ignore function first-sequence more-sequences))
(error "MAP not implemented."))))
(defun map-for-list (function first-sequence &rest more-sequences)
(numargs-case
(2 (function first-sequence)
(with-funcallable (mapf function)
(do-sequence-dispatch first-sequence
(list
(mapcar function first-sequence))
(vector
(with-subvector-accessor (sequence-ref first-sequence)
(let ((result nil))
(dotimes (i (length first-sequence))
(push (mapf (sequence-ref i))
result))
(nreverse result)))))))
(3 (function first-sequence second-sequence)
(sequence-double-dispatch (first-sequence second-sequence)
((list list)
(mapcar function first-sequence second-sequence))
((vector vector)
(with-funcallable (mapf function)
(with-subvector-accessor (first-sequence-ref first-sequence)
(with-subvector-accessor (second-sequence-ref second-sequence)
(do ((result nil)
(len1 (length first-sequence))
(len2 (length second-sequence))
(i 0 (1+ i))
(j 0 (1+ j)))
((or (>= i len1)
(>= j len2))
(nreverse result))
(declare (index i j))
(push (mapf (first-sequence-ref i) (second-sequence-ref j))
result))))))
((list vector)
(with-funcallable (mapf function)
(with-subvector-accessor (second-sequence-ref second-sequence)
(do ((result nil)
(len2 (length second-sequence))
(p first-sequence (cdr p))
(j 0 (1+ j)))
((or (endp p) (>= j len2))
(nreverse result))
(declare (index j))
(push (mapf (car p) (second-sequence-ref j))
result)))))
((vector list)
(with-funcallable (mapf function)
(with-subvector-accessor (first-sequence-ref first-sequence)
(do ((result nil)
(len1 (length first-sequence))
(p second-sequence (cdr p))
(j 0 (1+ j)))
((or (endp p) (>= j len1))
(nreverse result))
(declare (index j))
(push (mapf (first-sequence-ref j) (car p))
result)))))))
(t (function first-sequence &rest more-sequences)
(declare (dynamic-extent more-sequences)
(ignore function first-sequence more-sequences))
(error "MAP not implemented."))))
(defun map-for-vector (result function first-sequence &rest more-sequences)
(numargs-case
(3 (result function first-sequence)
(with-funcallable (mapf function)
(do-sequence-dispatch first-sequence
(vector
(do ((i 0 (1+ i)))
((>= i (length result)) result)
(declare (index i))
(setf (aref result i) (mapf (aref first-sequence i)))))
(list
(do ((i 0 (1+ i)))
((>= i (length result)) result)
(declare (index i))
(setf (aref result i) (mapf (pop first-sequence))))))))
(t (function first-sequence &rest more-sequences)
(declare (ignore function first-sequence more-sequences))
(error "MAP not implemented."))))
(defun map (result-type function first-sequence &rest more-sequences)
"=> result"
(declare (dynamic-extent more-sequences))
(cond
((null result-type)
(apply 'map-for-nil function first-sequence more-sequences))
((eq 'list result-type)
(apply 'map-for-list function first-sequence more-sequences))
((member result-type '(string simple-string))
(apply 'map-for-vector
(make-string (length first-sequence))
function first-sequence more-sequences))
((member result-type '(vector simple-vector))
(apply 'map-for-vector
(make-array (length first-sequence))
function first-sequence more-sequences))
(t (error "MAP not implemented."))))
(defun fill (sequence item &key (start 0) end)
"=> sequence"
(let ((start (check-the index start)))
(etypecase sequence
(list
(do ((p (nthcdr start sequence) (cdr p))
(i start (1+ i)))
((or (null p) (and end (>= i end))))
(declare (index i))
(setf (car p) item)))
((simple-array (unsigned-byte 32) 1)
(let* ((length (array-dimension sequence 0))
(end (or end length)))
(unless (<= 0 end length)
(error 'index-out-of-range :index end :range length))
(do ((i start (1+ i)))
((>= i end))
(declare (index i))
(setf (memref sequence (movitz-type-slot-offset 'movitz-basic-vector 'data)
:index i
:type :unsigned-byte32)
item))))
(vector
(let ((end (or end (length sequence))))
(with-subvector-accessor (sequence-ref sequence start end)
(do ((i start (1+ i)))
((>= i end))
(declare (index i))
(setf (sequence-ref i) item)))))))
sequence)
(defun replace (sequence-1 sequence-2 &key (start1 0) end1 (start2 0) end2)
(let ((start1 (check-the index start1))
(start2 (check-the index start2)))
(cond
((and (eq sequence-1 sequence-2)
(<= start2 start1 (or end2 start1)))
(if (= start1 start2)
sequence-1 ; no need to copy anything
;; must copy in reverse direction
(do-sequence-dispatch sequence-1
(vector
(let ((l (length sequence-1)))
(setf end1 (or end1 l)
end2 (or end2 l))
(assert (<= 0 start2 end2 l)))
(with-subvector-accessor (sequence-1-ref sequence-1 start1 end1)
(do* ((length (min (- end1 start1) (- end2 start2)))
(i (+ start1 length -1) (1- i))
(j (+ start2 length -1) (1- j)))
((< i start1) sequence-1)
(declare (index i j length))
(setf (sequence-1-ref i)
(sequence-1-ref j)))))
(list
(let* ((length (length sequence-1))
(reverse-list (nreverse sequence-1))
(size (min (- (or end1 length) start1) (- (or end2 length) start2))))
(do ((p (nthcdr (- length start1 size) reverse-list) (cdr p))
(q (nthcdr (- length start2 size) reverse-list) (cdr q))
(i 0 (1+ i)))
((>= i size) (nreverse reverse-list))
(declare (index i))
(setf (car p) (car q))))))))
;; (not (eq sequence-1 sequence-2)) ..
(t (do-sequence-dispatch sequence-1
(vector
(setf end1 (or end1 (length sequence-1)))
(do-sequence-dispatch sequence-2
(vector
(setf end2 (or end2 (length sequence-2)))
(with-subvector-accessor (sequence-1-ref sequence-1 start1 end1)
(with-subvector-accessor (sequence-2-ref sequence-2 start2 end2)
(cond
((< (- end1 start1) (- end2 start2))
(do ((i start1 (1+ i))
(j start2 (1+ j)))
((>= i end1) sequence-1)
(declare (index i j))
(setf (sequence-1-ref i) (sequence-2-ref j))))
(t (do ((i start1 (1+ i))
(j start2 (1+ j)))
((>= j end2) sequence-1)
(declare (index i j))
(setf (sequence-1-ref i) (sequence-2-ref j))))))))
(list
(with-subvector-accessor (sequence-1-ref sequence-1 start1 end1)
(if (not end2)
(do ((i start1 (1+ i))
(p (nthcdr start2 sequence-2) (cdr p)))
((or (null p) (>= i end1)) sequence-1)
(declare (index i))
(setf (sequence-1-ref i) (car p)))
(do ((i start1 (1+ i))
(j start2 (1+ j))
(p (nthcdr start2 sequence-2) (cdr p)))
((or (>= i end1) (endp p) (>= j end2)) sequence-1)
(declare (index i j))
(setf (sequence-1-ref i) (car p))))))))
(list
(do-sequence-dispatch sequence-2
(vector
(setf end2 (or end2 (length sequence-2)))
(with-subvector-accessor (sequence-2-ref sequence-2 start2 end2)
(do ((p (nthcdr start1 sequence-1) (cdr p))
(i start1 (1+ i))
(j start2 (1+ j)))
((or (endp p) (>= j end2) (and end1 (>= i end1)))
sequence-1)
(declare (index i j))
(setf (car p) (sequence-2-ref j)))))
(list
(do ((i start1 (1+ i))
(j start2 (1+ j))
(p (nthcdr start1 sequence-1) (cdr p))
(q (nthcdr start2 sequence-2) (cdr q)))
((or (endp p) (endp q)
(and end1 (>= i end1))
(and end2 (>= j end2)))
sequence-1)
(declare (index i j))
(setf (car p) (car q)))))))
sequence-1))))
(defun find (item sequence &key from-end (start 0) end (key 'identity) test test-not)
(numargs-case
(2 (item sequence)
(do-sequence-dispatch sequence
(vector
(with-subvector-accessor (sequence-ref sequence)
(dotimes (i (length sequence))
(when (eql item (sequence-ref i))
(return item)))))
(list
(dolist (x sequence)
(when (eql item x)
(return x))))))
(t (item sequence &key from-end (start 0) end (key 'identity) test test-not)
(let ((start (check-the index start)))
(with-tester (test test-not)
(with-funcallable (key)
(do-sequence-dispatch sequence
(vector
(setf end (or end (length sequence)))
(with-subvector-accessor (sequence-ref sequence start end)
(if (not from-end)
(do ((i start (1+ i)))
((>= i end) nil)
(declare (index i))
(when (test item (key (aref sequence i)))
(return (sequence-ref i))))
(do ((i (1- end) (1- i)))
((< i start) nil)
(declare (index i))
(when (test item (key (sequence-ref i)))
(return (sequence-ref i)))))))
(list
(if end
(do ((p (nthcdr start sequence) (cdr p))
(i start (1+ i)))
((or (>= i end) (endp p)) nil)
(declare (index i))
(when (test item (key (car p)))
(return (or (and from-end
(find item (cdr p)
:from-end t :test test
:key key :end (- end i 1)))
(car p)))))
(do ((p (nthcdr start sequence) (cdr p)))
((endp p) nil)
(when (test item (key (car p)))
(return (or (and from-end (find item (cdr p) :from-end t :test test :key key))
(car p))))))))))))))
(defun find-if (predicate sequence &key from-end (start 0) end (key 'identity))
(numargs-case
(2 (predicate sequence)
(with-funcallable (predicate)
(do-sequence-dispatch sequence
(vector
(let ((end (length sequence)))
(with-subvector-accessor (sequence-ref sequence 0 end)
(do ((i 0 (1+ i)))
((>= i end))
(declare (index i))
(let ((x (sequence-ref i)))
(when (predicate x) (return x)))))))
(list
(do ((p sequence (cdr p)))
((endp p) nil)
(let ((x (car p)))
(when (predicate x) (return x))))))))
(t (predicate sequence &key from-end (start 0) end (key 'identity))
(let ((start (check-the index start)))
(with-funcallable (predicate)
(with-funcallable (key)
(do-sequence-dispatch sequence
(vector
(setf end (or end (length sequence)))
(with-subvector-accessor (sequence-ref sequence start end)
(cond
((not from-end)
(do ((i start (1+ i)))
((>= i end))
(declare (index i))
(when (predicate (key (sequence-ref i)))
(return (sequence-ref i)))))
(t (do ((i (1- end) (1- i)))
((< i start))
(declare (index i))
(when (predicate (key (sequence-ref i)))
(return (sequence-ref i))))))))
(list
(cond
(end
(do ((p (nthcdr start sequence) (cdr p))
(i start (1+ i)))
((or (>= i end) (endp p)) nil)
(declare (index i))
(when (predicate (key (car p)))
(return (or (and from-end
(find-if predicate (cdr p) :end (- end i 1) :key key :from-end t))
(car p))))))
(t (do ((p (nthcdr start sequence) (cdr p)))
((endp p) nil)
(when (predicate (key (car p)))
(return (or (and from-end
(find-if predicate (cdr p) :key key :from-end t))
(car p)))))))))))))))
(defun find-if-not (predicate sequence &rest key-args)
(declare (dynamic-extent key-args))
(apply #'find-if (complement predicate) sequence key-args))
(defun count (item sequence &key (start 0) end (key 'identity) test test-not from-end)
(let ((start (check-the index start)))
(with-tester (test test-not)
(with-funcallable (key)
(do-sequence-dispatch sequence
(vector
(let ((end (check-the index (or end (length sequence)))))
(with-subvector-accessor (sequence-ref sequence start end)
(cond
((not from-end)
(do ((i start (1+ i))
(n 0))
((>= i end) n)
(declare (index i n))
(when (test item (key (sequence-ref i)))
(incf n))))
(t (do ((i (1- end) (1- i))
(n 0))
((< i start) n)
(declare (index i n))
(when (test item (key (sequence-ref i)))
(incf n))))))))
(list
(cond
((not end)
(do ((p (nthcdr start sequence) (cdr p))
(n 0))
((endp p) n)
(declare (index n))
(when (test item (key (car p)))
(incf n))))
(t (do ((p (nthcdr start sequence) (cdr p))
(i start (1+ i))
(n 0))
((or (endp p) (>= i end)) n)
(declare (index i n))
(when (test item (key (car p)))
(incf n)))))))))))
(defun count-if (predicate sequence &key (start 0) end (key 'identity) from-end)
(numargs-case
(2 (predicate sequence)
(with-funcallable (predicate)
(do-sequence-dispatch sequence
(list
(let ((count 0))
(declare (index count))
(dolist (x sequence)
(when (predicate x)
(incf count)))
count))
(vector
(with-subvector-accessor (sequence-ref sequence)
(let ((count 0))
(declare (index count))
(dotimes (i (length sequence))
(when (predicate (sequence-ref i))
(incf count)))
count))))))
(t (predicate sequence &key (start 0) end (key 'identity) from-end)
(when from-end
(error "count-if from-end not implemented."))
(let ((start (check-the index start)))
(with-funcallable (predicate)
(with-funcallable (key)
(do-sequence-dispatch sequence
(list
(if (not end)
(do ((n 0)
(p (nthcdr start sequence) (cdr p)))
((endp p) n)
(declare (index n))
(when (predicate (key (car p)))
(incf n)))
(let ((end (check-the index end)))
(do ((n 0)
(i start (1+ i))
(p (nthcdr start sequence) (cdr p)))
((or (endp p) (>= i end)) n)
(declare (index i n))
(when (predicate (key (car p)))
(incf n))))))
(vector
(error "vector count-if not implemented.")))))))))
(defun count-if-not (predicate sequence &key (start 0) end (key 'identity) from-end)
(numargs-case
(2 (predicate sequence)
(with-funcallable (predicate)
(do-sequence-dispatch sequence
(list
(let ((count 0))
(declare (index count))
(dolist (x sequence)
(when (not (predicate x))
(incf count)))
count))
(vector
(with-subvector-accessor (sequence-ref sequence)
(let ((count 0))
(declare (index count))
(dotimes (i (length sequence))
(when (not (predicate (sequence-ref i)))
(incf count)))
count))))))
(t (predicate sequence &rest keys)
(apply #'count-if
(complement predicate)
sequence
keys))))
(macrolet ((every-some-body ()
"This function body is shared between every and some."
`(with-funcallable (predicate)
(cond
((null more-sequences) ; 1 sequence case
(do-sequence-dispatch first-sequence
(list
(do ((p first-sequence (cdr p)))
((null p) (default-value))
(test-return (predicate (car p)))))
(vector
(do* ((l (length first-sequence))
(i 0 (1+ i)))
((= l i) (default-value))
(declare (index i l))
(test-return (predicate (aref first-sequence i)))))))
((null (cdr more-sequences)) ; 2 sequences case
(let ((second-sequence (first more-sequences)))
(sequence-double-dispatch (first-sequence second-sequence)
((list list)
(do ((p0 first-sequence (cdr p0))
(p1 second-sequence (cdr p1)))
((or (endp p0) (endp p1)) (default-value))
(test-return (predicate (car p0) (car p1)))))
((vector vector)
(do ((end (min (length first-sequence) (length second-sequence)))
(i 0 (1+ i)))
((>= i end) (default-value))
(declare (index i))
(test-return (predicate (aref first-sequence i)
(aref second-sequence i)))))
((list vector)
(do ((end (length second-sequence))
(i 0 (1+ i))
(p first-sequence (cdr p)))
((or (endp p) (>= i end)) (default-value))
(declare (index i))
(test-return (predicate (car p) (aref second-sequence i)))))
((vector list)
(do ((end (length first-sequence))
(i 0 (1+ i))
(p second-sequence (cdr p)))
((or (endp p) (>= i end)) (default-value))
(declare (index i))
(test-return (predicate (aref first-sequence i) (car p))))))))
(t (flet ((next (p)
(do-sequence-dispatch p
(list (cdr p))
(vector p)))
(seqend (p i)
(do-sequence-dispatch p
(list (null p))
(vector (>= i (length p)))))
(seqelt (p i)
(do-sequence-dispatch p
(list (car p))
(vector (aref p i)))))
(do* ((i 0 (1+ i)) ; 3 or more sequences, conses at 4 or more.
(p0 first-sequence (next p0))
(p1 (car more-sequences) (next p1))
(p2 (cadr more-sequences) (next p2))
(p3+ (cddr more-sequences) (map-into p3+ #'next p3+)) ;a list of pointers
(arg3+ (make-list (length p3+))))
((or (seqend p0 i)
(seqend p1 i)
(seqend p2 i)
(dolist (p p3+ nil)
(when (seqend p i)
(return t))))
(default-value))
(declare (index i))
(do ((x arg3+ (cdr x))
(y p3+ (cdr y)))
((null x))
(setf (car x) (seqelt (car y) i)))
(test-return (apply predicate (seqelt p0 i) (seqelt p1 i)
(seqelt p2 i) arg3+)))))))))
(defun some (predicate first-sequence &rest more-sequences)
(declare (dynamic-extent more-sequences))
(macrolet ((test-return (form)
`(let ((x ,form)) (when x (return x))))
(default-value () nil))
(every-some-body)))
(defun every (predicate first-sequence &rest more-sequences)
(declare (dynamic-extent more-sequences))
(macrolet ((test-return (form)
`(unless ,form (return nil)))
(default-value () t))
(every-some-body))))
(defun notany (predicate first-sequence &rest more-sequences)
(declare (dynamic-extent more-sequences))
(not (apply 'some predicate first-sequence more-sequences)))
(defun notevery (predicate first-sequence &rest more-sequences)
(declare (dynamic-extent more-sequences))
(not (apply 'every predicate first-sequence more-sequences)))
(defun list-remove (item list test test-not key end count)
"Implements remove for lists. Assumes (not from-end)."
(cond
((endp list)
nil)
((eq 0 count)
list)
(t (with-tester (test test-not)
(with-funcallable (key)
(if (test item (key (car list)))
(list-remove item (cdr list) test test-not key
(when end (1- end))
(when count (1- count)))
(do ((i 1 (1+ i))
(p0 list (cdr p0))
(p1 (cdr list) (cdr p1)))
((or (endp p1) (and end (>= i end))) list)
(declare (index i))
(when (test item (key (car p1)))
(return
;; reiterate from <list> to <p1>, consing up a copy, with
;; the copy's tail being the recursive call to list-remove.
(do* ((new-list (cons (car list) nil))
(x (cdr list) (cdr x))
(new-x new-list))
((eq x p1)
(setf (cdr new-x) (list-remove item (cdr p1) test test-not key
(when end (- end i 1))
(when count (1- count))))
new-list)
(setf new-x
(setf (cdr new-x)
(cons (car x) nil)))))))))))))
(defun list-remove-simple (item list)
"The same as list-remove, without count, end, or key, with test=eql."
(cond
((endp list)
nil)
((eql item (car list))
(list-remove-simple item (cdr list)))
(t (do ((i 1 (1+ i))
(p0 list (cdr p0))
(p1 (cdr list) (cdr p1)))
((endp p1) list)
(declare (index i))
(when (eql item (car p1))
(return
;; reiterate from <list> to <p1>, consing up a copy, with
;; the copy's tail being the recursive call to list-remove.
(do* ((new-list (cons (car list) nil))
(x (cdr list) (cdr x))
(new-x new-list))
((eq x p1)
(setf (cdr new-x) (list-remove-simple item (cdr p1)))
new-list)
(setf new-x
(setf (cdr new-x)
(cons (car x) nil))))))))))
(defun remove (item sequence &key test test-not (start 0) end count (key 'identity) from-end)
(when test-not
(setf test (complement test-not)))
(do-sequence-dispatch sequence
(list
(setf sequence (nthcdr start sequence))
(when end (decf end start))
(cond
((endp sequence)
nil)
((not from-end)
(if (and (eq test 'eql)
(not end)
(not count)
(eq key 'identity))
(list-remove-simple item sequence)
(list-remove item sequence test test-not key end count)))
(t (error "from-end not implemented."))))
(vector
(error "vector remove not implemented."))))
(defun list-remove-if (test test-not list key end count)
"Implements remove-if for lists. Assumes (not from-end)."
(cond
((endp list)
nil)
((eq 0 count)
list)
(t (with-tester (test test-not)
(with-funcallable (key)
(and (do () ((or (endp list)
(and end (<= end 0))
(not (test (key (car list))))
(and count (<= (decf count) 0)))
list)
(when end (decf end))
(setf list (cdr list)))
(do ((i 1 (1+ i))
(p0 list (cdr p0))
(p1 (cdr list) (cdr p1)))
((or (endp p1) (and end (>= i end))) list)
(declare (index i))
(when (test (key (car p1)))
(return
;; reiterate from <list> to <p1>, consing up a copy, with
;; the copy's tail being the recursive call to list-remove.
(do* ((new-list (cons (car list) nil))
(x (cdr list) (cdr x))
(new-x new-list))
((eq x p1)
(setf (cdr new-x) (list-remove-if test test-not (cdr p1) key
(when end (- end i 1))
(when count (1- count))))
new-list)
(setf new-x
(setf (cdr new-x)
(cons (car x) nil)))))))))))))
(defun remove-if (test sequence &key from-end (start 0) end count (key 'identity))
(do-sequence-dispatch sequence
(list
(setf sequence (nthcdr start sequence))
(when end (decf end start))
(cond
((endp sequence)
nil)
((not from-end)
(list-remove-if test nil sequence key end count))
(t (error "from-end not implemented."))))
(vector
(error "vector remove not implemented."))))
(defun remove-if-not (test sequence &rest args)
(declare (dynamic-extent args))
(apply 'remove-if (complement test) sequence args))
(defun list-delete (item list test test-not key start end count)
"Implements delete-if for lists. Assumes (not from-end)."
(cond
((null list)
nil)
((eq 0 count)
list)
((eq start end)
list)
(t (with-tester (test test-not)
(with-funcallable (key)
(let ((i 0) ; for end checking
(c 0)) ; for count checking
(declare (index i c))
(cond
((= 0 start)
;; delete from head..
(do ()
((not (test item (key (car list)))))
(when (or (endp (setf list (cdr list)))
(eq (incf i) end)
(eq (incf c) count))
(return-from list-delete list)))
(setq start 1))
(t (incf i (1- start))))
;; now delete "inside" list
(do* ((p (nthcdr (1- start) list))
(q (cdr p)))
((or (endp q)
(eq (incf i) end))
list)
(cond
((test item (key (car q)))
(setf q (cdr q)
(cdr p) q)
(when (eq (incf c) count)
(return list)))
(t (setf p q
q (cdr q)))))))))))
(defun list-delete-if (test list key start end count)
"Implements delete-if for lists. Assumes (not from-end)."
(cond
((null list)
nil)
((eq 0 count)
list)
((eq start end)
list)
(t (with-funcallable (test)
(with-funcallable (key)
(let ((i 0) ; for end checking
(c 0)) ; for count checking
(declare (index i c))
(cond
((= 0 start)
;; delete from head..
(do ()
((not (test (key (car list)))))
(when (or (endp (setf list (cdr list)))
(eq (incf i) end)
(eq (incf c) count))
(return-from list-delete-if list)))
(setq start 1))
(t (incf i (1- start))))
;; now delete "inside" list
(do* ((p (nthcdr (1- start) list))
(q (cdr p)))
((or (endp q)
(eq (incf i) end))
list)
(cond
((test (key (car q)))
(setf q (cdr q)
(cdr p) q)
(when (eq (incf c) count)
(return list)))
(t (setf p q
q (cdr q)))))))))))
(defun delete (item sequence &key test test-not from-end (start 0) end count (key 'identity))
(do-sequence-dispatch sequence
(list
(when from-end
(error "from-end not implemented."))
(list-delete item sequence test test-not key start end count))
(vector
(error "vector delete not implemented."))))
(defun delete-if (test sequence &key from-end (start 0) end count (key 'identity))
(do-sequence-dispatch sequence
(list
(when from-end
(error "from-end not implemented."))
(list-delete-if test sequence key start end count))
(vector
(error "vector delete-if not implemented."))))
(defun delete-if-not (test sequence &rest key-args)
(declare (dynamic-extent key-args))
(apply 'delete-if (complement test) sequence key-args))
(defun remove-duplicates (sequence &key (test 'eql) (key 'identity) (start 0) end test-not from-end)
(when test-not
(setf test (complement test-not)))
(do-sequence-dispatch sequence
(list
(let ((list (nthcdr start sequence)))
(cond
((endp list)
nil)
((and (not end) (not from-end))
(do ((r nil))
((endp list) (nreverse r))
(let ((x (pop list)))
(unless (member x list :key key :test test)
(push x r)))))
(t (error "remove-duplicates not implemented.")))))
(vector
(error "vector remove-duplicates not implemented."))))
(defun delete-duplicates (sequence &key from-end (test 'eql) (key 'identity) test-not (start 0) end)
(let ((test (if test-not
(complement test-not)
test)))
(do-sequence-dispatch sequence
(list
(cond
(from-end
(error "from-end not implemented."))
((not end)
(when (not (endp sequence))
(when (= 0 start)
;; delete from head
(do ()
((not (find (car sequence) (cdr sequence) :test test :key key)))
(setf sequence (cdr sequence))))
(do* ((p (nthcdr start sequence))
(q (cdr p) (cdr p)))
((endp q) sequence)
(if (find (car q) (cdr q) :test test :key key)
(setf (cdr p) (cdr q))
(setf p (cdr p))))))
(t (error "delete-duplicates end parameter not implemented."))))
(vector
;;; (unless end
;;; (setf end (length sequence)))
;;; (do ((i start (1+ i))
;;; (c 0))
;;; ((>= i end)
;;; (cond
;;; ((= 0 c) sequence)
(error "vector delete-duplicates not implemented.")))))
(defun search (sequence-1 sequence-2 &key (test 'eql) (key 'identity)
(start1 0) end1 (start2 0) end2 test-not from-end)
(let ((test (if test-not
(complement test-not)
test)))
(declare (dynamic-extent test))
(let ((start1 (check-the index start1))
(start2 (check-the index start2)))
(do-sequence-dispatch sequence-2
(vector
(let ((end1 (check-the index (or end1 (length sequence-1))))
(end2 (check-the index (or end2 (length sequence-2)))))
(do ((stop (- end2 (- end1 start1 1)))
(i start2 (1+ i)))
((>= i stop) nil)
(declare (index i))
(let ((mismatch-position (mismatch sequence-1 sequence-2
:start1 start1 :end1 end1
:start2 i :end2 end2
:key key :test test)))
(when (or (not mismatch-position)
(= mismatch-position end1))
(return (or (and from-end
(search sequence-1 sequence-2
:from-end t :test test :key key
:start1 start1 :end1 end1
:start2 (1+ i) :end2 end2))
i)))))))
(list
(let ((end1 (check-the index (or end1 (length sequence-1)))))
(do ((stop (and end2 (- end2 start2 (- end1 start1 1))))
(p (nthcdr start2 sequence-2) (cdr p))
(i 0 (1+ i)))
((or (endp p) (and stop (>= i stop))) nil)
(declare (index i))
(let ((mismatch-position (mismatch sequence-1 p
:start1 start1 :end1 end1
:key key :test test)))
(when (or (not mismatch-position)
(= mismatch-position end1))
(return (+ start2 i
(or (and from-end
(search sequence-1 p
:start2 1 :end2 (and end2 (- end2 i start2))
:from-end t :test test :key key
:start1 start1 :end1 end1))
0))))))))))))
(defun insertion-sort (vector predicate key start end)
"Insertion-sort is used for stable-sort, and as a finalizer for
quick-sort with cut-off greater than 1."
(let ((start (check-the index start))
(end (check-the index end)))
(with-funcallable (predicate)
(with-subvector-accessor (vector-ref vector start end)
(if (not key)
(do ((i (1+ start) (1+ i)))
((>= i end))
(declare (index i))
;; insert vector[i] into [start...i-1]
(let ((v (vector-ref i))
(j (1- i)))
(when (predicate v (vector-ref j))
(setf (vector-ref i) (vector-ref j))
(do* ((j+1 j (1- j+1))
(j (1- j) (1- j)))
((or (< j start)
(not (predicate v (vector-ref j))))
(setf (vector-ref j+1) v))
(declare (index j j+1))
(setf (vector-ref j+1) (vector-ref j))))))
(with-funcallable (key)
(do ((i (1+ start) (1+ i))) ; the same, only with a key-function..
((>= i end))
(declare (index i))
;; insert vector[i] into [start...i-1]
(do* ((v (vector-ref i))
(vk (key v))
(j (1- i) (1- j))
(j+1 i (1- j+1)))
((or (<= j+1 start)
(not (predicate vk (key (vector-ref j)))))
(setf (vector-ref j+1) v))
(declare (index j j+1))
(setf (vector-ref j+1) (vector-ref j)))))))))
vector)
(defun quick-sort (vector predicate key start end cut-off)
(let ((start (check-the index start))
(end (check-the index end)))
(macrolet ((do-while (p &body body)
`(do () ((not ,p)) ,@body)))
(when (> (- end start) cut-off)
(with-subvector-accessor (vector-ref vector start end)
(with-funcallable (predicate)
(with-funcallable (key)
(prog* ((pivot (vector-ref start)) ; should do median-of-three here..
(keyed-pivot (key pivot))
(left (1+ start))
(right (1- end))
left-item right-item)
(declare (index left right))
;; do median-of-three..
(let ((p1 (vector-ref start))
(p2 (vector-ref (+ start cut-off -1)))
(p3 (vector-ref (1- end))))
(let ((kp1 (key p1))
(kp2 (key p2))
(kp3 (key p3)))
(cond
((predicate p1 p2)
(if (predicate p2 p3)
(setf pivot p2 keyed-pivot kp2)
(if (predicate p1 p3)
(setf pivot p3 keyed-pivot kp3)
(setf pivot p1 keyed-pivot kp1))))
((predicate p2 p3)
(if (predicate p1 p3)
(setf pivot p1 keyed-pivot kp1)
(setf pivot p3 keyed-pivot kp3)))
(t (setf pivot p2 keyed-pivot kp2)))))
partitioning-loop
(do-while (not (predicate keyed-pivot (key (setf left-item (vector-ref left)))))
(incf left)
(when (>= left end)
(setf right-item (vector-ref right))
(go partitioning-complete)))
(do-while (predicate keyed-pivot (key (setf right-item (vector-ref right))))
(decf right))
(when (< left right)
(setf (vector-ref left) right-item
(vector-ref right) left-item)
(incf left)
(decf right)
(go partitioning-loop))
partitioning-complete
(setf (vector-ref start) right-item ; (aref vector right)
(vector-ref right) pivot)
(when (and (> cut-off (- right start))
(> cut-off (- end right)))
(quick-sort vector predicate key start right cut-off)
(quick-sort vector predicate key (1+ right) end cut-off)))))))))
vector)
(defun sort (sequence predicate &key (key 'identity))
(do-sequence-dispatch sequence
(list
(sort-list sequence predicate key))
(vector
(quick-sort sequence predicate key 0 (length sequence) 9)
(insertion-sort sequence predicate key 0 (length sequence)))))
(defun stable-sort (sequence predicate &key key)
(do-sequence-dispatch sequence
(list
(error "Stable-sort not implemented for lists."))
(vector
(insertion-sort sequence predicate key 0 (length sequence)))))
(defun merge (result-type sequence-1 sequence-2 predicate &key (key 'identity))
(ecase result-type
(list
(sequence-double-dispatch (sequence-1 sequence-2)
((list list)
(merge-list-list sequence-1 sequence-2 predicate key))))))
(defun merge-list-list (list1 list2 predicate key)
(cond
((null list1)
list2)
((null list2)
list1)
(t (with-funcallable (predicate)
(with-funcallable (key)
(macrolet ((xpop (var)
`(let ((x ,var)) (setf ,var (cdr x)) x)))
(do* ((result (if (predicate (key (car list1)) (key (car list2)))
(xpop list1)
(xpop list2)))
(r result))
((null (setf r
(setf (cdr r)
(cond
((null list1) (xpop list2))
((null list2) (xpop list1))
((predicate (key (car list1)) (key (car list2)))
(xpop list1))
(t (xpop list2))))))
result))))))))
;;; Most of list-sorting snipped from cmucl.
;;; MERGE-LISTS* originally written by <NAME>.
;;; modified to return a pointer to the end of the result
;;; and to not cons header each time its called.
;;; It destructively merges list-1 with list-2. In the resulting
;;; list, elements of list-2 are guaranteed to come after equal elements
;;; of list-1.
(defun merge-lists* (list-1 list-2 predicate key merge-lists-header)
(with-funcallable (predicate)
(with-funcallable (key)
(do* ((result merge-lists-header)
(P result)) ; P points to last cell of result
((or (null list-1) (null list-2)) ; done when either list used up
(if (null list-1) ; in which case, append the
(rplacd p list-2) ; other list
(rplacd p list-1))
(do ((drag p lead)
(lead (cdr p) (cdr lead)))
((null lead)
(values (prog1 (cdr result) ; return the result sans header
(rplacd result nil)) ; (free memory, be careful)
drag)))) ; and return pointer to last element
(cond ((predicate (key (car list-2)) (key (car list-1)))
(rplacd p list-2) ; append the lesser list to last cell of
(setq p (cdr p)) ; result. Note: test must bo done for
(pop list-2)) ; list-2 < list-1 so merge will be
(t (rplacd p list-1) ; stable for list-1
(setq p (cdr p))
(pop list-1)))))))
;;; SORT-LIST uses a bottom up merge sort. First a pass is made over
;;; the list grabbing one element at a time and merging it with the next one
;;; form pairs of sorted elements. Then n is doubled, and elements are taken
;;; in runs of two, merging one run with the next to form quadruples of sorted
;;; elements. This continues until n is large enough that the inner loop only
;;; runs for one iteration; that is, there are only two runs that can be merged,
;;; the first run starting at the beginning of the list, and the second being
;;; the remaining elements.
(defun sort-list (list pred key)
(let ((head (cons :header list)) ; head holds on to everything
(n 1) ; bottom-up size of lists to be merged
unsorted ; unsorted is the remaining list to be
; broken into n size lists and merged
list-1 ; list-1 is one length n list to be merged
last ; last points to the last visited cell
(merge-lists-header (list :header)))
(declare (index n))
(do () (nil)
;; start collecting runs of n at the first element
(setf unsorted (cdr head))
;; tack on the first merge of two n-runs to the head holder
(setf last head)
(let ((n-1 (1- n)))
(do () (nil)
(setf list-1 unsorted)
(let ((temp (nthcdr n-1 list-1))
list-2)
(cond (temp
;; there are enough elements for a second run
(setf list-2 (cdr temp))
(setf (cdr temp) nil)
(setf temp (nthcdr n-1 list-2))
(cond (temp
(setf unsorted (cdr temp))
(setf (cdr temp) nil))
;; the second run goes off the end of the list
(t (setf unsorted nil)))
(multiple-value-bind (merged-head merged-last)
(merge-lists* list-1 list-2 pred key
merge-lists-header)
(setf (cdr last) merged-head)
(setf last merged-last))
(if (null unsorted) (return)))
;; if there is only one run, then tack it on to the end
(t (setf (cdr last) list-1)
(return)))))
(setf n (+ n n))
;; If the inner loop only executed once, then there were only enough
;; elements for two runs given n, so all the elements have been merged
;; into one list. This may waste one outer iteration to realize.
(if (eq list-1 (cdr head))
(return list-1))))))
(defun make-sequence (result-type size &key (initial-element nil initial-element-p))
"=> sequence"
(ecase result-type
(string
(if (not initial-element-p)
(make-string size)
(make-string size :initial-element initial-element)))
(vector
(make-array size :initial-element initial-element))
(list
(make-list size :initial-element initial-element))))
(defun concatenate (result-type &rest sequences)
"=> result-sequence"
(declare (dynamic-extent sequences))
(cond
((null sequences)
(make-sequence result-type 0))
((and (null (rest sequences))
(typep (first sequences) result-type))
(copy-seq (first sequences)))
((= 0 (length (first sequences)))
(apply #'concatenate result-type (cdr sequences)))
((member result-type '(vector string))
(let* ((r (make-sequence result-type
(let ((length 0))
(dolist (s sequences length)
(incf length (length s))))))
(i 0))
(declare (index i))
(dolist (s sequences)
(replace r s :start1 i)
(incf i (length s)))
r))
(t (error "Can't concatenate ~S yet: ~:S"
result-type
(copy-list sequences))))) ; no more dynamic-extent.
(defun substitute (newitem olditem sequence
&key (test 'eql) test-not (start 0) end count (key 'identity) from-end)
"=> result-sequence"
(when test-not
(setf test (complement test-not)))
(with-funcallable (test (if test-not (complement test-not) test))
(substitute-if newitem (lambda (x) (test olditem x)) sequence
:start start :end end
:count count :key key
:from-end from-end)))
(defun nsubstitute (newitem olditem sequence
&key (test 'eql) test-not (start 0) end count (key 'identity) from-end)
"=> result-sequence"
(when test-not
(setf test (complement test-not)))
(with-funcallable (test (if test-not (complement test-not) test))
(nsubstitute-if newitem (lambda (x) (test olditem x)) sequence
:start start :end end
:count count :key key
:from-end from-end)))
(defun substitute-if (newitem predicate sequence &rest args
&key (start 0) end count (key 'identity) from-end)
"=> result-sequence"
(declare (dynamic-extent args))
(with-funcallable (predicate)
(with-funcallable (key)
(do-sequence-dispatch sequence
(vector
(apply 'nsubstitute-if newitem predicate (copy-seq sequence) args))
(list
(if from-end
(apply 'nsubstitute-if newitem predicate (copy-list sequence) args)
(if (or (null sequence)
(and end (<= end start)))
nil
(multiple-value-bind (new-list new-tail)
(if (= 0 start)
(let ((new-list (list #0=(let ((x (pop sequence)))
(if (predicate (key x))
newitem
x)))))
(values new-list new-list))
(do* ((new-list (list (pop sequence)))
(new-tail new-list (cdr new-tail))
(i 1 (1+ i)))
((or (endp sequence) (>= i start))
(values new-list new-tail))
(setf (cdr new-tail) (list (pop sequence)))))
(cond
((and (not end) (not count))
(do ()
((endp sequence) new-list)
(setf new-tail
(setf (cdr new-tail) (list #0#)))))
((and end (not count))
(do ((i (- end start 1) (1- i)))
((or (endp sequence) (<= i 0))
(setf (cdr new-tail) (copy-list sequence))
new-list)
(setf new-tail
(setf (cdr new-tail) (list #0#)))))
((and (not end) count)
(do ((c 0))
((or (endp sequence) (>= c count))
(setf (cdr new-tail) (copy-list sequence))
new-list)
(setf new-tail
(setf (cdr new-tail) #1=(list (let ((x (pop sequence)))
(if (predicate (key x))
(progn (incf c) newitem)
x)))))))
((and end count)
(do ((i (- end start 1) (1- i))
(c 0))
((or (endp sequence) (<= i 0) (>= c count))
(setf (cdr new-tail)
(copy-list sequence))
new-list)
(setf new-tail
(setf (cdr new-tail) #1#))))
((error 'program-error)))))))))))
(defun nsubstitute-if (newitem predicate sequence &key (start 0) end count (key 'identity) from-end)
"=> sequence"
(if (<= count 0)
sequence
(with-funcallable (predicate)
(with-funcallable (key)
(do-sequence-dispatch sequence
(vector
(let ((end (or end (length sequence))))
(with-subvector-accessor (ref sequence start end)
(cond
((and (not count) (not from-end))
(do ((i start (1+ i)))
((>= i end) sequence)
(declare (index i))
(when (predicate (key (ref i)))
(setf (ref i) newitem))))
((and count (not from-end))
(do ((c 0)
(i start (1+ i)))
((>= i end) sequence)
(declare (index i c))
(when (predicate (key (ref i)))
(setf (ref i) newitem)
(when (>= (incf c) count)
(return sequence)))))
((and (not count) from-end)
(do ((i (1- end) (1- i)))
((< i start) sequence)
(declare (index i))
(when (predicate (key (ref i)))
(setf (ref i) newitem))))
((and count from-end)
(do ((c 0)
(i (1- end) (1- i)))
((< i start) sequence)
(declare (index c i))
(when (predicate (key (ref i)))
(setf (ref i) newitem)
(when (>= (incf c) count)
(return sequence)))))
((error 'program-error))))))
(list
(let ((p (nthcdr start sequence)))
(cond
(from-end
(nreverse (nsubstitute-if newitem predicate (nreverse sequence)
:start (if (not end) 0 (- (length sequence) end))
:end (if (plusp start) nil (- (length sequence) start))
:count count :key key)))
#+ignore ((and from-end count)
(let* ((end (and end (- end start)))
(existing-count (count-if predicate p :key key :end end)))
(do ((i count))
((>= i existing-count)
(nsubstitute-if newitem predicate p :end end :key key)
sequence)
(declare (index i))
(when (predicate (key (car p)))
(incf i))
(setf p (cdr p)))))
((and (not end) (not count))
(do ((p p (cdr p)))
((endp p) sequence)
(when (predicate (key (car p)))
(setf (car p) newitem))))
((and end (not count))
(do ((i start (1+ i))
(p p (cdr p)))
((or (endp p) (>= i end)) sequence)
(declare (index i))
(when (predicate (key (car p)))
(setf (car p) newitem))))
((and (not end) count)
(do ((c 0)
(p p (cdr p)))
((endp p) sequence)
(declare (index c))
(when (predicate (key (car p)))
(setf (car p) newitem)
(when (>= (incf c) count)
(return sequence)))))
((and end count)
(do ((c 0)
(i start (1+ i))
(p p (cdr p)))
((or (endp p) (>= i end)) sequence)
(declare (index c i))
(when (predicate (key (car p)))
(setf (car p) newitem)
(when (>= (incf c) count)
(return sequence)))))
((error 'program-error))))))))))
(defun substitute-if-not (newitem predicate sequence &rest keyargs)
(declare (dynamic-extent keyargs))
(apply #'substitute-if newitem (complement predicate) sequence keyargs))
(defun nsubstitute-if-not (newitem predicate sequence &rest keyargs)
(declare (dynamic-extent keyargs))
(apply #'nsubstitute-if newitem (complement predicate) sequence keyargs))
| true |
;;;;------------------------------------------------------------------
;;;;
;;;; Copyright (C) 2001-2005,
;;;; Department of Computer Science, University of Tromso, Norway.
;;;;
;;;; For distribution policy, see the accompanying file COPYING.
;;;;
;;;; Filename: sequences.lisp
;;;; Description:
;;;; Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;;;; Created at: Tue Sep 11 14:19:23 2001
;;;;
;;;; $Id$
;;;;
;;;;------------------------------------------------------------------
(require :muerte/basic-macros)
(provide :muerte/sequences)
(in-package muerte)
(defun sequencep (x)
(or (typep x 'vector)
(typep x 'cons)))
(defmacro do-sequence-dispatch (sequence-var (type0 &body forms0) (type1 &body forms1))
(cond
((and (eq 'list type0) (eq 'vector type1))
`(if (typep ,sequence-var 'list)
(progn ,@forms0)
(progn (check-type ,sequence-var vector)
,@forms1)))
((and (eq 'vector type0) (eq 'list type1))
`(if (not (typep ,sequence-var 'list))
(progn (check-type ,sequence-var vector)
,@forms0)
(progn ,@forms1)))
(t (error "do-sequence-dispatch only understands list and vector types, not ~W and ~W."
type0 type1))))
(defmacro with-tester ((test test-not) &body body)
(let ((function (gensym "with-test-"))
(notter (gensym "with-test-notter-")))
`(multiple-value-bind (,function ,notter)
(progn ;; the (values function boolean)
(ensure-tester ,test ,test-not))
(macrolet ((,test (&rest args)
`(xor (funcall%unsafe ,',function ,@args)
,',notter)))
,@body))))
(defun ensure-tester (test test-not)
(cond
(test-not
(when test
(error "Both test and test-not specified."))
(values (ensure-funcallable test-not)
t))
(test
(values (ensure-funcallable test)
nil))
(t (values #'eql
nil))))
(defun sequence-double-dispatch-error (seq0 seq1)
(error "The type-set (~A, ~A) has not been implemented in this sequence-double-dispatch."
(type-of seq0)
(type-of seq1)))
(defmacro sequence-double-dispatch ((seq0 seq1) &rest clauses)
`(case (logior (if (typep ,seq0 'list) 2 0)
(if (typep ,seq1 'list) 1 0))
,@(mapcar (lambda (clause)
(destructuring-bind ((type0 type1) . forms)
clause
(list* (logior (ecase type0 (list 2) (vector 0))
(ecase type1 (list 1) (vector 0)))
forms)))
clauses)
(t (sequence-double-dispatch-error ,seq0 ,seq1))))
(defun length (sequence)
(etypecase sequence
(list
(do ((x sequence (cdr x))
(length 0 (1+ length)))
((null x) length)
(declare (index length))))
(indirect-vector
(memref sequence (movitz-type-slot-offset 'movitz-basic-vector 'data)
:index 2))
((simple-array * 1)
(macrolet
((do-it ()
`(with-inline-assembly (:returns :eax)
(:compile-form (:result-mode :ebx) sequence)
(:movl (:ebx (:offset movitz-basic-vector num-elements))
:eax)
(:testl ,(logxor #xffffffff (1- (expt 2 14))) :eax)
(:jnz 'basic-vector-length-ok)
(:movzxw (:ebx (:offset movitz-basic-vector fill-pointer))
:eax)
basic-vector-length-ok)))
(do-it)))))
(defun length%list (sequence)
(do ((length 0 (1+ length))
(x sequence (cdr x)))
((null x) length)
(declare (type index length))))
(defun elt (sequence index)
(do-sequence-dispatch sequence
(vector (aref sequence index))
(list (nth index sequence))))
(defun (setf elt) (value sequence index)
(do-sequence-dispatch sequence
(vector (setf (aref sequence index) value))
(list (setf (nth index sequence) value))))
(defun reduce (function sequence &key (key 'identity) from-end
(start 0) (end (length sequence))
(initial-value nil initial-value-p))
(numargs-case
(2 (function sequence)
(with-funcallable (funcall-function function)
(do-sequence-dispatch sequence
(list
(cond
((null sequence)
(funcall-function))
((null (cdr sequence))
(car sequence))
(t (do* ((list sequence)
(result (funcall-function (pop list) (pop list))
(funcall-function result (pop list))))
((endp list)
result)))))
(vector
(let ((end (length sequence)))
(case end
(0 (funcall-function))
(1 (aref sequence 0))
(t (with-subvector-accessor (sequence-ref sequence 0 end)
(do* ((index 0)
(result (funcall-function (sequence-ref (prog1 index (incf index)))
(sequence-ref (prog1 index (incf index))))
(funcall-function result (sequence-ref (prog1 index (incf index))))))
((= index end) result)
(declare (index index)))))))))))
(t (function sequence &key (key 'identity) from-end
(start 0) end
(initial-value nil initial-value-p))
(let ((start (check-the index start)))
(with-funcallable (funcall-function function)
(with-funcallable (key)
(do-sequence-dispatch sequence
(list
(let ((list (nthcdr start sequence)))
(cond
((null list)
(if initial-value-p
initial-value
(funcall-function)))
((null (cdr list))
(if initial-value-p
(funcall-function initial-value (key (car list)))
(key (car list))))
((not from-end)
(if (not end)
(do ((result (funcall-function (if initial-value-p
initial-value
(key (pop list)))
(key (pop list)))
(funcall-function result (key (pop list)))))
((null list) result))
(do ((counter (1+ start) (1+ counter))
(result (funcall-function (if initial-value-p
initial-value
(key (pop list)))
(key (pop list)))
(funcall-function result (key (pop list)))))
((or (null list)
(= end counter))
result)
(declare (index counter)))))
(from-end
(do* ((end (or end (+ start (length list))))
(counter (1+ start) (1+ counter))
(list (nreverse (subseq sequence start end)))
(result (funcall-function (key (pop list))
(if initial-value-p
initial-value
(key (pop list))))
(funcall-function (key (pop list)) result)))
((or (null list)
(= end counter))
result)
(declare (index counter)))))))
(vector
(when from-end
(error "REDUCE from-end on vectors is not implemented."))
(let ((end (or (check-the index end)
(length sequence))))
(case (- end start)
(0 (if initial-value-p
initial-value
(funcall-function)))
(1 (if initial-value-p
(funcall-function initial-value (key (elt sequence start)))
(key (elt sequence start))))
(t (with-subvector-accessor (sequence-ref sequence start end)
(do* ((index start)
(result (funcall-function (if initial-value-p
initial-value
(key (sequence-ref (prog1 index (incf index)))))
(key (sequence-ref (prog1 index (incf index)))))
(funcall-function result (sequence-ref (prog1 index (incf index))))))
((= index end) result)
(declare (index index)))))))))))))))
(defun subseq (sequence start &optional end)
(do-sequence-dispatch sequence
(vector
(unless end
(setf end (length sequence)))
(with-subvector-accessor (old-ref sequence start end)
(let ((new-vector (make-array (- end start) :element-type (array-element-type sequence))))
(replace new-vector sequence :start2 start :end2 end)
#+ignore (with-subvector-accessor (new-ref new-vector)
(do ((i start (1+ i))
(j 0 (1+ j)))
((>= i end) new-vector)
(setf (new-ref j) (old-ref i))))
)))
(list
(let ((list-start (nthcdr start sequence)))
(cond
((not end)
(copy-list list-start))
((> start end)
(error "Start ~A is greater than end ~A." start end))
((endp list-start) nil)
((= start end) nil)
(t (do* ((p (cdr list-start) (cdr p))
(i (1+ start) (1+ i))
(head (cons (car list-start) nil))
(tail head))
((or (endp p) (>= i end)) head)
(declare (index i))
(setf (cdr tail) (cons (car p) nil)
tail (cdr tail)))))))))
(defsetf subseq (sequence start &optional (end nil end-p)) (new-sequence)
`(progn (replace ,sequence ,new-sequence :start1 ,start
,@(when end-p `(:end1 ,end)))
,new-sequence))
(defun copy-seq (sequence)
(subseq sequence 0))
(defun position (item sequence &key from-end test test-not (start 0) end (key 'identity))
(numargs-case
(2 (item sequence)
(do-sequence-dispatch sequence
(vector
(with-subvector-accessor (sequence-ref sequence)
(do ((end (length sequence))
(i 0 (1+ i)))
((>= i end))
(declare (index i end))
(when (eql (sequence-ref i) item)
(return i)))))
(list
(do ((i 0 (1+ i)))
((null sequence) nil)
(declare (index i))
(when (eql (pop sequence) item)
(return i))))))
(t (item sequence &key from-end test test-not (start 0) end (key 'identity))
(with-funcallable (key)
(with-tester (test test-not)
(do-sequence-dispatch sequence
(vector
(unless end
(setf end (length sequence)))
(with-subvector-accessor (sequence-ref sequence start end)
(cond
((not from-end)
(do ((i start (1+ i)))
((>= i end))
(declare (index i))
(when (test (key (sequence-ref i)) item)
(return i))))
(t (do ((i (1- end) (1- i)))
((< i start))
(declare (index i))
(when (test (key (sequence-ref i)) item)
(return i)))))))
(list
(cond
((not end)
(do ((p (nthcdr start sequence))
(i start (1+ i)))
((null p) nil)
(declare (index i))
(when (test (key (pop p)) item)
(return (if (not from-end)
i
(let ((next-i (position item p :key key :from-end t
:test test :test-not test-not)))
(if next-i (+ i 1 next-i ) i)))))))
(t (do ((p (nthcdr start sequence))
(i start (1+ i)))
((or (null p) (>= i end)) nil)
(declare (index i))
(when (test (key (pop p)) item)
(return (if (not from-end) i
(let ((next-i (position item p :end (- end 1 i) :from-end t
:key key :test test :test-not test-not)))
(if next-i (+ i 1 next-i ) i)))))))))))))))
(defun position-if (predicate sequence &key (start 0) end (key 'identity) from-end)
(numargs-case
(2 (predicate sequence)
(with-funcallable (predicate)
(do-sequence-dispatch sequence
(vector
(with-subvector-accessor (sequence-ref sequence)
(do ((end (length sequence))
(i 0 (1+ i)))
((>= i end))
(declare (index i end))
(when (predicate (sequence-ref i))
(return i)))))
(list
(do ((p sequence)
(i 0 (1+ i)))
((null p))
(declare (index i))
(when (predicate (pop p))
(return i)))))))
(t (predicate sequence &key (start 0) end (key 'identity) from-end)
(with-funcallable (predicate)
(with-funcallable (key)
(do-sequence-dispatch sequence
(vector
(setf end (or end (length sequence)))
(with-subvector-accessor (sequence-ref sequence start end)
(cond
((not from-end)
(do ((i start (1+ i)))
((>= i end))
(declare (index i))
(when (predicate (key (sequence-ref i)))
(return i))))
(t (do ((i (1- end) (1- i)))
((< i start))
(declare (index i))
(when (predicate (key (sequence-ref i)))
(return i)))))))
(list
(cond
(end
(do ((p (nthcdr start sequence))
(i start (1+ i)))
((or (>= i end) (null p)))
(declare (index i))
(when (predicate (key (pop p)))
(return (if (not from-end) i
(let ((next-i (position-if predicate p :key key
:from-end t :end (- end i 1))))
(if next-i (+ i 1 next-i) i)))))))
(t (do ((p (nthcdr start sequence))
(i start (1+ i)))
((null p))
(declare (index i))
(when (predicate (key (pop p)))
(return (if (not from-end) i
(let ((next-i (position-if predicate p :key key :from-end t)))
(if next-i (+ i 1 next-i) i)))))))))))))))
(defun position-if-not (predicate sequence &rest key-args)
(declare (dynamic-extent key-args))
(apply #'position-if (complement predicate) sequence key-args))
(defun nreverse (sequence)
(do-sequence-dispatch sequence
(list
(do ((prev-cons nil current-cons)
(next-cons (cdr sequence) (cdr next-cons))
(current-cons sequence next-cons))
((null current-cons) prev-cons)
(setf (cdr current-cons) prev-cons)))
(vector
(with-subvector-accessor (sequence-ref sequence)
(do ((i 0 (1+ i))
(j (1- (length sequence)) (1- j)))
((<= j i))
(declare (index i j))
(let ((x (sequence-ref i)))
(setf (sequence-ref i) (sequence-ref j)
(sequence-ref j) x))))
sequence)))
(defun reverse (sequence)
(do-sequence-dispatch sequence
(list
(let ((result nil))
(dolist (x sequence)
(push x result))
result))
(vector
(nreverse (copy-seq sequence)))))
(defun mismatch-eql-identity (sequence-1 sequence-2 start1 start2 end1 end2)
(do-sequence-dispatch sequence-1
(vector
(unless end1 (setf end1 (length sequence-1)))
(with-subvector-accessor (seq1-ref sequence-1 start1 end1)
(do-sequence-dispatch sequence-2
(vector
(unless end2 (setf end2 (length sequence-2)))
(with-subvector-accessor (seq2-ref sequence-2 start2 end2)
(macrolet ((test-return (index1 index2)
`(unless (eql (seq1-ref ,index1) (seq2-ref ,index2))
(return ,index1))))
(let ((length1 (- end1 start1))
(length2 (- end2 start2)))
(cond
((= length1 length2)
(do* ((i start1 (1+ i))
(j start2 (1+ j)))
((>= i end1) nil)
(declare (index i j))
(test-return i j)))
((< length1 length2)
(do* ((i start1 (1+ i))
(j start2 (1+ j)))
((>= i end1) end1)
(declare (index i j))
(test-return i j)))
((> length1 length2)
(do* ((i start1 (1+ i))
(j start2 (1+ j)))
((>= j end2) i)
(declare (index i j))
(test-return i j))))))))
(list
(let ((length1 (- end1 start1))
(start-cons2 (nthcdr start2 sequence-2)))
(cond
((and (zerop length1) (null start-cons2))
(if (and end2 (> end2 start2)) start1 nil))
((not end2)
(do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((>= i1 end1) (if (null p2) nil i1))
(declare (index i1))
(unless (and p2 (eql (seq1-ref i1) (car p2)))
(return i1))))
((< length1 (- end2 start2))
(do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((>= i1 end1) end1)
(declare (index i1))
(unless (eql (seq1-ref i1) (car p2))
(return i1))))
((> length1 (- end2 start2))
(do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((null p2) end1)
(declare (index i1))
(unless (eql (seq1-ref i1) (car p2))
(return i1))))
(t (do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((null p2) nil)
(declare (index i1))
(unless (eql (seq1-ref i1) (car p2))
(return i1))))))))))
(list
(do-sequence-dispatch sequence-2
(vector
(let ((mismatch-2 (mismatch-eql-identity sequence-2 sequence-1 start2 start1 end2 end1)))
(if (not mismatch-2)
nil
(+ start1 (- mismatch-2 start2)))))
(list
(let ((start-cons1 (nthcdr start1 sequence-1))
(start-cons2 (nthcdr start2 sequence-2)))
(assert (and start-cons1 start-cons2) (start1 start2) "Illegal bounding indexes.")
(cond
((and (not end1) (not end2))
(do ((p1 start-cons1 (cdr p1))
(p2 start-cons2 (cdr p2))
(i1 start1 (1+ i1)))
((null p1) (if (null p2) nil i1))
(declare (index i1))
(unless (and p2 (eql (car p1) (car p2)))
(return i1))))
(t (do ((p1 start-cons1 (cdr p1))
(p2 start-cons2 (cdr p2))
(i1 start1 (1+ i1))
(i2 start2 (1+ i2)))
((if end1 (>= i1 end1) (null p1))
(if (if end2 (>= i2 end2) (null p2)) nil i1))
(declare (index i1 i2))
(unless (and (or (not end2) (< i1 end2))
(eql (car p1) (car p2)))
(return i1)))))))))))
(define-compiler-macro mismatch (&whole form sequence-1 sequence-2
&key (start1 0) (start2 0) end1 end2
(test 'eql test-p) (key 'identity key-p) from-end)
(declare (ignore key test))
(cond
((and (not test-p) (not key-p))
(assert (not from-end) ()
"Mismatch :from-end not implemented.")
`(mismatch-eql-identity ,sequence-1 ,sequence-2 ,start1 ,start2 ,end1 ,end2))
(t form)))
(defun mismatch (sequence-1 sequence-2 &key (start1 0) (start2 0) end1 end2
test test-not (key 'identity) from-end)
(numargs-case
(2 (s1 s2)
(mismatch-eql-identity s1 s2 0 0 nil nil))
(t (sequence-1 sequence-2 &key (start1 0) (start2 0) end1 end2
test test-not (key 'identity) from-end)
(assert (not from-end) ()
"Mismatch :from-end not implemented.")
(with-tester (test test-not)
(with-funcallable (key)
(do-sequence-dispatch sequence-1
(vector
(unless end1 (setf end1 (length sequence-1)))
(with-subvector-accessor (sequence-1-ref sequence-1 start1 end1)
(do-sequence-dispatch sequence-2
(vector
(let ((end2 (check-the index (or end2 (length sequence-2)))))
(with-subvector-accessor (sequence-2-ref sequence-2 start2 end2)
(macrolet ((test-return (index1 index2)
`(unless (test (key (sequence-1-ref ,index1))
(key (sequence-2-ref ,index2)))
(return-from mismatch ,index1))))
(let ((length1 (- end1 start1))
(length2 (- end2 start2)))
(cond
((< length1 length2)
(dotimes (i length1)
(declare (index i))
(test-return (+ start1 i) (+ start2 i)))
end1)
((> length1 length2)
(dotimes (i length2)
(declare (index i))
(test-return (+ start1 i) (+ start2 i)))
(+ start1 length2))
(t (dotimes (i length1)
(declare (index i))
(test-return (+ start1 i) (+ start2 i)))
nil)))))))
(list
(let ((length1 (- end1 start1))
(start-cons2 (nthcdr start2 sequence-2)))
(cond
((and (zerop length1) (null start-cons2))
(if (and end2 (> end2 start2)) start1 nil))
((not end2)
(do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((>= i1 end1) (if (null p2) nil i1))
(declare (index i1))
(unless (and p2 (test (key (sequence-1-ref i1)) (key (car p2))))
(return-from mismatch i1))))
((< length1 (- end2 start2))
(do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((>= i1 end1) end1)
(declare (index i1))
(unless (test (key (sequence-1-ref i1)) (key (car p2)))
(return-from mismatch i1))))
((> length1 (- end2 start2))
(do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((null p2) end1)
(declare (index i1))
(unless (test (key (sequence-1-ref i1)) (key (car p2)))
(return-from mismatch i1))))
(t (do ((i1 start1 (1+ i1))
(p2 start-cons2 (cdr p2)))
((null p2) nil)
(declare (index i1))
(unless (test (key (sequence-1-ref i1)) (key (car p2)))
(return-from mismatch i1))))))))))
(list
(do-sequence-dispatch sequence-2
(vector
(let ((mismatch-2 (mismatch sequence-2 sequence-1 :from-end from-end :test test :key key
:start1 start2 :end1 end2 :start2 start1 :end2 end1)))
(if (not mismatch-2)
nil
(+ start1 (- mismatch-2 start2)))))
(list
(let ((start-cons1 (nthcdr start1 sequence-1))
(start-cons2 (nthcdr start2 sequence-2)))
(assert (and start-cons1 start-cons2) (start1 start2) "Illegal bounding indexes.")
(cond
((and (not end1) (not end2))
(do ((p1 start-cons1 (cdr p1))
(p2 start-cons2 (cdr p2))
(i1 start1 (1+ i1)))
((null p1) (if (null p2) nil i1))
(declare (index i1))
(unless (and p2 (test (key (car p1)) (key (car p2))))
(return i1))))
(t (do ((p1 start-cons1 (cdr p1))
(p2 start-cons2 (cdr p2))
(i1 start1 (1+ i1))
(i2 start2 (1+ i2)))
((if end1 (>= i1 end1) (null p1))
(if (if end2 (>= i2 end2) (null p2)) nil i1))
(declare (index i1 i2))
(unless p2
(if end2
(error "Illegal end2 bounding index.")
(return i1)))
(unless (and (or (not end2) (< i1 end2))
(test (key (car p1)) (key (car p2))))
(return i1)))))))))))))))
(defun map-into (result-sequence function first-sequence &rest more-sequences)
(declare (dynamic-extent more-sequences))
(assert (null more-sequences) ()
"MAP-INTO not implemented.")
(with-funcallable (map function)
(sequence-double-dispatch (result-sequence first-sequence)
((vector vector)
(let ((length (min (length result-sequence)
(length first-sequence))))
(with-subvector-accessor (result-ref result-sequence 0 length)
(with-subvector-accessor (first-sequence-ref first-sequence 0 length)
(dotimes (i length result-sequence)
(setf (result-ref i)
(map (first-sequence-ref i))))))))
((list list)
(do ((p result-sequence (cdr p))
(q first-sequence (cdr q)))
((or (null p) (null q))
result-sequence)
(setf (car p) (map (car q)))))
((vector list)
(with-subvector-accessor (result-ref result-sequence)
(do ((end (length result-sequence))
(i 0 (1+ i))
(p first-sequence (cdr p)))
((or (endp p) (>= i end)) result-sequence)
(declare (index i))
(setf (result-ref i) (map (car p))))))
((list vector)
(with-subvector-accessor (first-ref first-sequence)
(do ((end (length first-sequence))
(i 0 (1+ i))
(p result-sequence (cdr p)))
((or (endp p) (>= i end)) result-sequence)
(declare (index i))
(setf (car p) (map (first-ref i)))))))))
(defun map-for-nil (function first-sequence &rest more-sequences)
(numargs-case
(2 (function first-sequence)
(with-funcallable (mapf function)
(do-sequence-dispatch first-sequence
(list
(dolist (x first-sequence)
(mapf x)))
(vector
(with-subvector-accessor (sequence-ref first-sequence)
(dotimes (i (length first-sequence))
(mapf (sequence-ref i))))))))
(3 (function first-sequence second-sequence)
(with-funcallable (mapf function)
(sequence-double-dispatch (first-sequence second-sequence)
((list list)
(do ((p first-sequence (cdr p))
(q second-sequence (cdr q)))
((or (endp p) (endp q)))
(mapf (car p) (car q))))
((vector vector)
(with-subvector-accessor (first-sequence-ref first-sequence)
(with-subvector-accessor (second-sequence-ref second-sequence)
(do ((len1 (length first-sequence))
(len2 (length second-sequence))
(i 0 (1+ i))
(j 0 (1+ j)))
((or (>= i len1)
(>= j len2)))
(declare (index i j))
(mapf (first-sequence-ref i) (second-sequence-ref j))))))
)))
(t (function first-sequence &rest more-sequences)
(declare (ignore function first-sequence more-sequences))
(error "MAP not implemented."))))
(defun map-for-list (function first-sequence &rest more-sequences)
(numargs-case
(2 (function first-sequence)
(with-funcallable (mapf function)
(do-sequence-dispatch first-sequence
(list
(mapcar function first-sequence))
(vector
(with-subvector-accessor (sequence-ref first-sequence)
(let ((result nil))
(dotimes (i (length first-sequence))
(push (mapf (sequence-ref i))
result))
(nreverse result)))))))
(3 (function first-sequence second-sequence)
(sequence-double-dispatch (first-sequence second-sequence)
((list list)
(mapcar function first-sequence second-sequence))
((vector vector)
(with-funcallable (mapf function)
(with-subvector-accessor (first-sequence-ref first-sequence)
(with-subvector-accessor (second-sequence-ref second-sequence)
(do ((result nil)
(len1 (length first-sequence))
(len2 (length second-sequence))
(i 0 (1+ i))
(j 0 (1+ j)))
((or (>= i len1)
(>= j len2))
(nreverse result))
(declare (index i j))
(push (mapf (first-sequence-ref i) (second-sequence-ref j))
result))))))
((list vector)
(with-funcallable (mapf function)
(with-subvector-accessor (second-sequence-ref second-sequence)
(do ((result nil)
(len2 (length second-sequence))
(p first-sequence (cdr p))
(j 0 (1+ j)))
((or (endp p) (>= j len2))
(nreverse result))
(declare (index j))
(push (mapf (car p) (second-sequence-ref j))
result)))))
((vector list)
(with-funcallable (mapf function)
(with-subvector-accessor (first-sequence-ref first-sequence)
(do ((result nil)
(len1 (length first-sequence))
(p second-sequence (cdr p))
(j 0 (1+ j)))
((or (endp p) (>= j len1))
(nreverse result))
(declare (index j))
(push (mapf (first-sequence-ref j) (car p))
result)))))))
(t (function first-sequence &rest more-sequences)
(declare (dynamic-extent more-sequences)
(ignore function first-sequence more-sequences))
(error "MAP not implemented."))))
(defun map-for-vector (result function first-sequence &rest more-sequences)
(numargs-case
(3 (result function first-sequence)
(with-funcallable (mapf function)
(do-sequence-dispatch first-sequence
(vector
(do ((i 0 (1+ i)))
((>= i (length result)) result)
(declare (index i))
(setf (aref result i) (mapf (aref first-sequence i)))))
(list
(do ((i 0 (1+ i)))
((>= i (length result)) result)
(declare (index i))
(setf (aref result i) (mapf (pop first-sequence))))))))
(t (function first-sequence &rest more-sequences)
(declare (ignore function first-sequence more-sequences))
(error "MAP not implemented."))))
(defun map (result-type function first-sequence &rest more-sequences)
"=> result"
(declare (dynamic-extent more-sequences))
(cond
((null result-type)
(apply 'map-for-nil function first-sequence more-sequences))
((eq 'list result-type)
(apply 'map-for-list function first-sequence more-sequences))
((member result-type '(string simple-string))
(apply 'map-for-vector
(make-string (length first-sequence))
function first-sequence more-sequences))
((member result-type '(vector simple-vector))
(apply 'map-for-vector
(make-array (length first-sequence))
function first-sequence more-sequences))
(t (error "MAP not implemented."))))
(defun fill (sequence item &key (start 0) end)
"=> sequence"
(let ((start (check-the index start)))
(etypecase sequence
(list
(do ((p (nthcdr start sequence) (cdr p))
(i start (1+ i)))
((or (null p) (and end (>= i end))))
(declare (index i))
(setf (car p) item)))
((simple-array (unsigned-byte 32) 1)
(let* ((length (array-dimension sequence 0))
(end (or end length)))
(unless (<= 0 end length)
(error 'index-out-of-range :index end :range length))
(do ((i start (1+ i)))
((>= i end))
(declare (index i))
(setf (memref sequence (movitz-type-slot-offset 'movitz-basic-vector 'data)
:index i
:type :unsigned-byte32)
item))))
(vector
(let ((end (or end (length sequence))))
(with-subvector-accessor (sequence-ref sequence start end)
(do ((i start (1+ i)))
((>= i end))
(declare (index i))
(setf (sequence-ref i) item)))))))
sequence)
(defun replace (sequence-1 sequence-2 &key (start1 0) end1 (start2 0) end2)
(let ((start1 (check-the index start1))
(start2 (check-the index start2)))
(cond
((and (eq sequence-1 sequence-2)
(<= start2 start1 (or end2 start1)))
(if (= start1 start2)
sequence-1 ; no need to copy anything
;; must copy in reverse direction
(do-sequence-dispatch sequence-1
(vector
(let ((l (length sequence-1)))
(setf end1 (or end1 l)
end2 (or end2 l))
(assert (<= 0 start2 end2 l)))
(with-subvector-accessor (sequence-1-ref sequence-1 start1 end1)
(do* ((length (min (- end1 start1) (- end2 start2)))
(i (+ start1 length -1) (1- i))
(j (+ start2 length -1) (1- j)))
((< i start1) sequence-1)
(declare (index i j length))
(setf (sequence-1-ref i)
(sequence-1-ref j)))))
(list
(let* ((length (length sequence-1))
(reverse-list (nreverse sequence-1))
(size (min (- (or end1 length) start1) (- (or end2 length) start2))))
(do ((p (nthcdr (- length start1 size) reverse-list) (cdr p))
(q (nthcdr (- length start2 size) reverse-list) (cdr q))
(i 0 (1+ i)))
((>= i size) (nreverse reverse-list))
(declare (index i))
(setf (car p) (car q))))))))
;; (not (eq sequence-1 sequence-2)) ..
(t (do-sequence-dispatch sequence-1
(vector
(setf end1 (or end1 (length sequence-1)))
(do-sequence-dispatch sequence-2
(vector
(setf end2 (or end2 (length sequence-2)))
(with-subvector-accessor (sequence-1-ref sequence-1 start1 end1)
(with-subvector-accessor (sequence-2-ref sequence-2 start2 end2)
(cond
((< (- end1 start1) (- end2 start2))
(do ((i start1 (1+ i))
(j start2 (1+ j)))
((>= i end1) sequence-1)
(declare (index i j))
(setf (sequence-1-ref i) (sequence-2-ref j))))
(t (do ((i start1 (1+ i))
(j start2 (1+ j)))
((>= j end2) sequence-1)
(declare (index i j))
(setf (sequence-1-ref i) (sequence-2-ref j))))))))
(list
(with-subvector-accessor (sequence-1-ref sequence-1 start1 end1)
(if (not end2)
(do ((i start1 (1+ i))
(p (nthcdr start2 sequence-2) (cdr p)))
((or (null p) (>= i end1)) sequence-1)
(declare (index i))
(setf (sequence-1-ref i) (car p)))
(do ((i start1 (1+ i))
(j start2 (1+ j))
(p (nthcdr start2 sequence-2) (cdr p)))
((or (>= i end1) (endp p) (>= j end2)) sequence-1)
(declare (index i j))
(setf (sequence-1-ref i) (car p))))))))
(list
(do-sequence-dispatch sequence-2
(vector
(setf end2 (or end2 (length sequence-2)))
(with-subvector-accessor (sequence-2-ref sequence-2 start2 end2)
(do ((p (nthcdr start1 sequence-1) (cdr p))
(i start1 (1+ i))
(j start2 (1+ j)))
((or (endp p) (>= j end2) (and end1 (>= i end1)))
sequence-1)
(declare (index i j))
(setf (car p) (sequence-2-ref j)))))
(list
(do ((i start1 (1+ i))
(j start2 (1+ j))
(p (nthcdr start1 sequence-1) (cdr p))
(q (nthcdr start2 sequence-2) (cdr q)))
((or (endp p) (endp q)
(and end1 (>= i end1))
(and end2 (>= j end2)))
sequence-1)
(declare (index i j))
(setf (car p) (car q)))))))
sequence-1))))
(defun find (item sequence &key from-end (start 0) end (key 'identity) test test-not)
(numargs-case
(2 (item sequence)
(do-sequence-dispatch sequence
(vector
(with-subvector-accessor (sequence-ref sequence)
(dotimes (i (length sequence))
(when (eql item (sequence-ref i))
(return item)))))
(list
(dolist (x sequence)
(when (eql item x)
(return x))))))
(t (item sequence &key from-end (start 0) end (key 'identity) test test-not)
(let ((start (check-the index start)))
(with-tester (test test-not)
(with-funcallable (key)
(do-sequence-dispatch sequence
(vector
(setf end (or end (length sequence)))
(with-subvector-accessor (sequence-ref sequence start end)
(if (not from-end)
(do ((i start (1+ i)))
((>= i end) nil)
(declare (index i))
(when (test item (key (aref sequence i)))
(return (sequence-ref i))))
(do ((i (1- end) (1- i)))
((< i start) nil)
(declare (index i))
(when (test item (key (sequence-ref i)))
(return (sequence-ref i)))))))
(list
(if end
(do ((p (nthcdr start sequence) (cdr p))
(i start (1+ i)))
((or (>= i end) (endp p)) nil)
(declare (index i))
(when (test item (key (car p)))
(return (or (and from-end
(find item (cdr p)
:from-end t :test test
:key key :end (- end i 1)))
(car p)))))
(do ((p (nthcdr start sequence) (cdr p)))
((endp p) nil)
(when (test item (key (car p)))
(return (or (and from-end (find item (cdr p) :from-end t :test test :key key))
(car p))))))))))))))
(defun find-if (predicate sequence &key from-end (start 0) end (key 'identity))
(numargs-case
(2 (predicate sequence)
(with-funcallable (predicate)
(do-sequence-dispatch sequence
(vector
(let ((end (length sequence)))
(with-subvector-accessor (sequence-ref sequence 0 end)
(do ((i 0 (1+ i)))
((>= i end))
(declare (index i))
(let ((x (sequence-ref i)))
(when (predicate x) (return x)))))))
(list
(do ((p sequence (cdr p)))
((endp p) nil)
(let ((x (car p)))
(when (predicate x) (return x))))))))
(t (predicate sequence &key from-end (start 0) end (key 'identity))
(let ((start (check-the index start)))
(with-funcallable (predicate)
(with-funcallable (key)
(do-sequence-dispatch sequence
(vector
(setf end (or end (length sequence)))
(with-subvector-accessor (sequence-ref sequence start end)
(cond
((not from-end)
(do ((i start (1+ i)))
((>= i end))
(declare (index i))
(when (predicate (key (sequence-ref i)))
(return (sequence-ref i)))))
(t (do ((i (1- end) (1- i)))
((< i start))
(declare (index i))
(when (predicate (key (sequence-ref i)))
(return (sequence-ref i))))))))
(list
(cond
(end
(do ((p (nthcdr start sequence) (cdr p))
(i start (1+ i)))
((or (>= i end) (endp p)) nil)
(declare (index i))
(when (predicate (key (car p)))
(return (or (and from-end
(find-if predicate (cdr p) :end (- end i 1) :key key :from-end t))
(car p))))))
(t (do ((p (nthcdr start sequence) (cdr p)))
((endp p) nil)
(when (predicate (key (car p)))
(return (or (and from-end
(find-if predicate (cdr p) :key key :from-end t))
(car p)))))))))))))))
(defun find-if-not (predicate sequence &rest key-args)
(declare (dynamic-extent key-args))
(apply #'find-if (complement predicate) sequence key-args))
(defun count (item sequence &key (start 0) end (key 'identity) test test-not from-end)
(let ((start (check-the index start)))
(with-tester (test test-not)
(with-funcallable (key)
(do-sequence-dispatch sequence
(vector
(let ((end (check-the index (or end (length sequence)))))
(with-subvector-accessor (sequence-ref sequence start end)
(cond
((not from-end)
(do ((i start (1+ i))
(n 0))
((>= i end) n)
(declare (index i n))
(when (test item (key (sequence-ref i)))
(incf n))))
(t (do ((i (1- end) (1- i))
(n 0))
((< i start) n)
(declare (index i n))
(when (test item (key (sequence-ref i)))
(incf n))))))))
(list
(cond
((not end)
(do ((p (nthcdr start sequence) (cdr p))
(n 0))
((endp p) n)
(declare (index n))
(when (test item (key (car p)))
(incf n))))
(t (do ((p (nthcdr start sequence) (cdr p))
(i start (1+ i))
(n 0))
((or (endp p) (>= i end)) n)
(declare (index i n))
(when (test item (key (car p)))
(incf n)))))))))))
(defun count-if (predicate sequence &key (start 0) end (key 'identity) from-end)
(numargs-case
(2 (predicate sequence)
(with-funcallable (predicate)
(do-sequence-dispatch sequence
(list
(let ((count 0))
(declare (index count))
(dolist (x sequence)
(when (predicate x)
(incf count)))
count))
(vector
(with-subvector-accessor (sequence-ref sequence)
(let ((count 0))
(declare (index count))
(dotimes (i (length sequence))
(when (predicate (sequence-ref i))
(incf count)))
count))))))
(t (predicate sequence &key (start 0) end (key 'identity) from-end)
(when from-end
(error "count-if from-end not implemented."))
(let ((start (check-the index start)))
(with-funcallable (predicate)
(with-funcallable (key)
(do-sequence-dispatch sequence
(list
(if (not end)
(do ((n 0)
(p (nthcdr start sequence) (cdr p)))
((endp p) n)
(declare (index n))
(when (predicate (key (car p)))
(incf n)))
(let ((end (check-the index end)))
(do ((n 0)
(i start (1+ i))
(p (nthcdr start sequence) (cdr p)))
((or (endp p) (>= i end)) n)
(declare (index i n))
(when (predicate (key (car p)))
(incf n))))))
(vector
(error "vector count-if not implemented.")))))))))
(defun count-if-not (predicate sequence &key (start 0) end (key 'identity) from-end)
(numargs-case
(2 (predicate sequence)
(with-funcallable (predicate)
(do-sequence-dispatch sequence
(list
(let ((count 0))
(declare (index count))
(dolist (x sequence)
(when (not (predicate x))
(incf count)))
count))
(vector
(with-subvector-accessor (sequence-ref sequence)
(let ((count 0))
(declare (index count))
(dotimes (i (length sequence))
(when (not (predicate (sequence-ref i)))
(incf count)))
count))))))
(t (predicate sequence &rest keys)
(apply #'count-if
(complement predicate)
sequence
keys))))
(macrolet ((every-some-body ()
"This function body is shared between every and some."
`(with-funcallable (predicate)
(cond
((null more-sequences) ; 1 sequence case
(do-sequence-dispatch first-sequence
(list
(do ((p first-sequence (cdr p)))
((null p) (default-value))
(test-return (predicate (car p)))))
(vector
(do* ((l (length first-sequence))
(i 0 (1+ i)))
((= l i) (default-value))
(declare (index i l))
(test-return (predicate (aref first-sequence i)))))))
((null (cdr more-sequences)) ; 2 sequences case
(let ((second-sequence (first more-sequences)))
(sequence-double-dispatch (first-sequence second-sequence)
((list list)
(do ((p0 first-sequence (cdr p0))
(p1 second-sequence (cdr p1)))
((or (endp p0) (endp p1)) (default-value))
(test-return (predicate (car p0) (car p1)))))
((vector vector)
(do ((end (min (length first-sequence) (length second-sequence)))
(i 0 (1+ i)))
((>= i end) (default-value))
(declare (index i))
(test-return (predicate (aref first-sequence i)
(aref second-sequence i)))))
((list vector)
(do ((end (length second-sequence))
(i 0 (1+ i))
(p first-sequence (cdr p)))
((or (endp p) (>= i end)) (default-value))
(declare (index i))
(test-return (predicate (car p) (aref second-sequence i)))))
((vector list)
(do ((end (length first-sequence))
(i 0 (1+ i))
(p second-sequence (cdr p)))
((or (endp p) (>= i end)) (default-value))
(declare (index i))
(test-return (predicate (aref first-sequence i) (car p))))))))
(t (flet ((next (p)
(do-sequence-dispatch p
(list (cdr p))
(vector p)))
(seqend (p i)
(do-sequence-dispatch p
(list (null p))
(vector (>= i (length p)))))
(seqelt (p i)
(do-sequence-dispatch p
(list (car p))
(vector (aref p i)))))
(do* ((i 0 (1+ i)) ; 3 or more sequences, conses at 4 or more.
(p0 first-sequence (next p0))
(p1 (car more-sequences) (next p1))
(p2 (cadr more-sequences) (next p2))
(p3+ (cddr more-sequences) (map-into p3+ #'next p3+)) ;a list of pointers
(arg3+ (make-list (length p3+))))
((or (seqend p0 i)
(seqend p1 i)
(seqend p2 i)
(dolist (p p3+ nil)
(when (seqend p i)
(return t))))
(default-value))
(declare (index i))
(do ((x arg3+ (cdr x))
(y p3+ (cdr y)))
((null x))
(setf (car x) (seqelt (car y) i)))
(test-return (apply predicate (seqelt p0 i) (seqelt p1 i)
(seqelt p2 i) arg3+)))))))))
(defun some (predicate first-sequence &rest more-sequences)
(declare (dynamic-extent more-sequences))
(macrolet ((test-return (form)
`(let ((x ,form)) (when x (return x))))
(default-value () nil))
(every-some-body)))
(defun every (predicate first-sequence &rest more-sequences)
(declare (dynamic-extent more-sequences))
(macrolet ((test-return (form)
`(unless ,form (return nil)))
(default-value () t))
(every-some-body))))
(defun notany (predicate first-sequence &rest more-sequences)
(declare (dynamic-extent more-sequences))
(not (apply 'some predicate first-sequence more-sequences)))
(defun notevery (predicate first-sequence &rest more-sequences)
(declare (dynamic-extent more-sequences))
(not (apply 'every predicate first-sequence more-sequences)))
(defun list-remove (item list test test-not key end count)
"Implements remove for lists. Assumes (not from-end)."
(cond
((endp list)
nil)
((eq 0 count)
list)
(t (with-tester (test test-not)
(with-funcallable (key)
(if (test item (key (car list)))
(list-remove item (cdr list) test test-not key
(when end (1- end))
(when count (1- count)))
(do ((i 1 (1+ i))
(p0 list (cdr p0))
(p1 (cdr list) (cdr p1)))
((or (endp p1) (and end (>= i end))) list)
(declare (index i))
(when (test item (key (car p1)))
(return
;; reiterate from <list> to <p1>, consing up a copy, with
;; the copy's tail being the recursive call to list-remove.
(do* ((new-list (cons (car list) nil))
(x (cdr list) (cdr x))
(new-x new-list))
((eq x p1)
(setf (cdr new-x) (list-remove item (cdr p1) test test-not key
(when end (- end i 1))
(when count (1- count))))
new-list)
(setf new-x
(setf (cdr new-x)
(cons (car x) nil)))))))))))))
(defun list-remove-simple (item list)
"The same as list-remove, without count, end, or key, with test=eql."
(cond
((endp list)
nil)
((eql item (car list))
(list-remove-simple item (cdr list)))
(t (do ((i 1 (1+ i))
(p0 list (cdr p0))
(p1 (cdr list) (cdr p1)))
((endp p1) list)
(declare (index i))
(when (eql item (car p1))
(return
;; reiterate from <list> to <p1>, consing up a copy, with
;; the copy's tail being the recursive call to list-remove.
(do* ((new-list (cons (car list) nil))
(x (cdr list) (cdr x))
(new-x new-list))
((eq x p1)
(setf (cdr new-x) (list-remove-simple item (cdr p1)))
new-list)
(setf new-x
(setf (cdr new-x)
(cons (car x) nil))))))))))
(defun remove (item sequence &key test test-not (start 0) end count (key 'identity) from-end)
(when test-not
(setf test (complement test-not)))
(do-sequence-dispatch sequence
(list
(setf sequence (nthcdr start sequence))
(when end (decf end start))
(cond
((endp sequence)
nil)
((not from-end)
(if (and (eq test 'eql)
(not end)
(not count)
(eq key 'identity))
(list-remove-simple item sequence)
(list-remove item sequence test test-not key end count)))
(t (error "from-end not implemented."))))
(vector
(error "vector remove not implemented."))))
(defun list-remove-if (test test-not list key end count)
"Implements remove-if for lists. Assumes (not from-end)."
(cond
((endp list)
nil)
((eq 0 count)
list)
(t (with-tester (test test-not)
(with-funcallable (key)
(and (do () ((or (endp list)
(and end (<= end 0))
(not (test (key (car list))))
(and count (<= (decf count) 0)))
list)
(when end (decf end))
(setf list (cdr list)))
(do ((i 1 (1+ i))
(p0 list (cdr p0))
(p1 (cdr list) (cdr p1)))
((or (endp p1) (and end (>= i end))) list)
(declare (index i))
(when (test (key (car p1)))
(return
;; reiterate from <list> to <p1>, consing up a copy, with
;; the copy's tail being the recursive call to list-remove.
(do* ((new-list (cons (car list) nil))
(x (cdr list) (cdr x))
(new-x new-list))
((eq x p1)
(setf (cdr new-x) (list-remove-if test test-not (cdr p1) key
(when end (- end i 1))
(when count (1- count))))
new-list)
(setf new-x
(setf (cdr new-x)
(cons (car x) nil)))))))))))))
(defun remove-if (test sequence &key from-end (start 0) end count (key 'identity))
(do-sequence-dispatch sequence
(list
(setf sequence (nthcdr start sequence))
(when end (decf end start))
(cond
((endp sequence)
nil)
((not from-end)
(list-remove-if test nil sequence key end count))
(t (error "from-end not implemented."))))
(vector
(error "vector remove not implemented."))))
(defun remove-if-not (test sequence &rest args)
(declare (dynamic-extent args))
(apply 'remove-if (complement test) sequence args))
(defun list-delete (item list test test-not key start end count)
"Implements delete-if for lists. Assumes (not from-end)."
(cond
((null list)
nil)
((eq 0 count)
list)
((eq start end)
list)
(t (with-tester (test test-not)
(with-funcallable (key)
(let ((i 0) ; for end checking
(c 0)) ; for count checking
(declare (index i c))
(cond
((= 0 start)
;; delete from head..
(do ()
((not (test item (key (car list)))))
(when (or (endp (setf list (cdr list)))
(eq (incf i) end)
(eq (incf c) count))
(return-from list-delete list)))
(setq start 1))
(t (incf i (1- start))))
;; now delete "inside" list
(do* ((p (nthcdr (1- start) list))
(q (cdr p)))
((or (endp q)
(eq (incf i) end))
list)
(cond
((test item (key (car q)))
(setf q (cdr q)
(cdr p) q)
(when (eq (incf c) count)
(return list)))
(t (setf p q
q (cdr q)))))))))))
(defun list-delete-if (test list key start end count)
"Implements delete-if for lists. Assumes (not from-end)."
(cond
((null list)
nil)
((eq 0 count)
list)
((eq start end)
list)
(t (with-funcallable (test)
(with-funcallable (key)
(let ((i 0) ; for end checking
(c 0)) ; for count checking
(declare (index i c))
(cond
((= 0 start)
;; delete from head..
(do ()
((not (test (key (car list)))))
(when (or (endp (setf list (cdr list)))
(eq (incf i) end)
(eq (incf c) count))
(return-from list-delete-if list)))
(setq start 1))
(t (incf i (1- start))))
;; now delete "inside" list
(do* ((p (nthcdr (1- start) list))
(q (cdr p)))
((or (endp q)
(eq (incf i) end))
list)
(cond
((test (key (car q)))
(setf q (cdr q)
(cdr p) q)
(when (eq (incf c) count)
(return list)))
(t (setf p q
q (cdr q)))))))))))
(defun delete (item sequence &key test test-not from-end (start 0) end count (key 'identity))
(do-sequence-dispatch sequence
(list
(when from-end
(error "from-end not implemented."))
(list-delete item sequence test test-not key start end count))
(vector
(error "vector delete not implemented."))))
(defun delete-if (test sequence &key from-end (start 0) end count (key 'identity))
(do-sequence-dispatch sequence
(list
(when from-end
(error "from-end not implemented."))
(list-delete-if test sequence key start end count))
(vector
(error "vector delete-if not implemented."))))
(defun delete-if-not (test sequence &rest key-args)
(declare (dynamic-extent key-args))
(apply 'delete-if (complement test) sequence key-args))
(defun remove-duplicates (sequence &key (test 'eql) (key 'identity) (start 0) end test-not from-end)
(when test-not
(setf test (complement test-not)))
(do-sequence-dispatch sequence
(list
(let ((list (nthcdr start sequence)))
(cond
((endp list)
nil)
((and (not end) (not from-end))
(do ((r nil))
((endp list) (nreverse r))
(let ((x (pop list)))
(unless (member x list :key key :test test)
(push x r)))))
(t (error "remove-duplicates not implemented.")))))
(vector
(error "vector remove-duplicates not implemented."))))
(defun delete-duplicates (sequence &key from-end (test 'eql) (key 'identity) test-not (start 0) end)
(let ((test (if test-not
(complement test-not)
test)))
(do-sequence-dispatch sequence
(list
(cond
(from-end
(error "from-end not implemented."))
((not end)
(when (not (endp sequence))
(when (= 0 start)
;; delete from head
(do ()
((not (find (car sequence) (cdr sequence) :test test :key key)))
(setf sequence (cdr sequence))))
(do* ((p (nthcdr start sequence))
(q (cdr p) (cdr p)))
((endp q) sequence)
(if (find (car q) (cdr q) :test test :key key)
(setf (cdr p) (cdr q))
(setf p (cdr p))))))
(t (error "delete-duplicates end parameter not implemented."))))
(vector
;;; (unless end
;;; (setf end (length sequence)))
;;; (do ((i start (1+ i))
;;; (c 0))
;;; ((>= i end)
;;; (cond
;;; ((= 0 c) sequence)
(error "vector delete-duplicates not implemented.")))))
(defun search (sequence-1 sequence-2 &key (test 'eql) (key 'identity)
(start1 0) end1 (start2 0) end2 test-not from-end)
(let ((test (if test-not
(complement test-not)
test)))
(declare (dynamic-extent test))
(let ((start1 (check-the index start1))
(start2 (check-the index start2)))
(do-sequence-dispatch sequence-2
(vector
(let ((end1 (check-the index (or end1 (length sequence-1))))
(end2 (check-the index (or end2 (length sequence-2)))))
(do ((stop (- end2 (- end1 start1 1)))
(i start2 (1+ i)))
((>= i stop) nil)
(declare (index i))
(let ((mismatch-position (mismatch sequence-1 sequence-2
:start1 start1 :end1 end1
:start2 i :end2 end2
:key key :test test)))
(when (or (not mismatch-position)
(= mismatch-position end1))
(return (or (and from-end
(search sequence-1 sequence-2
:from-end t :test test :key key
:start1 start1 :end1 end1
:start2 (1+ i) :end2 end2))
i)))))))
(list
(let ((end1 (check-the index (or end1 (length sequence-1)))))
(do ((stop (and end2 (- end2 start2 (- end1 start1 1))))
(p (nthcdr start2 sequence-2) (cdr p))
(i 0 (1+ i)))
((or (endp p) (and stop (>= i stop))) nil)
(declare (index i))
(let ((mismatch-position (mismatch sequence-1 p
:start1 start1 :end1 end1
:key key :test test)))
(when (or (not mismatch-position)
(= mismatch-position end1))
(return (+ start2 i
(or (and from-end
(search sequence-1 p
:start2 1 :end2 (and end2 (- end2 i start2))
:from-end t :test test :key key
:start1 start1 :end1 end1))
0))))))))))))
(defun insertion-sort (vector predicate key start end)
"Insertion-sort is used for stable-sort, and as a finalizer for
quick-sort with cut-off greater than 1."
(let ((start (check-the index start))
(end (check-the index end)))
(with-funcallable (predicate)
(with-subvector-accessor (vector-ref vector start end)
(if (not key)
(do ((i (1+ start) (1+ i)))
((>= i end))
(declare (index i))
;; insert vector[i] into [start...i-1]
(let ((v (vector-ref i))
(j (1- i)))
(when (predicate v (vector-ref j))
(setf (vector-ref i) (vector-ref j))
(do* ((j+1 j (1- j+1))
(j (1- j) (1- j)))
((or (< j start)
(not (predicate v (vector-ref j))))
(setf (vector-ref j+1) v))
(declare (index j j+1))
(setf (vector-ref j+1) (vector-ref j))))))
(with-funcallable (key)
(do ((i (1+ start) (1+ i))) ; the same, only with a key-function..
((>= i end))
(declare (index i))
;; insert vector[i] into [start...i-1]
(do* ((v (vector-ref i))
(vk (key v))
(j (1- i) (1- j))
(j+1 i (1- j+1)))
((or (<= j+1 start)
(not (predicate vk (key (vector-ref j)))))
(setf (vector-ref j+1) v))
(declare (index j j+1))
(setf (vector-ref j+1) (vector-ref j)))))))))
vector)
(defun quick-sort (vector predicate key start end cut-off)
(let ((start (check-the index start))
(end (check-the index end)))
(macrolet ((do-while (p &body body)
`(do () ((not ,p)) ,@body)))
(when (> (- end start) cut-off)
(with-subvector-accessor (vector-ref vector start end)
(with-funcallable (predicate)
(with-funcallable (key)
(prog* ((pivot (vector-ref start)) ; should do median-of-three here..
(keyed-pivot (key pivot))
(left (1+ start))
(right (1- end))
left-item right-item)
(declare (index left right))
;; do median-of-three..
(let ((p1 (vector-ref start))
(p2 (vector-ref (+ start cut-off -1)))
(p3 (vector-ref (1- end))))
(let ((kp1 (key p1))
(kp2 (key p2))
(kp3 (key p3)))
(cond
((predicate p1 p2)
(if (predicate p2 p3)
(setf pivot p2 keyed-pivot kp2)
(if (predicate p1 p3)
(setf pivot p3 keyed-pivot kp3)
(setf pivot p1 keyed-pivot kp1))))
((predicate p2 p3)
(if (predicate p1 p3)
(setf pivot p1 keyed-pivot kp1)
(setf pivot p3 keyed-pivot kp3)))
(t (setf pivot p2 keyed-pivot kp2)))))
partitioning-loop
(do-while (not (predicate keyed-pivot (key (setf left-item (vector-ref left)))))
(incf left)
(when (>= left end)
(setf right-item (vector-ref right))
(go partitioning-complete)))
(do-while (predicate keyed-pivot (key (setf right-item (vector-ref right))))
(decf right))
(when (< left right)
(setf (vector-ref left) right-item
(vector-ref right) left-item)
(incf left)
(decf right)
(go partitioning-loop))
partitioning-complete
(setf (vector-ref start) right-item ; (aref vector right)
(vector-ref right) pivot)
(when (and (> cut-off (- right start))
(> cut-off (- end right)))
(quick-sort vector predicate key start right cut-off)
(quick-sort vector predicate key (1+ right) end cut-off)))))))))
vector)
(defun sort (sequence predicate &key (key 'identity))
(do-sequence-dispatch sequence
(list
(sort-list sequence predicate key))
(vector
(quick-sort sequence predicate key 0 (length sequence) 9)
(insertion-sort sequence predicate key 0 (length sequence)))))
(defun stable-sort (sequence predicate &key key)
(do-sequence-dispatch sequence
(list
(error "Stable-sort not implemented for lists."))
(vector
(insertion-sort sequence predicate key 0 (length sequence)))))
(defun merge (result-type sequence-1 sequence-2 predicate &key (key 'identity))
(ecase result-type
(list
(sequence-double-dispatch (sequence-1 sequence-2)
((list list)
(merge-list-list sequence-1 sequence-2 predicate key))))))
(defun merge-list-list (list1 list2 predicate key)
(cond
((null list1)
list2)
((null list2)
list1)
(t (with-funcallable (predicate)
(with-funcallable (key)
(macrolet ((xpop (var)
`(let ((x ,var)) (setf ,var (cdr x)) x)))
(do* ((result (if (predicate (key (car list1)) (key (car list2)))
(xpop list1)
(xpop list2)))
(r result))
((null (setf r
(setf (cdr r)
(cond
((null list1) (xpop list2))
((null list2) (xpop list1))
((predicate (key (car list1)) (key (car list2)))
(xpop list1))
(t (xpop list2))))))
result))))))))
;;; Most of list-sorting snipped from cmucl.
;;; MERGE-LISTS* originally written by PI:NAME:<NAME>END_PI.
;;; modified to return a pointer to the end of the result
;;; and to not cons header each time its called.
;;; It destructively merges list-1 with list-2. In the resulting
;;; list, elements of list-2 are guaranteed to come after equal elements
;;; of list-1.
(defun merge-lists* (list-1 list-2 predicate key merge-lists-header)
(with-funcallable (predicate)
(with-funcallable (key)
(do* ((result merge-lists-header)
(P result)) ; P points to last cell of result
((or (null list-1) (null list-2)) ; done when either list used up
(if (null list-1) ; in which case, append the
(rplacd p list-2) ; other list
(rplacd p list-1))
(do ((drag p lead)
(lead (cdr p) (cdr lead)))
((null lead)
(values (prog1 (cdr result) ; return the result sans header
(rplacd result nil)) ; (free memory, be careful)
drag)))) ; and return pointer to last element
(cond ((predicate (key (car list-2)) (key (car list-1)))
(rplacd p list-2) ; append the lesser list to last cell of
(setq p (cdr p)) ; result. Note: test must bo done for
(pop list-2)) ; list-2 < list-1 so merge will be
(t (rplacd p list-1) ; stable for list-1
(setq p (cdr p))
(pop list-1)))))))
;;; SORT-LIST uses a bottom up merge sort. First a pass is made over
;;; the list grabbing one element at a time and merging it with the next one
;;; form pairs of sorted elements. Then n is doubled, and elements are taken
;;; in runs of two, merging one run with the next to form quadruples of sorted
;;; elements. This continues until n is large enough that the inner loop only
;;; runs for one iteration; that is, there are only two runs that can be merged,
;;; the first run starting at the beginning of the list, and the second being
;;; the remaining elements.
(defun sort-list (list pred key)
(let ((head (cons :header list)) ; head holds on to everything
(n 1) ; bottom-up size of lists to be merged
unsorted ; unsorted is the remaining list to be
; broken into n size lists and merged
list-1 ; list-1 is one length n list to be merged
last ; last points to the last visited cell
(merge-lists-header (list :header)))
(declare (index n))
(do () (nil)
;; start collecting runs of n at the first element
(setf unsorted (cdr head))
;; tack on the first merge of two n-runs to the head holder
(setf last head)
(let ((n-1 (1- n)))
(do () (nil)
(setf list-1 unsorted)
(let ((temp (nthcdr n-1 list-1))
list-2)
(cond (temp
;; there are enough elements for a second run
(setf list-2 (cdr temp))
(setf (cdr temp) nil)
(setf temp (nthcdr n-1 list-2))
(cond (temp
(setf unsorted (cdr temp))
(setf (cdr temp) nil))
;; the second run goes off the end of the list
(t (setf unsorted nil)))
(multiple-value-bind (merged-head merged-last)
(merge-lists* list-1 list-2 pred key
merge-lists-header)
(setf (cdr last) merged-head)
(setf last merged-last))
(if (null unsorted) (return)))
;; if there is only one run, then tack it on to the end
(t (setf (cdr last) list-1)
(return)))))
(setf n (+ n n))
;; If the inner loop only executed once, then there were only enough
;; elements for two runs given n, so all the elements have been merged
;; into one list. This may waste one outer iteration to realize.
(if (eq list-1 (cdr head))
(return list-1))))))
(defun make-sequence (result-type size &key (initial-element nil initial-element-p))
"=> sequence"
(ecase result-type
(string
(if (not initial-element-p)
(make-string size)
(make-string size :initial-element initial-element)))
(vector
(make-array size :initial-element initial-element))
(list
(make-list size :initial-element initial-element))))
(defun concatenate (result-type &rest sequences)
"=> result-sequence"
(declare (dynamic-extent sequences))
(cond
((null sequences)
(make-sequence result-type 0))
((and (null (rest sequences))
(typep (first sequences) result-type))
(copy-seq (first sequences)))
((= 0 (length (first sequences)))
(apply #'concatenate result-type (cdr sequences)))
((member result-type '(vector string))
(let* ((r (make-sequence result-type
(let ((length 0))
(dolist (s sequences length)
(incf length (length s))))))
(i 0))
(declare (index i))
(dolist (s sequences)
(replace r s :start1 i)
(incf i (length s)))
r))
(t (error "Can't concatenate ~S yet: ~:S"
result-type
(copy-list sequences))))) ; no more dynamic-extent.
(defun substitute (newitem olditem sequence
&key (test 'eql) test-not (start 0) end count (key 'identity) from-end)
"=> result-sequence"
(when test-not
(setf test (complement test-not)))
(with-funcallable (test (if test-not (complement test-not) test))
(substitute-if newitem (lambda (x) (test olditem x)) sequence
:start start :end end
:count count :key key
:from-end from-end)))
(defun nsubstitute (newitem olditem sequence
&key (test 'eql) test-not (start 0) end count (key 'identity) from-end)
"=> result-sequence"
(when test-not
(setf test (complement test-not)))
(with-funcallable (test (if test-not (complement test-not) test))
(nsubstitute-if newitem (lambda (x) (test olditem x)) sequence
:start start :end end
:count count :key key
:from-end from-end)))
(defun substitute-if (newitem predicate sequence &rest args
&key (start 0) end count (key 'identity) from-end)
"=> result-sequence"
(declare (dynamic-extent args))
(with-funcallable (predicate)
(with-funcallable (key)
(do-sequence-dispatch sequence
(vector
(apply 'nsubstitute-if newitem predicate (copy-seq sequence) args))
(list
(if from-end
(apply 'nsubstitute-if newitem predicate (copy-list sequence) args)
(if (or (null sequence)
(and end (<= end start)))
nil
(multiple-value-bind (new-list new-tail)
(if (= 0 start)
(let ((new-list (list #0=(let ((x (pop sequence)))
(if (predicate (key x))
newitem
x)))))
(values new-list new-list))
(do* ((new-list (list (pop sequence)))
(new-tail new-list (cdr new-tail))
(i 1 (1+ i)))
((or (endp sequence) (>= i start))
(values new-list new-tail))
(setf (cdr new-tail) (list (pop sequence)))))
(cond
((and (not end) (not count))
(do ()
((endp sequence) new-list)
(setf new-tail
(setf (cdr new-tail) (list #0#)))))
((and end (not count))
(do ((i (- end start 1) (1- i)))
((or (endp sequence) (<= i 0))
(setf (cdr new-tail) (copy-list sequence))
new-list)
(setf new-tail
(setf (cdr new-tail) (list #0#)))))
((and (not end) count)
(do ((c 0))
((or (endp sequence) (>= c count))
(setf (cdr new-tail) (copy-list sequence))
new-list)
(setf new-tail
(setf (cdr new-tail) #1=(list (let ((x (pop sequence)))
(if (predicate (key x))
(progn (incf c) newitem)
x)))))))
((and end count)
(do ((i (- end start 1) (1- i))
(c 0))
((or (endp sequence) (<= i 0) (>= c count))
(setf (cdr new-tail)
(copy-list sequence))
new-list)
(setf new-tail
(setf (cdr new-tail) #1#))))
((error 'program-error)))))))))))
(defun nsubstitute-if (newitem predicate sequence &key (start 0) end count (key 'identity) from-end)
"=> sequence"
(if (<= count 0)
sequence
(with-funcallable (predicate)
(with-funcallable (key)
(do-sequence-dispatch sequence
(vector
(let ((end (or end (length sequence))))
(with-subvector-accessor (ref sequence start end)
(cond
((and (not count) (not from-end))
(do ((i start (1+ i)))
((>= i end) sequence)
(declare (index i))
(when (predicate (key (ref i)))
(setf (ref i) newitem))))
((and count (not from-end))
(do ((c 0)
(i start (1+ i)))
((>= i end) sequence)
(declare (index i c))
(when (predicate (key (ref i)))
(setf (ref i) newitem)
(when (>= (incf c) count)
(return sequence)))))
((and (not count) from-end)
(do ((i (1- end) (1- i)))
((< i start) sequence)
(declare (index i))
(when (predicate (key (ref i)))
(setf (ref i) newitem))))
((and count from-end)
(do ((c 0)
(i (1- end) (1- i)))
((< i start) sequence)
(declare (index c i))
(when (predicate (key (ref i)))
(setf (ref i) newitem)
(when (>= (incf c) count)
(return sequence)))))
((error 'program-error))))))
(list
(let ((p (nthcdr start sequence)))
(cond
(from-end
(nreverse (nsubstitute-if newitem predicate (nreverse sequence)
:start (if (not end) 0 (- (length sequence) end))
:end (if (plusp start) nil (- (length sequence) start))
:count count :key key)))
#+ignore ((and from-end count)
(let* ((end (and end (- end start)))
(existing-count (count-if predicate p :key key :end end)))
(do ((i count))
((>= i existing-count)
(nsubstitute-if newitem predicate p :end end :key key)
sequence)
(declare (index i))
(when (predicate (key (car p)))
(incf i))
(setf p (cdr p)))))
((and (not end) (not count))
(do ((p p (cdr p)))
((endp p) sequence)
(when (predicate (key (car p)))
(setf (car p) newitem))))
((and end (not count))
(do ((i start (1+ i))
(p p (cdr p)))
((or (endp p) (>= i end)) sequence)
(declare (index i))
(when (predicate (key (car p)))
(setf (car p) newitem))))
((and (not end) count)
(do ((c 0)
(p p (cdr p)))
((endp p) sequence)
(declare (index c))
(when (predicate (key (car p)))
(setf (car p) newitem)
(when (>= (incf c) count)
(return sequence)))))
((and end count)
(do ((c 0)
(i start (1+ i))
(p p (cdr p)))
((or (endp p) (>= i end)) sequence)
(declare (index c i))
(when (predicate (key (car p)))
(setf (car p) newitem)
(when (>= (incf c) count)
(return sequence)))))
((error 'program-error))))))))))
(defun substitute-if-not (newitem predicate sequence &rest keyargs)
(declare (dynamic-extent keyargs))
(apply #'substitute-if newitem (complement predicate) sequence keyargs))
(defun nsubstitute-if-not (newitem predicate sequence &rest keyargs)
(declare (dynamic-extent keyargs))
(apply #'nsubstitute-if newitem (complement predicate) sequence keyargs))
|
[
{
"context": ";-*- Mode: Lisp -*-\n;;;; Author: Paul Dietz\n;;;; Created: Thu Nov 21 09:48:38 2002\n;;;; Cont",
"end": 49,
"score": 0.9998592138290405,
"start": 39,
"tag": "NAME",
"value": "Paul Dietz"
}
] |
Code/Loop/Test/loop17.lisp
|
gwerbin/SICL
| 842 |
;-*- Mode: Lisp -*-
;;;; Author: Paul Dietz
;;;; Created: Thu Nov 21 09:48:38 2002
;;;; Contains: Miscellaneous loop tests
(cl:in-package :sicl-loop-test)
;;; Initially and finally take multiple forms,
;;; and execute them in the right order
(deftest loop.17.1
(loop
with x = 0
initially (incf x 1) (incf x (+ x x))
initially (incf x (+ x x x))
until t
finally (incf x 100) (incf x (+ x x))
finally (return x))
336)
(deftest loop.17.2
(loop
with x = 0
until t
initially (incf x 1) (incf x (+ x x))
finally (incf x 100) (incf x (+ x x))
initially (incf x (+ x x x))
finally (return x))
336)
(deftest loop.17.3
(let ((x 0))
(loop
with y = (incf x 1)
initially (incf x 2)
until t
finally (return (values x y))))
3 1)
(deftest loop.17.4
(loop
doing (return 'a)
finally (return 'b))
a)
(deftest loop.17.5
(loop
return 'a
finally (return 'b))
a)
(deftest loop.17.6
(let ((x 0))
(tagbody
(loop
do (go done)
finally (incf x))
done)
x)
0)
(deftest loop.17.7
(let ((x 0))
(catch 'done
(loop
do (throw 'done nil)
finally (incf x)))
x)
0)
(deftest loop.17.8
(loop
for x in '(1 2 3)
collect x
finally (return 'good))
good)
(deftest loop.17.9
(loop
for x in '(1 2 3)
append (list x)
finally (return 'good))
good)
(deftest loop.17.10
(loop
for x in '(1 2 3)
nconc (list x)
finally (return 'good))
good)
(deftest loop.17.11
(loop
for x in '(1 2 3)
count (> x 1)
finally (return 'good))
good)
(deftest loop.17.12
(loop
for x in '(1 2 3)
sum x
finally (return 'good))
good)
(deftest loop.17.13
(loop
for x in '(1 2 3)
maximize x
finally (return 'good))
good)
(deftest loop.17.14
(loop
for x in '(1 2 3)
minimize x
finally (return 'good))
good)
;;; iteration clause grouping
;; (deftest loop.17.20
;; (loop
;; for i from 1 to 5
;; for j = 0 then (+ j i)
;; collect j)
;; (0 2 5 9 14))
;; (deftest loop.17.21
;; (loop
;; for i from 1 to 5
;; and j = 0 then (+ j i)
;; collect j)
;; (0 1 3 6 10))
;;; Test that explicit calls to macroexpand in subforms
;;; are done in the correct environment
(deftest loop.17.22
(macrolet
((%m (z) z))
(loop with x = 0
initially (expand-in-current-env (%m (incf x)))
until t
finally (expand-in-current-env (%m (return x)))))
1)
|
26199
|
;-*- Mode: Lisp -*-
;;;; Author: <NAME>
;;;; Created: Thu Nov 21 09:48:38 2002
;;;; Contains: Miscellaneous loop tests
(cl:in-package :sicl-loop-test)
;;; Initially and finally take multiple forms,
;;; and execute them in the right order
(deftest loop.17.1
(loop
with x = 0
initially (incf x 1) (incf x (+ x x))
initially (incf x (+ x x x))
until t
finally (incf x 100) (incf x (+ x x))
finally (return x))
336)
(deftest loop.17.2
(loop
with x = 0
until t
initially (incf x 1) (incf x (+ x x))
finally (incf x 100) (incf x (+ x x))
initially (incf x (+ x x x))
finally (return x))
336)
(deftest loop.17.3
(let ((x 0))
(loop
with y = (incf x 1)
initially (incf x 2)
until t
finally (return (values x y))))
3 1)
(deftest loop.17.4
(loop
doing (return 'a)
finally (return 'b))
a)
(deftest loop.17.5
(loop
return 'a
finally (return 'b))
a)
(deftest loop.17.6
(let ((x 0))
(tagbody
(loop
do (go done)
finally (incf x))
done)
x)
0)
(deftest loop.17.7
(let ((x 0))
(catch 'done
(loop
do (throw 'done nil)
finally (incf x)))
x)
0)
(deftest loop.17.8
(loop
for x in '(1 2 3)
collect x
finally (return 'good))
good)
(deftest loop.17.9
(loop
for x in '(1 2 3)
append (list x)
finally (return 'good))
good)
(deftest loop.17.10
(loop
for x in '(1 2 3)
nconc (list x)
finally (return 'good))
good)
(deftest loop.17.11
(loop
for x in '(1 2 3)
count (> x 1)
finally (return 'good))
good)
(deftest loop.17.12
(loop
for x in '(1 2 3)
sum x
finally (return 'good))
good)
(deftest loop.17.13
(loop
for x in '(1 2 3)
maximize x
finally (return 'good))
good)
(deftest loop.17.14
(loop
for x in '(1 2 3)
minimize x
finally (return 'good))
good)
;;; iteration clause grouping
;; (deftest loop.17.20
;; (loop
;; for i from 1 to 5
;; for j = 0 then (+ j i)
;; collect j)
;; (0 2 5 9 14))
;; (deftest loop.17.21
;; (loop
;; for i from 1 to 5
;; and j = 0 then (+ j i)
;; collect j)
;; (0 1 3 6 10))
;;; Test that explicit calls to macroexpand in subforms
;;; are done in the correct environment
(deftest loop.17.22
(macrolet
((%m (z) z))
(loop with x = 0
initially (expand-in-current-env (%m (incf x)))
until t
finally (expand-in-current-env (%m (return x)))))
1)
| true |
;-*- Mode: Lisp -*-
;;;; Author: PI:NAME:<NAME>END_PI
;;;; Created: Thu Nov 21 09:48:38 2002
;;;; Contains: Miscellaneous loop tests
(cl:in-package :sicl-loop-test)
;;; Initially and finally take multiple forms,
;;; and execute them in the right order
(deftest loop.17.1
(loop
with x = 0
initially (incf x 1) (incf x (+ x x))
initially (incf x (+ x x x))
until t
finally (incf x 100) (incf x (+ x x))
finally (return x))
336)
(deftest loop.17.2
(loop
with x = 0
until t
initially (incf x 1) (incf x (+ x x))
finally (incf x 100) (incf x (+ x x))
initially (incf x (+ x x x))
finally (return x))
336)
(deftest loop.17.3
(let ((x 0))
(loop
with y = (incf x 1)
initially (incf x 2)
until t
finally (return (values x y))))
3 1)
(deftest loop.17.4
(loop
doing (return 'a)
finally (return 'b))
a)
(deftest loop.17.5
(loop
return 'a
finally (return 'b))
a)
(deftest loop.17.6
(let ((x 0))
(tagbody
(loop
do (go done)
finally (incf x))
done)
x)
0)
(deftest loop.17.7
(let ((x 0))
(catch 'done
(loop
do (throw 'done nil)
finally (incf x)))
x)
0)
(deftest loop.17.8
(loop
for x in '(1 2 3)
collect x
finally (return 'good))
good)
(deftest loop.17.9
(loop
for x in '(1 2 3)
append (list x)
finally (return 'good))
good)
(deftest loop.17.10
(loop
for x in '(1 2 3)
nconc (list x)
finally (return 'good))
good)
(deftest loop.17.11
(loop
for x in '(1 2 3)
count (> x 1)
finally (return 'good))
good)
(deftest loop.17.12
(loop
for x in '(1 2 3)
sum x
finally (return 'good))
good)
(deftest loop.17.13
(loop
for x in '(1 2 3)
maximize x
finally (return 'good))
good)
(deftest loop.17.14
(loop
for x in '(1 2 3)
minimize x
finally (return 'good))
good)
;;; iteration clause grouping
;; (deftest loop.17.20
;; (loop
;; for i from 1 to 5
;; for j = 0 then (+ j i)
;; collect j)
;; (0 2 5 9 14))
;; (deftest loop.17.21
;; (loop
;; for i from 1 to 5
;; and j = 0 then (+ j i)
;; collect j)
;; (0 1 3 6 10))
;;; Test that explicit calls to macroexpand in subforms
;;; are done in the correct environment
(deftest loop.17.22
(macrolet
((%m (z) z))
(loop with x = 0
initially (expand-in-current-env (%m (incf x)))
until t
finally (expand-in-current-env (%m (return x)))))
1)
|
[
{
"context": "art of ld35\n (c) 2016 Shirakumo http://tymoon.eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n",
"end": 88,
"score": 0.9999021887779236,
"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.shirak",
"end": 113,
"score": 0.9998881220817566,
"start": 99,
"tag": "NAME",
"value": "Nicolas Hafner"
},
{
"context": ".eu ([email protected])\n Author: Nicolas Hafner <[email protected]>\n|#\n\n(in-package #:org.shirakumo.fraf.ld35)\n(in-r",
"end": 133,
"score": 0.9999094009399414,
"start": 115,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
player.lisp
|
Shirakumo/ld35
| 0 |
#|
This file is a part of ld35
(c) 2016 Shirakumo http://tymoon.eu ([email protected])
Author: Nicolas Hafner <[email protected]>
|#
(in-package #:org.shirakumo.fraf.ld35)
(in-readtable :qtools)
(define-subject colleen (sprite-subject collidable-subject rotated-subject pivoted-subject savable)
((velocity :initarg :velocity :accessor velocity)
(facing :initarg :facing :accessor facing))
(:default-initargs
:velocity (vec 0 0 0)
:location (vec 0 0 0)
:bounds (vec 50 80 10)
:pivot (vec -25 0 5)
:facing :left
:name :player
:animations '((idle 2.0 20 :texture "colleen-idle.png")
(walk 0.7 20 :texture "colleen-walking.png"))))
(defun nvclamp (vec x y z)
(vsetf vec
(max (- x) (min x (vx vec)))
(max (- y) (min y (vy vec)))
(max (- z) (min z (vz vec)))))
(defmethod initialize-instance :after ((colleen colleen) &key)
(setf *player* colleen))
(define-handler (colleen tick) (ev)
(with-slots (location velocity angle facing) colleen
(let* ((ang (* (/ angle 180) PI))
(vec (nvrot (vec -1 0 0) (vec 0 1 0) ang)))
(when (< 0.01 (abs (- (vx vec) (ecase facing (:left -1) (:right 1)))))
(incf angle 20)))
(nv+ location velocity)
(nvclamp location 230 0 230)))
(define-handler (colleen movement) (ev)
(with-slots (location velocity facing) colleen
(typecase ev
(start-left
(setf facing :left)
(setf (vx velocity) -7))
(start-right
(setf facing :right)
(setf (vx velocity) 7))
(start-up
(setf (vz velocity) -7))
(start-down
(setf (vz velocity) 7))
(stop-left
(when (< (vx velocity) 0)
(setf (vx velocity) 0)))
(stop-right
(when (< 0 (vx velocity))
(setf (vx velocity) 0)))
(stop-up
(when (< (vz velocity) 0)
(setf (vz velocity) 0)))
(stop-down
(when (< 0 (vz velocity))
(setf (vz velocity) 0))))
(if (< 0 (vlength velocity))
(setf (animation colleen) 'walk)
(setf (animation colleen) 'idle))))
(defmethod paint ((colleen colleen) target)
(call-next-method))
|
98372
|
#|
This file is a part of ld35
(c) 2016 Shirakumo http://tymoon.eu (<EMAIL>)
Author: <NAME> <<EMAIL>>
|#
(in-package #:org.shirakumo.fraf.ld35)
(in-readtable :qtools)
(define-subject colleen (sprite-subject collidable-subject rotated-subject pivoted-subject savable)
((velocity :initarg :velocity :accessor velocity)
(facing :initarg :facing :accessor facing))
(:default-initargs
:velocity (vec 0 0 0)
:location (vec 0 0 0)
:bounds (vec 50 80 10)
:pivot (vec -25 0 5)
:facing :left
:name :player
:animations '((idle 2.0 20 :texture "colleen-idle.png")
(walk 0.7 20 :texture "colleen-walking.png"))))
(defun nvclamp (vec x y z)
(vsetf vec
(max (- x) (min x (vx vec)))
(max (- y) (min y (vy vec)))
(max (- z) (min z (vz vec)))))
(defmethod initialize-instance :after ((colleen colleen) &key)
(setf *player* colleen))
(define-handler (colleen tick) (ev)
(with-slots (location velocity angle facing) colleen
(let* ((ang (* (/ angle 180) PI))
(vec (nvrot (vec -1 0 0) (vec 0 1 0) ang)))
(when (< 0.01 (abs (- (vx vec) (ecase facing (:left -1) (:right 1)))))
(incf angle 20)))
(nv+ location velocity)
(nvclamp location 230 0 230)))
(define-handler (colleen movement) (ev)
(with-slots (location velocity facing) colleen
(typecase ev
(start-left
(setf facing :left)
(setf (vx velocity) -7))
(start-right
(setf facing :right)
(setf (vx velocity) 7))
(start-up
(setf (vz velocity) -7))
(start-down
(setf (vz velocity) 7))
(stop-left
(when (< (vx velocity) 0)
(setf (vx velocity) 0)))
(stop-right
(when (< 0 (vx velocity))
(setf (vx velocity) 0)))
(stop-up
(when (< (vz velocity) 0)
(setf (vz velocity) 0)))
(stop-down
(when (< 0 (vz velocity))
(setf (vz velocity) 0))))
(if (< 0 (vlength velocity))
(setf (animation colleen) 'walk)
(setf (animation colleen) 'idle))))
(defmethod paint ((colleen colleen) target)
(call-next-method))
| true |
#|
This file is a part of ld35
(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.ld35)
(in-readtable :qtools)
(define-subject colleen (sprite-subject collidable-subject rotated-subject pivoted-subject savable)
((velocity :initarg :velocity :accessor velocity)
(facing :initarg :facing :accessor facing))
(:default-initargs
:velocity (vec 0 0 0)
:location (vec 0 0 0)
:bounds (vec 50 80 10)
:pivot (vec -25 0 5)
:facing :left
:name :player
:animations '((idle 2.0 20 :texture "colleen-idle.png")
(walk 0.7 20 :texture "colleen-walking.png"))))
(defun nvclamp (vec x y z)
(vsetf vec
(max (- x) (min x (vx vec)))
(max (- y) (min y (vy vec)))
(max (- z) (min z (vz vec)))))
(defmethod initialize-instance :after ((colleen colleen) &key)
(setf *player* colleen))
(define-handler (colleen tick) (ev)
(with-slots (location velocity angle facing) colleen
(let* ((ang (* (/ angle 180) PI))
(vec (nvrot (vec -1 0 0) (vec 0 1 0) ang)))
(when (< 0.01 (abs (- (vx vec) (ecase facing (:left -1) (:right 1)))))
(incf angle 20)))
(nv+ location velocity)
(nvclamp location 230 0 230)))
(define-handler (colleen movement) (ev)
(with-slots (location velocity facing) colleen
(typecase ev
(start-left
(setf facing :left)
(setf (vx velocity) -7))
(start-right
(setf facing :right)
(setf (vx velocity) 7))
(start-up
(setf (vz velocity) -7))
(start-down
(setf (vz velocity) 7))
(stop-left
(when (< (vx velocity) 0)
(setf (vx velocity) 0)))
(stop-right
(when (< 0 (vx velocity))
(setf (vx velocity) 0)))
(stop-up
(when (< (vz velocity) 0)
(setf (vz velocity) 0)))
(stop-down
(when (< 0 (vz velocity))
(setf (vz velocity) 0))))
(if (< 0 (vlength velocity))
(setf (animation colleen) 'walk)
(setf (animation colleen) 'idle))))
(defmethod paint ((colleen colleen) target)
(call-next-method))
|
[
{
"context": " (make-instance 'api-client :token \"123\"))))\n\n;; make fake http server and receive http-c",
"end": 470,
"score": 0.8008852005004883,
"start": 467,
"tag": "PASSWORD",
"value": "123"
},
{
"context": "e 'api-client\n :token \"123\")))\n (unwind-protect\n (progn (setf han",
"end": 659,
"score": 0.8096365332603455,
"start": 656,
"tag": "PASSWORD",
"value": "123"
},
{
"context": " :token \"456\"))))\n\n ;; don't give token, use cl",
"end": 2178,
"score": 0.5265782475471497,
"start": 2175,
"tag": "PASSWORD",
"value": "456"
},
{
"context": " \"http://127.0.0.1:5000\"))))\n\n ;; give username and p",
"end": 2452,
"score": 0.9870889186859131,
"start": 2443,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " :passd \"bb\")))))\n \n (clack:stop handler))))\n\n(let ",
"end": 3015,
"score": 0.999050498008728,
"start": 3013,
"tag": "PASSWORD",
"value": "bb"
}
] |
client-test.lisp
|
ccqpein/Github-api-CL
| 6 |
(defpackage #:client-test
(:use #:CL #:lisp-unit)
(:import-from #:github-client
#:token-p
#:token
#:token-p-or-input
#:api-client
#:http-call
#:github-api-call))
(in-package #:client-test)
(define-test token-p-test
(assert-false (token-p
(make-instance 'api-client)))
(assert-true (token-p
(make-instance 'api-client :token "123"))))
;; make fake http server and receive http-call
(define-test http-call-test
(let (handler
env
(clt (make-instance 'api-client
:token "123")))
(unwind-protect
(progn (setf handler
(clack:clackup
(lambda (request)
(setf env request) ;; update env
(list 200
'(:content-type "text/plain")
(list (gethash "authorization" (car (last env))))))
:server :woo))
;; default method is :GET
(assert-equal :GET
(progn (http-call clt "http://127.0.0.1:5000")
(alexandria:doplist (k v env)
(if (eq k :REQUEST-METHOD)
(return v)))))
;; give some method
(assert-equal :DELETE
(progn (http-call clt
"http://127.0.0.1:5000"
:method "delete")
(alexandria:doplist (k v env)
(if (eq k :REQUEST-METHOD)
(return v)))))
;; give token
(assert-equal "token 456"
(car (multiple-value-list
(http-call clt
"http://127.0.0.1:5000"
:token "456"))))
;; don't give token, use client token
(assert-equal "token 123"
(car (multiple-value-list
(http-call clt
"http://127.0.0.1:5000"))))
;; give username and passd
(setf (github-client::token clt) "") ;; empty token first
(assert-equal (format nil "Basic ~a"
(cl-base64:string-to-base64-string "aa:bb"))
(car (multiple-value-list
(http-call clt
"http://127.0.0.1:5000"
:user-name "aa"
:passd "bb")))))
(clack:stop handler))))
(let ((*print-errors* t)
(*print-failures* t))
(run-tests :all :client-test))
|
70907
|
(defpackage #:client-test
(:use #:CL #:lisp-unit)
(:import-from #:github-client
#:token-p
#:token
#:token-p-or-input
#:api-client
#:http-call
#:github-api-call))
(in-package #:client-test)
(define-test token-p-test
(assert-false (token-p
(make-instance 'api-client)))
(assert-true (token-p
(make-instance 'api-client :token "<PASSWORD>"))))
;; make fake http server and receive http-call
(define-test http-call-test
(let (handler
env
(clt (make-instance 'api-client
:token "<PASSWORD>")))
(unwind-protect
(progn (setf handler
(clack:clackup
(lambda (request)
(setf env request) ;; update env
(list 200
'(:content-type "text/plain")
(list (gethash "authorization" (car (last env))))))
:server :woo))
;; default method is :GET
(assert-equal :GET
(progn (http-call clt "http://127.0.0.1:5000")
(alexandria:doplist (k v env)
(if (eq k :REQUEST-METHOD)
(return v)))))
;; give some method
(assert-equal :DELETE
(progn (http-call clt
"http://127.0.0.1:5000"
:method "delete")
(alexandria:doplist (k v env)
(if (eq k :REQUEST-METHOD)
(return v)))))
;; give token
(assert-equal "token 456"
(car (multiple-value-list
(http-call clt
"http://127.0.0.1:5000"
:token "<PASSWORD>"))))
;; don't give token, use client token
(assert-equal "token 123"
(car (multiple-value-list
(http-call clt
"http://127.0.0.1:5000"))))
;; give username and passd
(setf (github-client::token clt) "") ;; empty token first
(assert-equal (format nil "Basic ~a"
(cl-base64:string-to-base64-string "aa:bb"))
(car (multiple-value-list
(http-call clt
"http://127.0.0.1:5000"
:user-name "aa"
:passd "<PASSWORD>")))))
(clack:stop handler))))
(let ((*print-errors* t)
(*print-failures* t))
(run-tests :all :client-test))
| true |
(defpackage #:client-test
(:use #:CL #:lisp-unit)
(:import-from #:github-client
#:token-p
#:token
#:token-p-or-input
#:api-client
#:http-call
#:github-api-call))
(in-package #:client-test)
(define-test token-p-test
(assert-false (token-p
(make-instance 'api-client)))
(assert-true (token-p
(make-instance 'api-client :token "PI:PASSWORD:<PASSWORD>END_PI"))))
;; make fake http server and receive http-call
(define-test http-call-test
(let (handler
env
(clt (make-instance 'api-client
:token "PI:PASSWORD:<PASSWORD>END_PI")))
(unwind-protect
(progn (setf handler
(clack:clackup
(lambda (request)
(setf env request) ;; update env
(list 200
'(:content-type "text/plain")
(list (gethash "authorization" (car (last env))))))
:server :woo))
;; default method is :GET
(assert-equal :GET
(progn (http-call clt "http://127.0.0.1:5000")
(alexandria:doplist (k v env)
(if (eq k :REQUEST-METHOD)
(return v)))))
;; give some method
(assert-equal :DELETE
(progn (http-call clt
"http://127.0.0.1:5000"
:method "delete")
(alexandria:doplist (k v env)
(if (eq k :REQUEST-METHOD)
(return v)))))
;; give token
(assert-equal "token 456"
(car (multiple-value-list
(http-call clt
"http://127.0.0.1:5000"
:token "PI:PASSWORD:<PASSWORD>END_PI"))))
;; don't give token, use client token
(assert-equal "token 123"
(car (multiple-value-list
(http-call clt
"http://127.0.0.1:5000"))))
;; give username and passd
(setf (github-client::token clt) "") ;; empty token first
(assert-equal (format nil "Basic ~a"
(cl-base64:string-to-base64-string "aa:bb"))
(car (multiple-value-list
(http-call clt
"http://127.0.0.1:5000"
:user-name "aa"
:passd "PI:PASSWORD:<PASSWORD>END_PI")))))
(clack:stop handler))))
(let ((*print-errors* t)
(*print-failures* t))
(run-tests :all :client-test))
|
[
{
"context": ";; \n;; Copyright (C) 2018, Rockwell Collins\n;; All rights reserved.\n;; \n;; This software may ",
"end": 43,
"score": 0.9998257756233215,
"start": 27,
"tag": "NAME",
"value": "Rockwell Collins"
}
] |
books/coi/quantification/quantified-congruence.lisp
|
mayankmanj/acl2
| 305 |
;;
;; Copyright (C) 2018, Rockwell Collins
;; All rights reserved.
;;
;; This software may be modified and distributed under the terms
;; of the 3-clause BSD license. See the LICENSE file for details.
;;
;;
(in-package "QUANT")
(include-book "misc/beta-reduce" :dir :system)
(include-book "coi/util/pseudo-translate" :dir :system)
(include-book "xdoc/top" :dir :system)
(include-book "quantified-equivalence")
(defstub quantification-key-witness () nil)
(encapsulate
(
((congruent-predicate * *) => *)
((congruent-predicate-witness *) => *)
((universally-quantified) => *)
)
(local (defun universally-quantified ()
(quantification-key-witness)))
(local (defund congruent-predicate (x y) (equal x y)))
(local
(defun-sk forall-predicate (x)
(forall (a) (congruent-predicate a x))
:strengthen t))
(local
(defun-sk exists-predicate (x)
(exists (a) (congruent-predicate a x))
:strengthen t))
(local
(defun congruent-predicate-witness (x)
(if (universally-quantified) (forall-predicate-witness x)
(exists-predicate-witness x))))
(defthm existential-constraint
(implies
(not (universally-quantified))
(and (implies (congruent-predicate a x)
(congruent-predicate (congruent-predicate-witness x) x))
(or (equal (congruent-predicate-witness x)
(congruent-predicate-witness x1))
(let ((a (congruent-predicate-witness x)))
(and (congruent-predicate a x)
(not (let ((x x1))
(congruent-predicate a x)))))
(let ((a (congruent-predicate-witness x1)))
(and (let ((x x1)) (congruent-predicate a x))
(not (congruent-predicate a x)))))))
:hints (("goal" :use (exists-predicate-suff
exists-predicate-witness-strengthen))))
(defthm universal-constratint
(implies
(universally-quantified)
(and (implies (not (congruent-predicate a x))
(not (congruent-predicate (congruent-predicate-witness x) x)))
(or (equal (congruent-predicate-witness x)
(congruent-predicate-witness x1))
(let ((a (congruent-predicate-witness x)))
(and (not (congruent-predicate a x))
(not (let ((x x1))
(not (congruent-predicate a x))))))
(let ((a (congruent-predicate-witness x1)))
(and (let ((x x1))
(not (congruent-predicate a x)))
(not (not (congruent-predicate a x))))))))
:hints (("goal" :use (forall-predicate-necc
forall-predicate-witness-strengthen))))
)
(defun iff-equiv (x y)
(iff x y))
(defequiv iff-equiv)
(encapsulate
(
((congruent-predicate-hyps *) => *)
((congruent-predicate-relation * *) => *)
((congruent-predicate-equiv * *) => *)
)
(local (defun congruent-predicate-hyps (x) (declare (ignore x)) nil))
(local (defun congruent-predicate-relation (x y) (declare (ignore x y)) nil))
(local (defun congruent-predicate-equiv (x y) (equal x y)))
(defthm essential-congruence
(implies
(and
(congruent-predicate-hyps x)
(congruent-predicate-relation x y)
(congruent-predicate-equiv x y))
(iff-equiv (congruent-predicate a x)
(congruent-predicate a y))))
)
(defthm congruent-predicate-witness-congruence
(implies
(and
(congruent-predicate-hyps x)
(congruent-predicate-relation x y)
(congruent-predicate-equiv x y))
(equal (congruent-predicate-witness x)
(congruent-predicate-witness y)))
:hints (("Goal" :use ((:instance existential-constraint
(x1 y))
(:instance universal-constratint
(x1 y))
(:instance essential-congruence
(a (congruent-predicate-witness x)))
(:instance essential-congruence
(a (congruent-predicate-witness y)))))))
(defun congruent-predicate-quantified (x)
(congruent-predicate (congruent-predicate-witness x) x))
(defthm congruent-predicate-congruence
(implies
(and
(congruent-predicate-hyps x)
(congruent-predicate-relation x y)
(congruent-predicate-equiv x y))
(iff (congruent-predicate-quantified x)
(congruent-predicate-quantified y)))
:hints (("Subgoal 1" :use (:instance essential-congruence
(a (congruent-predicate-witness y))))
("subgoal 2" :use (:instance essential-congruence
(a (congruent-predicate-witness y))))))
(defthm congruent-predicate-canary
(list
(CONGRUENT-PREDICATE-QUANTIFIED X)
(CONGRUENT-PREDICATE-HYPS X)
(CONGRUENT-PREDICATE-RELATION X Y)
(CONGRUENT-PREDICATE-EQUIV X Y)
(CONGRUENT-PREDICATE-WITNESS X)
(CONGRUENT-PREDICATE A X)
(UNIVERSALLY-QUANTIFIED)
)
:rule-classes nil)
(defun number-symbol (x base)
(declare (type symbol x base))
(intern-in-package-of-symbol
(coerce
(acl2::packn1 (list x 1))
'string)
base))
(defthm symbolp-number-symbol
(implies
(and (symbolp x) (symbolp base))
(symbolp (number-symbol x base))))
(in-theory (disable number-symbol))
(local
(defthm symbol-listp-implies-true-listp
(implies
(symbol-listp list)
(true-listp list))
:rule-classes (:forward-chaining)))
(defun number-symbol-list (list base)
(declare (type (satisfies symbol-listp) list)
(type symbol base))
(if (not (consp list)) nil
(cons (number-symbol (car list) base)
(number-symbol-list (cdr list) base))))
(defthm symbol-listp-number-symbol-list
(implies
(and (symbol-listp x) (symbolp base))
(symbol-listp (number-symbol-list x base))))
(defun make-binding-out-rec (args args1 index x x1)
(declare (type integer index))
(if (not (and (consp args) (consp args1))) nil
(cons `(,(car args) (nth ,index ,x))
(cons `(,(car args1) (nth ,index ,x1))
(make-binding-out-rec (cdr args) (cdr args1) (1+ index) x x1)))))
(defthm true-listp-make-binding-out-rec
(true-listp (make-binding-out-rec args args1 index x x1)))
(defun make-binding-out (args args1 x x1)
(declare (type (satisfies symbol-listp) args args1))
(make-binding-out-rec args args1 0 x x1))
(defthm true-listp-make-binding-out
(true-listp (make-binding-out args args1 x x1)))
(in-theory (disable make-binding-out))
(defun make-binding-into (x x1 args args1)
(declare (type (satisfies symbol-listp) args args1))
`((,x (list ,@args))
(,x1 (list ,@args1))))
(defthm true-listp-make-binding-into
(true-listp (make-binding-into x x1 args args1)))
(in-theory (disable make-binding-into))
(defun lambda-term-p (term)
(declare (type t term))
(case-match term
(('lambda a ('declare &) b) (and (symbol-listp a)
(pseudo-termp b)))
(('lambda a b) (and (symbol-listp a)
(pseudo-termp b)))
(& (symbolp term))))
(defun into-args-rec (args index x)
(declare (type integer index))
(if (not (consp args)) nil
(cons `(nth ,index ,x)
(into-args-rec (cdr args) (1+ index) x))))
(defthm true-listp-into-args-rec
(true-listp (into-args-rec args index x)))
(defun into-args (args x)
(declare (type (satisfies symbol-listp) args))
(into-args-rec args 0 x))
(defun make-mv-rec (n index term)
(declare (type (integer 0 *) n index))
(if (zp n) nil
(cons `(mv-nth ,index ,term)
(make-mv-rec (1- n) (1+ index) term))))
(defthm true-listp-make-mv-rec
(true-listp (make-mv-rec args index x)))
(defun make-mv (n term)
(declare (type (integer 0 *) n))
(if (equal n 1)
(list term)
(make-mv-rec n 0 term)))
(defthm true-listp-make-mv
(true-listp (make-mv args x)))
(in-theory (disable make-mv))
(defthm true-listp-into-args
(true-listp (into-args args x)))
(in-theory (disable into-args))
(defthm open-nth
(equal (nth a (cons b x))
(if (zp a) b
(nth (1- a) x))))
(defun good-congruence-listp (list)
(declare (type t list))
(if (not (consp list)) (null list)
(let ((congruence (car list)))
(and (consp congruence)
(symbolp (car congruence))
(consp (cdr congruence))
(symbolp (cadr congruence))
(null (cddr congruence))
(good-congruence-listp (cdr list))))))
(defthm good-congruence-listp-implies-alistp
(implies
(good-congruence-listp list)
(alistp list))
:rule-classes (:forward-chaining))
(defthm assoc-good-congruence-listp
(implies
(and
(good-congruence-listp list)
(assoc-equal key list))
(and
(consp (assoc-equal key list))
(consp (cdr (assoc-equal key list)))
(symbolp (cadr (assoc-equal key list)))))
:rule-classes (:forward-chaining))
(defun symbol-pairlistp (pairlist)
(declare (type t pairlist))
(if (not (consp pairlist)) (null pairlist)
(let ((entry (car pairlist)))
(and (consp entry)
(symbolp (car entry))
(symbolp (cdr entry))
(symbol-pairlistp (cdr pairlist))))))
(defthm symbol-pairlistp-pairlis$
(implies
(and
(symbol-listp x)
(symbol-listp y))
(symbol-pairlistp (pairlis$ x y))))
(defun make-equiv-body (pairlist congruences)
(declare (type (satisfies good-congruence-listp) congruences)
(type (satisfies symbol-pairlistp) pairlist))
(if (not (consp pairlist)) nil
(let ((pair (car pairlist)))
(let ((arg1 (car pair))
(arg2 (cdr pair)))
(let ((hit (assoc arg1 congruences)))
(let ((equiv (if (not hit) `(equal ,arg1 ,arg2)
`(,(cadr hit) ,arg1 ,arg2))))
(cons equiv (make-equiv-body (cdr pairlist) congruences))))))))
(defun make-binding (keys vals)
(declare (type t keys vals))
(if (not (and (consp keys) (consp vals))) nil
(cons (list (car keys) (car vals))
(make-binding (cdr keys) (cdr vals)))))
(defun tcons (a list)
(declare (type t list))
(if (not (consp list)) (list a)
(cons (car list) (tcons a (cdr list)))))
(defun make-congruences-rec (lemma fn name n iff vars parg0 arg0 narg0 parg1 arg1 narg1 congruences hyps relation suffix)
(declare (xargs :ruler-extenders :all)
(type symbol name iff arg0 arg1 suffix)
(type integer n)
(type (satisfies symbol-listp) vars parg0 parg1 narg0 narg1)
(type (satisfies good-congruence-listp) congruences)
)
(let ((events (if (not (consp narg0)) nil
(make-congruences-rec lemma fn name (1+ n) iff vars
(tcons arg0 parg0) (car narg0) (cdr narg0)
(tcons arg1 parg1) (car narg1) (cdr narg1)
congruences hyps relation suffix))))
(let ((hit (assoc arg0 congruences)))
(if (not hit) events
(let ((equiv (cadr hit)))
(let ((name (acl2::packn-pos (list equiv '- n '-implies- iff '- name suffix) name)))
(cons `(defthm ,name
(implies
,(if (and (not hyps) (not relation)) `(,equiv ,arg0 ,arg1)
`(and
,(or hyps t)
,(if relation (beta-reduce-lambda-term-full `(,relation ,@parg0 ,arg0 ,@narg0 ,@parg0 ,arg1 ,@narg0)) t)
(,equiv ,arg0 ,arg1)))
,(if (or hyps relation)
`(iff (,iff ,(beta-reduce-lambda-term-full `(,fn ,@vars ,@parg0 ,arg0 ,@narg0))
,(beta-reduce-lambda-term-full `(,fn ,@vars ,@parg0 ,arg1 ,@narg0))) t)
`(,iff ,(beta-reduce-lambda-term-full `(,fn ,@vars ,@parg0 ,arg0 ,@narg0))
,(beta-reduce-lambda-term-full `(,fn ,@vars ,@parg0 ,arg1 ,@narg0)))))
,@(and lemma
`(:hints (("Goal" :use (:instance ,lemma
,@(make-binding (append parg1 narg1)
(append parg0 narg0)))))))
,@(and (not hyps) (not relation) `(:rule-classes (:congruence))))
events)))))))
(local (in-theory (disable mv-nth)))
(defthm true-listp-make-congruences-rec
(true-listp (make-congruences-rec lemma fn name n iff vars parg0 arg0 narg0 parg1 arg1 narg1 congruences hyps relation suffix)))
(defun make-congruences (lemma fn name iff vars arg0 arg1 congruences hyps relation suffix)
(declare (type symbol name iff suffix)
(type (satisfies symbol-listp) vars arg0 arg1)
(type (satisfies good-congruence-listp) congruences))
(if (consp arg0)
(make-congruences-rec lemma fn name 1 iff vars nil (car arg0) (cdr arg0) nil (car arg1) (cdr arg1) congruences hyps relation suffix)
nil))
(defthm true-listp-make-congruences
(true-listp (make-congruences lemma fn name iff vars arg0 arg1 congruences hyps relation suffix)))
(in-theory (disable make-congruences))
(defun make-witness-congruences-rec (vars n lemma fn arg0 arg1 congruences hyps relation suffix)
(declare (type integer n)
(type symbol fn suffix)
(type (satisfies symbol-listp) arg0 arg1)
(type (satisfies good-congruence-listp) congruences)
(xargs :guard-debug t))
(if (not (consp vars)) nil
(let ((name (acl2::packn-pos (list 'mv-nth- n '- fn) fn)))
(let ((fn0 `(lambda (,@arg0) (mv-nth ,n (,fn ,@arg0)))))
(let ((events (make-congruences lemma fn0 name 'equal nil arg0 arg1 congruences hyps relation suffix)))
(append events (make-witness-congruences-rec (cdr vars) (1+ n) lemma fn arg0 arg1 congruences hyps relation suffix)))))))
(defthm true-listp-make-witness-congruences-rec
(true-listp (make-witness-congruences-rec vars n lemma fn arg0 arg1 congruences hyps relation suffix)))
(defun make-witness-congruences (vars lemma fn arg0 arg1 congruences hyps relation suffix)
(declare (type symbol fn suffix)
(type (satisfies symbol-listp) arg0 arg1)
(type (satisfies good-congruence-listp) congruences))
(if (and (consp vars) (null (cdr vars)))
(make-congruences lemma fn fn 'equal nil arg0 arg1 congruences hyps relation suffix)
(make-witness-congruences-rec vars 0 lemma fn arg0 arg1 congruences hyps relation suffix)))
(defthm true-listp-make-witness-congruences
(true-listp (make-witness-congruences vars lemma fn arg0 arg1 congruences hyps relation suffix)))
(in-theory (disable make-witness-congruences))
(defun all-congruences-apply-to-args (congruences args)
(declare (type (satisfies good-congruence-listp) congruences)
(type (satisfies symbol-listp) args))
(if (not (consp congruences)) t
(let ((congruence (car congruences)))
(let ((name (car congruence)))
(and (member-equal name args)
(all-congruences-apply-to-args (cdr congruences) args))))))
(local (in-theory (disable acl2::packn-pos make-congruences add-suffix lambda-term-p pseudo-termp string-append)))
(defun soft-alist (list)
(declare (type (satisfies alistp) list))
(if (not (consp list)) nil
(let ((entry (car list)))
(cons (list (car entry) (cdr entry))
(soft-alist (cdr list))))))
(defun all-equal-rec (x y)
(declare (type t x y))
(if (not (and (consp x) (consp y))) nil
(cons `(equal ,(car x) ,(car y))
(all-equal-rec (cdr x) (cdr y)))))
(defthm true-listp-all-equal-rec
(true-listp (all-equal-rec x y)))
(defun all-equal (x y)
(declare (type t x y))
(if (and (consp x) (null (cdr x))
(consp y) (null (cdr y)))
`(equal ,(car x) ,(car y))
`(and ,@(all-equal-rec x y))))
(in-theory (disable all-equal))
(defun prove-quantified-congruence-fn (name vars args args1 congruent-predicate hyps relation congruences quantifier suffix iff hints)
(declare (ignorable quantifier)
(type symbol name quantifier suffix)
(type (satisfies symbol-listp) vars args)
(type (satisfies symbol-listp) args1)
(type (satisfies pseudo-termp) congruent-predicate)
(type (satisfies good-congruence-listp) congruences)
(xargs :guard-debug t
:guard (and (or (not hyps) (pseudo-termp hyps))
(all-congruences-apply-to-args congruences args)
(or (not relation) (equal relation acl2::*nil*) (lambda-term-p relation)))))
(let* (;(x (acl2::packn-pos (list "X") name))
;(y (acl2::packn-pos (list "Y") name))
(hyps (if (not hyps) nil (if (equal hyps acl2::*nil*) nil hyps)))
(relation (if (not relation) nil (if (equal relation acl2::*nil*) nil relation)))
(relation-hyp (if (not relation) acl2::*t* (beta-reduce-lambda-term-full `(,relation ,@args ,@args1))))
(iff (if iff 'iff 'equal))
(suffix (if (equal suffix '||) suffix (acl2::packn-pos (list "-" suffix) suffix)))
(congruent-predicate-congruence (acl2::add-suffix name (concatenate 'acl2::string "-CONGRUENCE" (symbol-name suffix))))
(congruent-predicate-witness (acl2::add-suffix name "-WITNESS"))
(congruent-predicate-lemma (if (equal quantifier :exists) (acl2::add-suffix name "-SUFF") (acl2::add-suffix name "-NECC")))
(congruent-predicate-witness-congruence (acl2::add-suffix congruent-predicate-witness (concatenate 'acl2::string "-CONGRUENCE" (symbol-name suffix))))
(congruent-predicate-rule (acl2::add-suffix congruent-predicate-witness "-STRENGTHEN"))
;;(congruent-predicate-witness-canary (acl2::add-suffix congruent-predicate-witness "-CANARY"))
(congruent-predicate-raw `(lambda (,@vars ,@args) ,(beta-reduce-lambda-term-full congruent-predicate)))
;(congruent-predicate (if (equal quantifier :exists) congruent-predicate-raw `(lambda (,@vars ,@args) (not (,congruent-predicate-raw ,@vars ,@args)))))
;(a1 (acl2::packn-pos (list a 1) 'quant::prove-quantified-congruence-fn))
(local-congruent-predicate (acl2::packn-pos (list name '-congruent-predicate) 'quant::prove-quantified-congruence-fn))
(local-definition (acl2::packn-pos (list name '-definition) 'quant::prove-quantified-congruence-fn))
(congruent-predicate-equiv (acl2::packn-pos (list name '-equiv suffix) 'quant::prove-quantified-congruence-fn))
(congruent-predicate-quantified-x `(lambda (x) (,name ,@(into-args args 'x))))
(congruent-predicate-hyps-x `(lambda (x) ,(beta-reduce-lambda-term-full `((lambda (,@args) ,(or hyps acl2::*t*)) ,@(into-args args 'x)))))
(congruent-predicate-relation-x `(lambda (x y) ,(beta-reduce-lambda-term-full (if relation `(,relation ,@(into-args args 'x) ,@(into-args args 'y)) t))))
(congruent-predicate-equiv-x `(lambda (x y) (,congruent-predicate-equiv ,@(into-args args 'x) ,@(into-args args 'y))))
(congruent-predicate-x `(lambda (a x) (,local-congruent-predicate ,@(into-args vars 'a) ,@(into-args args 'x))))
(congruent-predicate-x-witness `(lambda (x) (list ,@(make-mv (len vars) `(,congruent-predicate-witness ,@(into-args args 'x))))))
(finst `((congruent-predicate-hyps ,congruent-predicate-hyps-x)
(congruent-predicate-relation ,congruent-predicate-relation-x)
(congruent-predicate-equiv ,congruent-predicate-equiv-x)
(congruent-predicate-witness ,congruent-predicate-x-witness)
(congruent-predicate ,congruent-predicate-x)
(congruent-predicate-quantified ,congruent-predicate-quantified-x)
(universally-quantified (lambda () ,(if (equal quantifier :exists) nil t)))))
)
`(encapsulate
()
(local (in-theory (disable nth)))
(local
(defun ,local-congruent-predicate (,@vars ,@args)
(declare (ignorable ,@vars ,@args))
,(beta-reduce-lambda-term-full `(,congruent-predicate-raw ,@vars ,@args))))
(defun ,congruent-predicate-equiv (,@args ,@args1)
(and ,@(make-equiv-body (pairlis$ args args1) congruences)))
(local
(defthm big-bang-congruence
(implies
(and
,(or hyps t)
,relation-hyp
(,congruent-predicate-equiv ,@args ,@args1))
(iff (iff-equiv (,local-congruent-predicate ,@vars ,@args)
(,local-congruent-predicate ,@vars ,@args1))
t))))
;; I honestly don't know if this helps .. what if we simply did the big-bang version?
;; (let ((events (make-congruences nil local-congruent-predicate local-congruent-predicate 'iff-equiv vars args args1 congruences hyps relation suffix)))
;; (and events `((local
;; (encapsulate
;; ()
;; ,@events
;; )))))
(local
(defthm ,local-definition
(equal (,name ,@args)
;; We will need to duplicate the witness here for multiple vars ..
(,local-congruent-predicate ,@(make-mv (len vars) `(,congruent-predicate-witness ,@args)) ,@args))
:hints (("Goal" :in-theory (enable ,name)))))
(local (in-theory (disable iff-equiv ,name ,local-congruent-predicate ,local-definition)))
(local
(defthm congruent-predicate-witness-canary
t
:rule-classes nil
:hints (("Goal" :use (:functional-instance congruent-predicate-canary
,@finst
))
(and stable-under-simplificationp
'(:in-theory (disable ,congruent-predicate-lemma)
:use ((:instance ,congruent-predicate-rule
,@(make-binding-out args args1 'x 'x1))
(:instance ,congruent-predicate-lemma
,@(soft-alist (pairlis$ vars (into-args vars 'a)))
,@(soft-alist (pairlis$ args (into-args args 'x)))))))
(and stable-under-simplificationp
'(:in-theory (enable ,local-definition)))
(and stable-under-simplificationp
'(:in-theory (enable ,local-congruent-predicate)))
)))
(defthm ,congruent-predicate-witness-congruence
(implies
(and
,(or hyps t)
,relation-hyp
(,congruent-predicate-equiv ,@args ,@args1))
,(all-equal (make-mv (len vars) `(,congruent-predicate-witness ,@args))
(make-mv (len vars) `(,congruent-predicate-witness ,@args1))))
:rule-classes nil
:hints (("Goal" :do-not-induct t
:use (:functional-instance (:instance congruent-predicate-witness-congruence
,@(make-binding-into 'x 'y args args1))
,@finst))
,@hints))
(defthm ,congruent-predicate-congruence
(implies
(and
,(or hyps t)
,relation-hyp
(,congruent-predicate-equiv ,@args ,@args1))
(,iff (,name ,@args)
(,name ,@args1)))
:rule-classes nil
:hints (("Goal" :do-not-induct t
:use (:functional-instance (:instance congruent-predicate-congruence
,@(make-binding-into 'x 'y args args1))
,@finst
))
,@hints))
(local (in-theory (union-theories '(,congruent-predicate-equiv) (theory 'acl2::minimal-theory))))
(local (in-theory (disable ,name)))
,@(make-witness-congruences vars congruent-predicate-witness-congruence congruent-predicate-witness args args1 congruences hyps relation suffix)
,@(make-congruences congruent-predicate-congruence name name iff nil args args1 congruences hyps relation suffix)
)))
(defun decompose-quantified-formula (expr)
(declare (type t expr))
(case-match expr
((`forall vars expr) (mv :forall vars expr))
((`exists vars expr) (mv :exists vars expr))
(& (mv nil nil expr))))
(defun acl2::pseudo-translate-lambda (fn fn-args-lst wrld)
(declare (xargs :mode :program))
(if (symbolp fn) (mv t fn nil)
(case-match fn
(('lambda args &)
(mv-let (flg term) (acl2::pseudo-translate `(,fn ,@args) fn-args-lst wrld)
(case-match term
((('lambda formals body) . &)
(mv flg `(lambda ,formals ,body) (nthcdr (len args) formals)))
(& (mv nil fn nil)))))
(& (mv nil fn nil)))))
(defmacro congruence (name args body &key (suffix '||) (hyps 'nil) (relation 'nil) (congruences 'nil) (iff 'nil) (hints 'nil))
(mv-let (quantifier vars congruent-predicate) (decompose-quantified-formula body)
`(make-event
(let ((name ',name)
(vars ',vars)
(args ',args)
(hyps ',hyps)
(relation ',relation)
(congruences ',congruences)
(suffix ',suffix)
(congruent-predicate ',congruent-predicate)
(quantifier ',quantifier)
(iff ',iff)
(hints ',hints)
)
(mv-let (flg congruent-predicate) (acl2::pseudo-translate congruent-predicate nil (w state))
(declare (ignore flg))
(mv-let (flg hyps) (acl2::pseudo-translate hyps nil (w state))
(declare (ignore flg))
(let ((args1 (acl2::generate-variable-lst-simple args (append vars args))))
(prove-quantified-congruence-fn name vars args args1 congruent-predicate hyps relation congruences quantifier suffix iff hints))))))
))
(local
(encapsulate
()
(defun my-member (a x)
(member a x))
(defun-sk fred (z)
(exists (a) (my-member a z))
:strengthen t)
(defun member-equalx (x y)
(equal x y))
(defun similar (x y)
(declare (ignore x y))
t)
(defequiv member-equalx)
(defcong member-equalx iff (my-member a x) 2)
(in-theory (disable my-member (my-member) member-equalx))
(quant::congruence fred (z)
(exists (a) (my-member a z))
:congruences ((z member-equalx))
;; In some cases, the congruence may only be conditional.
:hyps (true-listp z)
;; Or there may be additional relations that must hold
:relation (lambda (x y) (similar x y))
;; The quantified predicate may not be strictly Boolean
;; If that is so, set the :iff flag to t
:iff t
)
;; We don't actually get ACL2 congruence rules in this case
;; but we do get the following properties ..
(defthmd fred-witness-congruence-result1
(implies (and (true-listp z)
(similar z z1)
(member-equalx z z1))
(equal (fred-witness z)
(fred-witness z1)))
:hints (("goal" :use fred-witness-congruence)))
(defthm fred-congruence-result2
(implies (and (true-listp z)
(similar z z1)
(member-equalx z z1))
(iff (fred z) (fred z1)))
:hints (("goal" :use fred-congruence)))
))
(local
(encapsulate
()
(encapsulate
(
((deuce * * *) => *)
((deuce-equiv * *) => *)
)
(local
(defun deuce-equiv (x y)
(equal x y)))
(defequiv deuce-equiv)
(local
(defun deuce (a b x)
(declare (ignore a b x))
t))
(defthm booleanp-deuce
(booleanp (deuce a b x))
:rule-classes (:type-prescription))
(defcong deuce-equiv equal (deuce a b x) 3)
)
(encapsulate
()
;; We now support multiple quantified variables
(defun-sk existentially-quantified-deuce (z)
(exists (a b) (deuce a b z))
:strengthen t)
(quant::congruence existentially-quantified-deuce (z)
(exists (a b) (deuce a b z))
:congruences ((z deuce-equiv))
)
)
))
(local
(encapsulate
()
(encapsulate
(
((pred * * *) => *)
((pred-equiv * *) => *)
)
(local
(defun pred-equiv (x y)
(equal x y)))
(defequiv pred-equiv)
(local
(defun pred (a x y)
(declare (ignore a x y))
t))
(defthm booleanp-pred
(booleanp (pred a x y))
:rule-classes (:type-prescription))
(defcong pred-equiv equal (pred a x y) 2)
)
(local
(encapsulate
()
(local
(encapsulate
()
;; Existentially quantified
;; The :strengthen t argument is required.
(defun-sk existentially-quantified-pred (v z)
(exists (a) (pred a v z))
:strengthen t)
(quant::congruence existentially-quantified-pred (v z)
(exists (a) (pred a v z))
:congruences ((v pred-equiv))
)
;; The following congruences now follow naturally ..
(defthmd test1
(implies
(pred-equiv v1 v2)
(equal (existentially-quantified-pred-witness v1 z)
(existentially-quantified-pred-witness v2 z))))
(defthmd test2
(implies
(pred-equiv v1 v2)
(equal (existentially-quantified-pred v1 z)
(existentially-quantified-pred v2 z))))
))
))
(local
(encapsulate
()
(local
(encapsulate
()
;; Universally quantified
;; The :strengthen t argument is required.
(defun-sk universally-quantified-pred (v z)
(forall (a) (pred a v z))
:strengthen t)
(quant::congruence universally-quantified-pred (v z)
(forall (a) (pred a v z))
:iff t
:congruences ((v pred-equiv)))
;; The following congruences now follow naturally ..
(defthmd test1
(implies
(pred-equiv v1 v2)
(equal (universally-quantified-pred-witness v1 z)
(universally-quantified-pred-witness v2 z))))
(defthmd test2
(implies
(pred-equiv v1 v2)
(equal (universally-quantified-pred v1 z)
(universally-quantified-pred v2 z))))
))))
))
(acl2::defxdoc quant::congruence
:short "A macro to prove congruence rules for quantified formulae and their associated witnesses"
:parents (acl2::defun-sk)
:long "<p>
The @('quant::congruence') macro can be used to prove
@(tsee acl2::congruence) rules for quantified formulae and their associated
witnesses introduced using @(tsee acl2::defun-sk). Note: this macro only
works for formula that are introduced with the :strengthen t keyword.
</p>
<p>Usage:</p> @({
(include-book \"coi/quantification/quantified-congruence\" :dir :system)
;; Given a predicate that satisfies some congruence
(defcong pred-equiv equal (pred a x y) 2)
;; A quantified formula involving pred introduced using
;; defun-sk with the :strengthen t option.
(defun-sk quantified-pred (v z)
(forall (a) (pred a v z))
:strengthen t)
;; We prove congruence rules relative to 'v'
(quant::congruence quantified-pred (v z)
(forall (a) (pred a v z))
:congruences ((v pred-equiv)))
;; The following lemmas now follow directly ..
(defthmd witness-congruence
(implies
(pred-equiv v1 v2)
(equal (quantified-pred-witness v1 z)
(quantified-pred-witness v2 z))))
(defthmd quantified-congruence
(implies
(pred-equiv v1 v2)
(equal (quantified-pred v1 z)
(quantified-pred v2 z))))
})
")
|
36533
|
;;
;; Copyright (C) 2018, <NAME>
;; All rights reserved.
;;
;; This software may be modified and distributed under the terms
;; of the 3-clause BSD license. See the LICENSE file for details.
;;
;;
(in-package "QUANT")
(include-book "misc/beta-reduce" :dir :system)
(include-book "coi/util/pseudo-translate" :dir :system)
(include-book "xdoc/top" :dir :system)
(include-book "quantified-equivalence")
(defstub quantification-key-witness () nil)
(encapsulate
(
((congruent-predicate * *) => *)
((congruent-predicate-witness *) => *)
((universally-quantified) => *)
)
(local (defun universally-quantified ()
(quantification-key-witness)))
(local (defund congruent-predicate (x y) (equal x y)))
(local
(defun-sk forall-predicate (x)
(forall (a) (congruent-predicate a x))
:strengthen t))
(local
(defun-sk exists-predicate (x)
(exists (a) (congruent-predicate a x))
:strengthen t))
(local
(defun congruent-predicate-witness (x)
(if (universally-quantified) (forall-predicate-witness x)
(exists-predicate-witness x))))
(defthm existential-constraint
(implies
(not (universally-quantified))
(and (implies (congruent-predicate a x)
(congruent-predicate (congruent-predicate-witness x) x))
(or (equal (congruent-predicate-witness x)
(congruent-predicate-witness x1))
(let ((a (congruent-predicate-witness x)))
(and (congruent-predicate a x)
(not (let ((x x1))
(congruent-predicate a x)))))
(let ((a (congruent-predicate-witness x1)))
(and (let ((x x1)) (congruent-predicate a x))
(not (congruent-predicate a x)))))))
:hints (("goal" :use (exists-predicate-suff
exists-predicate-witness-strengthen))))
(defthm universal-constratint
(implies
(universally-quantified)
(and (implies (not (congruent-predicate a x))
(not (congruent-predicate (congruent-predicate-witness x) x)))
(or (equal (congruent-predicate-witness x)
(congruent-predicate-witness x1))
(let ((a (congruent-predicate-witness x)))
(and (not (congruent-predicate a x))
(not (let ((x x1))
(not (congruent-predicate a x))))))
(let ((a (congruent-predicate-witness x1)))
(and (let ((x x1))
(not (congruent-predicate a x)))
(not (not (congruent-predicate a x))))))))
:hints (("goal" :use (forall-predicate-necc
forall-predicate-witness-strengthen))))
)
(defun iff-equiv (x y)
(iff x y))
(defequiv iff-equiv)
(encapsulate
(
((congruent-predicate-hyps *) => *)
((congruent-predicate-relation * *) => *)
((congruent-predicate-equiv * *) => *)
)
(local (defun congruent-predicate-hyps (x) (declare (ignore x)) nil))
(local (defun congruent-predicate-relation (x y) (declare (ignore x y)) nil))
(local (defun congruent-predicate-equiv (x y) (equal x y)))
(defthm essential-congruence
(implies
(and
(congruent-predicate-hyps x)
(congruent-predicate-relation x y)
(congruent-predicate-equiv x y))
(iff-equiv (congruent-predicate a x)
(congruent-predicate a y))))
)
(defthm congruent-predicate-witness-congruence
(implies
(and
(congruent-predicate-hyps x)
(congruent-predicate-relation x y)
(congruent-predicate-equiv x y))
(equal (congruent-predicate-witness x)
(congruent-predicate-witness y)))
:hints (("Goal" :use ((:instance existential-constraint
(x1 y))
(:instance universal-constratint
(x1 y))
(:instance essential-congruence
(a (congruent-predicate-witness x)))
(:instance essential-congruence
(a (congruent-predicate-witness y)))))))
(defun congruent-predicate-quantified (x)
(congruent-predicate (congruent-predicate-witness x) x))
(defthm congruent-predicate-congruence
(implies
(and
(congruent-predicate-hyps x)
(congruent-predicate-relation x y)
(congruent-predicate-equiv x y))
(iff (congruent-predicate-quantified x)
(congruent-predicate-quantified y)))
:hints (("Subgoal 1" :use (:instance essential-congruence
(a (congruent-predicate-witness y))))
("subgoal 2" :use (:instance essential-congruence
(a (congruent-predicate-witness y))))))
(defthm congruent-predicate-canary
(list
(CONGRUENT-PREDICATE-QUANTIFIED X)
(CONGRUENT-PREDICATE-HYPS X)
(CONGRUENT-PREDICATE-RELATION X Y)
(CONGRUENT-PREDICATE-EQUIV X Y)
(CONGRUENT-PREDICATE-WITNESS X)
(CONGRUENT-PREDICATE A X)
(UNIVERSALLY-QUANTIFIED)
)
:rule-classes nil)
(defun number-symbol (x base)
(declare (type symbol x base))
(intern-in-package-of-symbol
(coerce
(acl2::packn1 (list x 1))
'string)
base))
(defthm symbolp-number-symbol
(implies
(and (symbolp x) (symbolp base))
(symbolp (number-symbol x base))))
(in-theory (disable number-symbol))
(local
(defthm symbol-listp-implies-true-listp
(implies
(symbol-listp list)
(true-listp list))
:rule-classes (:forward-chaining)))
(defun number-symbol-list (list base)
(declare (type (satisfies symbol-listp) list)
(type symbol base))
(if (not (consp list)) nil
(cons (number-symbol (car list) base)
(number-symbol-list (cdr list) base))))
(defthm symbol-listp-number-symbol-list
(implies
(and (symbol-listp x) (symbolp base))
(symbol-listp (number-symbol-list x base))))
(defun make-binding-out-rec (args args1 index x x1)
(declare (type integer index))
(if (not (and (consp args) (consp args1))) nil
(cons `(,(car args) (nth ,index ,x))
(cons `(,(car args1) (nth ,index ,x1))
(make-binding-out-rec (cdr args) (cdr args1) (1+ index) x x1)))))
(defthm true-listp-make-binding-out-rec
(true-listp (make-binding-out-rec args args1 index x x1)))
(defun make-binding-out (args args1 x x1)
(declare (type (satisfies symbol-listp) args args1))
(make-binding-out-rec args args1 0 x x1))
(defthm true-listp-make-binding-out
(true-listp (make-binding-out args args1 x x1)))
(in-theory (disable make-binding-out))
(defun make-binding-into (x x1 args args1)
(declare (type (satisfies symbol-listp) args args1))
`((,x (list ,@args))
(,x1 (list ,@args1))))
(defthm true-listp-make-binding-into
(true-listp (make-binding-into x x1 args args1)))
(in-theory (disable make-binding-into))
(defun lambda-term-p (term)
(declare (type t term))
(case-match term
(('lambda a ('declare &) b) (and (symbol-listp a)
(pseudo-termp b)))
(('lambda a b) (and (symbol-listp a)
(pseudo-termp b)))
(& (symbolp term))))
(defun into-args-rec (args index x)
(declare (type integer index))
(if (not (consp args)) nil
(cons `(nth ,index ,x)
(into-args-rec (cdr args) (1+ index) x))))
(defthm true-listp-into-args-rec
(true-listp (into-args-rec args index x)))
(defun into-args (args x)
(declare (type (satisfies symbol-listp) args))
(into-args-rec args 0 x))
(defun make-mv-rec (n index term)
(declare (type (integer 0 *) n index))
(if (zp n) nil
(cons `(mv-nth ,index ,term)
(make-mv-rec (1- n) (1+ index) term))))
(defthm true-listp-make-mv-rec
(true-listp (make-mv-rec args index x)))
(defun make-mv (n term)
(declare (type (integer 0 *) n))
(if (equal n 1)
(list term)
(make-mv-rec n 0 term)))
(defthm true-listp-make-mv
(true-listp (make-mv args x)))
(in-theory (disable make-mv))
(defthm true-listp-into-args
(true-listp (into-args args x)))
(in-theory (disable into-args))
(defthm open-nth
(equal (nth a (cons b x))
(if (zp a) b
(nth (1- a) x))))
(defun good-congruence-listp (list)
(declare (type t list))
(if (not (consp list)) (null list)
(let ((congruence (car list)))
(and (consp congruence)
(symbolp (car congruence))
(consp (cdr congruence))
(symbolp (cadr congruence))
(null (cddr congruence))
(good-congruence-listp (cdr list))))))
(defthm good-congruence-listp-implies-alistp
(implies
(good-congruence-listp list)
(alistp list))
:rule-classes (:forward-chaining))
(defthm assoc-good-congruence-listp
(implies
(and
(good-congruence-listp list)
(assoc-equal key list))
(and
(consp (assoc-equal key list))
(consp (cdr (assoc-equal key list)))
(symbolp (cadr (assoc-equal key list)))))
:rule-classes (:forward-chaining))
(defun symbol-pairlistp (pairlist)
(declare (type t pairlist))
(if (not (consp pairlist)) (null pairlist)
(let ((entry (car pairlist)))
(and (consp entry)
(symbolp (car entry))
(symbolp (cdr entry))
(symbol-pairlistp (cdr pairlist))))))
(defthm symbol-pairlistp-pairlis$
(implies
(and
(symbol-listp x)
(symbol-listp y))
(symbol-pairlistp (pairlis$ x y))))
(defun make-equiv-body (pairlist congruences)
(declare (type (satisfies good-congruence-listp) congruences)
(type (satisfies symbol-pairlistp) pairlist))
(if (not (consp pairlist)) nil
(let ((pair (car pairlist)))
(let ((arg1 (car pair))
(arg2 (cdr pair)))
(let ((hit (assoc arg1 congruences)))
(let ((equiv (if (not hit) `(equal ,arg1 ,arg2)
`(,(cadr hit) ,arg1 ,arg2))))
(cons equiv (make-equiv-body (cdr pairlist) congruences))))))))
(defun make-binding (keys vals)
(declare (type t keys vals))
(if (not (and (consp keys) (consp vals))) nil
(cons (list (car keys) (car vals))
(make-binding (cdr keys) (cdr vals)))))
(defun tcons (a list)
(declare (type t list))
(if (not (consp list)) (list a)
(cons (car list) (tcons a (cdr list)))))
(defun make-congruences-rec (lemma fn name n iff vars parg0 arg0 narg0 parg1 arg1 narg1 congruences hyps relation suffix)
(declare (xargs :ruler-extenders :all)
(type symbol name iff arg0 arg1 suffix)
(type integer n)
(type (satisfies symbol-listp) vars parg0 parg1 narg0 narg1)
(type (satisfies good-congruence-listp) congruences)
)
(let ((events (if (not (consp narg0)) nil
(make-congruences-rec lemma fn name (1+ n) iff vars
(tcons arg0 parg0) (car narg0) (cdr narg0)
(tcons arg1 parg1) (car narg1) (cdr narg1)
congruences hyps relation suffix))))
(let ((hit (assoc arg0 congruences)))
(if (not hit) events
(let ((equiv (cadr hit)))
(let ((name (acl2::packn-pos (list equiv '- n '-implies- iff '- name suffix) name)))
(cons `(defthm ,name
(implies
,(if (and (not hyps) (not relation)) `(,equiv ,arg0 ,arg1)
`(and
,(or hyps t)
,(if relation (beta-reduce-lambda-term-full `(,relation ,@parg0 ,arg0 ,@narg0 ,@parg0 ,arg1 ,@narg0)) t)
(,equiv ,arg0 ,arg1)))
,(if (or hyps relation)
`(iff (,iff ,(beta-reduce-lambda-term-full `(,fn ,@vars ,@parg0 ,arg0 ,@narg0))
,(beta-reduce-lambda-term-full `(,fn ,@vars ,@parg0 ,arg1 ,@narg0))) t)
`(,iff ,(beta-reduce-lambda-term-full `(,fn ,@vars ,@parg0 ,arg0 ,@narg0))
,(beta-reduce-lambda-term-full `(,fn ,@vars ,@parg0 ,arg1 ,@narg0)))))
,@(and lemma
`(:hints (("Goal" :use (:instance ,lemma
,@(make-binding (append parg1 narg1)
(append parg0 narg0)))))))
,@(and (not hyps) (not relation) `(:rule-classes (:congruence))))
events)))))))
(local (in-theory (disable mv-nth)))
(defthm true-listp-make-congruences-rec
(true-listp (make-congruences-rec lemma fn name n iff vars parg0 arg0 narg0 parg1 arg1 narg1 congruences hyps relation suffix)))
(defun make-congruences (lemma fn name iff vars arg0 arg1 congruences hyps relation suffix)
(declare (type symbol name iff suffix)
(type (satisfies symbol-listp) vars arg0 arg1)
(type (satisfies good-congruence-listp) congruences))
(if (consp arg0)
(make-congruences-rec lemma fn name 1 iff vars nil (car arg0) (cdr arg0) nil (car arg1) (cdr arg1) congruences hyps relation suffix)
nil))
(defthm true-listp-make-congruences
(true-listp (make-congruences lemma fn name iff vars arg0 arg1 congruences hyps relation suffix)))
(in-theory (disable make-congruences))
(defun make-witness-congruences-rec (vars n lemma fn arg0 arg1 congruences hyps relation suffix)
(declare (type integer n)
(type symbol fn suffix)
(type (satisfies symbol-listp) arg0 arg1)
(type (satisfies good-congruence-listp) congruences)
(xargs :guard-debug t))
(if (not (consp vars)) nil
(let ((name (acl2::packn-pos (list 'mv-nth- n '- fn) fn)))
(let ((fn0 `(lambda (,@arg0) (mv-nth ,n (,fn ,@arg0)))))
(let ((events (make-congruences lemma fn0 name 'equal nil arg0 arg1 congruences hyps relation suffix)))
(append events (make-witness-congruences-rec (cdr vars) (1+ n) lemma fn arg0 arg1 congruences hyps relation suffix)))))))
(defthm true-listp-make-witness-congruences-rec
(true-listp (make-witness-congruences-rec vars n lemma fn arg0 arg1 congruences hyps relation suffix)))
(defun make-witness-congruences (vars lemma fn arg0 arg1 congruences hyps relation suffix)
(declare (type symbol fn suffix)
(type (satisfies symbol-listp) arg0 arg1)
(type (satisfies good-congruence-listp) congruences))
(if (and (consp vars) (null (cdr vars)))
(make-congruences lemma fn fn 'equal nil arg0 arg1 congruences hyps relation suffix)
(make-witness-congruences-rec vars 0 lemma fn arg0 arg1 congruences hyps relation suffix)))
(defthm true-listp-make-witness-congruences
(true-listp (make-witness-congruences vars lemma fn arg0 arg1 congruences hyps relation suffix)))
(in-theory (disable make-witness-congruences))
(defun all-congruences-apply-to-args (congruences args)
(declare (type (satisfies good-congruence-listp) congruences)
(type (satisfies symbol-listp) args))
(if (not (consp congruences)) t
(let ((congruence (car congruences)))
(let ((name (car congruence)))
(and (member-equal name args)
(all-congruences-apply-to-args (cdr congruences) args))))))
(local (in-theory (disable acl2::packn-pos make-congruences add-suffix lambda-term-p pseudo-termp string-append)))
(defun soft-alist (list)
(declare (type (satisfies alistp) list))
(if (not (consp list)) nil
(let ((entry (car list)))
(cons (list (car entry) (cdr entry))
(soft-alist (cdr list))))))
(defun all-equal-rec (x y)
(declare (type t x y))
(if (not (and (consp x) (consp y))) nil
(cons `(equal ,(car x) ,(car y))
(all-equal-rec (cdr x) (cdr y)))))
(defthm true-listp-all-equal-rec
(true-listp (all-equal-rec x y)))
(defun all-equal (x y)
(declare (type t x y))
(if (and (consp x) (null (cdr x))
(consp y) (null (cdr y)))
`(equal ,(car x) ,(car y))
`(and ,@(all-equal-rec x y))))
(in-theory (disable all-equal))
(defun prove-quantified-congruence-fn (name vars args args1 congruent-predicate hyps relation congruences quantifier suffix iff hints)
(declare (ignorable quantifier)
(type symbol name quantifier suffix)
(type (satisfies symbol-listp) vars args)
(type (satisfies symbol-listp) args1)
(type (satisfies pseudo-termp) congruent-predicate)
(type (satisfies good-congruence-listp) congruences)
(xargs :guard-debug t
:guard (and (or (not hyps) (pseudo-termp hyps))
(all-congruences-apply-to-args congruences args)
(or (not relation) (equal relation acl2::*nil*) (lambda-term-p relation)))))
(let* (;(x (acl2::packn-pos (list "X") name))
;(y (acl2::packn-pos (list "Y") name))
(hyps (if (not hyps) nil (if (equal hyps acl2::*nil*) nil hyps)))
(relation (if (not relation) nil (if (equal relation acl2::*nil*) nil relation)))
(relation-hyp (if (not relation) acl2::*t* (beta-reduce-lambda-term-full `(,relation ,@args ,@args1))))
(iff (if iff 'iff 'equal))
(suffix (if (equal suffix '||) suffix (acl2::packn-pos (list "-" suffix) suffix)))
(congruent-predicate-congruence (acl2::add-suffix name (concatenate 'acl2::string "-CONGRUENCE" (symbol-name suffix))))
(congruent-predicate-witness (acl2::add-suffix name "-WITNESS"))
(congruent-predicate-lemma (if (equal quantifier :exists) (acl2::add-suffix name "-SUFF") (acl2::add-suffix name "-NECC")))
(congruent-predicate-witness-congruence (acl2::add-suffix congruent-predicate-witness (concatenate 'acl2::string "-CONGRUENCE" (symbol-name suffix))))
(congruent-predicate-rule (acl2::add-suffix congruent-predicate-witness "-STRENGTHEN"))
;;(congruent-predicate-witness-canary (acl2::add-suffix congruent-predicate-witness "-CANARY"))
(congruent-predicate-raw `(lambda (,@vars ,@args) ,(beta-reduce-lambda-term-full congruent-predicate)))
;(congruent-predicate (if (equal quantifier :exists) congruent-predicate-raw `(lambda (,@vars ,@args) (not (,congruent-predicate-raw ,@vars ,@args)))))
;(a1 (acl2::packn-pos (list a 1) 'quant::prove-quantified-congruence-fn))
(local-congruent-predicate (acl2::packn-pos (list name '-congruent-predicate) 'quant::prove-quantified-congruence-fn))
(local-definition (acl2::packn-pos (list name '-definition) 'quant::prove-quantified-congruence-fn))
(congruent-predicate-equiv (acl2::packn-pos (list name '-equiv suffix) 'quant::prove-quantified-congruence-fn))
(congruent-predicate-quantified-x `(lambda (x) (,name ,@(into-args args 'x))))
(congruent-predicate-hyps-x `(lambda (x) ,(beta-reduce-lambda-term-full `((lambda (,@args) ,(or hyps acl2::*t*)) ,@(into-args args 'x)))))
(congruent-predicate-relation-x `(lambda (x y) ,(beta-reduce-lambda-term-full (if relation `(,relation ,@(into-args args 'x) ,@(into-args args 'y)) t))))
(congruent-predicate-equiv-x `(lambda (x y) (,congruent-predicate-equiv ,@(into-args args 'x) ,@(into-args args 'y))))
(congruent-predicate-x `(lambda (a x) (,local-congruent-predicate ,@(into-args vars 'a) ,@(into-args args 'x))))
(congruent-predicate-x-witness `(lambda (x) (list ,@(make-mv (len vars) `(,congruent-predicate-witness ,@(into-args args 'x))))))
(finst `((congruent-predicate-hyps ,congruent-predicate-hyps-x)
(congruent-predicate-relation ,congruent-predicate-relation-x)
(congruent-predicate-equiv ,congruent-predicate-equiv-x)
(congruent-predicate-witness ,congruent-predicate-x-witness)
(congruent-predicate ,congruent-predicate-x)
(congruent-predicate-quantified ,congruent-predicate-quantified-x)
(universally-quantified (lambda () ,(if (equal quantifier :exists) nil t)))))
)
`(encapsulate
()
(local (in-theory (disable nth)))
(local
(defun ,local-congruent-predicate (,@vars ,@args)
(declare (ignorable ,@vars ,@args))
,(beta-reduce-lambda-term-full `(,congruent-predicate-raw ,@vars ,@args))))
(defun ,congruent-predicate-equiv (,@args ,@args1)
(and ,@(make-equiv-body (pairlis$ args args1) congruences)))
(local
(defthm big-bang-congruence
(implies
(and
,(or hyps t)
,relation-hyp
(,congruent-predicate-equiv ,@args ,@args1))
(iff (iff-equiv (,local-congruent-predicate ,@vars ,@args)
(,local-congruent-predicate ,@vars ,@args1))
t))))
;; I honestly don't know if this helps .. what if we simply did the big-bang version?
;; (let ((events (make-congruences nil local-congruent-predicate local-congruent-predicate 'iff-equiv vars args args1 congruences hyps relation suffix)))
;; (and events `((local
;; (encapsulate
;; ()
;; ,@events
;; )))))
(local
(defthm ,local-definition
(equal (,name ,@args)
;; We will need to duplicate the witness here for multiple vars ..
(,local-congruent-predicate ,@(make-mv (len vars) `(,congruent-predicate-witness ,@args)) ,@args))
:hints (("Goal" :in-theory (enable ,name)))))
(local (in-theory (disable iff-equiv ,name ,local-congruent-predicate ,local-definition)))
(local
(defthm congruent-predicate-witness-canary
t
:rule-classes nil
:hints (("Goal" :use (:functional-instance congruent-predicate-canary
,@finst
))
(and stable-under-simplificationp
'(:in-theory (disable ,congruent-predicate-lemma)
:use ((:instance ,congruent-predicate-rule
,@(make-binding-out args args1 'x 'x1))
(:instance ,congruent-predicate-lemma
,@(soft-alist (pairlis$ vars (into-args vars 'a)))
,@(soft-alist (pairlis$ args (into-args args 'x)))))))
(and stable-under-simplificationp
'(:in-theory (enable ,local-definition)))
(and stable-under-simplificationp
'(:in-theory (enable ,local-congruent-predicate)))
)))
(defthm ,congruent-predicate-witness-congruence
(implies
(and
,(or hyps t)
,relation-hyp
(,congruent-predicate-equiv ,@args ,@args1))
,(all-equal (make-mv (len vars) `(,congruent-predicate-witness ,@args))
(make-mv (len vars) `(,congruent-predicate-witness ,@args1))))
:rule-classes nil
:hints (("Goal" :do-not-induct t
:use (:functional-instance (:instance congruent-predicate-witness-congruence
,@(make-binding-into 'x 'y args args1))
,@finst))
,@hints))
(defthm ,congruent-predicate-congruence
(implies
(and
,(or hyps t)
,relation-hyp
(,congruent-predicate-equiv ,@args ,@args1))
(,iff (,name ,@args)
(,name ,@args1)))
:rule-classes nil
:hints (("Goal" :do-not-induct t
:use (:functional-instance (:instance congruent-predicate-congruence
,@(make-binding-into 'x 'y args args1))
,@finst
))
,@hints))
(local (in-theory (union-theories '(,congruent-predicate-equiv) (theory 'acl2::minimal-theory))))
(local (in-theory (disable ,name)))
,@(make-witness-congruences vars congruent-predicate-witness-congruence congruent-predicate-witness args args1 congruences hyps relation suffix)
,@(make-congruences congruent-predicate-congruence name name iff nil args args1 congruences hyps relation suffix)
)))
(defun decompose-quantified-formula (expr)
(declare (type t expr))
(case-match expr
((`forall vars expr) (mv :forall vars expr))
((`exists vars expr) (mv :exists vars expr))
(& (mv nil nil expr))))
(defun acl2::pseudo-translate-lambda (fn fn-args-lst wrld)
(declare (xargs :mode :program))
(if (symbolp fn) (mv t fn nil)
(case-match fn
(('lambda args &)
(mv-let (flg term) (acl2::pseudo-translate `(,fn ,@args) fn-args-lst wrld)
(case-match term
((('lambda formals body) . &)
(mv flg `(lambda ,formals ,body) (nthcdr (len args) formals)))
(& (mv nil fn nil)))))
(& (mv nil fn nil)))))
(defmacro congruence (name args body &key (suffix '||) (hyps 'nil) (relation 'nil) (congruences 'nil) (iff 'nil) (hints 'nil))
(mv-let (quantifier vars congruent-predicate) (decompose-quantified-formula body)
`(make-event
(let ((name ',name)
(vars ',vars)
(args ',args)
(hyps ',hyps)
(relation ',relation)
(congruences ',congruences)
(suffix ',suffix)
(congruent-predicate ',congruent-predicate)
(quantifier ',quantifier)
(iff ',iff)
(hints ',hints)
)
(mv-let (flg congruent-predicate) (acl2::pseudo-translate congruent-predicate nil (w state))
(declare (ignore flg))
(mv-let (flg hyps) (acl2::pseudo-translate hyps nil (w state))
(declare (ignore flg))
(let ((args1 (acl2::generate-variable-lst-simple args (append vars args))))
(prove-quantified-congruence-fn name vars args args1 congruent-predicate hyps relation congruences quantifier suffix iff hints))))))
))
(local
(encapsulate
()
(defun my-member (a x)
(member a x))
(defun-sk fred (z)
(exists (a) (my-member a z))
:strengthen t)
(defun member-equalx (x y)
(equal x y))
(defun similar (x y)
(declare (ignore x y))
t)
(defequiv member-equalx)
(defcong member-equalx iff (my-member a x) 2)
(in-theory (disable my-member (my-member) member-equalx))
(quant::congruence fred (z)
(exists (a) (my-member a z))
:congruences ((z member-equalx))
;; In some cases, the congruence may only be conditional.
:hyps (true-listp z)
;; Or there may be additional relations that must hold
:relation (lambda (x y) (similar x y))
;; The quantified predicate may not be strictly Boolean
;; If that is so, set the :iff flag to t
:iff t
)
;; We don't actually get ACL2 congruence rules in this case
;; but we do get the following properties ..
(defthmd fred-witness-congruence-result1
(implies (and (true-listp z)
(similar z z1)
(member-equalx z z1))
(equal (fred-witness z)
(fred-witness z1)))
:hints (("goal" :use fred-witness-congruence)))
(defthm fred-congruence-result2
(implies (and (true-listp z)
(similar z z1)
(member-equalx z z1))
(iff (fred z) (fred z1)))
:hints (("goal" :use fred-congruence)))
))
(local
(encapsulate
()
(encapsulate
(
((deuce * * *) => *)
((deuce-equiv * *) => *)
)
(local
(defun deuce-equiv (x y)
(equal x y)))
(defequiv deuce-equiv)
(local
(defun deuce (a b x)
(declare (ignore a b x))
t))
(defthm booleanp-deuce
(booleanp (deuce a b x))
:rule-classes (:type-prescription))
(defcong deuce-equiv equal (deuce a b x) 3)
)
(encapsulate
()
;; We now support multiple quantified variables
(defun-sk existentially-quantified-deuce (z)
(exists (a b) (deuce a b z))
:strengthen t)
(quant::congruence existentially-quantified-deuce (z)
(exists (a b) (deuce a b z))
:congruences ((z deuce-equiv))
)
)
))
(local
(encapsulate
()
(encapsulate
(
((pred * * *) => *)
((pred-equiv * *) => *)
)
(local
(defun pred-equiv (x y)
(equal x y)))
(defequiv pred-equiv)
(local
(defun pred (a x y)
(declare (ignore a x y))
t))
(defthm booleanp-pred
(booleanp (pred a x y))
:rule-classes (:type-prescription))
(defcong pred-equiv equal (pred a x y) 2)
)
(local
(encapsulate
()
(local
(encapsulate
()
;; Existentially quantified
;; The :strengthen t argument is required.
(defun-sk existentially-quantified-pred (v z)
(exists (a) (pred a v z))
:strengthen t)
(quant::congruence existentially-quantified-pred (v z)
(exists (a) (pred a v z))
:congruences ((v pred-equiv))
)
;; The following congruences now follow naturally ..
(defthmd test1
(implies
(pred-equiv v1 v2)
(equal (existentially-quantified-pred-witness v1 z)
(existentially-quantified-pred-witness v2 z))))
(defthmd test2
(implies
(pred-equiv v1 v2)
(equal (existentially-quantified-pred v1 z)
(existentially-quantified-pred v2 z))))
))
))
(local
(encapsulate
()
(local
(encapsulate
()
;; Universally quantified
;; The :strengthen t argument is required.
(defun-sk universally-quantified-pred (v z)
(forall (a) (pred a v z))
:strengthen t)
(quant::congruence universally-quantified-pred (v z)
(forall (a) (pred a v z))
:iff t
:congruences ((v pred-equiv)))
;; The following congruences now follow naturally ..
(defthmd test1
(implies
(pred-equiv v1 v2)
(equal (universally-quantified-pred-witness v1 z)
(universally-quantified-pred-witness v2 z))))
(defthmd test2
(implies
(pred-equiv v1 v2)
(equal (universally-quantified-pred v1 z)
(universally-quantified-pred v2 z))))
))))
))
(acl2::defxdoc quant::congruence
:short "A macro to prove congruence rules for quantified formulae and their associated witnesses"
:parents (acl2::defun-sk)
:long "<p>
The @('quant::congruence') macro can be used to prove
@(tsee acl2::congruence) rules for quantified formulae and their associated
witnesses introduced using @(tsee acl2::defun-sk). Note: this macro only
works for formula that are introduced with the :strengthen t keyword.
</p>
<p>Usage:</p> @({
(include-book \"coi/quantification/quantified-congruence\" :dir :system)
;; Given a predicate that satisfies some congruence
(defcong pred-equiv equal (pred a x y) 2)
;; A quantified formula involving pred introduced using
;; defun-sk with the :strengthen t option.
(defun-sk quantified-pred (v z)
(forall (a) (pred a v z))
:strengthen t)
;; We prove congruence rules relative to 'v'
(quant::congruence quantified-pred (v z)
(forall (a) (pred a v z))
:congruences ((v pred-equiv)))
;; The following lemmas now follow directly ..
(defthmd witness-congruence
(implies
(pred-equiv v1 v2)
(equal (quantified-pred-witness v1 z)
(quantified-pred-witness v2 z))))
(defthmd quantified-congruence
(implies
(pred-equiv v1 v2)
(equal (quantified-pred v1 z)
(quantified-pred v2 z))))
})
")
| true |
;;
;; Copyright (C) 2018, PI:NAME:<NAME>END_PI
;; All rights reserved.
;;
;; This software may be modified and distributed under the terms
;; of the 3-clause BSD license. See the LICENSE file for details.
;;
;;
(in-package "QUANT")
(include-book "misc/beta-reduce" :dir :system)
(include-book "coi/util/pseudo-translate" :dir :system)
(include-book "xdoc/top" :dir :system)
(include-book "quantified-equivalence")
(defstub quantification-key-witness () nil)
(encapsulate
(
((congruent-predicate * *) => *)
((congruent-predicate-witness *) => *)
((universally-quantified) => *)
)
(local (defun universally-quantified ()
(quantification-key-witness)))
(local (defund congruent-predicate (x y) (equal x y)))
(local
(defun-sk forall-predicate (x)
(forall (a) (congruent-predicate a x))
:strengthen t))
(local
(defun-sk exists-predicate (x)
(exists (a) (congruent-predicate a x))
:strengthen t))
(local
(defun congruent-predicate-witness (x)
(if (universally-quantified) (forall-predicate-witness x)
(exists-predicate-witness x))))
(defthm existential-constraint
(implies
(not (universally-quantified))
(and (implies (congruent-predicate a x)
(congruent-predicate (congruent-predicate-witness x) x))
(or (equal (congruent-predicate-witness x)
(congruent-predicate-witness x1))
(let ((a (congruent-predicate-witness x)))
(and (congruent-predicate a x)
(not (let ((x x1))
(congruent-predicate a x)))))
(let ((a (congruent-predicate-witness x1)))
(and (let ((x x1)) (congruent-predicate a x))
(not (congruent-predicate a x)))))))
:hints (("goal" :use (exists-predicate-suff
exists-predicate-witness-strengthen))))
(defthm universal-constratint
(implies
(universally-quantified)
(and (implies (not (congruent-predicate a x))
(not (congruent-predicate (congruent-predicate-witness x) x)))
(or (equal (congruent-predicate-witness x)
(congruent-predicate-witness x1))
(let ((a (congruent-predicate-witness x)))
(and (not (congruent-predicate a x))
(not (let ((x x1))
(not (congruent-predicate a x))))))
(let ((a (congruent-predicate-witness x1)))
(and (let ((x x1))
(not (congruent-predicate a x)))
(not (not (congruent-predicate a x))))))))
:hints (("goal" :use (forall-predicate-necc
forall-predicate-witness-strengthen))))
)
(defun iff-equiv (x y)
(iff x y))
(defequiv iff-equiv)
(encapsulate
(
((congruent-predicate-hyps *) => *)
((congruent-predicate-relation * *) => *)
((congruent-predicate-equiv * *) => *)
)
(local (defun congruent-predicate-hyps (x) (declare (ignore x)) nil))
(local (defun congruent-predicate-relation (x y) (declare (ignore x y)) nil))
(local (defun congruent-predicate-equiv (x y) (equal x y)))
(defthm essential-congruence
(implies
(and
(congruent-predicate-hyps x)
(congruent-predicate-relation x y)
(congruent-predicate-equiv x y))
(iff-equiv (congruent-predicate a x)
(congruent-predicate a y))))
)
(defthm congruent-predicate-witness-congruence
(implies
(and
(congruent-predicate-hyps x)
(congruent-predicate-relation x y)
(congruent-predicate-equiv x y))
(equal (congruent-predicate-witness x)
(congruent-predicate-witness y)))
:hints (("Goal" :use ((:instance existential-constraint
(x1 y))
(:instance universal-constratint
(x1 y))
(:instance essential-congruence
(a (congruent-predicate-witness x)))
(:instance essential-congruence
(a (congruent-predicate-witness y)))))))
(defun congruent-predicate-quantified (x)
(congruent-predicate (congruent-predicate-witness x) x))
(defthm congruent-predicate-congruence
(implies
(and
(congruent-predicate-hyps x)
(congruent-predicate-relation x y)
(congruent-predicate-equiv x y))
(iff (congruent-predicate-quantified x)
(congruent-predicate-quantified y)))
:hints (("Subgoal 1" :use (:instance essential-congruence
(a (congruent-predicate-witness y))))
("subgoal 2" :use (:instance essential-congruence
(a (congruent-predicate-witness y))))))
(defthm congruent-predicate-canary
(list
(CONGRUENT-PREDICATE-QUANTIFIED X)
(CONGRUENT-PREDICATE-HYPS X)
(CONGRUENT-PREDICATE-RELATION X Y)
(CONGRUENT-PREDICATE-EQUIV X Y)
(CONGRUENT-PREDICATE-WITNESS X)
(CONGRUENT-PREDICATE A X)
(UNIVERSALLY-QUANTIFIED)
)
:rule-classes nil)
(defun number-symbol (x base)
(declare (type symbol x base))
(intern-in-package-of-symbol
(coerce
(acl2::packn1 (list x 1))
'string)
base))
(defthm symbolp-number-symbol
(implies
(and (symbolp x) (symbolp base))
(symbolp (number-symbol x base))))
(in-theory (disable number-symbol))
(local
(defthm symbol-listp-implies-true-listp
(implies
(symbol-listp list)
(true-listp list))
:rule-classes (:forward-chaining)))
(defun number-symbol-list (list base)
(declare (type (satisfies symbol-listp) list)
(type symbol base))
(if (not (consp list)) nil
(cons (number-symbol (car list) base)
(number-symbol-list (cdr list) base))))
(defthm symbol-listp-number-symbol-list
(implies
(and (symbol-listp x) (symbolp base))
(symbol-listp (number-symbol-list x base))))
(defun make-binding-out-rec (args args1 index x x1)
(declare (type integer index))
(if (not (and (consp args) (consp args1))) nil
(cons `(,(car args) (nth ,index ,x))
(cons `(,(car args1) (nth ,index ,x1))
(make-binding-out-rec (cdr args) (cdr args1) (1+ index) x x1)))))
(defthm true-listp-make-binding-out-rec
(true-listp (make-binding-out-rec args args1 index x x1)))
(defun make-binding-out (args args1 x x1)
(declare (type (satisfies symbol-listp) args args1))
(make-binding-out-rec args args1 0 x x1))
(defthm true-listp-make-binding-out
(true-listp (make-binding-out args args1 x x1)))
(in-theory (disable make-binding-out))
(defun make-binding-into (x x1 args args1)
(declare (type (satisfies symbol-listp) args args1))
`((,x (list ,@args))
(,x1 (list ,@args1))))
(defthm true-listp-make-binding-into
(true-listp (make-binding-into x x1 args args1)))
(in-theory (disable make-binding-into))
(defun lambda-term-p (term)
(declare (type t term))
(case-match term
(('lambda a ('declare &) b) (and (symbol-listp a)
(pseudo-termp b)))
(('lambda a b) (and (symbol-listp a)
(pseudo-termp b)))
(& (symbolp term))))
(defun into-args-rec (args index x)
(declare (type integer index))
(if (not (consp args)) nil
(cons `(nth ,index ,x)
(into-args-rec (cdr args) (1+ index) x))))
(defthm true-listp-into-args-rec
(true-listp (into-args-rec args index x)))
(defun into-args (args x)
(declare (type (satisfies symbol-listp) args))
(into-args-rec args 0 x))
(defun make-mv-rec (n index term)
(declare (type (integer 0 *) n index))
(if (zp n) nil
(cons `(mv-nth ,index ,term)
(make-mv-rec (1- n) (1+ index) term))))
(defthm true-listp-make-mv-rec
(true-listp (make-mv-rec args index x)))
(defun make-mv (n term)
(declare (type (integer 0 *) n))
(if (equal n 1)
(list term)
(make-mv-rec n 0 term)))
(defthm true-listp-make-mv
(true-listp (make-mv args x)))
(in-theory (disable make-mv))
(defthm true-listp-into-args
(true-listp (into-args args x)))
(in-theory (disable into-args))
(defthm open-nth
(equal (nth a (cons b x))
(if (zp a) b
(nth (1- a) x))))
(defun good-congruence-listp (list)
(declare (type t list))
(if (not (consp list)) (null list)
(let ((congruence (car list)))
(and (consp congruence)
(symbolp (car congruence))
(consp (cdr congruence))
(symbolp (cadr congruence))
(null (cddr congruence))
(good-congruence-listp (cdr list))))))
(defthm good-congruence-listp-implies-alistp
(implies
(good-congruence-listp list)
(alistp list))
:rule-classes (:forward-chaining))
(defthm assoc-good-congruence-listp
(implies
(and
(good-congruence-listp list)
(assoc-equal key list))
(and
(consp (assoc-equal key list))
(consp (cdr (assoc-equal key list)))
(symbolp (cadr (assoc-equal key list)))))
:rule-classes (:forward-chaining))
(defun symbol-pairlistp (pairlist)
(declare (type t pairlist))
(if (not (consp pairlist)) (null pairlist)
(let ((entry (car pairlist)))
(and (consp entry)
(symbolp (car entry))
(symbolp (cdr entry))
(symbol-pairlistp (cdr pairlist))))))
(defthm symbol-pairlistp-pairlis$
(implies
(and
(symbol-listp x)
(symbol-listp y))
(symbol-pairlistp (pairlis$ x y))))
(defun make-equiv-body (pairlist congruences)
(declare (type (satisfies good-congruence-listp) congruences)
(type (satisfies symbol-pairlistp) pairlist))
(if (not (consp pairlist)) nil
(let ((pair (car pairlist)))
(let ((arg1 (car pair))
(arg2 (cdr pair)))
(let ((hit (assoc arg1 congruences)))
(let ((equiv (if (not hit) `(equal ,arg1 ,arg2)
`(,(cadr hit) ,arg1 ,arg2))))
(cons equiv (make-equiv-body (cdr pairlist) congruences))))))))
(defun make-binding (keys vals)
(declare (type t keys vals))
(if (not (and (consp keys) (consp vals))) nil
(cons (list (car keys) (car vals))
(make-binding (cdr keys) (cdr vals)))))
(defun tcons (a list)
(declare (type t list))
(if (not (consp list)) (list a)
(cons (car list) (tcons a (cdr list)))))
(defun make-congruences-rec (lemma fn name n iff vars parg0 arg0 narg0 parg1 arg1 narg1 congruences hyps relation suffix)
(declare (xargs :ruler-extenders :all)
(type symbol name iff arg0 arg1 suffix)
(type integer n)
(type (satisfies symbol-listp) vars parg0 parg1 narg0 narg1)
(type (satisfies good-congruence-listp) congruences)
)
(let ((events (if (not (consp narg0)) nil
(make-congruences-rec lemma fn name (1+ n) iff vars
(tcons arg0 parg0) (car narg0) (cdr narg0)
(tcons arg1 parg1) (car narg1) (cdr narg1)
congruences hyps relation suffix))))
(let ((hit (assoc arg0 congruences)))
(if (not hit) events
(let ((equiv (cadr hit)))
(let ((name (acl2::packn-pos (list equiv '- n '-implies- iff '- name suffix) name)))
(cons `(defthm ,name
(implies
,(if (and (not hyps) (not relation)) `(,equiv ,arg0 ,arg1)
`(and
,(or hyps t)
,(if relation (beta-reduce-lambda-term-full `(,relation ,@parg0 ,arg0 ,@narg0 ,@parg0 ,arg1 ,@narg0)) t)
(,equiv ,arg0 ,arg1)))
,(if (or hyps relation)
`(iff (,iff ,(beta-reduce-lambda-term-full `(,fn ,@vars ,@parg0 ,arg0 ,@narg0))
,(beta-reduce-lambda-term-full `(,fn ,@vars ,@parg0 ,arg1 ,@narg0))) t)
`(,iff ,(beta-reduce-lambda-term-full `(,fn ,@vars ,@parg0 ,arg0 ,@narg0))
,(beta-reduce-lambda-term-full `(,fn ,@vars ,@parg0 ,arg1 ,@narg0)))))
,@(and lemma
`(:hints (("Goal" :use (:instance ,lemma
,@(make-binding (append parg1 narg1)
(append parg0 narg0)))))))
,@(and (not hyps) (not relation) `(:rule-classes (:congruence))))
events)))))))
(local (in-theory (disable mv-nth)))
(defthm true-listp-make-congruences-rec
(true-listp (make-congruences-rec lemma fn name n iff vars parg0 arg0 narg0 parg1 arg1 narg1 congruences hyps relation suffix)))
(defun make-congruences (lemma fn name iff vars arg0 arg1 congruences hyps relation suffix)
(declare (type symbol name iff suffix)
(type (satisfies symbol-listp) vars arg0 arg1)
(type (satisfies good-congruence-listp) congruences))
(if (consp arg0)
(make-congruences-rec lemma fn name 1 iff vars nil (car arg0) (cdr arg0) nil (car arg1) (cdr arg1) congruences hyps relation suffix)
nil))
(defthm true-listp-make-congruences
(true-listp (make-congruences lemma fn name iff vars arg0 arg1 congruences hyps relation suffix)))
(in-theory (disable make-congruences))
(defun make-witness-congruences-rec (vars n lemma fn arg0 arg1 congruences hyps relation suffix)
(declare (type integer n)
(type symbol fn suffix)
(type (satisfies symbol-listp) arg0 arg1)
(type (satisfies good-congruence-listp) congruences)
(xargs :guard-debug t))
(if (not (consp vars)) nil
(let ((name (acl2::packn-pos (list 'mv-nth- n '- fn) fn)))
(let ((fn0 `(lambda (,@arg0) (mv-nth ,n (,fn ,@arg0)))))
(let ((events (make-congruences lemma fn0 name 'equal nil arg0 arg1 congruences hyps relation suffix)))
(append events (make-witness-congruences-rec (cdr vars) (1+ n) lemma fn arg0 arg1 congruences hyps relation suffix)))))))
(defthm true-listp-make-witness-congruences-rec
(true-listp (make-witness-congruences-rec vars n lemma fn arg0 arg1 congruences hyps relation suffix)))
(defun make-witness-congruences (vars lemma fn arg0 arg1 congruences hyps relation suffix)
(declare (type symbol fn suffix)
(type (satisfies symbol-listp) arg0 arg1)
(type (satisfies good-congruence-listp) congruences))
(if (and (consp vars) (null (cdr vars)))
(make-congruences lemma fn fn 'equal nil arg0 arg1 congruences hyps relation suffix)
(make-witness-congruences-rec vars 0 lemma fn arg0 arg1 congruences hyps relation suffix)))
(defthm true-listp-make-witness-congruences
(true-listp (make-witness-congruences vars lemma fn arg0 arg1 congruences hyps relation suffix)))
(in-theory (disable make-witness-congruences))
(defun all-congruences-apply-to-args (congruences args)
(declare (type (satisfies good-congruence-listp) congruences)
(type (satisfies symbol-listp) args))
(if (not (consp congruences)) t
(let ((congruence (car congruences)))
(let ((name (car congruence)))
(and (member-equal name args)
(all-congruences-apply-to-args (cdr congruences) args))))))
(local (in-theory (disable acl2::packn-pos make-congruences add-suffix lambda-term-p pseudo-termp string-append)))
(defun soft-alist (list)
(declare (type (satisfies alistp) list))
(if (not (consp list)) nil
(let ((entry (car list)))
(cons (list (car entry) (cdr entry))
(soft-alist (cdr list))))))
(defun all-equal-rec (x y)
(declare (type t x y))
(if (not (and (consp x) (consp y))) nil
(cons `(equal ,(car x) ,(car y))
(all-equal-rec (cdr x) (cdr y)))))
(defthm true-listp-all-equal-rec
(true-listp (all-equal-rec x y)))
(defun all-equal (x y)
(declare (type t x y))
(if (and (consp x) (null (cdr x))
(consp y) (null (cdr y)))
`(equal ,(car x) ,(car y))
`(and ,@(all-equal-rec x y))))
(in-theory (disable all-equal))
(defun prove-quantified-congruence-fn (name vars args args1 congruent-predicate hyps relation congruences quantifier suffix iff hints)
(declare (ignorable quantifier)
(type symbol name quantifier suffix)
(type (satisfies symbol-listp) vars args)
(type (satisfies symbol-listp) args1)
(type (satisfies pseudo-termp) congruent-predicate)
(type (satisfies good-congruence-listp) congruences)
(xargs :guard-debug t
:guard (and (or (not hyps) (pseudo-termp hyps))
(all-congruences-apply-to-args congruences args)
(or (not relation) (equal relation acl2::*nil*) (lambda-term-p relation)))))
(let* (;(x (acl2::packn-pos (list "X") name))
;(y (acl2::packn-pos (list "Y") name))
(hyps (if (not hyps) nil (if (equal hyps acl2::*nil*) nil hyps)))
(relation (if (not relation) nil (if (equal relation acl2::*nil*) nil relation)))
(relation-hyp (if (not relation) acl2::*t* (beta-reduce-lambda-term-full `(,relation ,@args ,@args1))))
(iff (if iff 'iff 'equal))
(suffix (if (equal suffix '||) suffix (acl2::packn-pos (list "-" suffix) suffix)))
(congruent-predicate-congruence (acl2::add-suffix name (concatenate 'acl2::string "-CONGRUENCE" (symbol-name suffix))))
(congruent-predicate-witness (acl2::add-suffix name "-WITNESS"))
(congruent-predicate-lemma (if (equal quantifier :exists) (acl2::add-suffix name "-SUFF") (acl2::add-suffix name "-NECC")))
(congruent-predicate-witness-congruence (acl2::add-suffix congruent-predicate-witness (concatenate 'acl2::string "-CONGRUENCE" (symbol-name suffix))))
(congruent-predicate-rule (acl2::add-suffix congruent-predicate-witness "-STRENGTHEN"))
;;(congruent-predicate-witness-canary (acl2::add-suffix congruent-predicate-witness "-CANARY"))
(congruent-predicate-raw `(lambda (,@vars ,@args) ,(beta-reduce-lambda-term-full congruent-predicate)))
;(congruent-predicate (if (equal quantifier :exists) congruent-predicate-raw `(lambda (,@vars ,@args) (not (,congruent-predicate-raw ,@vars ,@args)))))
;(a1 (acl2::packn-pos (list a 1) 'quant::prove-quantified-congruence-fn))
(local-congruent-predicate (acl2::packn-pos (list name '-congruent-predicate) 'quant::prove-quantified-congruence-fn))
(local-definition (acl2::packn-pos (list name '-definition) 'quant::prove-quantified-congruence-fn))
(congruent-predicate-equiv (acl2::packn-pos (list name '-equiv suffix) 'quant::prove-quantified-congruence-fn))
(congruent-predicate-quantified-x `(lambda (x) (,name ,@(into-args args 'x))))
(congruent-predicate-hyps-x `(lambda (x) ,(beta-reduce-lambda-term-full `((lambda (,@args) ,(or hyps acl2::*t*)) ,@(into-args args 'x)))))
(congruent-predicate-relation-x `(lambda (x y) ,(beta-reduce-lambda-term-full (if relation `(,relation ,@(into-args args 'x) ,@(into-args args 'y)) t))))
(congruent-predicate-equiv-x `(lambda (x y) (,congruent-predicate-equiv ,@(into-args args 'x) ,@(into-args args 'y))))
(congruent-predicate-x `(lambda (a x) (,local-congruent-predicate ,@(into-args vars 'a) ,@(into-args args 'x))))
(congruent-predicate-x-witness `(lambda (x) (list ,@(make-mv (len vars) `(,congruent-predicate-witness ,@(into-args args 'x))))))
(finst `((congruent-predicate-hyps ,congruent-predicate-hyps-x)
(congruent-predicate-relation ,congruent-predicate-relation-x)
(congruent-predicate-equiv ,congruent-predicate-equiv-x)
(congruent-predicate-witness ,congruent-predicate-x-witness)
(congruent-predicate ,congruent-predicate-x)
(congruent-predicate-quantified ,congruent-predicate-quantified-x)
(universally-quantified (lambda () ,(if (equal quantifier :exists) nil t)))))
)
`(encapsulate
()
(local (in-theory (disable nth)))
(local
(defun ,local-congruent-predicate (,@vars ,@args)
(declare (ignorable ,@vars ,@args))
,(beta-reduce-lambda-term-full `(,congruent-predicate-raw ,@vars ,@args))))
(defun ,congruent-predicate-equiv (,@args ,@args1)
(and ,@(make-equiv-body (pairlis$ args args1) congruences)))
(local
(defthm big-bang-congruence
(implies
(and
,(or hyps t)
,relation-hyp
(,congruent-predicate-equiv ,@args ,@args1))
(iff (iff-equiv (,local-congruent-predicate ,@vars ,@args)
(,local-congruent-predicate ,@vars ,@args1))
t))))
;; I honestly don't know if this helps .. what if we simply did the big-bang version?
;; (let ((events (make-congruences nil local-congruent-predicate local-congruent-predicate 'iff-equiv vars args args1 congruences hyps relation suffix)))
;; (and events `((local
;; (encapsulate
;; ()
;; ,@events
;; )))))
(local
(defthm ,local-definition
(equal (,name ,@args)
;; We will need to duplicate the witness here for multiple vars ..
(,local-congruent-predicate ,@(make-mv (len vars) `(,congruent-predicate-witness ,@args)) ,@args))
:hints (("Goal" :in-theory (enable ,name)))))
(local (in-theory (disable iff-equiv ,name ,local-congruent-predicate ,local-definition)))
(local
(defthm congruent-predicate-witness-canary
t
:rule-classes nil
:hints (("Goal" :use (:functional-instance congruent-predicate-canary
,@finst
))
(and stable-under-simplificationp
'(:in-theory (disable ,congruent-predicate-lemma)
:use ((:instance ,congruent-predicate-rule
,@(make-binding-out args args1 'x 'x1))
(:instance ,congruent-predicate-lemma
,@(soft-alist (pairlis$ vars (into-args vars 'a)))
,@(soft-alist (pairlis$ args (into-args args 'x)))))))
(and stable-under-simplificationp
'(:in-theory (enable ,local-definition)))
(and stable-under-simplificationp
'(:in-theory (enable ,local-congruent-predicate)))
)))
(defthm ,congruent-predicate-witness-congruence
(implies
(and
,(or hyps t)
,relation-hyp
(,congruent-predicate-equiv ,@args ,@args1))
,(all-equal (make-mv (len vars) `(,congruent-predicate-witness ,@args))
(make-mv (len vars) `(,congruent-predicate-witness ,@args1))))
:rule-classes nil
:hints (("Goal" :do-not-induct t
:use (:functional-instance (:instance congruent-predicate-witness-congruence
,@(make-binding-into 'x 'y args args1))
,@finst))
,@hints))
(defthm ,congruent-predicate-congruence
(implies
(and
,(or hyps t)
,relation-hyp
(,congruent-predicate-equiv ,@args ,@args1))
(,iff (,name ,@args)
(,name ,@args1)))
:rule-classes nil
:hints (("Goal" :do-not-induct t
:use (:functional-instance (:instance congruent-predicate-congruence
,@(make-binding-into 'x 'y args args1))
,@finst
))
,@hints))
(local (in-theory (union-theories '(,congruent-predicate-equiv) (theory 'acl2::minimal-theory))))
(local (in-theory (disable ,name)))
,@(make-witness-congruences vars congruent-predicate-witness-congruence congruent-predicate-witness args args1 congruences hyps relation suffix)
,@(make-congruences congruent-predicate-congruence name name iff nil args args1 congruences hyps relation suffix)
)))
(defun decompose-quantified-formula (expr)
(declare (type t expr))
(case-match expr
((`forall vars expr) (mv :forall vars expr))
((`exists vars expr) (mv :exists vars expr))
(& (mv nil nil expr))))
(defun acl2::pseudo-translate-lambda (fn fn-args-lst wrld)
(declare (xargs :mode :program))
(if (symbolp fn) (mv t fn nil)
(case-match fn
(('lambda args &)
(mv-let (flg term) (acl2::pseudo-translate `(,fn ,@args) fn-args-lst wrld)
(case-match term
((('lambda formals body) . &)
(mv flg `(lambda ,formals ,body) (nthcdr (len args) formals)))
(& (mv nil fn nil)))))
(& (mv nil fn nil)))))
(defmacro congruence (name args body &key (suffix '||) (hyps 'nil) (relation 'nil) (congruences 'nil) (iff 'nil) (hints 'nil))
(mv-let (quantifier vars congruent-predicate) (decompose-quantified-formula body)
`(make-event
(let ((name ',name)
(vars ',vars)
(args ',args)
(hyps ',hyps)
(relation ',relation)
(congruences ',congruences)
(suffix ',suffix)
(congruent-predicate ',congruent-predicate)
(quantifier ',quantifier)
(iff ',iff)
(hints ',hints)
)
(mv-let (flg congruent-predicate) (acl2::pseudo-translate congruent-predicate nil (w state))
(declare (ignore flg))
(mv-let (flg hyps) (acl2::pseudo-translate hyps nil (w state))
(declare (ignore flg))
(let ((args1 (acl2::generate-variable-lst-simple args (append vars args))))
(prove-quantified-congruence-fn name vars args args1 congruent-predicate hyps relation congruences quantifier suffix iff hints))))))
))
(local
(encapsulate
()
(defun my-member (a x)
(member a x))
(defun-sk fred (z)
(exists (a) (my-member a z))
:strengthen t)
(defun member-equalx (x y)
(equal x y))
(defun similar (x y)
(declare (ignore x y))
t)
(defequiv member-equalx)
(defcong member-equalx iff (my-member a x) 2)
(in-theory (disable my-member (my-member) member-equalx))
(quant::congruence fred (z)
(exists (a) (my-member a z))
:congruences ((z member-equalx))
;; In some cases, the congruence may only be conditional.
:hyps (true-listp z)
;; Or there may be additional relations that must hold
:relation (lambda (x y) (similar x y))
;; The quantified predicate may not be strictly Boolean
;; If that is so, set the :iff flag to t
:iff t
)
;; We don't actually get ACL2 congruence rules in this case
;; but we do get the following properties ..
(defthmd fred-witness-congruence-result1
(implies (and (true-listp z)
(similar z z1)
(member-equalx z z1))
(equal (fred-witness z)
(fred-witness z1)))
:hints (("goal" :use fred-witness-congruence)))
(defthm fred-congruence-result2
(implies (and (true-listp z)
(similar z z1)
(member-equalx z z1))
(iff (fred z) (fred z1)))
:hints (("goal" :use fred-congruence)))
))
(local
(encapsulate
()
(encapsulate
(
((deuce * * *) => *)
((deuce-equiv * *) => *)
)
(local
(defun deuce-equiv (x y)
(equal x y)))
(defequiv deuce-equiv)
(local
(defun deuce (a b x)
(declare (ignore a b x))
t))
(defthm booleanp-deuce
(booleanp (deuce a b x))
:rule-classes (:type-prescription))
(defcong deuce-equiv equal (deuce a b x) 3)
)
(encapsulate
()
;; We now support multiple quantified variables
(defun-sk existentially-quantified-deuce (z)
(exists (a b) (deuce a b z))
:strengthen t)
(quant::congruence existentially-quantified-deuce (z)
(exists (a b) (deuce a b z))
:congruences ((z deuce-equiv))
)
)
))
(local
(encapsulate
()
(encapsulate
(
((pred * * *) => *)
((pred-equiv * *) => *)
)
(local
(defun pred-equiv (x y)
(equal x y)))
(defequiv pred-equiv)
(local
(defun pred (a x y)
(declare (ignore a x y))
t))
(defthm booleanp-pred
(booleanp (pred a x y))
:rule-classes (:type-prescription))
(defcong pred-equiv equal (pred a x y) 2)
)
(local
(encapsulate
()
(local
(encapsulate
()
;; Existentially quantified
;; The :strengthen t argument is required.
(defun-sk existentially-quantified-pred (v z)
(exists (a) (pred a v z))
:strengthen t)
(quant::congruence existentially-quantified-pred (v z)
(exists (a) (pred a v z))
:congruences ((v pred-equiv))
)
;; The following congruences now follow naturally ..
(defthmd test1
(implies
(pred-equiv v1 v2)
(equal (existentially-quantified-pred-witness v1 z)
(existentially-quantified-pred-witness v2 z))))
(defthmd test2
(implies
(pred-equiv v1 v2)
(equal (existentially-quantified-pred v1 z)
(existentially-quantified-pred v2 z))))
))
))
(local
(encapsulate
()
(local
(encapsulate
()
;; Universally quantified
;; The :strengthen t argument is required.
(defun-sk universally-quantified-pred (v z)
(forall (a) (pred a v z))
:strengthen t)
(quant::congruence universally-quantified-pred (v z)
(forall (a) (pred a v z))
:iff t
:congruences ((v pred-equiv)))
;; The following congruences now follow naturally ..
(defthmd test1
(implies
(pred-equiv v1 v2)
(equal (universally-quantified-pred-witness v1 z)
(universally-quantified-pred-witness v2 z))))
(defthmd test2
(implies
(pred-equiv v1 v2)
(equal (universally-quantified-pred v1 z)
(universally-quantified-pred v2 z))))
))))
))
(acl2::defxdoc quant::congruence
:short "A macro to prove congruence rules for quantified formulae and their associated witnesses"
:parents (acl2::defun-sk)
:long "<p>
The @('quant::congruence') macro can be used to prove
@(tsee acl2::congruence) rules for quantified formulae and their associated
witnesses introduced using @(tsee acl2::defun-sk). Note: this macro only
works for formula that are introduced with the :strengthen t keyword.
</p>
<p>Usage:</p> @({
(include-book \"coi/quantification/quantified-congruence\" :dir :system)
;; Given a predicate that satisfies some congruence
(defcong pred-equiv equal (pred a x y) 2)
;; A quantified formula involving pred introduced using
;; defun-sk with the :strengthen t option.
(defun-sk quantified-pred (v z)
(forall (a) (pred a v z))
:strengthen t)
;; We prove congruence rules relative to 'v'
(quant::congruence quantified-pred (v z)
(forall (a) (pred a v z))
:congruences ((v pred-equiv)))
;; The following lemmas now follow directly ..
(defthmd witness-congruence
(implies
(pred-equiv v1 v2)
(equal (quantified-pred-witness v1 z)
(quantified-pred-witness v2 z))))
(defthmd quantified-congruence
(implies
(pred-equiv v1 v2)
(equal (quantified-pred v1 z)
(quantified-pred v2 z))))
})
")
|
[
{
"context": "em cl-factorial\n :name \"cl-factorial\"\n :author \"Thomas HOULLIER\"\n :components\n ((:module \"src\"\n :components ",
"end": 73,
"score": 0.9998194575309753,
"start": 58,
"tag": "NAME",
"value": "Thomas HOULLIER"
}
] |
cl-factorial.asd
|
thomashoullier/cl-factorial
| 0 |
(defsystem cl-factorial
:name "cl-factorial"
:author "Thomas HOULLIER"
:components
((:module "src"
:components ((:file "package")
(:file "constants" :depends-on ("package"))
(:file "stirling" :depends-on ("package" "constants"))
(:file "iter" :depends-on ("package")))))
:in-order-to ((test-op (test-op "cl-factorial/test"))))
(defsystem cl-factorial/test
:name "cl-factorial/test"
:depends-on ("rove" "cl-factorial")
:components
((:module "test"
:components ((:file "rove-suite"))))
:perform (test-op (o c) (symbol-call :rove '#:run c)))
|
88479
|
(defsystem cl-factorial
:name "cl-factorial"
:author "<NAME>"
:components
((:module "src"
:components ((:file "package")
(:file "constants" :depends-on ("package"))
(:file "stirling" :depends-on ("package" "constants"))
(:file "iter" :depends-on ("package")))))
:in-order-to ((test-op (test-op "cl-factorial/test"))))
(defsystem cl-factorial/test
:name "cl-factorial/test"
:depends-on ("rove" "cl-factorial")
:components
((:module "test"
:components ((:file "rove-suite"))))
:perform (test-op (o c) (symbol-call :rove '#:run c)))
| true |
(defsystem cl-factorial
:name "cl-factorial"
:author "PI:NAME:<NAME>END_PI"
:components
((:module "src"
:components ((:file "package")
(:file "constants" :depends-on ("package"))
(:file "stirling" :depends-on ("package" "constants"))
(:file "iter" :depends-on ("package")))))
:in-order-to ((test-op (test-op "cl-factorial/test"))))
(defsystem cl-factorial/test
:name "cl-factorial/test"
:depends-on ("rove" "cl-factorial")
:components
((:module "test"
:components ((:file "rove-suite"))))
:perform (test-op (o c) (symbol-call :rove '#:run c)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.